repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Drusy/auvergne-webcams-ios
Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftArrayPropertyTests.swift
2
10504
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import Realm import RealmTestSupport class SwiftRLMArrayPropertyTests: RLMTestCase { // Swift models func testBasicArray() { let string = SwiftRLMStringObject() string.stringCol = "string" let realm = realmWithTestPath() realm.beginWriteTransaction() realm.add(string) try! realm.commitWriteTransaction() XCTAssertEqual(SwiftRLMStringObject.allObjects(in: realm).count, UInt(1), "There should be a single SwiftRLMStringObject in the realm") let array = SwiftRLMArrayPropertyObject() array.name = "arrayObject" array.array.add(string) XCTAssertEqual(array.array.count, UInt(1)) XCTAssertEqual(array.array.firstObject()!.stringCol, "string") realm.beginWriteTransaction() realm.add(array) array.array.add(string) try! realm.commitWriteTransaction() let arrayObjects = SwiftRLMArrayPropertyObject.allObjects(in: realm) as! RLMResults<SwiftRLMArrayPropertyObject> XCTAssertEqual(arrayObjects.count, UInt(1), "There should be a single SwiftRLMStringObject in the realm") let cmp = arrayObjects.firstObject()!.array.firstObject()! XCTAssertTrue(string.isEqual(to: cmp), "First array object should be the string object we added") } func testPopulateEmptyArray() { let realm = realmWithTestPath() realm.beginWriteTransaction() let array = SwiftRLMArrayPropertyObject.create(in: realm, withValue: ["arrayObject", [], []]) XCTAssertNotNil(array.array, "Should be able to get an empty array") XCTAssertEqual(array.array.count, UInt(0), "Should start with no array elements") let obj = SwiftRLMStringObject() obj.stringCol = "a" array.array.add(obj) array.array.add(SwiftRLMStringObject.create(in: realm, withValue: ["b"])) array.array.add(obj) try! realm.commitWriteTransaction() XCTAssertEqual(array.array.count, UInt(3), "Should have three elements in array") XCTAssertEqual(array.array[0].stringCol, "a", "First element should have property value 'a'") XCTAssertEqual(array.array[1].stringCol, "b", "Second element should have property value 'b'") XCTAssertEqual(array.array[2].stringCol, "a", "Third element should have property value 'a'") for obj in array.array { XCTAssertFalse(obj.description.isEmpty, "Object should have description") } } func testModifyDetatchedArray() { let realm = realmWithTestPath() realm.beginWriteTransaction() let arObj = SwiftRLMArrayPropertyObject.create(in: realm, withValue: ["arrayObject", [], []]) XCTAssertNotNil(arObj.array, "Should be able to get an empty array") XCTAssertEqual(arObj.array.count, UInt(0), "Should start with no array elements") let obj = SwiftRLMStringObject() obj.stringCol = "a" let array = arObj.array array.add(obj) array.add(SwiftRLMStringObject.create(in: realm, withValue: ["b"])) try! realm.commitWriteTransaction() XCTAssertEqual(array.count, UInt(2), "Should have two elements in array") XCTAssertEqual(array[0].stringCol, "a", "First element should have property value 'a'") XCTAssertEqual(array[1].stringCol, "b", "Second element should have property value 'b'") } func testInsertMultiple() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = SwiftRLMArrayPropertyObject.create(in: realm, withValue: ["arrayObject", [], []]) let child1 = SwiftRLMStringObject.create(in: realm, withValue: ["a"]) let child2 = SwiftRLMStringObject() child2.stringCol = "b" obj.array.addObjects([child2, child1] as NSArray) try! realm.commitWriteTransaction() let children = SwiftRLMStringObject.allObjects(in: realm) XCTAssertEqual((children[0] as! SwiftRLMStringObject).stringCol, "a", "First child should be 'a'") XCTAssertEqual((children[1] as! SwiftRLMStringObject).stringCol, "b", "Second child should be 'b'") } // FIXME: Support unmanaged RLMArray's in Swift-defined models // func testUnmanaged() { // let realm = realmWithTestPath() // // let array = SwiftRLMArrayPropertyObject() // array.name = "name" // XCTAssertNotNil(array.array, "RLMArray property should get created on access") // // let obj = SwiftRLMStringObject() // obj.stringCol = "a" // array.array.addObject(obj) // array.array.addObject(obj) // // realm.beginWriteTransaction() // realm.addObject(array) // try! realm.commitWriteTransaction() // // XCTAssertEqual(array.array.count, UInt(2), "Should have two elements in array") // XCTAssertEqual((array.array[0] as SwiftRLMStringObject).stringCol, "a", "First element should have property value 'a'") // XCTAssertEqual((array.array[1] as SwiftRLMStringObject).stringCol, "a", "Second element should have property value 'a'") // } // Objective-C models func testBasicArray_objc() { let string = StringObject() string.stringCol = "string" let realm = realmWithTestPath() realm.beginWriteTransaction() realm.add(string) try! realm.commitWriteTransaction() XCTAssertEqual(StringObject.allObjects(in: realm).count, UInt(1), "There should be a single StringObject in the realm") let array = ArrayPropertyObject() array.name = "arrayObject" array.array.add(string) realm.beginWriteTransaction() realm.add(array) try! realm.commitWriteTransaction() let arrayObjects = ArrayPropertyObject.allObjects(in: realm) XCTAssertEqual(arrayObjects.count, UInt(1), "There should be a single StringObject in the realm") let cmp = (arrayObjects.firstObject() as! ArrayPropertyObject).array.firstObject()! XCTAssertTrue(string.isEqual(to: cmp), "First array object should be the string object we added") } func testPopulateEmptyArray_objc() { let realm = realmWithTestPath() realm.beginWriteTransaction() let array = ArrayPropertyObject.create(in: realm, withValue: ["arrayObject", [], []]) XCTAssertNotNil(array.array, "Should be able to get an empty array") XCTAssertEqual(array.array.count, UInt(0), "Should start with no array elements") let obj = StringObject() obj.stringCol = "a" array.array.add(obj) array.array.add(StringObject.create(in: realm, withValue: ["b"])) array.array.add(obj) try! realm.commitWriteTransaction() XCTAssertEqual(array.array.count, UInt(3), "Should have three elements in array") XCTAssertEqual((array.array[0]).stringCol!, "a", "First element should have property value 'a'") XCTAssertEqual((array.array[1]).stringCol!, "b", "Second element should have property value 'b'") XCTAssertEqual((array.array[2]).stringCol!, "a", "Third element should have property value 'a'") for idx in 0..<array.array.count { XCTAssertFalse(array.array[idx].description.isEmpty, "Object should have description") } } func testModifyDetatchedArray_objc() { let realm = realmWithTestPath() realm.beginWriteTransaction() let arObj = ArrayPropertyObject.create(in: realm, withValue: ["arrayObject", [], []]) XCTAssertNotNil(arObj.array, "Should be able to get an empty array") XCTAssertEqual(arObj.array.count, UInt(0), "Should start with no array elements") let obj = StringObject() obj.stringCol = "a" let array = arObj.array! array.add(obj) array.add(StringObject.create(in: realm, withValue: ["b"])) try! realm.commitWriteTransaction() XCTAssertEqual(array.count, UInt(2), "Should have two elements in array") XCTAssertEqual(array[0].stringCol!, "a", "First element should have property value 'a'") XCTAssertEqual(array[1].stringCol!, "b", "Second element should have property value 'b'") } func testInsertMultiple_objc() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = ArrayPropertyObject.create(in: realm, withValue: ["arrayObject", [], []]) let child1 = StringObject.create(in: realm, withValue: ["a"]) let child2 = StringObject() child2.stringCol = "b" obj.array.addObjects([child2, child1] as NSArray) try! realm.commitWriteTransaction() let children = StringObject.allObjects(in: realm) XCTAssertEqual((children[0] as! StringObject).stringCol!, "a", "First child should be 'a'") XCTAssertEqual((children[1] as! StringObject).stringCol!, "b", "Second child should be 'b'") } func testUnmanaged_objc() { let realm = realmWithTestPath() let array = ArrayPropertyObject() array.name = "name" XCTAssertNotNil(array.array, "RLMArray property should get created on access") let obj = StringObject() obj.stringCol = "a" array.array.add(obj) array.array.add(obj) realm.beginWriteTransaction() realm.add(array) try! realm.commitWriteTransaction() XCTAssertEqual(array.array.count, UInt(2), "Should have two elements in array") XCTAssertEqual(array.array[0].stringCol!, "a", "First element should have property value 'a'") XCTAssertEqual(array.array[1].stringCol!, "a", "Second element should have property value 'a'") } }
apache-2.0
bdfd3051a45bc0912c67d9d5a37a9ee2
41.354839
143
0.65099
4.662228
false
true
false
false
AkshayNG/iSwift
iSwift/Extensions/UIImageView+Extension.swift
1
1194
// // UIImageView+Extension.swift // iSwift // // Created by Akshay Gajarlawar on 24/03/19. // Copyright © 2019 yantrana. All rights reserved. // import Foundation func downloadImage(imageURL:URL, placeholderImage:UIImage?, cachePolicy:NSURLRequest.CachePolicy, finished: (() -> Void)?) { self.image = placeholderImage let request = URLRequest.init(url: imageURL, cachePolicy: cachePolicy, timeoutInterval: 60.0) URLSession.shared.dataTask(with: request) { (data, response, error) in if(error == nil) { if(data != nil) { DispatchQueue.main.async { self.image = UIImage.init(data: data!) if(finished != nil) { finished!() } } } else { print("Error downloading image :: Data not found") if(finished != nil) { finished!() } } } else { print("Error downloading image :: %@",error!.localizedDescription) if(finished != nil) { finished!() } } }.resume() }
mit
3373d06defd4337d4c1a1132a5821593
27.404762
97
0.506287
4.660156
false
false
false
false
google/swift-structural
Sources/StructuralExamples/PointN.swift
1
125304
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import StructuralCore public struct Point1: Equatable, Hashable, Codable { public var _1: Float public init( _1: Float ) { self._1 = _1 } } extension Point1: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralEmpty > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point1.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralEmpty() ) ) } set { self._1 = newValue.body .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value } } extension Point1: MyAdditive {} extension Point1: MyComparable {} extension Point1: MyDebugString {} extension Point1: MyDecodeJSON {} extension Point1: MyDefaultInitializable {} extension Point1: MyEncodeJSON {} extension Point1: MyEquatable {} extension Point1: MyHashable {} extension Point1: MyInplaceAdd {} extension Point1: MyZero {} public struct Point2: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public init( _1: Float, _2: Float ) { self._1 = _1 self._2 = _2 } } extension Point2: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point2.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralEmpty() ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value } } extension Point2: MyAdditive {} extension Point2: MyComparable {} extension Point2: MyDebugString {} extension Point2: MyDecodeJSON {} extension Point2: MyDefaultInitializable {} extension Point2: MyEncodeJSON {} extension Point2: MyEquatable {} extension Point2: MyHashable {} extension Point2: MyInplaceAdd {} extension Point2: MyZero {} public struct Point3: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public init( _1: Float, _2: Float, _3: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 } } extension Point3: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point3.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralEmpty() ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value } } extension Point3: MyAdditive {} extension Point3: MyComparable {} extension Point3: MyDebugString {} extension Point3: MyDecodeJSON {} extension Point3: MyDefaultInitializable {} extension Point3: MyEncodeJSON {} extension Point3: MyEquatable {} extension Point3: MyHashable {} extension Point3: MyInplaceAdd {} extension Point3: MyZero {} public struct Point4: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public init( _1: Float, _2: Float, _3: Float, _4: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 } } extension Point4: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point4.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralEmpty() ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value } } extension Point4: MyAdditive {} extension Point4: MyComparable {} extension Point4: MyDebugString {} extension Point4: MyDecodeJSON {} extension Point4: MyDefaultInitializable {} extension Point4: MyEncodeJSON {} extension Point4: MyEquatable {} extension Point4: MyHashable {} extension Point4: MyInplaceAdd {} extension Point4: MyZero {} public struct Point5: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 } } extension Point5: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point5.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralEmpty() ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value } } extension Point5: MyAdditive {} extension Point5: MyComparable {} extension Point5: MyDebugString {} extension Point5: MyDecodeJSON {} extension Point5: MyDefaultInitializable {} extension Point5: MyEncodeJSON {} extension Point5: MyEquatable {} extension Point5: MyHashable {} extension Point5: MyInplaceAdd {} extension Point5: MyZero {} public struct Point6: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 } } extension Point6: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point6.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value } } extension Point6: MyAdditive {} extension Point6: MyComparable {} extension Point6: MyDebugString {} extension Point6: MyDecodeJSON {} extension Point6: MyDefaultInitializable {} extension Point6: MyEncodeJSON {} extension Point6: MyEquatable {} extension Point6: MyHashable {} extension Point6: MyInplaceAdd {} extension Point6: MyZero {} public struct Point7: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 } } extension Point7: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point7.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value } } extension Point7: MyAdditive {} extension Point7: MyComparable {} extension Point7: MyDebugString {} extension Point7: MyDecodeJSON {} extension Point7: MyDefaultInitializable {} extension Point7: MyEncodeJSON {} extension Point7: MyEquatable {} extension Point7: MyHashable {} extension Point7: MyInplaceAdd {} extension Point7: MyZero {} public struct Point8: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 } } extension Point8: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point8.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value } } extension Point8: MyAdditive {} extension Point8: MyComparable {} extension Point8: MyDebugString {} extension Point8: MyDecodeJSON {} extension Point8: MyDefaultInitializable {} extension Point8: MyEncodeJSON {} extension Point8: MyEquatable {} extension Point8: MyHashable {} extension Point8: MyInplaceAdd {} extension Point8: MyZero {} public struct Point9: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 } } extension Point9: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point9.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value } } extension Point9: MyAdditive {} extension Point9: MyComparable {} extension Point9: MyDebugString {} extension Point9: MyDecodeJSON {} extension Point9: MyDefaultInitializable {} extension Point9: MyEncodeJSON {} extension Point9: MyEquatable {} extension Point9: MyHashable {} extension Point9: MyInplaceAdd {} extension Point9: MyZero {} public struct Point10: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 } } extension Point10: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point10.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value } } extension Point10: MyAdditive {} extension Point10: MyComparable {} extension Point10: MyDebugString {} extension Point10: MyDecodeJSON {} extension Point10: MyDefaultInitializable {} extension Point10: MyEncodeJSON {} extension Point10: MyEquatable {} extension Point10: MyHashable {} extension Point10: MyInplaceAdd {} extension Point10: MyZero {} public struct Point11: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public var _11: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float, _11: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 self._11 = _11 } } extension Point11: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point11.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralCons( StructuralProperty( "_11", _11, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value self._11 = newValue.body .next .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value self._11 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .value .value } } extension Point11: MyAdditive {} extension Point11: MyComparable {} extension Point11: MyDebugString {} extension Point11: MyDecodeJSON {} extension Point11: MyDefaultInitializable {} extension Point11: MyEncodeJSON {} extension Point11: MyEquatable {} extension Point11: MyHashable {} extension Point11: MyInplaceAdd {} extension Point11: MyZero {} public struct Point12: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public var _11: Float public var _12: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float, _11: Float, _12: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 self._11 = _11 self._12 = _12 } } extension Point12: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point12.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralCons( StructuralProperty( "_11", _11, isMutable: true), StructuralCons( StructuralProperty( "_12", _12, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value self._11 = newValue.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value self._11 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .value .value } } extension Point12: MyAdditive {} extension Point12: MyComparable {} extension Point12: MyDebugString {} extension Point12: MyDecodeJSON {} extension Point12: MyDefaultInitializable {} extension Point12: MyEncodeJSON {} extension Point12: MyEquatable {} extension Point12: MyHashable {} extension Point12: MyInplaceAdd {} extension Point12: MyZero {} public struct Point13: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public var _11: Float public var _12: Float public var _13: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float, _11: Float, _12: Float, _13: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 self._11 = _11 self._12 = _12 self._13 = _13 } } extension Point13: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point13.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralCons( StructuralProperty( "_11", _11, isMutable: true), StructuralCons( StructuralProperty( "_12", _12, isMutable: true), StructuralCons( StructuralProperty( "_13", _13, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value self._11 = newValue.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value self._11 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } extension Point13: MyAdditive {} extension Point13: MyComparable {} extension Point13: MyDebugString {} extension Point13: MyDecodeJSON {} extension Point13: MyDefaultInitializable {} extension Point13: MyEncodeJSON {} extension Point13: MyEquatable {} extension Point13: MyHashable {} extension Point13: MyInplaceAdd {} extension Point13: MyZero {} public struct Point14: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public var _11: Float public var _12: Float public var _13: Float public var _14: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float, _11: Float, _12: Float, _13: Float, _14: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 self._11 = _11 self._12 = _12 self._13 = _13 self._14 = _14 } } extension Point14: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point14.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralCons( StructuralProperty( "_11", _11, isMutable: true), StructuralCons( StructuralProperty( "_12", _12, isMutable: true), StructuralCons( StructuralProperty( "_13", _13, isMutable: true), StructuralCons( StructuralProperty( "_14", _14, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value self._11 = newValue.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._14 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value self._11 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._14 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } extension Point14: MyAdditive {} extension Point14: MyComparable {} extension Point14: MyDebugString {} extension Point14: MyDecodeJSON {} extension Point14: MyDefaultInitializable {} extension Point14: MyEncodeJSON {} extension Point14: MyEquatable {} extension Point14: MyHashable {} extension Point14: MyInplaceAdd {} extension Point14: MyZero {} public struct Point15: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public var _11: Float public var _12: Float public var _13: Float public var _14: Float public var _15: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float, _11: Float, _12: Float, _13: Float, _14: Float, _15: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 self._11 = _11 self._12 = _12 self._13 = _13 self._14 = _14 self._15 = _15 } } extension Point15: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralEmpty > > > > > > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point15.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralCons( StructuralProperty( "_11", _11, isMutable: true), StructuralCons( StructuralProperty( "_12", _12, isMutable: true), StructuralCons( StructuralProperty( "_13", _13, isMutable: true), StructuralCons( StructuralProperty( "_14", _14, isMutable: true), StructuralCons( StructuralProperty( "_15", _15, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value self._11 = newValue.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._14 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._15 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value self._11 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._14 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._15 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } extension Point15: MyAdditive {} extension Point15: MyComparable {} extension Point15: MyDebugString {} extension Point15: MyDecodeJSON {} extension Point15: MyDefaultInitializable {} extension Point15: MyEncodeJSON {} extension Point15: MyEquatable {} extension Point15: MyHashable {} extension Point15: MyInplaceAdd {} extension Point15: MyZero {} public struct Point16: Equatable, Hashable, Codable { public var _1: Float public var _2: Float public var _3: Float public var _4: Float public var _5: Float public var _6: Float public var _7: Float public var _8: Float public var _9: Float public var _10: Float public var _11: Float public var _12: Float public var _13: Float public var _14: Float public var _15: Float public var _16: Float public init( _1: Float, _2: Float, _3: Float, _4: Float, _5: Float, _6: Float, _7: Float, _8: Float, _9: Float, _10: Float, _11: Float, _12: Float, _13: Float, _14: Float, _15: Float, _16: Float ) { self._1 = _1 self._2 = _2 self._3 = _3 self._4 = _4 self._5 = _5 self._6 = _6 self._7 = _7 self._8 = _8 self._9 = _9 self._10 = _10 self._11 = _11 self._12 = _12 self._13 = _13 self._14 = _14 self._15 = _15 self._16 = _16 } } extension Point16: Structural { public typealias StructuralRepresentation = StructuralStruct< StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty<Float>, StructuralCons< StructuralProperty< Float >, StructuralEmpty > > > > > > > > > > > > > > > > > public var structuralRepresentation: StructuralRepresentation { get { return StructuralStruct( Point16.self, StructuralCons( StructuralProperty("_1", _1, isMutable: true), StructuralCons( StructuralProperty("_2", _2, isMutable: true), StructuralCons( StructuralProperty("_3", _3, isMutable: true), StructuralCons( StructuralProperty("_4", _4, isMutable: true), StructuralCons( StructuralProperty("_5", _5, isMutable: true), StructuralCons( StructuralProperty("_6", _6, isMutable: true), StructuralCons( StructuralProperty("_7", _7, isMutable: true), StructuralCons( StructuralProperty("_8", _8, isMutable: true), StructuralCons( StructuralProperty("_9", _9, isMutable: true), StructuralCons( StructuralProperty( "_10", _10, isMutable: true), StructuralCons( StructuralProperty( "_11", _11, isMutable: true), StructuralCons( StructuralProperty( "_12", _12, isMutable: true), StructuralCons( StructuralProperty( "_13", _13, isMutable: true), StructuralCons( StructuralProperty( "_14", _14, isMutable: true), StructuralCons( StructuralProperty( "_15", _15, isMutable: true), StructuralCons( StructuralProperty( "_16", _16, isMutable: true), StructuralEmpty() ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) } set { self._1 = newValue.body .value .value self._2 = newValue.body .next .value .value self._3 = newValue.body .next .next .value .value self._4 = newValue.body .next .next .next .value .value self._5 = newValue.body .next .next .next .next .value .value self._6 = newValue.body .next .next .next .next .next .value .value self._7 = newValue.body .next .next .next .next .next .next .value .value self._8 = newValue.body .next .next .next .next .next .next .next .value .value self._9 = newValue.body .next .next .next .next .next .next .next .next .value .value self._10 = newValue.body .next .next .next .next .next .next .next .next .next .value .value self._11 = newValue.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._14 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._15 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._16 = newValue.body .next .next .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } public init(structuralRepresentation: StructuralRepresentation) { self._1 = structuralRepresentation.body .value .value self._2 = structuralRepresentation.body .next .value .value self._3 = structuralRepresentation.body .next .next .value .value self._4 = structuralRepresentation.body .next .next .next .value .value self._5 = structuralRepresentation.body .next .next .next .next .value .value self._6 = structuralRepresentation.body .next .next .next .next .next .value .value self._7 = structuralRepresentation.body .next .next .next .next .next .next .value .value self._8 = structuralRepresentation.body .next .next .next .next .next .next .next .value .value self._9 = structuralRepresentation.body .next .next .next .next .next .next .next .next .value .value self._10 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .value .value self._11 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .value .value self._12 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .value .value self._13 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._14 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._15 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value self._16 = structuralRepresentation.body .next .next .next .next .next .next .next .next .next .next .next .next .next .next .next .value .value } } extension Point16: MyAdditive {} extension Point16: MyComparable {} extension Point16: MyDebugString {} extension Point16: MyDecodeJSON {} extension Point16: MyDefaultInitializable {} extension Point16: MyEncodeJSON {} extension Point16: MyEquatable {} extension Point16: MyHashable {} extension Point16: MyInplaceAdd {} extension Point16: MyZero {}
apache-2.0
c5270358e6beeef01d3fd5542ba41fa1
27.614752
101
0.320732
6.793017
false
false
false
false
swift-tweets/tweetup-kit
Sources/TweetupKit/ArrayExtensions.swift
1
985
extension Array where Element: Equatable { internal func separated(by separator: Element) -> [[Element]] { var separated: [[Element]] = [[]] for element in self { if element == separator { separated.append([]) } else { separated[separated.endIndex - 1].append(element) } } return separated } } extension Array where Element: Hashable { internal func trimmingElements(in set: Set<Element>) -> [Element] { var trimmed = [Element]() var elements = [Element]() for element in self { if set.contains(element) { if !trimmed.isEmpty { elements.append(element) } } else { elements.forEach { trimmed.append($0) } elements = [] trimmed.append(element) } } return trimmed } }
mit
0ce734f337115fb667a183d817557164
27.142857
71
0.481218
5.26738
false
false
false
false
wftllc/hahastream
HahaStreamUnitTests/HahaProviderTest.swift
1
5331
import XCTest import Foundation import UIKit import Moya @testable import Haha_Stream /* To make tests work, you MUST have a Config.plist included in the test bundle which has the key "HahaProviderApiKey" and a value of your api key. */ class HahaProviderTest: XCTestCase { let ApiKeyPath = "HahaProviderApiKey" var provider: HahaProvider!; override func setUp() { super.setUp() self.continueAfterFailure = false; let apiKey = loadApiKey() XCTAssertNotNil(apiKey) self.provider = HahaProvider(apiKey: apiKey); XCTAssertNotNil(provider) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testLoggedIn() { let exp = expectation(description: "wait") self.provider.getDeviceActivationStatus(success: { status in XCTAssert(status.isActivated) exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp.fulfill() }); waitForExpectations(timeout: 25, handler: nil) } func testNotLoggedIn() { let exp = expectation(description: "wait") self.provider.apiKey = nil self.provider.getDeviceActivationStatus(success: { status in XCTAssertFalse(status.isActivated) exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp.fulfill() }); waitForExpectations(timeout: 25, handler: nil) } func xtestVCSScraping() { let exp = expectation(description: "wait") var vcses:[VCS] = [] self.provider.getVCSChannels(success: { (result) in vcses = result exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp.fulfill() }); XCTAssertGreaterThan(vcses.count, 1) waitForExpectations(timeout: 25, handler: nil) } //channels are under sports right now func xtestChannels() { let exp = expectation(description: "wait") var channels:[Channel] = [] provider.getChannels(success: { (channelsRes) in channels = channelsRes; exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp.fulfill() }) waitForExpectations(timeout: 25, handler: nil) print(channels) XCTAssertGreaterThan(channels.count, 0) for channel in channels { let exp = expectation(description: "wait") provider.getStream(channel: channel, success: { (stream) in exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp.fulfill() }) waitForExpectations(timeout: 25, handler: nil) } } func testContentList() { let exp = expectation(description: "wait") var items:[ContentItem] = [] provider.getContentList(success: { (results) in items = results; exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp.fulfill() }) waitForExpectations(timeout: 25, handler: nil) print(items) var foundGame = false var foundChannel = false let exp2 = expectation(description: "channel stream") for item in items { if let channel = item.channel { foundChannel = true //nba tv seems to be always live if channel.title == "NBA TV" { provider.getStream(channel: channel, success: { (stream) in XCTAssertNotNil(stream) exp2.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") exp2.fulfill() }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") exp2.fulfill() }) } } else if let _ = item.game { foundGame = true } } XCTAssert(foundGame) XCTAssert(foundChannel) waitForExpectations(timeout: 25, handler: nil) } func testSportsGamesStreamFetchingFlow() { var exp = expectation(description: "wait") var sports: [Sport] = [] provider.getSports(success: { (sportsRes) in sports = sportsRes; exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") }) waitForExpectations(timeout: 25, handler: nil) print(sports) XCTAssertGreaterThan(sports.count, 0) for sport in sports { //just make sure the failure callbacks don't get hit. exp = expectation(description: "fetch \(sport.name) games" ) print(sport) provider.getGames(sport: sport, date: nil, success: { (games) in print(games) exp.fulfill() }, apiError: { (error) in XCTFail("apiError: \(error)") }, networkFailure: { (error) in XCTFail("networkFailure: \(error)") }) waitForExpectations(timeout: 25, handler: nil) } } func loadApiKey() -> String? { let bundle = Bundle(for: HahaProviderTest.self); guard let path = bundle.path(forResource: "Config", ofType: "plist") else { return nil } let dict = NSDictionary(contentsOfFile: path); return dict?.value(forKeyPath: ApiKeyPath) as? String; } }
mit
698899e1a1ef21acd430d24b7f7b99e4
26.060914
144
0.669105
3.432711
false
true
false
false
liutongchao/LCRefresh
Source/LCRefreshHeader.swift
1
4224
// // LCRefreshHeader.swift // LCRefresh // // Created by 刘通超 on 16/8/2. // Copyright © 2016年 West. All rights reserved. // import UIKit public final class LCRefreshHeader: LCBaseRefreshHeader { public let image = UIImageView() public let contenLab = UILabel() public let activity = UIActivityIndicatorView() required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public init(frame: CGRect) { super.init(frame: frame) configView() } public init(refreshBlock:@escaping (()->Void)) { super.init(frame: CGRect(x: LCRefresh.Const.Header.X, y: LCRefresh.Const.Header.Y, width: LCRefresh.Const.Common.screenWidth, height: LCRefresh.Const.Header.height)) self.backgroundColor = UIColor.clear self.refreshBlock = refreshBlock configView() } public init(width:CGFloat ,refreshBlock:@escaping (()->Void)) { super.init(frame: CGRect(x: LCRefresh.Const.Header.X, y: LCRefresh.Const.Header.Y, width:width , height: LCRefresh.Const.Header.height)) self.backgroundColor = UIColor.clear self.refreshBlock = refreshBlock configView() } func configView() { addSubview(contenLab) addSubview(image) addSubview(activity) contenLab.frame = self.bounds contenLab.textAlignment = .center contenLab.text = "下拉可以刷新" contenLab.font = UIFont.systemFont(ofSize: 14) image.frame = CGRect.init(x: 0, y: 0, width: 18, height: 30) image.center = CGPoint.init(x: 40, y: LCRefresh.Const.Header.height/2) let bundleImage = UIImage.init(named: "LCRefresh.bundle/lc_refresh_down.png") if bundleImage != nil { image.image = bundleImage }else{ image.image = UIImage.init(named: "Frameworks/LCRefresh.framework/LCRefresh.bundle/lc_refresh_down.png") } activity.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) activity.activityIndicatorViewStyle = .gray activity.center = CGPoint.init(x: 40, y: LCRefresh.Const.Header.height/2) } public override func setRefreshStatus(status: LCRefreshHeaderStatus) { refreshStatus = status switch status { case .normal: setNomalStatus() break case .waitRefresh: setWaitRefreshStatus() break case .refreshing: setRefreshingStatus() break case .end: setEndStatus() break } } } extension LCRefreshHeader{ /** 各种状态切换 */ func setNomalStatus() { if activity.isAnimating { activity.stopAnimating() } activity.isHidden = true contenLab.text = "下拉可以刷新" image.isHidden = false UIView.animate(withDuration: 0.3, animations: { self.image.transform = CGAffineTransform.identity }) } func setWaitRefreshStatus() { if activity.isAnimating { activity.stopAnimating() } activity.isHidden = true contenLab.text = "松开立即刷新" image.isHidden = false UIView.animate(withDuration: 0.3, animations: { self.image.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) }) } func setRefreshingStatus() { activity.isHidden = false activity.startAnimating() contenLab.text = "正在刷新数据..." image.isHidden = true self.image.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) } func setEndStatus() { activity.isHidden = false contenLab.text = "完成刷新" image.isHidden = true } func animatIdentity() { UIView.animate(withDuration: 0.3, animations: { self.image.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) }) } }
mit
8b6e537b44b0844d7143a5aa5564883f
26.832215
173
0.588618
4.478402
false
false
false
false
frootloops/swift
stdlib/public/core/Algorithm.swift
2
5208
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Returns the lesser of two comparable values. /// /// - Parameters: /// - x: A value to compare. /// - y: Another value to compare. /// - Returns: The lesser of `x` and `y`. If `x` is equal to `y`, returns `x`. @_inlineable public func min<T : Comparable>(_ x: T, _ y: T) -> T { // In case `x == y` we pick `x`. // This preserves any pre-existing order in case `T` has identity, // which is important for e.g. the stability of sorting algorithms. // `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`. return y < x ? y : x } /// Returns the least argument passed. /// /// - Parameters: /// - x: A value to compare. /// - y: Another value to compare. /// - z: A third value to compare. /// - rest: Zero or more additional values. /// - Returns: The least of all the arguments. If there are multiple equal /// least arguments, the result is the first one. @_inlineable public func min<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T { var minValue = min(min(x, y), z) // In case `value == minValue`, we pick `minValue`. See min(_:_:). for value in rest where value < minValue { minValue = value } return minValue } /// Returns the greater of two comparable values. /// /// - Parameters: /// - x: A value to compare. /// - y: Another value to compare. /// - Returns: The greater of `x` and `y`. If `x` is equal to `y`, returns `y`. @_inlineable public func max<T : Comparable>(_ x: T, _ y: T) -> T { // In case `x == y`, we pick `y`. See min(_:_:). return y >= x ? y : x } /// Returns the greatest argument passed. /// /// - Parameters: /// - x: A value to compare. /// - y: Another value to compare. /// - z: A third value to compare. /// - rest: Zero or more additional values. /// - Returns: The greatest of all the arguments. If there are multiple equal /// greatest arguments, the result is the last one. @_inlineable public func max<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T { var maxValue = max(max(x, y), z) // In case `value == maxValue`, we pick `value`. See min(_:_:). for value in rest where value >= maxValue { maxValue = value } return maxValue } /// The iterator for `EnumeratedSequence`. /// /// An instance of `EnumeratedIterator` wraps a base iterator and yields /// successive `Int` values, starting at zero, along with the elements of the /// underlying base iterator. The following example enumerates the elements of /// an array: /// /// var iterator = ["foo", "bar"].enumerated().makeIterator() /// iterator.next() // (0, "foo") /// iterator.next() // (1, "bar") /// iterator.next() // nil /// /// To create an instance of `EnumeratedIterator`, call /// `enumerated().makeIterator()` on a sequence or collection. @_fixed_layout public struct EnumeratedIterator<Base: IteratorProtocol> { @_versioned internal var _base: Base @_versioned internal var _count: Int /// Construct from a `Base` iterator. @_inlineable @_versioned internal init(_base: Base) { self._base = _base self._count = 0 } } extension EnumeratedIterator: IteratorProtocol, Sequence { /// The type of element returned by `next()`. public typealias Element = (offset: Int, element: Base.Element) /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @_inlineable public mutating func next() -> Element? { guard let b = _base.next() else { return nil } let result = (offset: _count, element: b) _count += 1 return result } } /// An enumeration of the elements of a sequence or collection. /// /// `EnumeratedSequence` is a sequence of pairs (*n*, *x*), where *n*s are /// consecutive `Int` values starting at zero, and *x*s are the elements of a /// base sequence. /// /// To create an instance of `EnumeratedSequence`, call `enumerated()` on a /// sequence or collection. The following example enumerates the elements of /// an array. /// /// var s = ["foo", "bar"].enumerated() /// for (n, x) in s { /// print("\(n): \(x)") /// } /// // Prints "0: foo" /// // Prints "1: bar" @_fixed_layout public struct EnumeratedSequence<Base: Sequence> { @_versioned internal var _base: Base /// Construct from a `Base` sequence. @_inlineable @_versioned internal init(_base: Base) { self._base = _base } } extension EnumeratedSequence: Sequence { /// Returns an iterator over the elements of this sequence. @_inlineable public func makeIterator() -> EnumeratedIterator<Base.Iterator> { return EnumeratedIterator(_base: _base.makeIterator()) } }
apache-2.0
0e0ae977e0e91d8cd080f79416b018ec
31.347826
80
0.615399
3.760289
false
false
false
false
manuelCarlos/AutoLayout-park
timelineLayout/timelineLayout/TableViewCell.swift
1
6177
// // TableViewCell.swift // TableViewController // // Created by Manuel Lopes on 05/04/16. import UIKit class TableViewCell: UITableViewCell { static var reuseIdentifier: String { return "\(self)"} let body = UILabel() let name = UILabel() let time = UILabel() let avatar = UIImageView() let at = UILabel() let buttonStack = UIStackView() //MARK:- Closure to build buttons private var createButtonWithImage: (String) -> UIButton = { name in let button = RippleButton(type: .custom) button.setImage(UIImage(named: name), for: UIControlState()) button.rippleColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) button.rippleBackgroundColor = .clear // button.shadowRippleEnable = true button.rippleOverBounds = true button.widthAnchor.constraint(equalTo: button.heightAnchor).isActive = true return button } //MARK:- Initializers override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } //MARK:- Apply Constraints override func updateConstraints() { // Layout Guides let margins = contentView.layoutMarginsGuide applyNameLabelConstraints(on: margins) applyTimeLabelConstraints(on: margins) applyProfilePicConstrainst(on: margins) applyBodyLabelConstraints(on: margins) applyButtonsConstraints(on: margins) super.updateConstraints() } //MARK: Reuse // if this is not overriden then not ALL the cells will get the updated font size! override func prepareForReuse() { super.prepareForReuse() name.font = UIFont.preferredFont(forTextStyle: .headline) time.font = UIFont.preferredFont(forTextStyle: .subheadline) body.font = UIFont.preferredFont(forTextStyle: .body) } //MARK:- Private Convenience Methods private func applyButtonsConstraints(on margins: UILayoutGuide) { buttonStack.topAnchor.constraint(equalTo: body.bottomAnchor, constant: 10).isActive = true buttonStack.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true buttonStack.heightAnchor.constraint(equalToConstant: 20).isActive = true buttonStack.centerXAnchor.constraint(equalTo: body.centerXAnchor).isActive = true } private func applyNameLabelConstraints(on margins: UILayoutGuide) { name.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 10).isActive = true name.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true } private func applyTimeLabelConstraints(on margins: UILayoutGuide) { time.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true time.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true } private func applyBodyLabelConstraints(on margins: UILayoutGuide) { body.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 10).isActive = true body.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true body.topAnchor.constraint(equalTo: name.bottomAnchor, constant: 10.0).isActive = true } private func applyProfilePicConstrainst(on margins: UILayoutGuide) { avatar.leadingAnchor.constraint(equalTo: margins.leadingAnchor,constant: -3).isActive = true avatar.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true avatar.heightAnchor.constraint(equalTo: avatar.widthAnchor).isActive = true avatar.heightAnchor.constraint(equalToConstant: 50).isActive = true } //MARK:x Config the cell, labels, image and buttons private func setupPic() { avatar.translatesAutoresizingMaskIntoConstraints = false avatar.contentMode = .scaleAspectFit contentView.addSubview(avatar) } private func setupButtons() { let reply = createButtonWithImage("Arrow") let box = createButtonWithImage("Box") let cloud = createButtonWithImage("Cloud") let glasses = createButtonWithImage("Glasses") buttonStack.insertArrangedSubview(reply, at: 0) buttonStack.insertArrangedSubview(box, at: 1) buttonStack.insertArrangedSubview(cloud, at: 2) buttonStack.insertArrangedSubview(glasses, at: 3) buttonStack.axis = .horizontal buttonStack.distribution = .fillEqually buttonStack.spacing = UIScreen.main.bounds.size.width / 6.5 buttonStack.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(buttonStack) } private func setupLabels() { name.numberOfLines = 0 name.textAlignment = .center name.textColor = .darkGray name.font = UIFont.preferredFont(forTextStyle: .headline) name.translatesAutoresizingMaskIntoConstraints = false time.numberOfLines = 0 time.textAlignment = .center time.textColor = .darkGray time.font = UIFont.preferredFont(forTextStyle: .subheadline) time.translatesAutoresizingMaskIntoConstraints = false body.numberOfLines = 0 // set to 0 to force to display untruncated text. body.textAlignment = .natural body.textColor = .darkGray body.font = UIFont.preferredFont(forTextStyle: .body) body.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(name) contentView.addSubview(time) contentView.addSubview(body) } private func setup() { // set the separator line to full width of cell preservesSuperviewLayoutMargins = false separatorInset = .zero layoutMargins = .zero setupLabels() setupPic() setupButtons() setNeedsUpdateConstraints() } }// ENd
mit
007dd416d5300475c5e9256fbd026475
37.12963
112
0.67719
5.186398
false
false
false
false
Bartlebys/Bartleby
Bartleby.xOS/core/extensions/ManagedModel+RelationsResolution.swift
1
5523
// // ManagedModel+RelationsResolution.swift // BartlebyKit // // Created by Benoit Pereira da silva on 16/12/2016. // // import Foundation extension ManagedModel:RelationsResolution{ /// Resolve the Related Objects /// /// - Parameters: /// - relationship: the searched relationship /// - Returns: return the related Objects open func relations<T:Relational>(_ relationship:Relationship)->[T]{ var related=[T]() for object in self.getContractedRelations(relationship){ if let candidate = try? Bartleby.registredObjectByUID(object) as ManagedModel{ if let casted = candidate as? T{ related.append(casted) } } } return related } /// Resolve the filtered Related Objects /// /// - Parameters: /// - relationship: the searched relationship /// - included: the filtering closure /// - Returns: return the related Objects open func filteredRelations<T:Relational>(_ relationship:Relationship,included:(T)->(Bool))->[T]{ var related=[T]() for object in self.getContractedRelations(relationship){ if let candidate = try? Bartleby.registredObjectByUID(object) as ManagedModel{ if let casted = candidate as? T{ if included(casted) == true { related.append(casted) } } } } return related } /// Resolve the filtered Related Objects /// /// - Parameters: /// - relationship: the searched relationship /// - included: the filtering closure /// - Returns: return the related Objects as values and the UID as keys open func hashedFilteredRelations<T:Relational>(_ relationship:Relationship,included:(T)->(Bool))->[UID:T]{ var related=[String:T]() for object in self.getContractedRelations(relationship){ if let candidate = try? Bartleby.registredObjectByUID(object) as ManagedModel{ if let casted = candidate as? T{ if included(casted) == true { related[casted.UID]=casted } } } } return related } /// Resolve the Related Objects /// /// - Parameters: /// - relationship: the searched relationships /// - Returns: return the related Objects open func relationsInSet<T:Relational>(_ relationships:Set<Relationship>)->[T]{ var related=[T]() var objectsUID=[String]() for relationShip in relationships{ objectsUID.append(contentsOf:self.getContractedRelations(relationShip)) } for objectUID in objectsUID{ if let candidate = try? Bartleby.registredObjectByUID(objectUID) as ManagedModel{ if let casted = candidate as? T{ related.append(casted) } } } return related } /// Resolve the filtered Related Objects /// /// - Parameters: /// - relationship: the searched relationships /// - included: the filtering closure /// - Returns: return the related Objects open func filteredRelationsInSet<T:Relational>(_ relationships:Set<Relationship>,included:(T)->(Bool))->[T]{ var related=[T]() var objectsUID=[String]() for relationShip in relationships{ objectsUID.append(contentsOf:self.getContractedRelations(relationShip)) } for objectUID in objectsUID{ if let candidate = try? Bartleby.registredObjectByUID(objectUID) as ManagedModel{ if let casted = candidate as? T{ if included(casted) == true { related.append(casted) } } } } return related } /// Resolve the Related Object and returns the first one /// /// - Parameters: /// - relationship: the searched relationships open func firstRelation<T:Relational>(_ relationship:Relationship)->T?{ // Internal relations. let objectsUID=self.getContractedRelations(relationship) if objectsUID.count>0{ for objectUID in objectsUID{ if let candidate = try? Bartleby.registredObjectByUID(objectUID) as ManagedModel{ if let casted = candidate as? T{ return casted } } } } return nil } /// Resolve the Related Object and returns the first one /// /// - Parameters: /// - relationship: the searched relationships /// - included: the filtering closure // - Returns: return the related Object open func filteredFirstRelation<T:Relational>(_ relationship:Relationship,included:(T)->(Bool))->T?{ // Internal relations. let objectsUID=self.getContractedRelations(relationship) if objectsUID.count>0{ for objectUID in objectsUID{ if let candidate = try? Bartleby.registredObjectByUID(objectUID) as ManagedModel{ if let castedCandidate = candidate as? T { if included(castedCandidate) == true { return castedCandidate } } } } } return nil } }
apache-2.0
319a5f3ba93543a036738a17d182f6d4
32.472727
112
0.567626
5.099723
false
false
false
false
JGiola/swift-corelibs-foundation
Foundation/NSRange.swift
1
13712
// 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 // #if DEPLOYMENT_RUNTIME_SWIFT import CoreFoundation public struct _NSRange { public var location: Int public var length: Int public init() { location = 0 length = 0 } public init(location: Int, length: Int) { self.location = location self.length = length } } public typealias NSRange = _NSRange public typealias NSRangePointer = UnsafeMutablePointer<NSRange> public func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange { return NSRange(location: loc, length: len) } public func NSMaxRange(_ range: NSRange) -> Int { return range.location + range.length } public func NSLocationInRange(_ loc: Int, _ range: NSRange) -> Bool { return !(loc < range.location) && (loc - range.location) < range.length } public func NSEqualRanges(_ range1: NSRange, _ range2: NSRange) -> Bool { return range1.location == range2.location && range1.length == range2.length } public func NSUnionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let maxend: Int if max1 > max2 { maxend = max1 } else { maxend = max2 } let minloc: Int if range1.location < range2.location { minloc = range1.location } else { minloc = range2.location } return NSRange(location: minloc, length: maxend - minloc) } public func NSIntersectionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let minend: Int if max1 < max2 { minend = max1 } else { minend = max2 } if range2.location <= range1.location && range1.location < max2 { return NSRange(location: range1.location, length: minend - range1.location) } else if range1.location <= range2.location && range2.location < max1 { return NSRange(location: range2.location, length: minend - range2.location) } return NSRange(location: 0, length: 0) } public func NSStringFromRange(_ range: NSRange) -> String { return "{\(range.location), \(range.length)}" } public func NSRangeFromString(_ aString: String) -> NSRange { let emptyRange = NSRange(location: 0, length: 0) if aString.isEmpty { // fail early if the string is empty return emptyRange } let scanner = Scanner(string: aString) let digitSet = CharacterSet.decimalDigits let _ = scanner.scanUpToCharactersFromSet(digitSet) if scanner.isAtEnd { // fail early if there are no decimal digits return emptyRange } guard let location = scanner.scanInt() else { return emptyRange } let partialRange = NSRange(location: location, length: 0) if scanner.isAtEnd { // return early if there are no more characters after the first int in the string return partialRange } let _ = scanner.scanUpToCharactersFromSet(digitSet) if scanner.isAtEnd { // return early if there are no integer characters after the first int in the string return partialRange } guard let length = scanner.scanInt() else { return partialRange } return NSRange(location: location, length: length) } #else @_exported import Foundation // Clang module #endif extension NSRange : Hashable { public var hashValue: Int { #if arch(i386) || arch(arm) return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 16))) #elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64le) return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 32))) #endif } public static func==(_ lhs: NSRange, _ rhs: NSRange) -> Bool { return lhs.location == rhs.location && lhs.length == rhs.length } } extension NSRange : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "{\(location), \(length)}" } public var debugDescription: String { guard location != NSNotFound else { return "{NSNotFound, \(length)}" } return "{\(location), \(length)}" } } extension NSRange { public init?(_ string: String) { var savedLocation = 0 if string.isEmpty { // fail early if the string is empty return nil } let scanner = Scanner(string: string) let digitSet = CharacterSet.decimalDigits let _ = scanner.scanUpToCharacters(from: digitSet, into: nil) if scanner.isAtEnd { // fail early if there are no decimal digits return nil } var location = 0 savedLocation = scanner.scanLocation guard scanner.scanInt(&location) else { return nil } if scanner.isAtEnd { // return early if there are no more characters after the first int in the string return nil } if scanner.scanString(".", into: nil) { scanner.scanLocation = savedLocation var double = 0.0 guard scanner.scanDouble(&double) else { return nil } guard let integral = Int(exactly: double) else { return nil } location = integral } let _ = scanner.scanUpToCharacters(from: digitSet, into: nil) if scanner.isAtEnd { // return early if there are no integer characters after the first int in the string return nil } var length = 0 savedLocation = scanner.scanLocation guard scanner.scanInt(&length) else { return nil } if !scanner.isAtEnd { if scanner.scanString(".", into: nil) { scanner.scanLocation = savedLocation var double = 0.0 guard scanner.scanDouble(&double) else { return nil } guard let integral = Int(exactly: double) else { return nil } length = integral } } self.location = location self.length = length } } extension NSRange { public var lowerBound: Int { return location } public var upperBound: Int { return location + length } public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) } public mutating func formUnion(_ other: NSRange) { self = union(other) } public func union(_ other: NSRange) -> NSRange { let max1 = location + length let max2 = other.location + other.length let maxend = (max1 < max2) ? max2 : max1 let minloc = location < other.location ? location : other.location return NSRange(location: minloc, length: maxend - minloc) } public func intersection(_ other: NSRange) -> NSRange? { let max1 = location + length let max2 = other.location + other.length let minend = (max1 < max2) ? max1 : max2 if other.location <= location && location < max2 { return NSRange(location: location, length: minend - location) } else if location <= other.location && other.location < max1 { return NSRange(location: other.location, length: minend - other.location); } return nil } } //===----------------------------------------------------------------------===// // Ranges //===----------------------------------------------------------------------===// extension NSRange { public init<R: RangeExpression>(_ region: R) where R.Bound: FixedWidthInteger { let r = region.relative(to: 0..<R.Bound.max) location = numericCast(r.lowerBound) length = numericCast(r.count) } public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S) where R.Bound == S.Index, S.Index == String.Index { let r = region.relative(to: target) self = NSRange( location: r.lowerBound.encodedOffset - target.startIndex.encodedOffset, length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset ) } @available(swift, deprecated: 4, renamed: "Range.init(_:)") public func toRange() -> Range<Int>? { if location == NSNotFound { return nil } return location..<(location+length) } } extension Range where Bound: BinaryInteger { public init?(_ range: NSRange) { guard range.location != NSNotFound else { return nil } self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound))) } } // This additional overload will mean Range.init(_:) defaults to Range<Int> when // no additional type context is provided: extension Range where Bound == Int { public init?(_ range: NSRange) { guard range.location != NSNotFound else { return nil } self.init(uncheckedBounds: (range.lowerBound, range.upperBound)) } } extension Range where Bound == String.Index { public init?(_ range: NSRange, in string: String) { let u = string.utf16 guard range.location != NSNotFound, let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex), let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex), let lowerBound = String.Index(start, within: string), let upperBound = String.Index(end, within: string) else { return nil } self = lowerBound..<upperBound } } extension NSRange : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["location": location, "length": length]) } } extension NSRange : CustomPlaygroundDisplayConvertible { public var playgroundDescription: Any { return (Int64(location), Int64(length)) } } extension NSRange : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() let location = try container.decode(Int.self) let length = try container.decode(Int.self) self.init(location: location, length: length) } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(self.location) try container.encode(self.length) } } #if DEPLOYMENT_RUNTIME_SWIFT extension NSRange { internal init(_ range: CFRange) { location = range.location == kCFNotFound ? NSNotFound : range.location length = range.length } } extension CFRange { internal init(_ range: NSRange) { let _location = range.location == NSNotFound ? kCFNotFound : range.location self.init(location: _location, length: range.length) } } extension NSRange { public init(_ x: Range<Int>) { location = x.lowerBound length = x.count } } extension NSRange: NSSpecialValueCoding { init(bytes: UnsafeRawPointer) { self.location = bytes.load(as: Int.self) self.length = bytes.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self) } init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if let location = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.location") { self.location = location.intValue } else { self.location = 0 } if let length = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.length") { self.length = length.intValue } else { self.length = 0 } } func encodeWithCoder(_ aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(NSNumber(value: self.location), forKey: "NS.rangeval.location") aCoder.encode(NSNumber(value: self.length), forKey: "NS.rangeval.length") } static func objCType() -> String { #if arch(i386) || arch(arm) return "{_NSRange=II}" #elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) return "{_NSRange=QQ}" #else NSUnimplemented() #endif } func getValue(_ value: UnsafeMutableRawPointer) { value.initializeMemory(as: NSRange.self, repeating: self, count: 1) } func isEqual(_ aValue: Any) -> Bool { if let other = aValue as? NSRange { return other.location == self.location && other.length == self.length } else { return false } } var hash: Int { return hashValue } } extension NSValue { public convenience init(range: NSRange) { self.init() self._concreteValue = NSSpecialValue(range) } public var rangeValue: NSRange { let specialValue = self._concreteValue as! NSSpecialValue return specialValue._value as! NSRange } } #endif
apache-2.0
fa74f85d4bc4ba8c42d5f68c77ccfce2
31.416076
110
0.606987
4.500164
false
false
false
false
iAugux/Augus
Extensions/UIButton+Extension.swift
1
840
// // UIButton+Extension.swift // // Created by Augus on 2/6/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit extension UIButton { override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { let minimalWidthAndHeight: CGFloat = 36 let buttonSize = frame.size let widthToAdd = (minimalWidthAndHeight - buttonSize.width > 0) ? minimalWidthAndHeight - buttonSize.width : 0 let heightToAdd = (minimalWidthAndHeight - buttonSize.height > 0) ? minimalWidthAndHeight - buttonSize.height : 0 let largerFrame = CGRect(x: 0-(widthToAdd / 2), y: 0-(heightToAdd / 2), width: buttonSize.width + widthToAdd, height: buttonSize.height + heightToAdd) return CGRectContainsPoint(largerFrame, point) ? self : nil } }
mit
bfc02f2268d44d2549405f4b99b0d4ff
31.307692
158
0.667461
4.302564
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/Tree/106_ConstructBinaryTreeFromInorderAndPostorderTraversal.swift
1
2538
// // 106_ConstructBinaryTreeFromInorderAndPostorderTraversal.swift // HRSwift // // Created by yansong li on 2016-08-06. // Copyright © 2016 yansong li. All rights reserved. // import Foundation /** Title:106 Construct Binary Tree From Inorder and Postorder Traversal URL: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ Space: O(n) Time: O(n) */ class BuildTreeInorderPostOrder_Solution { func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? { guard inorder.count > 0 && postorder.count > 0 && inorder.count == postorder.count else { return nil } return treeBuildHelper(inorder, inorderStart: 0, inorderEnd: inorder.count - 1, postorder: postorder, postStart: 0, postEnd: postorder.count - 1) } fileprivate func treeBuildHelper(_ inorder: [Int], inorderStart: Int, inorderEnd: Int, postorder: [Int], postStart: Int, postEnd: Int) -> TreeNode? { guard inorderStart <= inorderEnd && postStart <= postEnd else { return nil } var mid: Int = 0 let rootVal = postorder[postEnd] let rootNode = TreeNode(rootVal) for i in inorderStart...inorderEnd { if inorder[i] == rootVal { mid = i break } } // Note: when calculate postEnd we use the following formula: // X - postStart : is how many elements between those two index // mid - inorderStart = left tree element counts // X - postStart + 1(the first element) == mid - inorderStart rootNode.left = treeBuildHelper(inorder, inorderStart: inorderStart, inorderEnd: mid - 1, postorder: postorder, postStart: postStart, postEnd: postStart + mid - inorderStart - 1) rootNode.right = treeBuildHelper(inorder, inorderStart: mid + 1, inorderEnd: inorderEnd, postorder: postorder, postStart: postStart + mid - inorderStart, postEnd: postEnd - 1) return rootNode } }
mit
dbebb0f54f7ad169f7db4a90fcf9a212
36.865672
95
0.516752
4.612727
false
false
false
false
lramirezsuarez/IntegratingMapsiOS
MapsIntegration/MapsIntegration/ViewController.swift
1
1989
// // ViewController.swift // MapsIntegration // // Created by Luis Ramirez on 7/20/17. // Copyright © 2017 Lucho. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! override func viewDidLoad() { super.viewDidLoad() let latitude : CLLocationDegrees = 6.268 let longitude : CLLocationDegrees = -75.666 let latDelta : CLLocationDegrees = 2 let lonDelta : CLLocationDegrees = 2 let span : MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta) let location : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region : MKCoordinateRegion = MKCoordinateRegion(center: location, span: span) map.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.title = "Holi lo mejor" annotation.subtitle = "Esta es un annotation" annotation.coordinate = location map.addAnnotation(annotation) let uilongPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:))) //The : sends the information to the function uilongPress.minimumPressDuration = 2 map.addGestureRecognizer(uilongPress) } func longpress(gestureRecognizer: UIGestureRecognizer) { let touchPoint = gestureRecognizer.location(in: self.map) let coordinate = map.convert(touchPoint, toCoordinateFrom: self.map) let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = "New place" annotation.subtitle = "You did a long press here" map.addAnnotation(annotation) } }
mit
2bffd87e31d50dbde2874973abca9a88
29.584615
179
0.644366
5.476584
false
false
false
false
thebnich/firefox-ios
Utils/KeychainCache.swift
29
2224
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import XCGLogger private let log = Logger.keychainLogger public protocol JSONLiteralConvertible { func asJSON() -> JSON } public class KeychainCache<T: JSONLiteralConvertible> { public let branch: String public let label: String public var value: T? { didSet { checkpoint() } } public init(branch: String, label: String, value: T?) { self.branch = branch self.label = label self.value = value } public class func fromBranch(branch: String, withLabel label: String?, withDefault defaultValue: T? = nil, factory: JSON -> T?) -> KeychainCache<T> { if let l = label { if let s = KeychainWrapper.stringForKey("\(branch).\(l)") { if let t = factory(JSON.parse(s)) { log.info("Read \(branch) from Keychain with label \(branch).\(l).") return KeychainCache(branch: branch, label: l, value: t) } else { log.warning("Found \(branch) in Keychain with label \(branch).\(l), but could not parse it.") } } else { log.warning("Did not find \(branch) in Keychain with label \(branch).\(l).") } } else { log.warning("Did not find \(branch) label in Keychain.") } // Fall through to missing. log.warning("Failed to read \(branch) from Keychain.") let label = label ?? Bytes.generateGUID() return KeychainCache(branch: branch, label: label, value: defaultValue) } public func checkpoint() { log.info("Storing \(self.branch) in Keychain with label \(self.branch).\(self.label).") // TODO: PII logging. if let value = value { let jsonString = value.asJSON().toString(false) KeychainWrapper.setString(jsonString, forKey: "\(branch).\(label)") } else { KeychainWrapper.removeObjectForKey("\(branch).\(label)") } } }
mpl-2.0
abcc0221a739963437ffc4ae7a157385
35.459016
153
0.583633
4.538776
false
false
false
false
xGoPox/Twelve
Twelve/SpriteNode/Number.swift
1
1766
// // Number.swift // Twelve // // Created by Clement Yerochewski on 1/28/17. // Copyright © 2017 Clement Yerochewski. All rights reserved. // import SpriteKit class NumberSpriteNode : SKSpriteNode { typealias GridPosition = (row: Int, column: Int) var gridPosition: GridPosition var value = 1 convenience init() { self.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } protocol Adjacent { // func isAdjacentWithNumber(_ number : NumberSpriteNode) throws } extension NumberSpriteNode : Adjacent { func adjacentNumber(on matrix:[[NumberSpriteNode]]) -> NumberSpriteNode? { var row = -1 var column = -1 while row < 2 { column = -1 while column < 2 { let rowTmp = self.gridPosition.row + row let columnTmp = self.gridPosition.column + column if rowTmp >= 0 && rowTmp < matrix[0].count && columnTmp >= 0 && columnTmp < matrix[0].count { if matrix[rowTmp][columnTmp].value == self.value.followingNumber() { return matrix[rowTmp][columnTmp] } } column += 1 } row += 1 } return nil } } extension Sequence where Iterator.Element == NumberSpriteNode { func possibility(on matrix:[[NumberSpriteNode]]) -> NumberSpriteNode? { return self.first { $0.adjacentNumber(on: matrix) != nil } } } func ==(lhs: NumberSpriteNode, rhs: NumberSpriteNode) -> Bool { return lhs.gridPosition.column == rhs.gridPosition.column && lhs.gridPosition.row == rhs.gridPosition.row }
mit
cb7bc5d23e9cae77e8a5fd118b2af271
24.214286
109
0.580737
4.304878
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observables/Implementations/Zip.swift
60
3512
// // Zip.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation protocol ZipSinkProtocol : class { func next(index: Int) func fail(error: ErrorType) func done(index: Int) } class ZipSink<O: ObserverType> : Sink<O>, ZipSinkProtocol { typealias Element = O.E let _arity: Int let _lock = NSRecursiveLock() // state private var _isDone: [Bool] init(arity: Int, observer: O) { _isDone = [Bool](count: arity, repeatedValue: false) _arity = arity super.init(observer: observer) } func getResult() throws -> Element { abstractMethod() } func hasElements(index: Int) -> Bool { abstractMethod() } func next(index: Int) { var hasValueAll = true for i in 0 ..< _arity { if !hasElements(i) { hasValueAll = false break } } if hasValueAll { do { let result = try getResult() self.forwardOn(.Next(result)) } catch let e { self.forwardOn(.Error(e)) dispose() } } else { var allOthersDone = true let arity = _isDone.count for i in 0 ..< arity { if i != index && !_isDone[i] { allOthersDone = false break } } if allOthersDone { forwardOn(.Completed) self.dispose() } } } func fail(error: ErrorType) { forwardOn(.Error(error)) dispose() } func done(index: Int) { _isDone[index] = true var allDone = true for done in _isDone { if !done { allDone = false break } } if allDone { forwardOn(.Completed) dispose() } } } class ZipObserver<ElementType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias E = ElementType typealias ValueSetter = (ElementType) -> () private var _parent: ZipSinkProtocol? let _lock: NSRecursiveLock // state private let _index: Int private let _this: Disposable private let _setNextValue: ValueSetter init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: ValueSetter, this: Disposable) { _lock = lock _parent = parent _index = index _this = this _setNextValue = setNextValue } func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { if let _ = _parent { switch event { case .Next(_): break case .Error(_): _this.dispose() case .Completed: _this.dispose() } } if let parent = _parent { switch event { case .Next(let value): _setNextValue(value) parent.next(_index) case .Error(let error): parent.fail(error) case .Completed: parent.done(_index) } } } }
mit
c03ae63ee7678a903c2e66ede1ba2887
21.363057
115
0.468812
4.862881
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.ActivityInterval.swift
1
2055
import Foundation public extension AnyCharacteristic { static func activityInterval( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Activity Interval", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.activityInterval( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func activityInterval( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Activity Interval", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<UInt32> { GenericCharacteristic<UInt32>( type: .activityInterval, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
f1fd5741d893f64b1ead0a64864c0e1c
32.688525
67
0.580049
5.407895
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/CoreStore/Sources/DynamicSchema+Convenience.swift
2
15834
// // DynamicSchema+Convenience.swift // CoreStore // // Copyright © 2017 John Rommel Estropia // // 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 import Foundation // MARK: - DynamicSchema public extension DynamicSchema { /** Prints the `DynamicSchema` as their corresponding `CoreStoreObject` Swift declarations. This is useful for converting current `XcodeDataModelSchema`-based models into the new `CoreStoreSchema` framework. Additional adjustments may need to be done to the generated source code; for example: `Transformable` concrete types need to be provided, as well as `default` values. - Important: After transitioning to the new `CoreStoreSchema` framework, it is recommended to add the new schema as a new version that the existing versions' `XcodeDataModelSchema` can migrate to. It is discouraged to load existing SQLite files created with `XcodeDataModelSchema` directly into a `CoreStoreSchema`. - returns: a string that represents the source code for the `DynamicSchema` as their corresponding `CoreStoreObject` Swift declarations. */ public func printCoreStoreSchema() -> String { let model = self.rawModel() let entitiesByName = model.entitiesByName var output = "/// Generated by CoreStore on \(DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short))\n" var addedInverse: Set<String> = [] for (entityName, entity) in entitiesByName { let superName: String if let superEntity = entity.superentity { superName = superEntity.name! } else { superName = String(describing: CoreStoreObject.self) } output.append("class \(entityName): \(superName) {\n") defer { output.append("}\n") } let attributesByName = entity.attributesByName if !attributesByName.isEmpty { output.append(" \n") for (attributeName, attribute) in attributesByName { let containerType: String if attribute.attributeType == .transformableAttributeType { if attribute.isOptional { containerType = "Transformable.Optional" } else { containerType = "Transformable.Required" } } else { if attribute.isOptional { containerType = "Value.Optional" } else { containerType = "Value.Required" } } let valueType: Any.Type var defaultString = "" switch attribute.attributeType { case .integer16AttributeType: valueType = Int16.self if let defaultValue = (attribute.defaultValue as! Int16.ImportableNativeType?).flatMap(Int16.cs_fromImportableNativeType), defaultValue != Int16.cs_emptyValue() { defaultString = ", default: \(defaultValue)" } case .integer32AttributeType: valueType = Int32.self if let defaultValue = (attribute.defaultValue as! Int32.ImportableNativeType?).flatMap(Int32.cs_fromImportableNativeType), defaultValue != Int32.cs_emptyValue() { defaultString = ", default: \(defaultValue)" } case .integer64AttributeType: valueType = Int64.self if let defaultValue = (attribute.defaultValue as! Int64.ImportableNativeType?).flatMap(Int64.cs_fromImportableNativeType), defaultValue != Int64.cs_emptyValue() { defaultString = ", default: \(defaultValue)" } case .decimalAttributeType: valueType = NSDecimalNumber.self if let defaultValue = (attribute.defaultValue as! NSDecimalNumber.ImportableNativeType?).flatMap(NSDecimalNumber.cs_fromImportableNativeType), defaultValue != NSDecimalNumber.cs_emptyValue() { defaultString = ", default: NSDecimalNumber(string: \"\(defaultValue.description(withLocale: nil))\")" } case .doubleAttributeType: valueType = Double.self if let defaultValue = (attribute.defaultValue as! Double.ImportableNativeType?).flatMap(Double.cs_fromImportableNativeType), defaultValue != Double.cs_emptyValue() { defaultString = ", default: \(defaultValue)" } case .floatAttributeType: valueType = Float.self if let defaultValue = (attribute.defaultValue as! Float.ImportableNativeType?).flatMap(Float.cs_fromImportableNativeType), defaultValue != Float.cs_emptyValue() { defaultString = ", default: \(defaultValue)" } case .stringAttributeType: valueType = String.self if let defaultValue = (attribute.defaultValue as! String.ImportableNativeType?).flatMap(String.cs_fromImportableNativeType), defaultValue != String.cs_emptyValue() { // TODO: escape strings defaultString = ", default: \"\(defaultValue)\"" } case .booleanAttributeType: valueType = Bool.self if let defaultValue = (attribute.defaultValue as! Bool.ImportableNativeType?).flatMap(Bool.cs_fromImportableNativeType), defaultValue != Bool.cs_emptyValue() { defaultString = ", default: \(defaultValue ? "true" : "false")" } case .dateAttributeType: valueType = Date.self if let defaultValue = (attribute.defaultValue as! Date.ImportableNativeType?).flatMap(Date.cs_fromImportableNativeType) { defaultString = ", default: Date(timeIntervalSinceReferenceDate: \(defaultValue.timeIntervalSinceReferenceDate))" } case .binaryDataAttributeType: valueType = Data.self if let defaultValue = (attribute.defaultValue as! Data.ImportableNativeType?).flatMap(Data.cs_fromImportableNativeType), defaultValue != Data.cs_emptyValue() { let count = defaultValue.count let bytes = defaultValue.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in return (0 ..< (count / MemoryLayout<UInt8>.size)) .map({ "\("0x\(String(pointer[$0], radix: 16, uppercase: false))")" }) } defaultString = ", default: Data(bytes: [\(bytes.joined(separator: ", "))])" } case .transformableAttributeType: if let attributeValueClassName = attribute.attributeValueClassName { valueType = NSClassFromString(attributeValueClassName)! } else { valueType = (NSCoding & NSCopying).self } if let defaultValue = attribute.defaultValue { defaultString = ", default: /* \"\(defaultValue)\" */" } else if !attribute.isOptional { defaultString = ", default: /* required */" } default: fatalError("Unsupported attribute type: \(attribute.attributeType.rawValue)") } let indexedString = attribute.isIndexed ? ", isIndexed: true" : "" let transientString = attribute.isTransient ? ", isTransient: true" : "" // TODO: escape strings let versionHashModifierString = attribute.versionHashModifier .flatMap({ ", versionHashModifier: \"\($0)\"" }) ?? "" // TODO: escape strings let renamingIdentifierString = attribute.renamingIdentifier .flatMap({ ($0 == attributeName ? "" : ", renamingIdentifier: \"\($0)\"") as String }) ?? "" output.append(" let \(attributeName) = \(containerType)<\(String(describing: valueType))>(\"\(attributeName)\"\(indexedString)\(defaultString)\(transientString)\(versionHashModifierString)\(renamingIdentifierString))\n") } } let relationshipsByName = entity.relationshipsByName if !relationshipsByName.isEmpty { output.append(" \n") for (relationshipName, relationship) in relationshipsByName { let containerType: String var minCountString = "" var maxCountString = "" if relationship.isToMany { let minCount = relationship.minCount let maxCount = relationship.maxCount if relationship.isOrdered { containerType = "Relationship.ToManyOrdered" } else { containerType = "Relationship.ToManyUnordered" } if minCount > 0 { minCountString = ", minCount: \(minCount)" } if maxCount > 0 { maxCountString = ", maxCount: \(maxCount)" } } else { containerType = "Relationship.ToOne" } var inverseString = "" let relationshipQualifier = "\(entityName).\(relationshipName)" if !addedInverse.contains(relationshipQualifier), let inverseRelationship = relationship.inverseRelationship { inverseString = ", inverse: { $0.\(inverseRelationship.name) }" addedInverse.insert("\(relationship.destinationEntity!.name!).\(inverseRelationship.name)") } var deleteRuleString = "" if relationship.deleteRule != .nullifyDeleteRule { switch relationship.deleteRule { case .cascadeDeleteRule: deleteRuleString = ", deleteRule: .cascade" case .denyDeleteRule: deleteRuleString = ", deleteRule: .deny" case .nullifyDeleteRule: deleteRuleString = ", deleteRule: .nullify" default: fatalError("Unsupported delete rule \((relationship.deleteRule)) for relationship \"\(relationshipQualifier)\"") } } let versionHashModifierString = relationship.versionHashModifier .flatMap({ ", versionHashModifier: \"\($0)\"" }) ?? "" let renamingIdentifierString = relationship.renamingIdentifier .flatMap({ ($0 == relationshipName ? "" : ", renamingIdentifier: \"\($0)\"") as String }) ?? "" output.append(" let \(relationshipName) = \(containerType)<\(relationship.destinationEntity!.name!)>(\"\(relationshipName)\"\(inverseString)\(deleteRuleString)\(minCountString)\(maxCountString)\(versionHashModifierString)\(renamingIdentifierString))\n") } } } output.append("\n\n\n") output.append("CoreStoreSchema(\n") output.append(" modelVersion: \"\(self.modelVersion)\",\n") output.append(" entities: [\n") for (entityName, entity) in entitiesByName { var abstractString = "" if entity.isAbstract { abstractString = ", isAbstract: true" } var versionHashModifierString = "" if let versionHashModifier = entity.versionHashModifier { versionHashModifierString = ", versionHashModifier: \"\(versionHashModifier)\"" } output.append(" Entity<\(entityName)>(\"\(entityName)\"\(abstractString)\(versionHashModifierString)),\n") } output.append(" ],\n") output.append(" versionLock: \(VersionLock(entityVersionHashesByName: model.entityVersionHashesByName).description.components(separatedBy: "\n").joined(separator: "\n "))\n") output.append(")\n\n") return output } }
mit
3fc4c59dee8b939e1bf0032524a8f60a
52.489865
375
0.495926
6.547974
false
false
false
false
juliangrosshauser/ReactiveCocoa
ReactiveCocoa/Swift/Property.swift
113
7474
/// Represents a property that allows observation of its changes. public protocol PropertyType { typealias Value /// The current value of the property. var value: Value { get } /// A producer for Signals that will send the property's current value, /// followed by all changes over time. var producer: SignalProducer<Value, NoError> { get } } /// A read-only property that allows observation of its changes. public struct PropertyOf<T>: PropertyType { public typealias Value = T private let _value: () -> T private let _producer: () -> SignalProducer<T, NoError> public var value: T { return _value() } public var producer: SignalProducer<T, NoError> { return _producer() } /// Initializes a property as a read-only view of the given property. public init<P: PropertyType where P.Value == T>(_ property: P) { _value = { property.value } _producer = { property.producer } } /// Initializes a property that first takes on `initialValue`, then each value /// sent on a signal created by `producer`. public init(initialValue: T, producer: SignalProducer<T, NoError>) { let mutableProperty = MutableProperty(initialValue) mutableProperty <~ producer self.init(mutableProperty) } /// Initializes a property that first takes on `initialValue`, then each value /// sent on `signal`. public init(initialValue: T, signal: Signal<T, NoError>) { let mutableProperty = MutableProperty(initialValue) mutableProperty <~ signal self.init(mutableProperty) } } /// A property that never changes. public struct ConstantProperty<T>: PropertyType { public typealias Value = T public let value: T public let producer: SignalProducer<T, NoError> /// Initializes the property to have the given value. public init(_ value: T) { self.value = value self.producer = SignalProducer(value: value) } } /// Represents an observable property that can be mutated directly. /// /// Only classes can conform to this protocol, because instances must support /// weak references (and value types currently do not). public protocol MutablePropertyType: class, PropertyType { var value: Value { get set } } /// A mutable property of type T that allows observation of its changes. /// /// Instances of this class are thread-safe. public final class MutableProperty<T>: MutablePropertyType { public typealias Value = T private let observer: Signal<T, NoError>.Observer /// Need a recursive lock around `value` to allow recursive access to /// `value`. Note that recursive sets will still deadlock because the /// underlying producer prevents sending recursive events. private let lock = NSRecursiveLock() private var _value: T /// The current value of the property. /// /// Setting this to a new value will notify all observers of any Signals /// created from the `values` producer. public var value: T { get { lock.lock() let value = _value lock.unlock() return value } set { lock.lock() _value = newValue sendNext(observer, newValue) lock.unlock() } } /// A producer for Signals that will send the property's current value, /// followed by all changes over time, then complete when the property has /// deinitialized. public let producer: SignalProducer<T, NoError> /// Initializes the property with the given value to start. public init(_ initialValue: T) { lock.name = "org.reactivecocoa.ReactiveCocoa.MutableProperty" (producer, observer) = SignalProducer<T, NoError>.buffer(1) _value = initialValue sendNext(observer, initialValue) } deinit { sendCompleted(observer) } } extension MutableProperty: SinkType { public func put(value: T) { self.value = value } } /// Wraps a `dynamic` property, or one defined in Objective-C, using Key-Value /// Coding and Key-Value Observing. /// /// Use this class only as a last resort! `MutableProperty` is generally better /// unless KVC/KVO is required by the API you're using (for example, /// `NSOperation`). @objc public final class DynamicProperty: RACDynamicPropertySuperclass, MutablePropertyType { public typealias Value = AnyObject? private weak var object: NSObject? private let keyPath: String /// The current value of the property, as read and written using Key-Value /// Coding. public var value: AnyObject? { @objc(rac_value) get { return object?.valueForKeyPath(keyPath) } @objc(setRac_value:) set(newValue) { object?.setValue(newValue, forKeyPath: keyPath) } } /// A producer that will create a Key-Value Observer for the given object, /// send its initial value then all changes over time, and then complete /// when the observed object has deallocated. /// /// By definition, this only works if the object given to init() is /// KVO-compliant. Most UI controls are not! public var producer: SignalProducer<AnyObject?, NoError> { if let object = object { return object.rac_valuesForKeyPath(keyPath, observer: nil).toSignalProducer() // Errors aren't possible, but the compiler doesn't know that. |> catch { error in assert(false, "Received unexpected error from KVO signal: \(error)") return .empty } } else { return .empty } } /// Initializes a property that will observe and set the given key path of /// the given object. `object` must support weak references! public init(object: NSObject?, keyPath: String) { self.object = object self.keyPath = keyPath /// DynamicProperty stay alive as long as object is alive. /// This is made possible by strong reference cycles. super.init() object?.rac_willDeallocSignal()?.toSignalProducer().start(completed: { self }) } } infix operator <~ { associativity right // Binds tighter than assignment but looser than everything else, including `|>` precedence 93 } /// Binds a signal to a property, updating the property's value to the latest /// value sent by the signal. /// /// The binding will automatically terminate when the property is deinitialized, /// or when the signal sends a `Completed` event. public func <~ <P: MutablePropertyType>(property: P, signal: Signal<P.Value, NoError>) -> Disposable { let disposable = CompositeDisposable() disposable += property.producer.start(completed: { disposable.dispose() }) disposable += signal.observe(next: { [weak property] value in property?.value = value }, completed: { disposable.dispose() }) return disposable } /// Creates a signal from the given producer, which will be immediately bound to /// the given property, updating the property's value to the latest value sent /// by the signal. /// /// The binding will automatically terminate when the property is deinitialized, /// or when the created signal sends a `Completed` event. public func <~ <P: MutablePropertyType>(property: P, producer: SignalProducer<P.Value, NoError>) -> Disposable { var disposable: Disposable! producer.startWithSignal { signal, signalDisposable in property <~ signal disposable = signalDisposable property.producer.start(completed: { signalDisposable.dispose() }) } return disposable } /// Binds `destinationProperty` to the latest values of `sourceProperty`. /// /// The binding will automatically terminate when either property is /// deinitialized. public func <~ <Destination: MutablePropertyType, Source: PropertyType where Source.Value == Destination.Value>(destinationProperty: Destination, sourceProperty: Source) -> Disposable { return destinationProperty <~ sourceProperty.producer }
mit
8efb193391c6d0a202b5da4c77fbc7ae
29.506122
185
0.725983
4.064165
false
false
false
false
mparrish91/gifRecipes
test/UsersTest.swift
1
6688
// // UsersTest.swift // reddift // // Created by sonson on 2015/06/01. // Copyright (c) 2015年 sonson. All rights reserved. // import XCTest class UsersTest: SessionTestSpec { /** Test procedure 1. Get speficified user contents */ func testGetUserContents() { let username = "sonson_twit" for content in UserContent.cases { for sort in UserContentSortBy.cases { for within in TimeFilterWithin.cases { let _ = userContentsWith(username, content: content, sort: sort, timeFilterWithin: within) Thread.sleep(forTimeInterval: 1) break } break } } } /** Test procedure 1. Get speficified user profile */ func testGetUserProfile() { let username = "reddift_test_1" let msg = "Get \(username)'s user profile." var isSucceeded = false let documentOpenExpectation = self.expectation(description: msg) do { try self.session?.getUserProfile(username, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let json): print(json) isSucceeded = true } XCTAssert(isSucceeded, msg) documentOpenExpectation.fulfill() }) self.waitForExpectations(timeout: self.timeoutDuration, handler: nil) } catch { XCTFail((error as NSError).description) } } /** This test is always failed. Why...? Anyone knows the reasons? Test procedure 1. Get notifications. */ // func testGetNotifications() { // let msg = "Get notifications for me. Maybe, this test is always failed." // var isSucceeded = false // let documentOpenExpectation = self.expectation(description: msg) // do { // try self.session?.getNotifications(.new, completion: { (result) -> Void in // switch result { // case .failure(let error): // print(error) // case .success(let json): // print(json) // isSucceeded = true // } // XCTAssert(isSucceeded, msg) // documentOpenExpectation.fulfill() // }) // self.waitForExpectations(timeout: self.timeoutDuration, handler: nil) // } catch { XCTFail((error as NSError).description) } // } /** Test procedure 1. Save friend list to initialFriends. 2. Make reddift_test_1 friend. 3. Make reddift_test_2 friend. 4. Save friend list to intermediateFriends. 5. Make reddift_test_1 unfriend. 6. Save friend list to intermediateFriends2. 7. Make reddift_test_2 unfriend. 8. Save friend list to finalFriends. 9. Compare initialFriends and intermediateFriends. 10. Compare initialFriends and intermediateFriends2. 11. Confirm initialFriends is equal to finalFriends. */ func testMakeItFriendAndUnfriend() { let username1 = "reddift_test_1" let username2 = "reddift_test_2" let usernames = [username1, username2] // 1. let initialFriends = friends() // 2-3 // note must be blank... This is a bug of reddit.com? // https://github.com/sonsongithub/reddift/issues/180 usernames.forEach({ makeFriend($0, note:"") }) // 4 let intermediateFriends = friends() // 5 makeUnfriend(usernames[0]) // 6 let intermediateFriends2 = friends() // 7 makeUnfriend(usernames[1]) // 8 let finalFriends = friends() // Create friends' name list for test. let initialFriendsNames = initialFriends.map({$0.name}) let intermediateFriendsNames = intermediateFriends.map({$0.name}) let intermediateFriendsNames2 = intermediateFriends2.map({$0.name}) let finalFriendsNames = finalFriends.map({$0.name}) // 9 XCTAssert(intermediateFriendsNames.hasSameElements(initialFriendsNames + usernames)) // 10 XCTAssert(intermediateFriendsNames2.hasSameElements(initialFriendsNames + [username2])) // 11 XCTAssert(finalFriendsNames.hasSameElements(initialFriendsNames)) } /** Test procedure 1. Get reddift_test_1's trophies. */ func testGetTrophies() { let msg = "Get reddift_test_1's trophy." var isSucceeded = false let documentOpenExpectation = self.expectation(description: msg) do { try self.session?.getTrophies("reddift_test_1", completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let trophies): print(trophies) isSucceeded = true } XCTAssert(isSucceeded, msg) documentOpenExpectation.fulfill() }) self.waitForExpectations(timeout: self.timeoutDuration, handler: nil) } catch { XCTFail((error as NSError).description) } } } extension UsersTest { /// Get user contents with username, a type of content, sort and time filter. func userContentsWith(_ username: String, content: UserContent, sort: UserContentSortBy, timeFilterWithin: TimeFilterWithin) -> Listing? { var listing: Listing? = nil let msg = "Get \(username)'s user contents." let documentOpenExpectation = self.expectation(description: msg) var isSucceeded = false do { try self.session?.getUserContent(username, content: content, sort: sort, timeFilterWithin: timeFilterWithin, paginator: Paginator(), completion: { (result) -> Void in switch result { case .failure(let error): // Return 404 code when there are not any data. isSucceeded = (error.code == HttpStatus.notFound.rawValue) print(error) case .success(let list): listing = list isSucceeded = true } documentOpenExpectation.fulfill() }) self.waitForExpectations(timeout: self.timeoutDuration, handler: nil) } catch { XCTFail((error as NSError).description) } XCTAssert(isSucceeded, msg) return listing } }
mit
5d085ba81196c770758089b4156a1e94
35.736264
178
0.57239
4.806614
false
true
false
false
pixelmaid/DynamicBrushes
swift/Palette-Knife/models/base/TimeSeries.swift
1
2669
// // TimeSeries.swift // PaletteKnife // // Created by JENNIFER MARY JACOBS on 6/28/16. // Copyright © 2016 pixelmaid. All rights reserved. // import Foundation class TimeSeries: Emitter{ var timer:NSDate! var intervalTimer:Timer! //TODO: this is duplication to facilitate KVC- should be removed/fixed internal let _time:Observable<Float> override init(){ //==BEGIN OBSERVABLES==// self._time = Observable<Float>(0) _time.name = "time"; //==END OBSERVABLES==// timer = NSDate() super.init() //==BEGIN APPEND OBSERVABLES==// observables.append(_time); //==END APPEND OBSERVABLES==// self.events = ["TIME_INTERVAL"] self.createKeyStorage(); } func getTimeElapsed()->Float{ let currentTime = NSDate(); let t = currentTime.timeIntervalSince(timer as Date) return Float(t); } func startInterval(){ #if DEBUG print("start interval") #endif intervalTimer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(TimeSeries.timerIntervalCallback), userInfo: nil, repeats: true) } func stopInterval(){ #if DEBUG // print("stop interval") #endif if(intervalTimer != nil){ #if DEBUG print("invalidate timer") #endif intervalTimer.invalidate(); } } override func destroy(){ self.stopInterval(); super.destroy(); } @objc func timerIntervalCallback() { let currentTime = NSDate(); //TODO: Fix how this is calucated to deal with lag.. let t = Float(currentTime.timeIntervalSince(timer as Date)) self._time.set(newValue: t) for key in keyStorage["TIME_INTERVAL"]! { if(key.1 != nil){ let condition = key.1; let evaluation = condition?.evaluate(); if(evaluation == true){ NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"TIME_INTERVAL"]) } } else{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"TIME_INTERVAL"]) } } } }
mit
57fc96e2f6ac52450e2393820e57358e
23.477064
176
0.523238
4.680702
false
false
false
false
kykim/SwiftCheck
Tests/SwiftCheckTests/CartesianSpec.swift
1
17112
// // CartesianSpec.swift // SwiftCheck // // Created by Adam Kuipers on 9/21/16. // Copyright © 2016 Typelift. All rights reserved. // // This is a GYB generated file; any changes will be overwritten // during the build phase. Edit the template instead, // found in Templates/CartesianSpec.swift.gyb import SwiftCheck import XCTest import Foundation final class CartesianSpec : XCTestCase { func testGeneratedZips() { let g3 = Gen<(Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3)) property("Gen.zip3 behaves") <- forAllNoShrink(g3) { (tuple : (Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.2 == 3 } let g4 = Gen<(Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4)) property("Gen.zip4 behaves") <- forAllNoShrink(g4) { (tuple : (Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.3 == 4 } let g5 = Gen<(Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5)) property("Gen.zip5 behaves") <- forAllNoShrink(g5) { (tuple : (Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.4 == 5 } let g6 = Gen<(Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6)) property("Gen.zip6 behaves") <- forAllNoShrink(g6) { (tuple : (Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.5 == 6 } let g7 = Gen<(Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7)) property("Gen.zip7 behaves") <- forAllNoShrink(g7) { (tuple : (Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.6 == 7 } let g8 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8)) property("Gen.zip8 behaves") <- forAllNoShrink(g8) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.7 == 8 } let g9 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9)) property("Gen.zip9 behaves") <- forAllNoShrink(g9) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.8 == 9 } let g10 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10)) property("Gen.zip10 behaves") <- forAllNoShrink(g10) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.9 == 10 } let g11 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11)) property("Gen.zip11 behaves") <- forAllNoShrink(g11) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.10 == 11 } let g12 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12)) property("Gen.zip12 behaves") <- forAllNoShrink(g12) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.11 == 12 } let g13 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13)) property("Gen.zip13 behaves") <- forAllNoShrink(g13) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.12 == 13 } let g14 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14)) property("Gen.zip14 behaves") <- forAllNoShrink(g14) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.13 == 14 } let g15 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15)) property("Gen.zip15 behaves") <- forAllNoShrink(g15) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.14 == 15 } let g16 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16)) property("Gen.zip16 behaves") <- forAllNoShrink(g16) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.15 == 16 } let g17 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17)) property("Gen.zip17 behaves") <- forAllNoShrink(g17) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.16 == 17 } let g18 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18)) property("Gen.zip18 behaves") <- forAllNoShrink(g18) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.17 == 18 } let g19 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19)) property("Gen.zip19 behaves") <- forAllNoShrink(g19) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.18 == 19 } let g20 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19), Gen.pure(20)) property("Gen.zip20 behaves") <- forAllNoShrink(g20) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.19 == 20 } let g21 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19), Gen.pure(20), Gen.pure(21)) property("Gen.zip21 behaves") <- forAllNoShrink(g21) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.20 == 21 } let g22 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.zip(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19), Gen.pure(20), Gen.pure(21), Gen.pure(22)) property("Gen.zip22 behaves") <- forAllNoShrink(g22) { (tuple : (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> Bool in tuple.0 == 1 && tuple.21 == 22 } } func testGeneratedMaps() { let g3 = Gen<(Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3)) { max($0, $1, $2) } property("Gen.zip3 behaves") <- forAllNoShrink(g3) { maxInt in maxInt == 3 } let g4 = Gen<(Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4)) { max($0, $1, $2, $3) } property("Gen.zip4 behaves") <- forAllNoShrink(g4) { maxInt in maxInt == 4 } let g5 = Gen<(Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5)) { max($0, $1, $2, $3, $4) } property("Gen.zip5 behaves") <- forAllNoShrink(g5) { maxInt in maxInt == 5 } let g6 = Gen<(Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6)) { max($0, $1, $2, $3, $4, $5) } property("Gen.zip6 behaves") <- forAllNoShrink(g6) { maxInt in maxInt == 6 } let g7 = Gen<(Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7)) { max($0, $1, $2, $3, $4, $5, $6) } property("Gen.zip7 behaves") <- forAllNoShrink(g7) { maxInt in maxInt == 7 } let g8 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8)) { max($0, $1, $2, $3, $4, $5, $6, $7) } property("Gen.zip8 behaves") <- forAllNoShrink(g8) { maxInt in maxInt == 8 } let g9 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8) } property("Gen.zip9 behaves") <- forAllNoShrink(g9) { maxInt in maxInt == 9 } let g10 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) } property("Gen.zip10 behaves") <- forAllNoShrink(g10) { maxInt in maxInt == 10 } let g11 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) } property("Gen.zip11 behaves") <- forAllNoShrink(g11) { maxInt in maxInt == 11 } let g12 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) } property("Gen.zip12 behaves") <- forAllNoShrink(g12) { maxInt in maxInt == 12 } let g13 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) } property("Gen.zip13 behaves") <- forAllNoShrink(g13) { maxInt in maxInt == 13 } let g14 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) } property("Gen.zip14 behaves") <- forAllNoShrink(g14) { maxInt in maxInt == 14 } let g15 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) } property("Gen.zip15 behaves") <- forAllNoShrink(g15) { maxInt in maxInt == 15 } let g16 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) } property("Gen.zip16 behaves") <- forAllNoShrink(g16) { maxInt in maxInt == 16 } let g17 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) } property("Gen.zip17 behaves") <- forAllNoShrink(g17) { maxInt in maxInt == 17 } let g18 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) } property("Gen.zip18 behaves") <- forAllNoShrink(g18) { maxInt in maxInt == 18 } let g19 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) } property("Gen.zip19 behaves") <- forAllNoShrink(g19) { maxInt in maxInt == 19 } let g20 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19), Gen.pure(20)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19) } property("Gen.zip20 behaves") <- forAllNoShrink(g20) { maxInt in maxInt == 20 } let g21 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19), Gen.pure(20), Gen.pure(21)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) } property("Gen.zip21 behaves") <- forAllNoShrink(g21) { maxInt in maxInt == 21 } let g22 = Gen<(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)>.map(Gen.pure(1), Gen.pure(2), Gen.pure(3), Gen.pure(4), Gen.pure(5), Gen.pure(6), Gen.pure(7), Gen.pure(8), Gen.pure(9), Gen.pure(10), Gen.pure(11), Gen.pure(12), Gen.pure(13), Gen.pure(14), Gen.pure(15), Gen.pure(16), Gen.pure(17), Gen.pure(18), Gen.pure(19), Gen.pure(20), Gen.pure(21), Gen.pure(22)) { max($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) } property("Gen.zip22 behaves") <- forAllNoShrink(g22) { maxInt in maxInt == 22 } } }
mit
d3189bc2954159daa8d74817287c33d8
63.814394
538
0.586523
2.343973
false
false
false
false
CodaFi/swift
stdlib/public/core/FloatingPoint.swift
1
76911
//===--- FloatingPoint.swift ----------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A floating-point numeric type. /// /// Floating-point types are used to represent fractional numbers, like 5.5, /// 100.0, or 3.14159274. Each floating-point type has its own possible range /// and precision. The floating-point types in the standard library are /// `Float`, `Double`, and `Float80` where available. /// /// Create new instances of floating-point types using integer or /// floating-point literals. For example: /// /// let temperature = 33.2 /// let recordHigh = 37.5 /// /// The `FloatingPoint` protocol declares common arithmetic operations, so you /// can write functions and algorithms that work on any floating-point type. /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// Because the `hypotenuse(_:_:)` function uses a generic parameter /// constrained to the `FloatingPoint` protocol, you can call it using any /// floating-point type. /// /// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// Floating-point values are represented as a *sign* and a *magnitude*, where /// the magnitude is calculated using the type's *radix* and the instance's /// *significand* and *exponent*. This magnitude calculation takes the /// following form for a floating-point value `x` of type `F`, where `**` is /// exponentiation: /// /// x.significand * F.radix ** x.exponent /// /// Here's an example of the number -8.5 represented as an instance of the /// `Double` type, which defines a radix of 2. /// /// let y = -8.5 /// // y.sign == .minus /// // y.significand == 1.0625 /// // y.exponent == 3 /// /// let magnitude = 1.0625 * Double(2 ** 3) /// // magnitude == 8.5 /// /// Types that conform to the `FloatingPoint` protocol provide most basic /// (clause 5) operations of the [IEEE 754 specification][spec]. The base, /// precision, and exponent range are not fixed in any way by this protocol, /// but it enforces the basic requirements of any IEEE 754 floating-point /// type. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// Additional Considerations /// ========================= /// /// In addition to representing specific numbers, floating-point types also /// have special values for working with overflow and nonnumeric results of /// calculation. /// /// Infinity /// -------- /// /// Any value whose magnitude is so great that it would round to a value /// outside the range of representable numbers is rounded to *infinity*. For a /// type `F`, positive and negative infinity are represented as `F.infinity` /// and `-F.infinity`, respectively. Positive infinity compares greater than /// every finite value and negative infinity, while negative infinity compares /// less than every finite value and positive infinity. Infinite values with /// the same sign are equal to each other. /// /// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity] /// print(values.sorted()) /// // Prints "[-inf, -10.0, 10.0, 25.0, inf]" /// /// Operations with infinite values follow real arithmetic as much as possible: /// Adding or subtracting a finite value, or multiplying or dividing infinity /// by a nonzero finite value, results in infinity. /// /// NaN ("not a number") /// -------------------- /// /// Floating-point types represent values that are neither finite numbers nor /// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with /// any value, including another NaN, results in `false`. /// /// let myNaN = Double.nan /// print(myNaN > 0) /// // Prints "false" /// print(myNaN < 0) /// // Prints "false" /// print(myNaN == .nan) /// // Prints "false" /// /// Because testing whether one NaN is equal to another NaN results in `false`, /// use the `isNaN` property to test whether a value is NaN. /// /// print(myNaN.isNaN) /// // Prints "true" /// /// NaN propagates through many arithmetic operations. When you are operating /// on many values, this behavior is valuable because operations on NaN simply /// forward the value and don't cause runtime errors. The following example /// shows how NaN values operate in different contexts. /// /// Imagine you have a set of temperature data for which you need to report /// some general statistics: the total number of observations, the number of /// valid observations, and the average temperature. First, a set of /// observations in Celsius is parsed from strings to `Double` values: /// /// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"] /// let tempsCelsius = temperatureData.map { Double($0) ?? .nan } /// print(tempsCelsius) /// // Prints "[21.5, 19.25, 27, nan, 28.25, nan, 23.0]" /// /// /// Note that some elements in the `temperatureData ` array are not valid /// numbers. When these invalid strings are parsed by the `Double` failable /// initializer, the example uses the nil-coalescing operator (`??`) to /// provide NaN as a fallback value. /// /// Next, the observations in Celsius are converted to Fahrenheit: /// /// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 } /// print(tempsFahrenheit) /// // Prints "[70.7, 66.65, 80.6, nan, 82.85, nan, 73.4]" /// /// The NaN values in the `tempsCelsius` array are propagated through the /// conversion and remain NaN in `tempsFahrenheit`. /// /// Because calculating the average of the observations involves combining /// every value of the `tempsFahrenheit` array, any NaN values cause the /// result to also be NaN, as seen in this example: /// /// let badAverage = tempsFahrenheit.reduce(0.0, +) / Double(tempsFahrenheit.count) /// // badAverage.isNaN == true /// /// Instead, when you need an operation to have a specific numeric result, /// filter out any NaN values using the `isNaN` property. /// /// let validTemps = tempsFahrenheit.filter { !$0.isNaN } /// let average = validTemps.reduce(0.0, +) / Double(validTemps.count) /// /// Finally, report the average temperature and observation counts: /// /// print("Average: \(average)°F in \(validTemps.count) " + /// "out of \(tempsFahrenheit.count) observations.") /// // Prints "Average: 74.84°F in 5 out of 7 observations." public protocol FloatingPoint: SignedNumeric, Strideable, Hashable where Magnitude == Self { /// A type that can represent any written exponent. associatedtype Exponent: SignedInteger /// Creates a new value from the given sign, exponent, and significand. /// /// The following example uses this initializer to create a new `Double` /// instance. `Double` is a binary floating-point type that has a radix of /// `2`. /// /// let x = Double(sign: .plus, exponent: -2, significand: 1.5) /// // x == 0.375 /// /// This initializer is equivalent to the following calculation, where `**` /// is exponentiation, computed as if by a single, correctly rounded, /// floating-point operation: /// /// let sign: FloatingPointSign = .plus /// let exponent = -2 /// let significand = 1.5 /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent /// // y == 0.375 /// /// As with any basic operation, if this value is outside the representable /// range of the type, overflow or underflow occurs, and zero, a subnormal /// value, or infinity may result. In addition, there are two other edge /// cases: /// /// - If the value you pass to `significand` is zero or infinite, the result /// is zero or infinite, regardless of the value of `exponent`. /// - If the value you pass to `significand` is NaN, the result is NaN. /// /// For any floating-point value `x` of type `F`, the result of the following /// is equal to `x`, with the distinction that the result is canonicalized /// if `x` is in a noncanonical encoding: /// /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand) /// /// This initializer implements the `scaleB` operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign to use for the new value. /// - exponent: The new value's exponent. /// - significand: The new value's significand. init(sign: FloatingPointSign, exponent: Exponent, significand: Self) /// Creates a new floating-point value using the sign of one value and the /// magnitude of another. /// /// The following example uses this initializer to create a new `Double` /// instance with the sign of `a` and the magnitude of `b`: /// /// let a = -21.5 /// let b = 305.15 /// let c = Double(signOf: a, magnitudeOf: b) /// print(c) /// // Prints "-305.15" /// /// This initializer implements the IEEE 754 `copysign` operation. /// /// - Parameters: /// - signOf: A value from which to use the sign. The result of the /// initializer has the same sign as `signOf`. /// - magnitudeOf: A value from which to use the magnitude. The result of /// the initializer has the same magnitude as `magnitudeOf`. init(signOf: Self, magnitudeOf: Self) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init(_ value: Int) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init<Source: BinaryInteger>(_ value: Source) /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. init?<Source: BinaryInteger>(exactly value: Source) /// The radix, or base of exponentiation, for a floating-point type. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// A conforming type may use any integer radix, but values other than 2 (for /// binary floating-point types) or 10 (for decimal floating-point types) /// are extraordinarily rare in practice. static var radix: Int { get } /// A quiet NaN ("not a number"). /// /// A NaN compares not equal, not greater than, and not less than every /// value, including itself. Passing a NaN to an operation generally results /// in NaN. /// /// let x = 1.21 /// // x > Double.nan == false /// // x < Double.nan == false /// // x == Double.nan == false /// /// Because a NaN always compares not equal to itself, to test whether a /// floating-point value is NaN, use its `isNaN` property instead of the /// equal-to operator (`==`). In the following example, `y` is NaN. /// /// let y = x + Double.nan /// print(y == Double.nan) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" static var nan: Self { get } /// A signaling NaN ("not a number"). /// /// The default IEEE 754 behavior of operations involving a signaling NaN is /// to raise the Invalid flag in the floating-point environment and return a /// quiet NaN. /// /// Operations on types conforming to the `FloatingPoint` protocol should /// support this behavior, but they might also support other options. For /// example, it would be reasonable to implement alternative operations in /// which operating on a signaling NaN triggers a runtime error or results /// in a diagnostic for debugging purposes. Types that implement alternative /// behaviors for a signaling NaN must document the departure. /// /// Other than these signaling operations, a signaling NaN behaves in the /// same manner as a quiet NaN. static var signalingNaN: Self { get } /// Positive infinity. /// /// Infinity compares greater than all finite numbers and equal to other /// infinite values. /// /// let x = Double.greatestFiniteMagnitude /// let y = x * 2 /// // y == Double.infinity /// // y > x static var infinity: Self { get } /// The greatest finite number representable by this type. /// /// This value compares greater than or equal to all finite numbers, but less /// than `infinity`. /// /// This value corresponds to type-specific C macros such as `FLT_MAX` and /// `DBL_MAX`. The naming of those macros is slightly misleading, because /// `infinity` is greater than this value. static var greatestFiniteMagnitude: Self { get } /// The mathematical constant pi. /// /// This value should be rounded toward zero to keep user computations with /// angles from inadvertently ending up in the wrong quadrant. A type that /// conforms to the `FloatingPoint` protocol provides the value for `pi` at /// its best possible precision. /// /// print(Double.pi) /// // Prints "3.14159265358979" static var pi: Self { get } // NOTE: Rationale for "ulp" instead of "epsilon": // We do not use that name because it is ambiguous at best and misleading // at worst: // // - Historically several definitions of "machine epsilon" have commonly // been used, which differ by up to a factor of two or so. By contrast // "ulp" is a term with a specific unambiguous definition. // // - Some languages have used "epsilon" to refer to wildly different values, // such as `leastNonzeroMagnitude`. // // - Inexperienced users often believe that "epsilon" should be used as a // tolerance for floating-point comparisons, because of the name. It is // nearly always the wrong value to use for this purpose. /// The unit in the last place of this value. /// /// This is the unit of the least significant digit in this value's /// significand. For most numbers `x`, this is the difference between `x` /// and the next greater (in magnitude) representable number. There are some /// edge cases to be aware of: /// /// - If `x` is not a finite number, then `x.ulp` is NaN. /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal /// number. If a type does not support subnormals, `x.ulp` may be rounded /// to zero. /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next /// greater representable value is `infinity`. /// /// See also the `ulpOfOne` static property. var ulp: Self { get } /// The unit in the last place of 1.0. /// /// The positive difference between 1.0 and the next greater representable /// number. `ulpOfOne` corresponds to the value represented by the C macros /// `FLT_EPSILON`, `DBL_EPSILON`, etc, and is sometimes called *epsilon* or /// *machine epsilon*. Swift deliberately avoids using the term "epsilon" /// because: /// /// - Historically "epsilon" has been used to refer to several different /// concepts in different languages, leading to confusion and bugs. /// /// - The name "epsilon" suggests that this quantity is a good tolerance to /// choose for approximate comparisons, but it is almost always unsuitable /// for that purpose. /// /// See also the `ulp` member property. static var ulpOfOne: Self { get } /// The least positive normal number. /// /// This value compares less than or equal to all positive normal numbers. /// There may be smaller positive numbers, but they are *subnormal*, meaning /// that they are represented with less precision than normal numbers. /// /// This value corresponds to type-specific C macros such as `FLT_MIN` and /// `DBL_MIN`. The naming of those macros is slightly misleading, because /// subnormals, zeros, and negative numbers are smaller than this value. static var leastNormalMagnitude: Self { get } /// The least positive number. /// /// This value compares less than or equal to all positive numbers, but /// greater than zero. If the type supports subnormal values, /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`; /// otherwise they are equal. static var leastNonzeroMagnitude: Self { get } /// The sign of the floating-point value. /// /// The `sign` property is `.minus` if the value's signbit is set, and /// `.plus` otherwise. For example: /// /// let x = -33.375 /// // x.sign == .minus /// /// Do not use this property to check whether a floating point value is /// negative. For a value `x`, the comparison `x.sign == .minus` is not /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` /// could be either `.plus` or `.minus`. var sign: FloatingPointSign { get } /// The exponent of the floating-point value. /// /// The *exponent* of a floating-point value is the integer part of the /// logarithm of the value's magnitude. For a value `x` of a floating-point /// type `F`, the magnitude can be calculated as the following, where `**` /// is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// The `exponent` property has the following edge cases: /// /// - If `x` is zero, then `x.exponent` is `Int.min`. /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` /// /// This property implements the `logB` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var exponent: Exponent { get } /// The significand of the floating-point value. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// If a type's radix is 2, then for finite nonzero numbers, the significand /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand` /// is defined as follows: /// /// - If `x` is zero, then `x.significand` is 0.0. /// - If `x` is infinite, then `x.significand` is infinity. /// - If `x` is NaN, then `x.significand` is NaN. /// - Note: The significand is frequently also called the *mantissa*, but /// significand is the preferred terminology in the [IEEE 754 /// specification][spec], to allay confusion with the use of mantissa for /// the fractional part of a logarithm. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var significand: Self { get } /// Adds two values and produces their sum, rounded to a /// representable value. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// let x = 1.5 /// let y = x + 2.25 /// // y == 3.75 /// /// The `+` operator implements the addition operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable, /// rounded to a representable value. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +=(lhs: inout Self, rhs: Self) /// Calculates the additive inverse of a value. /// /// The unary minus operator (prefix `-`) calculates the negation of its /// operand. The result is always exact. /// /// let x = 21.5 /// let y = -x /// // y == -21.5 /// /// - Parameter operand: The value to negate. override static prefix func - (_ operand: Self) -> Self /// Replaces this value with its additive inverse. /// /// The result is always exact. This example uses the `negate()` method to /// negate the value of the variable `x`: /// /// var x = 21.5 /// x.negate() /// // x == -21.5 override mutating func negate() /// Subtracts one value from another and produces their difference, rounded /// to a representable value. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x - 2.25 /// // y == 5.25 /// /// The `-` operator implements the subtraction operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in /// the left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -=(lhs: inout Self, rhs: Self) /// Multiplies two values and produces their product, rounding to a /// representable value. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x * 2.25 /// // y == 16.875 /// /// The `*` operator implements the multiplication operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *=(lhs: inout Self, rhs: Self) /// Returns the quotient of dividing the first value by the second, rounded /// to a representable value. /// /// The division operator (`/`) calculates the quotient of the division if /// `rhs` is nonzero. If `rhs` is zero, the result of the division is /// infinity, with the sign of the result matching the sign of `lhs`. /// /// let x = 16.875 /// let y = x / 2.25 /// // y == 7.5 /// /// let z = x / 0 /// // z.isInfinite == true /// /// The `/` operator implements the division operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the quotient in the /// left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /=(lhs: inout Self, rhs: Self) /// Returns the remainder of this value divided by the given value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// let r = x.remainder(dividingBy: 0.75) /// // r == -0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `remainder(dividingBy:)` method is always exact. This method implements /// the remainder operation defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other`. func remainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// x.formRemainder(dividingBy: 0.75) /// // x == -0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `formRemainder(dividingBy:)` method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formRemainder(dividingBy other: Self) /// Returns the remainder of this value divided by the given value using /// truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// let r = x.truncatingRemainder(dividingBy: 0.75) /// // r == 0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method /// is always exact. /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other` using /// truncating division. func truncatingRemainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value using truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// x.formTruncatingRemainder(dividingBy: 0.75) /// // x == 0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)` /// method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formTruncatingRemainder(dividingBy other: Self) /// Returns the square root of the value, rounded to a representable value. /// /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// /// func hypotenuse(_ a: Double, _ b: Double) -> Double { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// - Returns: The square root of the value. func squareRoot() -> Self /// Replaces this value with its square root, rounded to a representable /// value. mutating func formSquareRoot() /// Returns the result of adding the product of the two given values to this /// value, computed without intermediate rounding. /// /// This method is equivalent to the C `fma` function and implements the /// `fusedMultiplyAdd` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. /// - Returns: The product of `lhs` and `rhs`, added to this value. func addingProduct(_ lhs: Self, _ rhs: Self) -> Self /// Adds the product of the two given values to this value in place, computed /// without intermediate rounding. /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. mutating func addProduct(_ lhs: Self, _ rhs: Self) /// Returns the lesser of the two given values. /// /// This method returns the minimum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.minimum(10.0, -25.0) /// // -25.0 /// Double.minimum(10.0, .nan) /// // 10.0 /// Double.minimum(.nan, -25.0) /// // -25.0 /// Double.minimum(.nan, .nan) /// // nan /// /// The `minimum` method implements the `minNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The minimum of `x` and `y`, or whichever is a number if the /// other is NaN. static func minimum(_ x: Self, _ y: Self) -> Self /// Returns the greater of the two given values. /// /// This method returns the maximum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.maximum(10.0, -25.0) /// // 10.0 /// Double.maximum(10.0, .nan) /// // 10.0 /// Double.maximum(.nan, -25.0) /// // -25.0 /// Double.maximum(.nan, .nan) /// // nan /// /// The `maximum` method implements the `maxNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The greater of `x` and `y`, or whichever is a number if the /// other is NaN. static func maximum(_ x: Self, _ y: Self) -> Self /// Returns the value with lesser magnitude. /// /// This method returns the value with lesser magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.minimumMagnitude(10.0, -25.0) /// // 10.0 /// Double.minimumMagnitude(10.0, .nan) /// // 10.0 /// Double.minimumMagnitude(.nan, -25.0) /// // -25.0 /// Double.minimumMagnitude(.nan, .nan) /// // nan /// /// The `minimumMagnitude` method implements the `minNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is /// a number if the other is NaN. static func minimumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns the value with greater magnitude. /// /// This method returns the value with greater magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.maximumMagnitude(10.0, -25.0) /// // -25.0 /// Double.maximumMagnitude(10.0, .nan) /// // 10.0 /// Double.maximumMagnitude(.nan, -25.0) /// // -25.0 /// Double.maximumMagnitude(.nan, .nan) /// // nan /// /// The `maximumMagnitude` method implements the `maxNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is /// a number if the other is NaN. static func maximumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns this value rounded to an integral value using the specified /// rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// let x = 6.5 /// /// // Equivalent to the C 'round' function: /// print(x.rounded(.toNearestOrAwayFromZero)) /// // Prints "7.0" /// /// // Equivalent to the C 'trunc' function: /// print(x.rounded(.towardZero)) /// // Prints "6.0" /// /// // Equivalent to the C 'ceil' function: /// print(x.rounded(.up)) /// // Prints "7.0" /// /// // Equivalent to the C 'floor' function: /// print(x.rounded(.down)) /// // Prints "6.0" /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `rounded()` /// method instead. /// /// print(x.rounded()) /// // Prints "7.0" /// /// - Parameter rule: The rounding rule to use. /// - Returns: The integral value found by rounding using `rule`. func rounded(_ rule: FloatingPointRoundingRule) -> Self /// Rounds the value to an integral value using the specified rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// // Equivalent to the C 'round' function: /// var w = 6.5 /// w.round(.toNearestOrAwayFromZero) /// // w == 7.0 /// /// // Equivalent to the C 'trunc' function: /// var x = 6.5 /// x.round(.towardZero) /// // x == 6.0 /// /// // Equivalent to the C 'ceil' function: /// var y = 6.5 /// y.round(.up) /// // y == 7.0 /// /// // Equivalent to the C 'floor' function: /// var z = 6.5 /// z.round(.down) /// // z == 6.0 /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `round()` method /// instead. /// /// var w1 = 6.5 /// w1.round() /// // w1 == 7.0 /// /// - Parameter rule: The rounding rule to use. mutating func round(_ rule: FloatingPointRoundingRule) /// The least representable value that compares greater than this value. /// /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or /// `infinity`, `x.nextUp` is `x` itself. The following special cases also /// apply: /// /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`. /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`. /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`. /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`. var nextUp: Self { get } /// The greatest representable value that compares less than this value. /// /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or /// `-infinity`, `x.nextDown` is `x` itself. The following special cases /// also apply: /// /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`. /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`. /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`. /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`. var nextDown: Self { get } /// Returns a Boolean value indicating whether this instance is equal to the /// given value. /// /// This method serves as the basis for the equal-to operator (`==`) for /// floating-point values. When comparing two values with this method, `-0` /// is equal to `+0`. NaN is not equal to any value, including itself. For /// example: /// /// let x = 15.0 /// x.isEqual(to: 15.0) /// // true /// x.isEqual(to: .nan) /// // false /// Double.nan.isEqual(to: .nan) /// // false /// /// The `isEqual(to:)` method implements the equality predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` has the same value as this instance; /// otherwise, `false`. If either this value or `other` is NaN, the result /// of this method is `false`. func isEqual(to other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than the /// given value. /// /// This method serves as the basis for the less-than operator (`<`) for /// floating-point values. Some special cases apply: /// /// - Because NaN compares not less than nor greater than any value, this /// method returns `false` when called on NaN or when NaN is passed as /// `other`. /// - `-infinity` compares less than all values except for itself and NaN. /// - Every value except for NaN and `+infinity` compares less than /// `+infinity`. /// /// let x = 15.0 /// x.isLess(than: 20.0) /// // true /// x.isLess(than: .nan) /// // false /// Double.nan.isLess(than: x) /// // false /// /// The `isLess(than:)` method implements the less-than predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if this value is less than `other`; otherwise, `false`. /// If either this value or `other` is NaN, the result of this method is /// `false`. func isLess(than other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than or /// equal to the given value. /// /// This method serves as the basis for the less-than-or-equal-to operator /// (`<=`) for floating-point values. Some special cases apply: /// /// - Because NaN is incomparable with any value, this method returns `false` /// when called on NaN or when NaN is passed as `other`. /// - `-infinity` compares less than or equal to all values except NaN. /// - Every value except NaN compares less than or equal to `+infinity`. /// /// let x = 15.0 /// x.isLessThanOrEqualTo(20.0) /// // true /// x.isLessThanOrEqualTo(.nan) /// // false /// Double.nan.isLessThanOrEqualTo(x) /// // false /// /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal /// predicate defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` is greater than this value; otherwise, /// `false`. If either this value or `other` is NaN, the result of this /// method is `false`. func isLessThanOrEqualTo(_ other: Self) -> Bool /// Returns a Boolean value indicating whether this instance should precede /// or tie positions with the given value in an ascending sort. /// /// This relation is a refinement of the less-than-or-equal-to operator /// (`<=`) that provides a total order on all values of the type, including /// signed zeros and NaNs. /// /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an /// array of floating-point values, including some that are NaN: /// /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } /// print(numbers) /// // Prints "[-9.5, 2.5, 3.0, 21.25, nan]" /// /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order /// relation as defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: A floating-point value to compare to this value. /// - Returns: `true` if this value is ordered below or the same as `other` /// in a total ordering of the floating-point type; otherwise, `false`. func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool /// A Boolean value indicating whether this instance is normal. /// /// A *normal* value is a finite number that uses the full precision /// available to values of a type. Zero is neither a normal nor a subnormal /// number. var isNormal: Bool { get } /// A Boolean value indicating whether this instance is finite. /// /// All values other than NaN and infinity are considered finite, whether /// normal or subnormal. var isFinite: Bool { get } /// A Boolean value indicating whether the instance is equal to zero. /// /// The `isZero` property of a value `x` is `true` when `x` represents either /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison: /// `x == 0.0`. /// /// let x = -0.0 /// x.isZero // true /// x == 0.0 // true var isZero: Bool { get } /// A Boolean value indicating whether the instance is subnormal. /// /// A *subnormal* value is a nonzero number that has a lesser magnitude than /// the smallest normal number. Subnormal values do not use the full /// precision available to values of a type. /// /// Zero is neither a normal nor a subnormal number. Subnormal numbers are /// often called *denormal* or *denormalized*---these are different names /// for the same concept. var isSubnormal: Bool { get } /// A Boolean value indicating whether the instance is infinite. /// /// Note that `isFinite` and `isInfinite` do not form a dichotomy, because /// they are not total: If `x` is `NaN`, then both properties are `false`. var isInfinite: Bool { get } /// A Boolean value indicating whether the instance is NaN ("not a number"). /// /// Because NaN is not equal to any value, including NaN, use this property /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`) /// to test whether a value is or is not NaN. For example: /// /// let x = 0.0 /// let y = x * .infinity /// // y is a NaN /// /// // Comparing with the equal-to operator never returns 'true' /// print(x == Double.nan) /// // Prints "false" /// print(y == Double.nan) /// // Prints "false" /// /// // Test with the 'isNaN' property instead /// print(x.isNaN) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" /// /// This property is `true` for both quiet and signaling NaNs. var isNaN: Bool { get } /// A Boolean value indicating whether the instance is a signaling NaN. /// /// Signaling NaNs typically raise the Invalid flag when used in general /// computing operations. var isSignalingNaN: Bool { get } /// The classification of this value. /// /// A value's `floatingPointClass` property describes its "class" as /// described by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var floatingPointClass: FloatingPointClassification { get } /// A Boolean value indicating whether the instance's representation is in /// its canonical form. /// /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, /// encoding of a floating-point value. On platforms that fully support /// IEEE 754, every `Float` or `Double` value is canonical, but /// non-canonical values can exist on other platforms or for other types. /// Some examples: /// /// - On platforms that flush subnormal numbers to zero (such as armv7 /// with the default floating-point environment), Swift interprets /// subnormal `Float` and `Double` values as non-canonical zeros. /// (In Swift 5.1 and earlier, `isCanonical` is `true` for these /// values, which is the incorrect value.) /// /// - On i386 and x86_64, `Float80` has a number of non-canonical /// encodings. "Pseudo-NaNs", "pseudo-infinities", and "unnormals" are /// interpreted as non-canonical NaN encodings. "Pseudo-denormals" are /// interpreted as non-canonical encodings of subnormal values. /// /// - Decimal floating-point types admit a large number of non-canonical /// encodings. Consult the IEEE 754 standard for additional details. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var isCanonical: Bool { get } } /// The sign of a floating-point value. @frozen public enum FloatingPointSign: Int { /// The sign for a positive value. case plus /// The sign for a negative value. case minus // Explicit declarations of otherwise-synthesized members to make them // @inlinable, promising that we will never change the implementation. @inlinable public init?(rawValue: Int) { switch rawValue { case 0: self = .plus case 1: self = .minus default: return nil } } @inlinable public var rawValue: Int { switch self { case .plus: return 0 case .minus: return 1 } } @_transparent @inlinable public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool { return a.rawValue == b.rawValue } @inlinable public var hashValue: Int { return rawValue.hashValue } @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable public func _rawHashValue(seed: Int) -> Int { return rawValue._rawHashValue(seed: seed) } } /// The IEEE 754 floating-point classes. @frozen public enum FloatingPointClassification { /// A signaling NaN ("not a number"). /// /// A signaling NaN sets the floating-point exception status when used in /// many floating-point operations. case signalingNaN /// A silent NaN ("not a number") value. case quietNaN /// A value equal to `-infinity`. case negativeInfinity /// A negative value that uses the full precision of the floating-point type. case negativeNormal /// A negative, nonzero number that does not use the full precision of the /// floating-point type. case negativeSubnormal /// A value equal to zero with a negative sign. case negativeZero /// A value equal to zero with a positive sign. case positiveZero /// A positive, nonzero number that does not use the full precision of the /// floating-point type. case positiveSubnormal /// A positive value that uses the full precision of the floating-point type. case positiveNormal /// A value equal to `+infinity`. case positiveInfinity } /// A rule for rounding a floating-point number. public enum FloatingPointRoundingRule { /// Round to the closest allowed value; if two values are equally close, the /// one with greater magnitude is chosen. /// /// This rounding rule is also known as "schoolbook rounding." The following /// example shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrAwayFromZero) /// // 5.0 /// (5.5).rounded(.toNearestOrAwayFromZero) /// // 6.0 /// (-5.2).rounded(.toNearestOrAwayFromZero) /// // -5.0 /// (-5.5).rounded(.toNearestOrAwayFromZero) /// // -6.0 /// /// This rule is equivalent to the C `round` function and implements the /// `roundToIntegralTiesToAway` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrAwayFromZero /// Round to the closest allowed value; if two values are equally close, the /// even one is chosen. /// /// This rounding rule is also known as "bankers rounding," and is the /// default IEEE 754 rounding mode for arithmetic. The following example /// shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrEven) /// // 5.0 /// (5.5).rounded(.toNearestOrEven) /// // 6.0 /// (4.5).rounded(.toNearestOrEven) /// // 4.0 /// /// This rule implements the `roundToIntegralTiesToEven` operation defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrEven /// Round to the closest allowed value that is greater than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.up) /// // 6.0 /// (5.5).rounded(.up) /// // 6.0 /// (-5.2).rounded(.up) /// // -5.0 /// (-5.5).rounded(.up) /// // -5.0 /// /// This rule is equivalent to the C `ceil` function and implements the /// `roundToIntegralTowardPositive` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case up /// Round to the closest allowed value that is less than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.down) /// // 5.0 /// (5.5).rounded(.down) /// // 5.0 /// (-5.2).rounded(.down) /// // -6.0 /// (-5.5).rounded(.down) /// // -6.0 /// /// This rule is equivalent to the C `floor` function and implements the /// `roundToIntegralTowardNegative` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case down /// Round to the closest allowed value whose magnitude is less than or equal /// to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.towardZero) /// // 5.0 /// (5.5).rounded(.towardZero) /// // 5.0 /// (-5.2).rounded(.towardZero) /// // -5.0 /// (-5.5).rounded(.towardZero) /// // -5.0 /// /// This rule is equivalent to the C `trunc` function and implements the /// `roundToIntegralTowardZero` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case towardZero /// Round to the closest allowed value whose magnitude is greater than or /// equal to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.awayFromZero) /// // 6.0 /// (5.5).rounded(.awayFromZero) /// // 6.0 /// (-5.2).rounded(.awayFromZero) /// // -6.0 /// (-5.5).rounded(.awayFromZero) /// // -6.0 case awayFromZero } extension FloatingPoint { @_transparent public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.isEqual(to: rhs) } @_transparent public static func < (lhs: Self, rhs: Self) -> Bool { return lhs.isLess(than: rhs) } @_transparent public static func <= (lhs: Self, rhs: Self) -> Bool { return lhs.isLessThanOrEqualTo(rhs) } @_transparent public static func > (lhs: Self, rhs: Self) -> Bool { return rhs.isLess(than: lhs) } @_transparent public static func >= (lhs: Self, rhs: Self) -> Bool { return rhs.isLessThanOrEqualTo(lhs) } } /// A radix-2 (binary) floating-point type. /// /// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol /// with operations specific to floating-point binary types, as defined by the /// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in /// the standard library by `Float`, `Double`, and `Float80` where available. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral { /// A type that represents the encoded significand of a value. associatedtype RawSignificand: UnsignedInteger /// A type that represents the encoded exponent of a value. associatedtype RawExponent: UnsignedInteger /// Creates a new instance from the specified sign and bit patterns. /// /// The values passed as `exponentBitPattern` and `significandBitPattern` are /// interpreted in the binary interchange format defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign of the new value. /// - exponentBitPattern: The bit pattern to use for the exponent field of /// the new value. /// - significandBitPattern: The bit pattern to use for the significand /// field of the new value. init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Double) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float80) #endif /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. init<Source: BinaryFloatingPoint>(_ value: Source) /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. A value that is NaN ("not a number") cannot be /// represented exactly if its payload cannot be encoded exactly. /// /// - Parameter value: A floating-point value to be converted. init?<Source: BinaryFloatingPoint>(exactly value: Source) /// The number of bits used to represent the type's exponent. /// /// A binary floating-point type's `exponentBitCount` imposes a limit on the /// range of the exponent for normal, finite values. The *exponent bias* of /// a type `F` can be calculated as the following, where `**` is /// exponentiation: /// /// let bias = 2 ** (F.exponentBitCount - 1) - 1 /// /// The least normal exponent for values of the type `F` is `1 - bias`, and /// the largest finite exponent is `bias`. An all-zeros exponent is reserved /// for subnormals and zeros, and an all-ones exponent is reserved for /// infinity and NaN. /// /// For example, the `Float` type has an `exponentBitCount` of 8, which gives /// an exponent bias of `127` by the calculation above. /// /// let bias = 2 ** (Float.exponentBitCount - 1) - 1 /// // bias == 127 /// print(Float.greatestFiniteMagnitude.exponent) /// // Prints "127" /// print(Float.leastNormalMagnitude.exponent) /// // Prints "-126" static var exponentBitCount: Int { get } /// The available number of fractional significand bits. /// /// For fixed-width floating-point types, this is the actual number of /// fractional significand bits. /// /// For extensible floating-point types, `significandBitCount` should be the /// maximum allowed significand width (without counting any leading integral /// bit of the significand). If there is no upper limit, then /// `significandBitCount` should be `Int.max`. /// /// Note that `Float80.significandBitCount` is 63, even though 64 bits are /// used to store the significand in the memory representation of a /// `Float80` (unlike other floating-point types, `Float80` explicitly /// stores the leading integral significand bit, but the /// `BinaryFloatingPoint` APIs provide an abstraction so that users don't /// need to be aware of this detail). static var significandBitCount: Int { get } /// The raw encoding of the value's exponent field. /// /// This value is unadjusted by the type's exponent bias. var exponentBitPattern: RawExponent { get } /// The raw encoding of the value's significand field. /// /// The `significandBitPattern` property does not include the leading /// integral bit of the significand, even for types like `Float80` that /// store it explicitly. var significandBitPattern: RawSignificand { get } /// The floating-point value with the same sign and exponent as this value, /// but with a significand of 1.0. /// /// A *binade* is a set of binary floating-point values that all have the /// same sign and exponent. The `binade` property is a member of the same /// binade as this value, but with a unit significand. /// /// In this example, `x` has a value of `21.5`, which is stored as /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is /// equal to `1.0 * 2**4`, or `16.0`. /// /// let x = 21.5 /// // x.significand == 1.34375 /// // x.exponent == 4 /// /// let y = x.binade /// // y == 16.0 /// // y.significand == 1.0 /// // y.exponent == 4 var binade: Self { get } /// The number of bits required to represent the value's significand. /// /// If this value is a finite nonzero number, `significandWidth` is the /// number of fractional bits required to represent the value of /// `significand`; otherwise, `significandWidth` is -1. The value of /// `significandWidth` is always -1 or between zero and /// `significandBitCount`. For example: /// /// - For any representable power of two, `significandWidth` is zero, because /// `significand` is `1.0`. /// - If `x` is 10, `x.significand` is `1.01` in binary, so /// `x.significandWidth` is 2. /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in /// binary, and `x.significandWidth` is 23. var significandWidth: Int { get } } extension FloatingPoint { @inlinable // FIXME(sil-serialize-all) public static var ulpOfOne: Self { return (1 as Self).ulp } @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self lhs.round(rule) return lhs } @_transparent public func rounded() -> Self { return rounded(.toNearestOrAwayFromZero) } @_transparent public mutating func round() { round(.toNearestOrAwayFromZero) } @inlinable // FIXME(inline-always) public var nextDown: Self { @inline(__always) get { return -(-self).nextUp } } @inlinable // FIXME(inline-always) @inline(__always) public func truncatingRemainder(dividingBy other: Self) -> Self { var lhs = self lhs.formTruncatingRemainder(dividingBy: other) return lhs } @inlinable // FIXME(inline-always) @inline(__always) public func remainder(dividingBy other: Self) -> Self { var lhs = self lhs.formRemainder(dividingBy: other) return lhs } @_transparent public func squareRoot( ) -> Self { var lhs = self lhs.formSquareRoot( ) return lhs } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var addend = self addend.addProduct(lhs, rhs) return addend } @inlinable public static func minimum(_ x: Self, _ y: Self) -> Self { if x <= y || y.isNaN { return x } return y } @inlinable public static func maximum(_ x: Self, _ y: Self) -> Self { if x > y || y.isNaN { return x } return y } @inlinable public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude <= y.magnitude || y.isNaN { return x } return y } @inlinable public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude > y.magnitude || y.isNaN { return x } return y } @inlinable public var floatingPointClass: FloatingPointClassification { if isSignalingNaN { return .signalingNaN } if isNaN { return .quietNaN } if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity } if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal } if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal } return sign == .minus ? .negativeZero : .positiveZero } } extension BinaryFloatingPoint { @inlinable @inline(__always) public static var radix: Int { return 2 } @inlinable public init(signOf: Self, magnitudeOf: Self) { self.init( sign: signOf.sign, exponentBitPattern: magnitudeOf.exponentBitPattern, significandBitPattern: magnitudeOf.significandBitPattern ) } public // @testable static func _convert<Source: BinaryFloatingPoint>( from source: Source ) -> (value: Self, exact: Bool) { guard _fastPath(!source.isZero) else { return (source.sign == .minus ? -0.0 : 0, true) } guard _fastPath(source.isFinite) else { if source.isInfinite { return (source.sign == .minus ? -.infinity : .infinity, true) } // IEEE 754 requires that any NaN payload be propagated, if possible. let payload_ = source.significandBitPattern & ~(Source.nan.significandBitPattern | Source.signalingNaN.significandBitPattern) let mask = Self.greatestFiniteMagnitude.significandBitPattern & ~(Self.nan.significandBitPattern | Self.signalingNaN.significandBitPattern) let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask // Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern, // we do not *need* to rely on this relation, and therefore we do not. let value = source.isSignalingNaN ? Self( sign: source.sign, exponentBitPattern: Self.signalingNaN.exponentBitPattern, significandBitPattern: payload | Self.signalingNaN.significandBitPattern) : Self( sign: source.sign, exponentBitPattern: Self.nan.exponentBitPattern, significandBitPattern: payload | Self.nan.significandBitPattern) // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. return (value, false) } let exponent = source.exponent var exemplar = Self.leastNormalMagnitude let exponentBitPattern: Self.RawExponent let leadingBitIndex: Int let shift: Int let significandBitPattern: Self.RawSignificand if exponent < exemplar.exponent { // The floating-point result is either zero or subnormal. exemplar = Self.leastNonzeroMagnitude let minExponent = exemplar.exponent if exponent + 1 < minExponent { return (source.sign == .minus ? -0.0 : 0, false) } if _slowPath(exponent + 1 == minExponent) { // Although the most significant bit (MSB) of a subnormal source // significand is explicit, Swift BinaryFloatingPoint APIs actually // omit any explicit MSB from the count represented in // significandWidth. For instance: // // Double.leastNonzeroMagnitude.significandWidth == 0 // // Therefore, we do not need to adjust our work here for a subnormal // source. return source.significandWidth == 0 ? (source.sign == .minus ? -0.0 : 0, false) : (source.sign == .minus ? -exemplar : exemplar, false) } exponentBitPattern = 0 as Self.RawExponent leadingBitIndex = Int(Self.Exponent(exponent) - minExponent) shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let leadingBit = source.isNormal ? (1 as Self.RawSignificand) << leadingBitIndex : 0 significandBitPattern = leadingBit | (shift >= 0 ? Self.RawSignificand(source.significandBitPattern) << shift : Self.RawSignificand(source.significandBitPattern >> -shift)) } else { // The floating-point result is either normal or infinite. exemplar = Self.greatestFiniteMagnitude if exponent > exemplar.exponent { return (source.sign == .minus ? -.infinity : .infinity, false) } exponentBitPattern = exponent < 0 ? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent) : (1 as Self).exponentBitPattern + Self.RawExponent(exponent) leadingBitIndex = exemplar.significandWidth shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let sourceLeadingBit = source.isSubnormal ? (1 as Source.RawSignificand) << (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) : 0 significandBitPattern = shift >= 0 ? Self.RawSignificand( sourceLeadingBit ^ source.significandBitPattern) << shift : Self.RawSignificand( (sourceLeadingBit ^ source.significandBitPattern) >> -shift) } let value = Self( sign: source.sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) if source.significandWidth <= leadingBitIndex { return (value, true) } // We promise to round to the closest representation. Therefore, we must // take a look at the bits that we've just truncated. let ulp = (1 as Source.RawSignificand) << -shift let truncatedBits = source.significandBitPattern & (ulp - 1) if truncatedBits < ulp / 2 { return (value, false) } let rounded = source.sign == .minus ? value.nextDown : value.nextUp if _fastPath(truncatedBits > ulp / 2) { return (rounded, false) } // If two representable values are equally close, we return the value with // more trailing zeros in its significand bit pattern. return significandBitPattern.trailingZeroBitCount > rounded.significandBitPattern.trailingZeroBitCount ? (value, false) : (rounded, false) } /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init<Source: BinaryFloatingPoint>(_ value: Source) { #if !os(macOS) && !(os(iOS) && targetEnvironment(macCatalyst)) if #available(iOS 14.0, watchOS 7.0, tvOS 14.0, *) { if case let value_ as Float16 = value { self = Self(Float(value_)) return } } #endif switch value { case let value_ as Float: self = Self(value_) case let value_ as Double: self = Self(value_) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) case let value_ as Float80: self = Self(value_) #endif default: self = Self._convert(from: value).value } } /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init?<Source: BinaryFloatingPoint>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } @inlinable public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool { // Quick return when possible. if self < other { return true } if other > self { return false } // Self and other are either equal or unordered. // Every negative-signed value (even NaN) is less than every positive- // signed value, so if the signs do not match, we simply return the // sign bit of self. if sign != other.sign { return sign == .minus } // Sign bits match; look at exponents. if exponentBitPattern > other.exponentBitPattern { return sign == .minus } if exponentBitPattern < other.exponentBitPattern { return sign == .plus } // Signs and exponents match, look at significands. if significandBitPattern > other.significandBitPattern { return sign == .minus } if significandBitPattern < other.significandBitPattern { return sign == .plus } // Sign, exponent, and significand all match. return true } } extension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger { public // @testable static func _convert<Source: BinaryInteger>( from source: Source ) -> (value: Self, exact: Bool) { // Useful constants: let exponentBias = (1 as Self).exponentBitPattern let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1 // Zero is really extra simple, and saves us from trying to normalize a // value that cannot be normalized. if _fastPath(source == 0) { return (0, true) } // We now have a non-zero value; convert it to a strictly positive value // by taking the magnitude. let magnitude = source.magnitude var exponent = magnitude._binaryLogarithm() // If the exponent would be larger than the largest representable // exponent, the result is just an infinity of the appropriate sign. guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } // If exponent <= significandBitCount, we don't need to round it to // construct the significand; we just need to left-shift it into place; // the result is always exact as we've accounted for exponent-too-large // already and no rounding can occur. if exponent <= Self.significandBitCount { let shift = Self.significandBitCount &- exponent let significand = RawSignificand(magnitude) &<< shift let value = Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ) return (value, true) } // exponent > significandBitCount, so we need to do a rounding right // shift, and adjust exponent if needed let shift = exponent &- Self.significandBitCount let halfway = (1 as Source.Magnitude) << (shift - 1) let mask = 2 * halfway - 1 let fraction = magnitude & mask var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask if fraction > halfway || (fraction == halfway && significand & 1 == 1) { var carry = false (significand, carry) = significand.addingReportingOverflow(1) if carry || significand > significandMask { exponent += 1 guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } } } return (Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ), fraction == 0) } /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init<Source: BinaryInteger>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init?<Source: BinaryInteger>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } }
apache-2.0
2a7915b08833aba96261b4ea0f3231eb
36.79312
94
0.63882
4.080919
false
false
false
false
adrian-kubala/MyPlaces
MyPlaces/CLLocationCoordinate2D+Address.swift
1
607
// // CLLocationCoordinate2D+Address.swift // MyPlaces // // Created by Adrian Kubała on 07.04.2017. // Copyright © 2017 Adrian Kubała. All rights reserved. // import GoogleMaps extension CLLocationCoordinate2D { func formattedAddress(completion: @escaping (String?) -> ()) { DispatchQueue.main.async { let geocoder = GMSGeocoder() geocoder.reverseGeocodeCoordinate(self) { (response, error) in let result = response?.results()?.first let address = result?.lines?.reduce("") { $0 == "" ? $1 : $0 + ", " + $1 } completion(address) } } } }
mit
873489efa394e8af31eab0bee403679a
24.166667
82
0.625828
3.822785
false
false
false
false
ConceptsInCode/PackageTracker
PackageTracker/PackageTracker/ViewController.swift
1
2759
// // ViewController.swift // PackageTracker // // Created by BJ on 4/26/15. // Copyright (c) 2015 Concepts In Code. All rights reserved. // import UIKit import Foundation import CoreData class ViewController: UIViewController, UITableViewDataSource { var items = [String]() internal lazy var packageManager: PackageManager = { USPSManager() }() @IBOutlet weak var tableView: UITableView! @IBOutlet weak var trackingTextField: UITextField! @IBOutlet weak var trackPackageButton: UIButton! @IBAction func showHistory(sender: AnyObject?) { performSegueWithIdentifier("showHistorySegue", sender: nil) } private func parse(data: NSData) -> Info { let xmlParser = NSXMLParser(data: data) let packageInfo = Info() xmlParser.delegate = packageInfo xmlParser.parse() return packageInfo } // MARK: UITableViewDataSource methods func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCellWithIdentifier("PackageStatusLineCell") else { return UITableViewCell() } cell.textLabel?.text = items[indexPath.row] return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } private func userIDFromJSON() -> String? { guard let filePath = NSBundle.mainBundle().pathForResource("USPSConfig", ofType: "json") else { return nil } let data = NSData(contentsOfFile: filePath)! let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) let userID = json["userID"] as! String return userID } func fetchPackageInfo(packageID packageID: String, completion: (Void -> Void)? = nil) { guard let userID = userIDFromJSON() else { self.items = ["There's nothing to see here"] self.tableView?.reloadData() return } let requestInfo = USPSRequestInfo(userID: userID, packageID: packageID) packageManager.fetchPackageResults(requestInfo) { [weak self] items in defer { self?.tableView.reloadData() } if items.isEmpty { self?.items = ["There's nothing to see here"] } else { self?.items = items completion?() } } } } extension ViewController : PackageDependencyInjectable { func updateDetailsForPackageID(packageID: String, completion: Void -> Void) { fetchPackageInfo(packageID: packageID, completion: completion) } }
mit
bf9987a8e044bcd804ed7ec83c40e3c3
31.081395
116
0.639725
5.043876
false
false
false
false
gaurav1981/ioscreator
IOS8SwiftReorderingRowsTutorial/IOS8SwiftReorderingRowsTutorial/TableViewController.swift
37
3405
// // TableViewController.swift // IOS8SwiftReorderingRowsTutorial // // Created by Arthur Knopper on 05/01/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class TableViewController: UITableViewController { var tableData = ["One","Two","Three","Four","Five"] @IBAction func startEditing(sender: UIBarButtonItem) { self.editing = !self.editing } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return tableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... cell.textLabel?.text = tableData[indexPath.row] return cell } override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { var itemToMove = tableData[fromIndexPath.row] tableData.removeAtIndex(fromIndexPath.row) tableData.insert(itemToMove, atIndex: toIndexPath.row) } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
2bed545fda3a40e340539fb0381beca7
32.058252
157
0.685463
5.456731
false
false
false
false
TheNounProject/CollectionView
CollectionView/Layouts/CollectionViewHorizontalLayout.swift
1
5697
// // CollectionViewHorizontalLayout.swift // Lingo // // Created by Wesley Byrne on 3/1/16. // Copyright © 2016 The Noun Project. All rights reserved. // import Foundation /// The delegate for CollectionViewHorizontalListLayout @objc public protocol CollectionViewDelegateHorizontalListLayout: CollectionViewDelegate { /// Asks the delegate for the width of the item at a given index path /// /// - Parameter collectionView: The collection view containing the item /// - Parameter collectionViewLayout: The layout /// - Parameter indexPath: The index path for the item /// /// - Returns: The desired width of the item at indexPath @objc optional func collectionView (_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout, widthForItemAt indexPath: IndexPath) -> CGFloat } /// A full height horizontal scrolling layout open class CollectionViewHorizontalListLayout: CollectionViewLayout { override open var scrollDirection: CollectionViewScrollDirection { return CollectionViewScrollDirection.horizontal } private var delegate: CollectionViewDelegateHorizontalListLayout? { return self.collectionView?.delegate as? CollectionViewDelegateHorizontalListLayout } open var sectionInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) open var itemWidth: CGFloat = 100 open var itemSpacing: CGFloat = 8 public var centerContent: Bool = false var cache = [[CGRect]]() var contentWidth: CGFloat = 0 open override func prepare() { cache = [] self.allIndexPaths.removeAll() guard let cv = self.collectionView else { return } let numSections = cv.numberOfSections var xPos: CGFloat = 0 for sectionIdx in 0..<numSections { xPos += sectionInsets.left var items = [CGRect]() let numItems = cv.numberOfItems(in: sectionIdx) for idx in 0..<numItems { let ip = IndexPath.for(item: idx, section: sectionIdx) self.allIndexPaths.append(ip) var height = cv.bounds.height height -= sectionInsets.height let width = self.delegate?.collectionView?(cv, layout: self, widthForItemAt: ip) ?? itemWidth var x = xPos if !items.isEmpty { x += self.itemSpacing } let frame = CGRect(x: x, y: sectionInsets.top, width: width, height: height).integral items.append(frame) xPos = x + width } self.cache.append(items) } contentWidth = xPos + sectionInsets.right let cvWidth = cv.contentVisibleRect.width if contentWidth < cvWidth { let adjust = (cvWidth - contentWidth)/2 self.cache = self.cache.map { sec in return sec.map { $0.offsetBy(dx: adjust, dy: 0) } } self.contentWidth += adjust } } var _size = CGSize.zero open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { if !newBounds.size.equalTo(_size) { self._size = newBounds.size return true } return false } open override var collectionViewContentSize: CGSize { let numberOfSections = self.collectionView!.numberOfSections if numberOfSections == 0 { return CGSize.zero } var contentSize = self.collectionView!.bounds.size as CGSize contentSize.width = contentWidth return contentSize } open override func scrollRectForItem(at indexPath: IndexPath, atPosition: CollectionViewScrollPosition) -> CGRect? { return layoutAttributesForItem(at: indexPath)?.frame } open override func rectForSection(_ section: Int) -> CGRect { guard let sectionItems = self.cache.object(at: section), !sectionItems.isEmpty else { return CGRect.zero } return sectionItems.reduce(CGRect.null) { partialResult, rect in return partialResult.union(rect) } } open override func contentRectForSection(_ section: Int) -> CGRect { return rectForSection(section) } open override func indexPathsForItems(in rect: CGRect) -> [IndexPath] { var ips = [IndexPath]() for (sectionIdx, section) in cache.enumerated() { for (idx, item) in section.enumerated() { if rect.intersects(item) { let ip = IndexPath.for(item: idx, section: sectionIdx) ips.append(ip) } } } return ips } open override func layoutAttributesForItem(at indexPath: IndexPath) -> CollectionViewLayoutAttributes? { let attrs = CollectionViewLayoutAttributes(forCellWith: indexPath) attrs.alpha = 1 attrs.zIndex = 1000 let frame = cache[indexPath._section][indexPath._item] attrs.frame = frame return attrs } } open class HorizontalCollectionView: CollectionView { override public init() { super.init() self.hasVerticalScroller = false self.hasHorizontalScroller = false } required public init?(coder: NSCoder) { super.init(coder: coder) self.hasVerticalScroller = false self.hasHorizontalScroller = false } }
mit
c433fe6ebdb2dc60fbff281fd3368bfb
33.944785
120
0.604459
5.373585
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotatePulse.swift
12
4387
// // NVActivityIndicatorAnimationBallClipRotatePulse.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallClipRotatePulse: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let duration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9) smallCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color) bigCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color) } func smallCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) { // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale") animation.keyTimes = [0, 0.3, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.3, 1] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circleSize = size.width / 2 let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } func bigCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] rotateAnimation.values = [0, Double.pi, 2 * Double.pi] rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle let circle = NVActivityIndicatorShape.ringTwoHalfVertical.layerWith(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
apache-2.0
dfc03be10f1a30577f550df49b62766b
43.313131
137
0.687714
4.945885
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Models/Balance/Price/PriceQuoteAtTime.swift
1
926
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit /// A quoted price in fiat, for one currency, at a specific timestamp. public struct PriceQuoteAtTime: Equatable { /// The timestamp of the quote. public let timestamp: Date /// The value of the quote. public let moneyValue: MoneyValue /// The total market cap of the currency. public let marketCap: Double? /// The total market cap of the currency. public let volume24h: Double? /// Creates a quoted price. /// /// - Parameters: /// - response: A timestamp. /// - currency: A value. public init( timestamp: Date, moneyValue: MoneyValue, marketCap: Double? = nil, volume24h: Double? = nil ) { self.timestamp = timestamp self.moneyValue = moneyValue self.marketCap = marketCap self.volume24h = volume24h } }
lgpl-3.0
aba3d0eeeacfa3cfc69e82a4b6fe71d8
24.694444
70
0.627027
4.383886
false
false
false
false
Jnosh/swift
test/Sema/diag_c_style_for.swift
7
2501
// FIXME(integers): with the new integer protocols, the compiler does not seem // to be able to recognize C-style loops and provide fixits. // <rdar://problem/29937314> // XFAIL: * // RUN: %target-typecheck-verify-swift for var a = 0; a < 10; a += 1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-13= in }} {{14-20= ..< }} {{22-27=}} } for var b = 0; b < 10; b += 1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-13= in }} {{14-20= ..< }} {{22-27=}} } for var c=1;c != 5 ;c += 1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-11= in }} {{12-18= ..< }} {{20-24=}} } for var d=100;d<5;d+=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-11= in }} {{14-17= ..< }} {{18-22=}} } // next three aren't auto-fixable for var e = 3; e > 4; e+=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{none}} } for var f = 3; f < 4; f-=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{none}} } for var i = 6; i > 0; i-=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-13= in }} {{13-13=((0 + 1)...}} {{14-14=).reversed()}} {{14-27=}} } for var i = 100; i != 0; i-=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-13= in }} {{13-13=((0 + 1)...}} {{16-16=).reversed()}} {{16-30=}} } let start = Int8(4) let count = Int8(10) var other = Int8(2) for ; other<count; other+=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{none}} } // this should be fixable, and keep the type for (var number : Int8 = start; number < count; number+=1) { // expected-error {{C-style for statement has been removed in Swift 3}} {{6-10=}} {{23-26= in }} {{31-42= ..< }} {{47-57=}} print(number) } // should produce extra note for (var m : Int8 = start; m < count; m+=1) { // expected-error {{C-style for statement has been removed in Swift 3}} {{none}} m += 3 } for var o = 2; o < 888; o += 1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{5-9=}} {{10-13= in }} {{14-20= ..< }} {{23-31=}} } for var o = 2; o < 888; o += 11 { // expected-error {{C-style for statement has been removed in Swift 3}} {{none}} } // could theoretically fix this with "..." for var p = 2; p <= 8; p+=1 { // expected-error {{C-style for statement has been removed in Swift 3}} {{none}} }
apache-2.0
1c9830cc8fa97a82333df211bc7a97c7
42.12069
184
0.587765
2.891329
false
false
false
false
pmfon/xcui-stringer
examples/xcuistringer-sampleUITests/xcuistringer_sampleUITests.swift
1
1758
// // xcuistringer_sampleUITests.swift // xcuistringer-sampleUITests // // Created by Pedro Fonseca on 05/11/16. // Copyright © 2016 Pedro Fonseca. All rights reserved. // import XCTest class xcuistringer_sampleUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testButton() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. let button = XCUIApplication().buttons["button"] button.tap() XCTAssert(button.label == "Eeeek!") let image = XCUIApplication().images["image"] XCTAssert(image.exists && image.isHittable) } func testButtonFail() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. XCTAssertTrue(false); } }
mit
21ba78331d0765f2a01264855e710837
34.816327
182
0.651852
4.861496
false
true
false
false
karwa/swift-corelibs-foundation
TestFoundation/TestNSHTTPCookie.swift
1
5043
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import PortableFoundation import SwiftXCTest #endif class TestNSHTTPCookie: XCTestCase { static var allTests: [(String, (TestNSHTTPCookie) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_RequestHeaderFields", test_RequestHeaderFields) ] } func test_BasicConstruction() { let invalidVersionZeroCookie = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/" ]) XCTAssertNil(invalidVersionZeroCookie) let minimalVersionZeroCookie = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieDomain: "apple.com" ]) XCTAssertNotNil(minimalVersionZeroCookie) XCTAssert(minimalVersionZeroCookie?.name == "TestCookie") XCTAssert(minimalVersionZeroCookie?.value == "Test value @#$%^$&*") XCTAssert(minimalVersionZeroCookie?.path == "/") XCTAssert(minimalVersionZeroCookie?.domain == "apple.com") let versionZeroCookieWithOriginURL = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ]) XCTAssert(versionZeroCookieWithOriginURL?.domain == "apple.com") // Domain takes precedence over originURL inference let versionZeroCookieWithDomainAndOriginURL = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieDomain: "apple.com", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ]) XCTAssert(versionZeroCookieWithDomainAndOriginURL?.domain == "apple.com") // This is implicitly a v0 cookie. Properties that aren't valid for v0 should fail. let versionZeroCookieWithInvalidVersionOneProps = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieDomain: "apple.com", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")!, NSHTTPCookieComment: "This comment should be nil since this is a v0 cookie.", NSHTTPCookieCommentURL: NSURL(string: "https://apple.com")!, NSHTTPCookieDiscard: "TRUE", NSHTTPCookieExpires: NSDate(timeIntervalSince1970: 1000), NSHTTPCookieMaximumAge: "2000", NSHTTPCookiePort: "443,8443", NSHTTPCookieSecure: "YES" ]) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.comment) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.commentURL) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.isSessionOnly == true) // v0 should never use NSHTTPCookieMaximumAge XCTAssert( versionZeroCookieWithInvalidVersionOneProps?.expiresDate?.timeIntervalSince1970 == NSDate(timeIntervalSince1970: 1000).timeIntervalSince1970 ) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.portList) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.isSecure == true) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.version == 0) } func test_RequestHeaderFields() { let noCookies: [NSHTTPCookie] = [] XCTAssertEqual(NSHTTPCookie.requestHeaderFields(with: noCookies)["Cookie"], "") let basicCookies: [NSHTTPCookie] = [ NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie1", NSHTTPCookieValue: "testValue1", NSHTTPCookiePath: "/", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ])!, NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie2", NSHTTPCookieValue: "testValue2", NSHTTPCookiePath: "/", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ])!, ] let basicCookieString = NSHTTPCookie.requestHeaderFields(with: basicCookies)["Cookie"] XCTAssertEqual(basicCookieString, "TestCookie1=testValue1; TestCookie2=testValue2") } }
apache-2.0
27e4bb12d26713f7872a3def6bec9679
42.102564
94
0.645053
6.127582
false
true
false
false
johankasperi/SwiftHSVColorPicker
Source/ColorWheel.swift
2
10319
// // ColorWheel.swift // SwiftHSVColorPicker // // Created by johankasperi on 2015-08-20. // import UIKit protocol ColorWheelDelegate: class { func hueAndSaturationSelected(_ hue: CGFloat, saturation: CGFloat) } class ColorWheel: UIView { var color: UIColor! // Layer for the Hue and Saturation wheel var wheelLayer: CALayer! // Overlay layer for the brightness var brightnessLayer: CAShapeLayer! var brightness: CGFloat = 1.0 // Layer for the indicator var indicatorLayer: CAShapeLayer! var point: CGPoint! var indicatorCircleRadius: CGFloat = 12.0 var indicatorColor: CGColor = UIColor.lightGray.cgColor var indicatorBorderWidth: CGFloat = 2.0 // Retina scaling factor let scale: CGFloat = UIScreen.main.scale weak var delegate: ColorWheelDelegate? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } init(frame: CGRect, color: UIColor!) { super.init(frame: frame) self.color = color // Layer for the Hue/Saturation wheel wheelLayer = CALayer() wheelLayer.frame = CGRect(x: 20, y: 20, width: self.frame.width-40, height: self.frame.height-40) wheelLayer.contents = createColorWheel(wheelLayer.frame.size) self.layer.addSublayer(wheelLayer) // Layer for the brightness brightnessLayer = CAShapeLayer() brightnessLayer.path = UIBezierPath(roundedRect: CGRect(x: 20.5, y: 20.5, width: self.frame.width-40.5, height: self.frame.height-40.5), cornerRadius: (self.frame.height-40.5)/2).cgPath self.layer.addSublayer(brightnessLayer) // Layer for the indicator indicatorLayer = CAShapeLayer() indicatorLayer.strokeColor = indicatorColor indicatorLayer.lineWidth = indicatorBorderWidth indicatorLayer.fillColor = nil self.layer.addSublayer(indicatorLayer) setViewColor(color); } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { indicatorCircleRadius = 18.0 touchHandler(touches) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { touchHandler(touches) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { indicatorCircleRadius = 12.0 touchHandler(touches) } func touchHandler(_ touches: Set<UITouch>) { // Set reference to the location of the touch in member point if let touch = touches.first { point = touch.location(in: self) } let indicator = getIndicatorCoordinate(point) point = indicator.point var color = (hue: CGFloat(0), saturation: CGFloat(0)) if !indicator.isCenter { color = hueSaturationAtPoint(CGPoint(x: point.x*scale, y: point.y*scale)) } self.color = UIColor(hue: color.hue, saturation: color.saturation, brightness: self.brightness, alpha: 1.0) // Notify delegate of the new Hue and Saturation delegate?.hueAndSaturationSelected(color.hue, saturation: color.saturation) // Draw the indicator drawIndicator() } func drawIndicator() { // Draw the indicator if (point != nil) { indicatorLayer.path = UIBezierPath(roundedRect: CGRect(x: point.x-indicatorCircleRadius, y: point.y-indicatorCircleRadius, width: indicatorCircleRadius*2, height: indicatorCircleRadius*2), cornerRadius: indicatorCircleRadius).cgPath indicatorLayer.fillColor = self.color.cgColor } } func getIndicatorCoordinate(_ coord: CGPoint) -> (point: CGPoint, isCenter: Bool) { // Making sure that the indicator can't get outside the Hue and Saturation wheel let dimension: CGFloat = min(wheelLayer.frame.width, wheelLayer.frame.height) let radius: CGFloat = dimension/2 let wheelLayerCenter: CGPoint = CGPoint(x: wheelLayer.frame.origin.x + radius, y: wheelLayer.frame.origin.y + radius) let dx: CGFloat = coord.x - wheelLayerCenter.x let dy: CGFloat = coord.y - wheelLayerCenter.y let distance: CGFloat = sqrt(dx*dx + dy*dy) var outputCoord: CGPoint = coord // If the touch coordinate is outside the radius of the wheel, transform it to the edge of the wheel with polar coordinates if (distance > radius) { let theta: CGFloat = atan2(dy, dx) outputCoord.x = radius * cos(theta) + wheelLayerCenter.x outputCoord.y = radius * sin(theta) + wheelLayerCenter.y } // If the touch coordinate is close to center, focus it to the very center at set the color to white let whiteThreshold: CGFloat = 10 var isCenter = false if (distance < whiteThreshold) { outputCoord.x = wheelLayerCenter.x outputCoord.y = wheelLayerCenter.y isCenter = true } return (outputCoord, isCenter) } func createColorWheel(_ size: CGSize) -> CGImage { // Creates a bitmap of the Hue Saturation wheel let originalWidth: CGFloat = size.width let originalHeight: CGFloat = size.height let dimension: CGFloat = min(originalWidth*scale, originalHeight*scale) let bufferLength: Int = Int(dimension * dimension * 4) let bitmapData: CFMutableData = CFDataCreateMutable(nil, 0) CFDataSetLength(bitmapData, CFIndex(bufferLength)) let bitmap = CFDataGetMutableBytePtr(bitmapData) for y in stride(from: CGFloat(0), to: dimension, by: CGFloat(1)) { for x in stride(from: CGFloat(0), to: dimension, by: CGFloat(1)) { var hsv: HSV = (hue: 0, saturation: 0, brightness: 0, alpha: 0) var rgb: RGB = (red: 0, green: 0, blue: 0, alpha: 0) let color = hueSaturationAtPoint(CGPoint(x: x, y: y)) let hue = color.hue let saturation = color.saturation var a: CGFloat = 0.0 if (saturation < 1.0) { // Antialias the edge of the circle. if (saturation > 0.99) { a = (1.0 - saturation) * 100 } else { a = 1.0; } hsv.hue = hue hsv.saturation = saturation hsv.brightness = 1.0 hsv.alpha = a rgb = hsv2rgb(hsv) } let offset = Int(4 * (x + y * dimension)) bitmap?[offset] = UInt8(rgb.red*255) bitmap?[offset + 1] = UInt8(rgb.green*255) bitmap?[offset + 2] = UInt8(rgb.blue*255) bitmap?[offset + 3] = UInt8(rgb.alpha*255) } } // Convert the bitmap to a CGImage let colorSpace: CGColorSpace? = CGColorSpaceCreateDeviceRGB() let dataProvider: CGDataProvider? = CGDataProvider(data: bitmapData) let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo().rawValue | CGImageAlphaInfo.last.rawValue) let imageRef: CGImage? = CGImage(width: Int(dimension), height: Int(dimension), bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(dimension) * 4, space: colorSpace!, bitmapInfo: bitmapInfo, provider: dataProvider!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent) return imageRef! } func hueSaturationAtPoint(_ position: CGPoint) -> (hue: CGFloat, saturation: CGFloat) { // Get hue and saturation for a given point (x,y) in the wheel let c = wheelLayer.frame.width * scale / 2 let dx = CGFloat(position.x - c) / c let dy = CGFloat(position.y - c) / c let d = sqrt(CGFloat (dx * dx + dy * dy)) let saturation: CGFloat = d var hue: CGFloat if (d == 0) { hue = 0; } else { hue = acos(dx/d) / CGFloat(M_PI) / 2.0 if (dy < 0) { hue = 1.0 - hue } } return (hue, saturation) } func pointAtHueSaturation(_ hue: CGFloat, saturation: CGFloat) -> CGPoint { // Get a point (x,y) in the wheel for a given hue and saturation let dimension: CGFloat = min(wheelLayer.frame.width, wheelLayer.frame.height) let radius: CGFloat = saturation * dimension / 2 let x = dimension / 2 + radius * cos(hue * CGFloat(M_PI) * 2) + 20; let y = dimension / 2 + radius * sin(hue * CGFloat(M_PI) * 2) + 20; return CGPoint(x: x, y: y) } func setViewColor(_ color: UIColor!) { // Update the entire view with a given color var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if (!ok) { print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>") } self.color = color self.brightness = brightness brightnessLayer.fillColor = UIColor(white: 0, alpha: 1.0-self.brightness).cgColor point = pointAtHueSaturation(hue, saturation: saturation) drawIndicator() } func setViewBrightness(_ _brightness: CGFloat) { // Update the brightness of the view var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if (!ok) { print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>") } self.brightness = _brightness brightnessLayer.fillColor = UIColor(white: 0, alpha: 1.0-self.brightness).cgColor self.color = UIColor(hue: hue, saturation: saturation, brightness: _brightness, alpha: 1.0) drawIndicator() } }
mit
d691c75f8d60ad8877eedbc685c03a3a
39.948413
313
0.602675
4.426855
false
false
false
false
Tardis-x/iOS
Tardis/APPImages.swift
2
869
// // CHImages.swift // ChampySwift // // Created by Molnar Kristian on 5/4/16. // Copyright © 2016 AzinecLLC. All rights reserved. // import UIKit import Kingfisher import SwiftyJSON class APPImages: NSObject { func setUpBackground(imageView:UIImageView, urlString:String) { imageView.layer.masksToBounds = true let url = NSURL(string: urlString) var cachename = urlString let myCache = ImageCache(name: cachename) let optionInfo: KingfisherOptionsInfo = [ .TargetCache(myCache), .DownloadPriority(1), .Transition(ImageTransition.Fade(1)) ] imageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "Google"), optionsInfo: optionInfo, progressBlock: { (receivedSize, totalSize) in }) { (image, error, cacheType, imageURL) in } } }
apache-2.0
cbfa9c88bac56fbcc7b832af77d7d72e
19.666667
153
0.656682
4.15311
false
false
false
false
tarbrain/OHHTTPStubs
OHHTTPStubs/Sources/Swift/OHHTTPStubsSwift.swift
2
7778
/*********************************************************************************** * * Copyright (c) 2012 Olivier Halligon * * 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. * ***********************************************************************************/ /** * Swift Helpers */ // MARK: Syntaxic Sugar for OHHTTPStubs /** * Helper to return a `OHHTTPStubsResponse` given a fixture path, status code and optional headers. * * - Parameter filePath: the path of the file fixture to use for the response * - Parameter status: the status code to use for the response * - Parameter headers: the HTTP headers to use for the response * * - Returns: The `OHHTTPStubsResponse` instance that will stub with the given status code * & headers, and use the file content as the response body. */ public func fixture(filePath: String, status: Int32 = 200, headers: [NSObject: AnyObject]?) -> OHHTTPStubsResponse { return OHHTTPStubsResponse(fileAtPath: filePath, statusCode: status, headers: headers) } /** * Helper to call the stubbing function in a more concise way? * * - Parameter condition: the matcher block that determine if the request will be stubbed * - Parameter response: the stub reponse to use if the request is stubbed * * - Returns: The opaque `OHHTTPStubsDescriptor` that uniquely identifies the stub * and can be later used to remove it with `removeStub:` */ public func stub(condition: OHHTTPStubsTestBlock, response: OHHTTPStubsResponseBlock) -> OHHTTPStubsDescriptor { return OHHTTPStubs.stubRequestsPassingTest(condition, withStubResponse: response) } // MARK: Create OHHTTPStubsTestBlock matchers /** * Matcher testing that the `NSURLRequest` is using the **GET** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the GET method */ public func isMethodGET() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "GET" } } /** * Matcher testing that the `NSURLRequest` is using the **POST** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the POST method */ public func isMethodPOST() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "POST" } } /** * Matcher testing that the `NSURLRequest` is using the **PUT** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the PUT method */ public func isMethodPUT() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "PUT" } } /** * Matcher testing that the `NSURLRequest` is using the **DELETE** `HTTPMethod` * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * is using the DELETE method */ public func isMethodDELETE() -> OHHTTPStubsTestBlock { return { $0.HTTPMethod == "DELETE" } } /** * Matcher for testing an `NSURLRequest`'s **scheme**. * * - Parameter scheme: The scheme to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has the given scheme */ public func isScheme(scheme: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.scheme == scheme } } /** * Matcher for testing an `NSURLRequest`'s **host**. * * - Parameter host: The host to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has the given host */ public func isHost(host: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.host == host } } /** * Matcher for testing an `NSURLRequest`'s **path**. * * - Parameter path: The path to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has exactly the given path * * - Note: URL paths are usually absolute and thus starts with a '/' (which you * should include in the `path` parameter unless you're testing relative URLs) */ public func isPath(path: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.path == path } } /** * Matcher for testing an `NSURLRequest`'s **path extension**. * * - Parameter ext: The file extension to match (without the dot) * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request path * ends with the given extension */ public func isExtension(ext: String) -> OHHTTPStubsTestBlock { return { req in req.URL?.pathExtension == ext } } /** * Matcher for testing an `NSURLRequest`'s **query parameters**. * * - Parameter params: The dictionary of query parameters to check the presence for * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds if the request contains * the given query parameters with the given value. * * - Note: There is a difference between: * (1) using `[q:""]`, which matches a query parameter "?q=" with an empty value, and * (2) using `[q:nil]`, which matches a query parameter "?q" without a value at all */ @available(iOS 8.0, OSX 10.10, *) public func containsQueryParams(params: [String:String?]) -> OHHTTPStubsTestBlock { return { req in if let url = req.URL { let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) if let queryItems = comps?.queryItems { for (k,v) in params { if queryItems.filter({ qi in qi.name == k && qi.value == v }).count == 0 { return false } } return true } } return false } } // MARK: Operators on OHHTTPStubsTestBlock /** * Combine different `OHHTTPStubsTestBlock` matchers with an 'OR' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`OHHTTPStubsTestBlock`) that succeeds if either of the given matchers succeeds */ public func || (lhs: OHHTTPStubsTestBlock, rhs: OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in lhs(req) || rhs(req) } } /** * Combine different `OHHTTPStubsTestBlock` matchers with an 'AND' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`OHHTTPStubsTestBlock`) that only succeeds if both of the given matchers succeeds */ public func && (lhs: OHHTTPStubsTestBlock, rhs: OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in lhs(req) && rhs(req) } } /** * Create the opposite of a given `OHHTTPStubsTestBlock` matcher. * * - Parameter expr: the matcher to negate * * - Returns: a matcher (OHHTTPStubsTestBlock) that only succeeds if the expr matcher fails */ public prefix func ! (expr: OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in !expr(req) } }
mit
b947a27be273954ff3e63767886fcf1b
34.354545
116
0.679738
4.452204
false
true
false
false
GraphKit/MaterialKit
Sources/iOS/Depth.swift
3
3627
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(DepthPreset) public enum DepthPreset: Int { case none case depth1 case depth2 case depth3 case depth4 case depth5 } public struct Depth { /// Offset. public var offset: Offset /// Opacity. public var opacity: Float /// Radius. public var radius: CGFloat /// Preset. public var preset = DepthPreset.none { didSet { let depth = DepthPresetToValue(preset: preset) offset = depth.offset opacity = depth.opacity radius = depth.radius } } /** Initializer that takes in an offset, opacity, and radius. - Parameter offset: UIOffset. - Parameter opacity: Float. - Parameter radius: CGFloat. */ public init(offset: Offset = .zero, opacity: Float = 0, radius: CGFloat = 0) { self.offset = offset self.opacity = opacity self.radius = radius } /** Initializer that takes in a DepthPreset. - Parameter preset: DepthPreset. */ public init(preset: DepthPreset) { self.init() self.preset = preset } /** Static constructor for Depth with values of 0. - Returns: A Depth struct with values of 0. */ static var zero: Depth { return Depth() } } /// Converts the DepthPreset enum to a Depth value. public func DepthPresetToValue(preset: DepthPreset) -> Depth { switch preset { case .none: return .zero case .depth1: return Depth(offset: Offset(horizontal: 0, vertical: 0.5), opacity: 0.3, radius: 0.5) case .depth2: return Depth(offset: Offset(horizontal: 0, vertical: 1), opacity: 0.3, radius: 1) case .depth3: return Depth(offset: Offset(horizontal: 0, vertical: 2), opacity: 0.3, radius: 2) case .depth4: return Depth(offset: Offset(horizontal: 0, vertical: 4), opacity: 0.3, radius: 4) case .depth5: return Depth(offset: Offset(horizontal: 0, vertical: 8), opacity: 0.3, radius: 8) } }
agpl-3.0
95367446db696ffe0bcd9d7fa60c8464
32.275229
93
0.681004
4.154639
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/Login/View/LoginViewController.swift
1
2624
import UIKit.UIButton import UIKit.UIViewController class LoginViewController: UITableViewController, UITextFieldDelegate, LoginScene { // MARK: IBOutlets @IBOutlet private weak var loginButton: UIButton! { didSet { loginButton.accessibilityIdentifier = "org.eurofurence.login.confirm-button" } } @IBOutlet private weak var cancelButton: UIBarButtonItem! @IBOutlet private weak var registrationNumberTextField: UITextField! { didSet { registrationNumberTextField.accessibilityIdentifier = "org.eurofurence.login.registration-number" } } @IBOutlet private weak var usernameTextField: UITextField! { didSet { usernameTextField.accessibilityIdentifier = "org.eurofurence.login.username" } } @IBOutlet private weak var passwordTextField: UITextField! { didSet { passwordTextField.accessibilityIdentifier = "org.eurofurence.login.password" } } // MARK: IBActions @IBAction private func loginButtonTapped(_ sender: Any) { delegate?.loginSceneDidTapLoginButton() } @IBAction private func cancelButtonTapped(_ sender: Any) { delegate?.loginSceneDidTapCancelButton() } @IBAction private func registrationNumberDidChange(_ sender: UITextField) { guard let registrationNumber = sender.text else { return } delegate?.loginSceneDidUpdateRegistrationNumber(registrationNumber) } @IBAction private func usernameDidChange(_ sender: UITextField) { guard let username = sender.text else { return } delegate?.loginSceneDidUpdateUsername(username) } @IBAction private func passwordDidChange(_ sender: UITextField) { guard let password = sender.text else { return } delegate?.loginSceneDidUpdatePassword(password) } @IBAction private func passwordPrimaryActionTriggered(_ sender: Any) { delegate?.loginSceneDidTapLoginButton() } // MARK: Overrides override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) delegate?.loginSceneWillAppear() } // MARK: LoginScene var delegate: LoginSceneDelegate? func setLoginTitle(_ title: String) { super.title = title } func overrideRegistrationNumber(_ registrationNumber: String) { registrationNumberTextField.text = registrationNumber } func disableLoginButton() { loginButton.isEnabled = false } func enableLoginButton() { loginButton.isEnabled = true } }
mit
c0a883580a9bc747e2907b0fd9012750
27.835165
109
0.680259
5.466667
false
false
false
false
wbsmessi/DECMA
DECMA/DECTopBarView.swift
1
4614
// // DECTopBar.swift // DECMA // // Created by 马志敏 on 2017/6/5. // Copyright © 2017年 DEC.MA. All rights reserved. // import UIKit protocol DECTopBarViewDelegate { func DECTopBarItemSelected(barView:DECTopBarView,index:Int,selectedTitle:String) } class DECTopBarView: UIView { var typeValue:[String]! var typedelegate:DECTopBarViewDelegate? var item_width:CGFloat = 100 //未选中的字体颜色 var defaultColor = UIColor.black // 选中的字体颜色 var selectedColor = UIColor.blue override init(frame: CGRect) { super.init(frame: frame) } let bgscrollView = UIScrollView() init(frame: CGRect,value:[String]) { super.init(frame: frame) self.typeValue = value let wid = self.frame.width/CGFloat(value.count) self.item_width = wid > 100 ? wid:100 bgscrollView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) bgscrollView.backgroundColor = UIColor.white bgscrollView.contentSize = CGSize(width: CGFloat(typeValue.count) * item_width, height: bgscrollView.frame.height) bgscrollView.showsHorizontalScrollIndicator = false bgscrollView.showsVerticalScrollIndicator = false self.addSubview(bgscrollView) let bottomline = CALayer() bottomline.frame = CGRect(x: 0, y: bgscrollView.frame.height - 1, width: bgscrollView.frame.width, height: 1) bottomline.backgroundColor = UIColor.lightGray.cgColor self.layer.addSublayer(bottomline) self.creatView(array: typeValue) } func creatView(array: [String]){ // self.frame.width self.backgroundColor = UIColor.white initWithArray(array: array) } func initWithArray(array: [String]) { for i in 0..<array.count{ creatItem(index: i, title: array[i]) } } func creatItem(index:Int,title:String){ let btn = UIButton() //防止冲突,设置大些 btn.tag = index + 1000 btn.frame = CGRect(x: CGFloat(index) * item_width, y: 0, width: item_width, height: self.frame.height) btn.setTitle(title, for: .normal) btn.setTitleColor(defaultColor, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: 5) // btn.backgroundColor = UIColor.red bgscrollView.addSubview(btn) btn.addTarget(self, action: #selector(choseItem), for: .touchUpInside) let bottomBorder = CALayer() bottomBorder.frame = CGRect(x: btn.frame.width/4, y: btn.frame.height - 7, width: btn.frame.width/2, height: 2) bottomBorder.backgroundColor = UIColor.clear.cgColor btn.layer.addSublayer(bottomBorder) //设置第一个item选中 if index == 0{ btn.setTitleColor(selectedColor, for: .normal) bottomBorder.backgroundColor = selectedColor.cgColor self.selectedBtn = btn } } var selectedBtn:UIButton! func choseItem(btn:UIButton){ let currentTag:Int = btn.tag - 1000 DispatchQueue.main.async { //上一个还原 self.selectedBtn.setTitleColor(self.defaultColor, for: .normal) self.selectedBtn.layer.sublayers?.last?.backgroundColor = UIColor.clear.cgColor //标记新的item btn.setTitleColor(self.selectedColor, for: .normal) btn.layer.sublayers?.last?.backgroundColor = self.selectedColor.cgColor let title = self.typeValue[currentTag] self.typedelegate?.DECTopBarItemSelected(barView: self, index: currentTag,selectedTitle:title) self.selectedBtn = btn //做滚动 let current_x = self.item_width * CGFloat(currentTag) if current_x >= self.frame.width/2{ if current_x + self.frame.width/2 > CGFloat(self.typeValue.count) * self.item_width{ self.bgscrollView.setContentOffset(CGPoint(x: CGFloat(self.typeValue.count) * self.item_width - self.frame.width, y: 0), animated: true) }else{ self.bgscrollView.setContentOffset(CGPoint(x: current_x - self.frame.width/2, y: 0), animated: true) } }else{ self.bgscrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
69de061e51a66a8968eec4a26668ab40
36.658333
156
0.621155
4.126941
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Dialog/HBCIDialog.swift
1
18126
// // HBCIDialog.swift // HBCI4Swift // // Created by Frank Emminghaus on 07.01.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation open class HBCIDialog { let product:String; let version:String; var connection:HBCIConnection! var dialogId:String? var user:HBCIUser; var hbciVersion:String! // todo: replace with let once Xcode bug is fixed var syntax:HBCISyntax! // todo: replace with let once Xcode bug is fixed var messageNum = 1; var orders = Array<HBCIOrder>(); // the callback handler public static var callback:HBCICallback? public init(user:HBCIUser, product:String, version:String = "100") throws { self.product = product; self.version = version; self.user = user; self.hbciVersion = user.hbciVersion; if user.securityMethod == nil { logInfo("Security method for user not defined"); throw HBCIError.missingData("SecurityMethod"); } self.syntax = try HBCISyntax.syntaxWithVersion(hbciVersion); if user.securityMethod is HBCISecurityMethodDDV { self.connection = try HBCIDDVConnection(host: user.bankURL); return; } else { if let url = URL(string:user.bankURL) { self.connection = HBCIPinTanConnection(url: url); return; } else { logInfo("Could not create URL from \(user.bankURL)"); throw HBCIError.badURL(user.bankURL); } } } func sendMessage(_ message:String, values:Dictionary<String,Any>) throws ->HBCIResultMessage? { if let md = self.syntax.msgs[message] { if let msg = md.compose() as? HBCIMessage { for (path, value) in values { if !msg.setElementValue(value, path: path) { return nil; } } return try sendMessage(msg); } } return nil; } func sendMessage(_ msg:HBCIMessage) throws ->HBCIResultMessage? { if !msg.enumerateSegments() { logInfo(msg.description); return nil; } if !user.securityMethod.signMessage(msg) { logInfo(msg.description); return nil; } if !msg.finalize() { logInfo(msg.description); return nil; } if !msg.validate() { logInfo(msg.description); return nil; } logDebug("Message payload:"); logDebug(msg.messageString()); if let msg_crypted = user.securityMethod.encryptMessage(msg, dialog: self) { if !msg_crypted.validate() { logInfo(msg_crypted.description); return nil; } let msgData = msg_crypted.messageData(); logDebug("Encrypted message:"); logDebug(msg_crypted.messageString()); // send message to bank do { let result = try self.connection.sendMessage(msgData); logDebug("Message received:"); logDebug(HBCIResultMessage.debugDescription(result)); let resultMsg_crypted = HBCIResultMessage(syntax: self.syntax); if resultMsg_crypted.parse(result) { if let dialogId = resultMsg_crypted.valueForPath("MsgHead.dialogid") as? String { self.dialogId = dialogId; } self.messageNum += 1; if let value = user.securityMethod.decryptMessage(resultMsg_crypted, dialog: self) { if try value.checkResponses() { logDebug("Result Message:"); logDebug(value.description); return value } else { logDebug("Message received:"); logDebug(HBCIResultMessage.debugDescription(result)); logInfo("Message sent:"); logInfo(msg.messageString()); return value; } } logInfo("Message could not be decrypted"); logDebug(HBCIResultMessage.debugDescription(result)); logDebug(data: result); logInfo("Message sent:"); logInfo(msg.messageString()); // return unencrypted result at least to be able to check for responses let _ = try resultMsg_crypted.checkResponses(); return resultMsg_crypted; } else { logInfo("Message could not be parsed"); logDebug(HBCIResultMessage.debugDescription(result)); logDebug(data: result); return nil; } } catch { logInfo("Message sent: " + msg.messageString()); throw error; } } return nil; } func checkBPD_for_PSD2(_ resultMsg: HBCIResultMessage) { if resultMsg.isBankInPSD2Migration() { // now we are in PSD2 migration phase - start anonymous dialog to get "real" BPD/HIPINS do { let dialog = try HBCIAnonymousDialog(hbciVersion: hbciVersion, product: product); if let url = URL(string: user.bankURL) { if let result = try dialog.dialogWithURL(url, bankCode: user.bankCode) { if result.isOk() { user.parameters.bpdVersion = 0; // make sure parameters are updated result.updateParameterForUser(user); } else { logInfo("Anonymous dialog failed or is not supported"); } } else { logInfo("Anonymous dialog failed with no result"); } } else { logInfo("Unable to create URL from string " + user.bankURL); } } catch { logInfo("Anonymous dialog failed with exception"); } } } open func dialogInit() throws ->HBCIResultMessage? { if user.sysId == nil { logInfo("Dialog Init failed: missing sysId"); return nil; } var values:Dictionary<String,Any> = ["Idn.KIK.country":"280", "Idn.KIK.blz":user.bankCode, "Idn.customerid":user.customerId, "Idn.sysid":user.sysId!, "Idn.sysStatus":"1", "ProcPrep.BPD":user.parameters.bpdVersion, "ProcPrep.UPD":user.parameters.updVersion, "ProcPrep.lang":"1", "ProcPrep.prodName":product, "ProcPrep.prodVersion":version ]; if user.securityMethod is HBCISecurityMethodDDV { values["Idn.sysStatus"] = "0"; } self.dialogId = "0"; guard let msg = HBCIDialogInitMessage.newInstance(self) else { logInfo("Dialog Init failed: message could not be created"); return nil; } if !msg.setElementValues(values) { logInfo("Dialog Init failed: messages values could not be set)"); return nil; } guard try msg.send() else { logInfo("Dialog Init failed: message could not be sent"); return nil; } if let result = msg.result { if result.isOk() { result.updateParameterForUser(self.user); checkBPD_for_PSD2(result); return result; } } return nil; } open func dialogEnd() ->HBCIResultMessage? { if let dialogId = self.dialogId { let values:Dictionary<String,Any> = ["DialogEnd.dialogid":dialogId, "MsgHead.dialogid":dialogId, "MsgHead.msgnum":messageNum, "MsgTail.msgnum":messageNum]; do { if let result = try sendMessage("DialogEnd", values: values) { self.connection.close(); self.messageNum = 1; return result; } } catch { }; } self.connection.close(); self.messageNum = 1; return nil; } open func getBankTanMethods() -> [HBCITanMethod]? { // start anonymous dialog do { let dialog = try HBCIAnonymousDialog(hbciVersion: hbciVersion, product: product); if let url = URL(string: user.bankURL) { if let result = try dialog.dialogWithURL(url, bankCode: user.bankCode) { if result.isOk() || result.hasParameterSegments() { user.parameters.bpdVersion = 0; // make sure parameters are updated result.updateParameterForUser(user); return user.parameters.getAllTanMethods(); } } else { logInfo("Anonymous dialog failed with no result"); } } else { logInfo("Unable to create URL from string " + user.bankURL); } } catch { logInfo("Anonymous dialog failed with exception"); } return nil; } /* open func getTanMethods() throws ->HBCIResultMessage? { user.tanMethod = "999"; user.sysId = "0"; let values:Dictionary<String,Any> = ["Idn.KIK.country":"280", "Idn.KIK.blz":user.bankCode, "Idn.customerid":user.customerId, "Idn.sysid":"0", "Idn.sysStatus":"1", "ProcPrep.BPD":"0", "ProcPrep.UPD":"0", "ProcPrep.lang":"0", "ProcPrep.prodName":product, "ProcPrep.prodVersion":version]; self.dialogId = "0"; if let result = try sendMessage("DialogInit", values: values) { if result.isOk() { result.updateParameterForUser(self.user); checkBPD_for_PSD2(result); return result; } } return nil; } */ open func syncInitWithTan(_ tanMethod:String) throws -> HBCIResultMessage? { user.tanMethod = tanMethod; user.sysId = "0"; let values:Dictionary<String,Any> = ["Idn.KIK.country":"280", "Idn.KIK.blz":user.bankCode, "Idn.customerid":user.customerId, "Idn.sysid":"0", "Idn.sysStatus":"1", "ProcPrep.BPD":"0", "Sync.mode":0, "ProcPrep.UPD":"0", "ProcPrep.lang":"1", "ProcPrep.prodName":product, "ProcPrep.prodVersion":version]; self.dialogId = "0"; guard let msg = HBCISynchronizeMessage.newInstance(self) else { logInfo("Dialog Init failed: message could not be created"); return nil; } if !msg.setElementValues(values) { logInfo("Dialog Init failed: messages values could not be set)"); return nil; } guard try msg.send() else { logInfo("Dialog Init failed: message could not be sent"); self.messageNum = 1; return nil; } if let result = msg.result { if result.isOk() { result.updateParameterForUser(self.user); checkBPD_for_PSD2(result); for seg in result.segments { if seg.name == "SyncRes" { user.sysId = seg.elementValueForPath("sysid") as? String; if user.sysId == nil { logInfo("SysID could not be found"); } } } return result; } } self.messageNum = 1; return nil; } open func syncInit(_ tanMethod:String = "999") throws ->HBCIResultMessage? { user.tanMethod = tanMethod; user.sysId = "0"; let values:Dictionary<String,Any> = ["Idn.KIK.country":"280", "Idn.KIK.blz":user.bankCode, "Idn.customerid":user.customerId, "Idn.sysid":"0", "Idn.sysStatus":"1", "ProcPrep.BPD":"0", "Sync.mode":0, "ProcPrep.UPD":"0", "ProcPrep.lang":"1", "ProcPrep.prodName":product, "ProcPrep.prodVersion":version]; self.dialogId = "0"; /* guard let msg = HBCISynchronizeMessage.newInstance(self) else { logInfo("Dialog Init failed: message could not be created"); return nil; } if !msg.setElementValues(values) { logInfo("Dialog Init failed: messages values could not be set)"); return nil; } guard try msg.send() else { logInfo("Dialog Init failed: message could not be sent"); return nil; } if let result = msg.result { if result.isOk() { result.updateParameterForUser(self.user); checkBPD_for_PSD2(result); for seg in result.segments { if seg.name == "SyncRes" { user.sysId = seg.elementValueForPath("sysid") as? String; if user.sysId == nil { logInfo("SysID could not be found"); } } } return result; } } */ if let result = try sendMessage("Synchronize", values: values) { if result.isOk() { result.updateParameterForUser(self.user); checkBPD_for_PSD2(result); for seg in result.segments { if seg.name == "SyncRes" { user.sysId = seg.elementValueForPath("sysid") as? String; if user.sysId == nil { logInfo("SysID could not be found"); } } } } else { self.messageNum = 1; } return result; } self.messageNum = 1; return nil; } open func tanMediaInit() throws ->HBCIResultMessage? { if user.sysId == nil { logInfo("TanMediaDialog Init failed: missing sysId"); return nil; } var values:Dictionary<String,Any> = ["Idn.KIK.country":"280", "Idn.KIK.blz":user.bankCode, "Idn.customerid":user.customerId, "Idn.sysid":user.sysId!, "Idn.sysStatus":"1", "ProcPrep.BPD":user.parameters.bpdVersion, "ProcPrep.UPD":user.parameters.updVersion, "ProcPrep.lang":"1", "ProcPrep.prodName":product, "ProcPrep.prodVersion":version ]; if user.securityMethod is HBCISecurityMethodDDV { values["Idn.sysStatus"] = "0"; } self.dialogId = "0"; guard let msg = HBCITanMediaDialogInitMessage.newInstance(self) else { logInfo("TanMediaDialog Init failed: message could not be created"); return nil; } if !msg.setElementValues(values) { logInfo("TanMediaDialog Init failed: messages values could not be set)"); return nil; } guard try msg.send() else { logInfo("TanMediaDialog Init failed: message could not be sent"); return nil; } if let result = msg.result { if result.isOk() { result.updateParameterForUser(self.user); checkBPD_for_PSD2(result); return result; } } return nil; } }
gpl-2.0
5bc5ee643046e639fd127191df7b89ac
38.404348
104
0.448803
5.293808
false
false
false
false
pkluz/PKLocationManager
PKLocationManager/LocationMonitor.swift
2
793
// // PKLocationMonitor.swift // PKLocationManager // // Created by Philip Kluz on 6/20/14. // Copyright (c) 2014 NSExceptional. All rights reserved. // import Foundation import CoreLocation final internal class LocationMonitor { internal var monitoringObject: AnyObject internal var queue: dispatch_queue_t internal var handler: ((CLLocation) -> ())? internal var desiredAccuracy: CLLocationAccuracy internal init(monitoringObject object: AnyObject, queue: dispatch_queue_t = dispatch_get_main_queue(), desiredAccuracy: CLLocationAccuracy = kCLLocationAccuracyHundredMeters, handler: ((CLLocation) -> ())?) { self.monitoringObject = object self.queue = queue self.desiredAccuracy = desiredAccuracy self.handler = handler } }
mit
253c22f225b712cd57568e6bac272e9a
32.041667
212
0.718789
4.777108
false
false
false
false
paulofaria/SwiftHTTPServer
Libuv/UVStream.swift
3
5121
// Stream.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. typealias StreamRef = UnsafeMutablePointer<uv_stream_t> typealias WriteRef = UnsafeMutablePointer<uv_write_t> typealias ReadBlock = ReadResult -> Void typealias ListenBlock = (status: Int) -> Void enum ReadResult { case Chunk(Data) case EOF case Error(UVError) } class StreamContext { var readBlock: ReadBlock? var listenBlock: ListenBlock? } class UVStream { var stream: StreamRef init(_ stream: StreamRef) { self.stream = stream } func accept(client: UVStream) throws { let result = uv_accept(stream, client.stream) if result < 0 { throw UVError.Error(code: result) } } func listen(backlog numConnections: Int, callback: uv_connection_cb) throws { let result = uv_listen(stream, Int32(numConnections), callback) if result < 0 { throw UVError.Error(code: result) } } func close() { _context = nil uv_close(HandleRef(stream)) { handle in free(handle) } } } class WriteCompletionHandler { var completion: (Void -> Void)? init(_ completion: (Void -> Void)?) { self.completion = completion } } extension UVStream { var context: StreamContext { if _context == nil { _context = StreamContext() } return _context! } var _context: StreamContext? { get { return fromVoidPointer(stream.memory.data) } set { let _: StreamContext? = releaseVoidPointer(stream.memory.data) stream.memory.data = retainedVoidPointer(newValue) } } func read(callback: ReadBlock) throws { context.readBlock = callback uv_read_start(stream, alloc_buffer) { serverStream, bytesRead, buf in defer { free_buffer(buf) } let stream = UVStream(serverStream) let data: ReadResult if (bytesRead == Int(UV_EOF.rawValue)) { data = .EOF } else if (bytesRead < 0) { data = .Error(UVError.Error(code: Int32(bytesRead))) } else { data = .Chunk(Data(bytes: buf.memory.base, length: bytesRead)) } stream.context.readBlock?(data) } } func listen(numConnections: Int, theCallback: ListenBlock) throws { context.listenBlock = theCallback try listen(backlog: numConnections) { serverStream, status in let stream = UVStream(serverStream) stream.context.listenBlock?(status: Int(status)) } } func writeAndFree(buffer: BufferRef, completion: (Void -> Void)?) { let writeRef: WriteRef = WriteRef.alloc(1) // dealloced in the write callback writeRef.memory.data = UnsafeMutablePointer(Unmanaged.passRetained(WriteCompletionHandler(completion)).toOpaque()) uv_write(writeRef, stream, buffer, 1) { request, _ in let completionHandler = Unmanaged<WriteCompletionHandler>.fromOpaque(COpaquePointer(request.memory.data)).takeRetainedValue().completion free(request.memory.bufs) free(request) completionHandler?() } } func write(completion: (Void -> Void)?)(buffer: BufferRef) { writeAndFree(buffer, completion: completion) } } extension UVStream : Stream { func writeData(data: Data, completion: (Void -> Void)? = nil) { data.withBufferRef(write(completion)) } func readData(handler: Data -> Void) throws { try read { [unowned self] result in if case let .Chunk(data) = result { handler(data) } else { self.close() } } } }
mit
bc00caf8bb4ca53f0b87dd50c6188424
20.978541
148
0.603593
4.523852
false
false
false
false
EgeTart/MedicineDMW
DWM/CustomAlertView.swift
1
4952
// // CustomView.swift // DelegateDemo // // Created by 高永效 on 15/8/6. // Copyright © 2015年 高永效. All rights reserved. // import UIKit protocol CustomAlertViewDelegate { func buttonDidClicked(buttonType: String) } class CustomAlertView: UIView { var delegate: CustomAlertViewDelegate! init(title: String!, message: String, buttonsNum: Int) { super.init(frame: CGRect(x: 10, y: UIScreen.mainScreen().bounds.height / 2 - 140, width: UIScreen.mainScreen().bounds.width - 20, height: 160)) self.backgroundColor = UIColor.whiteColor() self.layer.cornerRadius = 5 let titleTable = UILabel(frame: CGRect(x: 5, y: 5, width: self.frame.width - 10, height: 40)) titleTable.font = UIFont.boldSystemFontOfSize(22) titleTable.textAlignment = NSTextAlignment.Center titleTable.text = title self.addSubview(titleTable) let seperateView = UIView(frame: CGRect(x: 0, y: 46, width: self.frame.width, height: 2.0)) seperateView.backgroundColor = UIColor(red: 144.0 / 255.0, green: 117.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0) self.addSubview(seperateView) let messageTable = UILabel(frame: CGRect(x: 5, y: 60, width: self.frame.width - 10, height: 30)) messageTable.font = UIFont.systemFontOfSize(18) messageTable.textAlignment = NSTextAlignment.Center messageTable.text = message self.addSubview(messageTable) let a = self.frame.width / 2.0 - (self.frame.width / 2.0 - 40) / 2.0 let b = self.frame.width / 2.0 - 40 if buttonsNum == 1 { let sureButton = UIButton(frame: CGRect(x: a , y: 110 , width: b , height: 30)) sureButton.setTitle("确定", forState: UIControlState.Normal) sureButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) sureButton.setTitleColor(UIColor.lightTextColor(), forState: UIControlState.Highlighted) sureButton.backgroundColor = UIColor(red: 144.0 / 255.0, green: 117.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0) sureButton.layer.cornerRadius = 5 sureButton.tag = 202 sureButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(sureButton) } if buttonsNum == 2 { let cancleButton = UIButton(frame: CGRect(x: 20, y: 110, width: self.frame.width / 2.0 - 30, height: 30)) cancleButton.setTitle("取消", forState: UIControlState.Normal) cancleButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) cancleButton.setTitleColor(UIColor.lightTextColor(), forState: UIControlState.Highlighted) cancleButton.backgroundColor = UIColor(red: 251.0 / 255.0, green: 251.0 / 255.0, blue: 251.0 / 255.0, alpha: 1.0) cancleButton.layer.cornerRadius = 5 cancleButton.layer.borderWidth = 0.3 cancleButton.layer.borderColor = UIColor.grayColor().CGColor // cancleButton.layer.borderColor = UIColor.grayColor() cancleButton.tag = 201 cancleButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(cancleButton) let sureButton = UIButton(frame: CGRect(x: self.frame.width / 2.0 + 10.0, y: 110, width: self.frame.width / 2.0 - 30, height: 30)) sureButton.setTitle("确定", forState: UIControlState.Normal) sureButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) sureButton.setTitleColor(UIColor.lightTextColor(), forState: UIControlState.Highlighted) sureButton.backgroundColor = UIColor(red: 144.0 / 255.0, green: 117.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0) sureButton.layer.cornerRadius = 5 sureButton.tag = 202 sureButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(sureButton) } } func buttonClicked(sender: AnyObject) { let button = sender as! UIButton var buttonType: String! if button.tag == 201 { buttonType = "Cancle" } else { buttonType = "Sure" } UIView.animateWithDuration(3.5, animations: { () -> Void in self.layer.opacity = 0.0 self.transform = CGAffineTransformMakeScale(0.0, 0.0) }) { (flag: Bool) -> Void in self.removeFromSuperview() } delegate.buttonDidClicked(buttonType) } required init!(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
020c2e4a3ee10b22d6c58e55be5dd33e
41.094017
151
0.617259
4.29007
false
false
false
false
ProteanBear/ProteanBear_Swift
library/pb.swift.basic/ExtensionString.swift
1
5059
// // ExtensionString.swift // pb.swift.basic // 扩展String对象 // Created by Maqiang on 15/6/17. // Copyright (c) 2015年 Maqiang. All rights reserved. // import Foundation extension String { /// 计算当前文字的尺寸 /// - parameter size:尺寸(宽度为0获取高度;高度为0获取宽度) /// - parameter font:字体 public func pbTextSize(_ size:CGSize,font:UIFont) -> CGSize { let attribute = [NSFontAttributeName: font] let rect=NSString(string:self).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attribute, context: nil) return CGSize(width: rect.width, height: rect.height) } /// 计算当前文字的高度 /// - parameter width :限制文字的宽度 /// - parameter font :字体 public func pbTextHeight(_ width:CGFloat,font:UIFont) -> CGFloat { let attribute = [NSFontAttributeName: font] let size=CGSize(width: width, height: 0) let rect=NSString(string:self).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attribute, context: nil) return rect.height } /// 获取当前时间的字符串描述,格式默认为 yyyy-MM-dd HH:mm:ss,默认为描述模式(转换为几分钟前) public static func date() -> String { return String.date(Date(), format: "yyyy-MM-dd HH:mm:ss") } /// 获取当前时间的字符串描述,格式默认为 yyyy-MM-dd HH:mm:ss /// - parameter useDescription:指定为true时使用描述模式,即转换成“几分钟前”之类的方式 public static func date(_ useDescription:Bool) -> String { return String.date(Date(), format: "yyyy-MM-dd HH:mm:ss",useDescription:useDescription) } /// 获取指定时间的字符串描述,格式默认为 yyyy-MM-dd HH:mm:ss,默认为描述模式(转换为几分钟前) /// - parameter date :指定时间 public static func date(_ date:Date) -> String { return String.date(date, format: "yyyy-MM-dd HH:mm:ss",useDescription: true) } /// 获取指定时间的字符串描述,格式默认为 yyyy-MM-dd HH:mm:ss /// - parameter date :指定时间 /// - parameter useDescription:指定为true时使用描述模式,即转换成“几分钟前”之类的方式 public static func date(_ date:Date,useDescription:Bool) -> String { return String.date(date, format: "yyyy-MM-dd HH:mm:ss",useDescription: true) } /// 获取当前时间的字符串描述并指定格式,默认为描述模式(转换为几分钟前) /// - parameter format :指定格式 public static func date(_ format:String) -> String { return String.date(Date(), format: format,useDescription: true) } /// 获取当前时间的字符串描述并指定格式 /// - parameter format :指定格式 /// - parameter useDescription:指定为true时使用描述模式,即转换成“几分钟前”之类的方式 public static func date(_ format:String,useDescription:Bool) -> String { return String.date(Date(), format: format,useDescription: useDescription) } /// 获取指定时间的字符串描述并指定格式,默认为描述模式(转换为几分钟前) /// - parameter date :指定时间 /// - parameter format :指定格式 public static func date(_ date:Date,format:String) -> String { return String.date(date, format: format, useDescription: true) } /// 获取指定时间的字符串描述并指定格式 /// - parameter date :指定时间 /// - parameter format :指定格式 /// - parameter useDescription:指定为true时使用描述模式,即转换成“几分钟前”之类的方式 public static func date(_ date:Date,format:String,useDescription:Bool) -> String { let formatter=DateFormatter() var result="" if(useDescription) { let interval=date.timeIntervalSince(Date()) if(interval<60) {result="刚刚更新"} else if(interval<60*60) {result=(interval/60).description+"分钟前"} else if(interval<60*60*24) { formatter.dateFormat="HH:mm" result=formatter.string(from: date) } else { formatter.dateFormat=format result=formatter.string(from: date) } } else { formatter.dateFormat=format result=formatter.string(from: date) } return result } /// 获取指定时间戳的字符串描述并指定格式 /// - parameter timestamp :时间戳 /// - parameter format :指定格式 public static func date(_ timestamp:Int64,format:String) -> String { let formatter=DateFormatter() formatter.dateFormat=format return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) } }
apache-2.0
cf7754f3fd6fde29fd022e91c518f805
34.008333
134
0.623423
3.774483
false
false
false
false
hsavit1/LeetCode-Solutions-in-Swift
Solutions/Solutions/Hard/Hard_010_Regular_Expression_Matching.swift
1
2789
/* https://oj.leetcode.com/problems/regular-expression-matching/ #10 Regular Expression Matching Level: hard Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true Inspired by @xiaohui7 at https://leetcode.com/discuss/18970/concise-recursive-and-dp-solutions-with-full-explanation-in */ // Helper private extension String { subscript (index: Int) -> Character { return self[advance(self.startIndex, index)] } subscript (range: Range<Int>) -> String { if range.endIndex > self.characters.count { return self[advance(self.startIndex, range.startIndex)..<advance(self.startIndex, self.characters.count)] } else { return self[advance(self.startIndex, range.startIndex)..<advance(self.startIndex, range.endIndex)] } } } class Hard_010_Regular_Expression_Matching { // recursion class func isMatch_recursion(s s: String, p: String) -> Bool { if p.characters.count == 0 { return s.characters.count == 0 } if p.characters.count > 1 && p[1] == "*" { return isMatch_recursion(s: s, p: p[2..<p.characters.count]) || s.characters.count != 0 && (s[0] == p[0] || p[0] == ".") && isMatch_recursion(s: s[1..<s.characters.count], p: p) } else { return s.characters.count != 0 && (s[0] == p[0] || p[0] == ".") && isMatch_recursion(s: s[1..<s.characters.count], p: p[1..<p.characters.count]) } } // dp class func isMatch(s s: String, p: String) -> Bool { let m: Int = s.characters.count let n: Int = p.characters.count var f: [[Bool]] = Array<Array<Bool>>(count: m + 1, repeatedValue: Array<Bool>(count: n + 1, repeatedValue: false)) f[0][0] = true for var i = 1; i <= m; i++ { f[i][0] = false } for var i = 1; i <= n; i++ { f[0][i] = i > 1 && "*" == p[i-1] && f[0][i-2] } for var i = 1; i <= m; i++ { for var j = 1; j <= n; j++ { if p[j-1] != "*" { f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || "." == p[j - 1]) } else { f[i][j] = f[i][j - 2] || (s[i - 1] == p[j - 2] || "." == p[j - 2]) && f[i - 1][j] } } } return f[m][n] } }
mit
dbf4833fef058985ffe7bb8535102538
33.271605
189
0.532252
3.264706
false
false
false
false
abelsanchezali/ViewBuilder
Source/Document/Cache/DocumentCacheKey.swift
1
1272
// // DocumentCacheKey.swift // ViewBuilder // // Created by Abel Sanchez on 8/2/17. // Copyright © 2017 Abel Sanchez. All rights reserved. // import Foundation /// Internal class used as key for documents in cache class DocumentCacheKey: NSObject { let path: String let includeParsingInfo: Bool let namespaces: [String: String] private let storedHash: Int init(path: String, namespaces: [String: String], includeParsingInfo: Bool) { self.path = path self.namespaces = namespaces self.includeParsingInfo = includeParsingInfo storedHash = HashHelper.computeHash([ path.hashValue, HashHelper.computeHash([String](namespaces.keys)), HashHelper.computeHash([String](namespaces.values)), includeParsingInfo.hashValue]) } override var hash: Int { return storedHash } override func isEqual(_ object: Any?) -> Bool { guard let other = object as? DocumentCacheKey else { return false } return self == other } } private func ==(lhs: DocumentCacheKey, rhs: DocumentCacheKey) -> Bool { return lhs.path == rhs.path && lhs.namespaces == rhs.namespaces && lhs.includeParsingInfo == rhs.includeParsingInfo }
mit
ca258f66c0640e5767d36ff0ab031d1d
27.886364
119
0.656176
4.459649
false
false
false
false
FusionOpz/EdgeIRC
EdgeIRC/to_be_frameworked/Classes/IRC/message/RSIRCMessage.swift
1
2555
// // RSIRCMessage.swift // EdgeIRC // // Copyright © 2015 Giuseppe Morana aka Eugenio // // 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 CocoaLumberjack /// An IRC Message public class RSIRCMessage: NSObject { private(set) var prefix: RSIRCMessagePrefix? private(set) var command: String? // private(set) var parameters: String? private(set) var params: RSIRCMessageParams? /// format: prefix + cmd + params + crlf /// e.g. :card.freenode.net 001 edgeChat :Welcome to the freenode Internet Relay Chat Network edgeChat /// e.g. :FusionOpz!~ISP-Provided.host.tld PRIVMSG edgeChat :Hi, I'm edgeChat! init?(message: String) { super.init() var msg = message // prefix if message.hasPrefix(":") { if let idx = msg.characters.indexOf(" ") { let prefixStr = msg.substringToIndex(idx) prefix = RSIRCMessagePrefix(prefix: prefixStr) msg = msg.substringFromIndex(idx.successor()) } else { return nil } } // command if let idx = msg.characters.indexOf(" ") { command = msg.substringToIndex(idx) msg = msg.substringFromIndex(idx.successor()) } else { return nil } // parameters params = RSIRCMessageParams(stringToParse: msg) //DDLogInfo("\(params)") //parameters = msg } }
mit
2675fcea3ae0a80017c3995e601aa806
35.5
106
0.650352
4.536412
false
false
false
false
digoreis/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0021.xcplaygroundpage/Contents.swift
1
6771
/*: # Naming Functions with Argument Labels * Proposal: [SE-0021](0021-generalized-naming.md) * Author: [Doug Gregor](https://github.com/DougGregor) * Review Manager: [Joe Groff](https://github.com/jckarter) * Status: **Implemented (Swift 2.2)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-January/000021.html) * Commit: [apple/swift@ecfde0e](https://github.com/apple/swift/commit/ecfde0e71c61184989fde0f93f8d6b7f5375b99a) ## Introduction Swift includes support for first-class functions, such that any function (or method) can be placed into a value of function type. However, when specifying the name of a function, one can only provide the base name, (e.g., `insertSubview`) without the argument labels. For overloaded functions, this means that one must disambiguate based on type information, which is awkward and verbose. This proposal allows one to provide argument labels when referencing a function, eliminating the need to provide type context in most cases. Swift-evolution thread: The first draft of this proposal was discussed [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151221/004555.html). It included support for naming getters/setters (separately brought up by Michael Henson [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/002168.html), continued [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002203.html)). Joe Groff [convinced](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151221/004579.html) me that lenses are a better approach for working with getters/setters, so I've dropped them from this version of the proposal. ## Motivation It's fairly common in Swift for multiple functions or methods to have the same "base name", but be distinguished by parameter labels. For example, `UIView` has three methods with the same base name `insertSubview`: ```swift extension UIView { func insertSubview(view: UIView, at index: Int) func insertSubview(view: UIView, aboveSubview siblingSubview: UIView) func insertSubview(view: UIView, belowSubview siblingSubview: UIView) } ``` When calling these methods, the argument labels distinguish the different methods, e.g., ```swift someView.insertSubview(view, at: 3) someView.insertSubview(view, aboveSubview: otherView) someView.insertSubview(view, belowSubview: otherView) ``` However, when referencing the function to create a function value, one cannot provide the labels: ```swift let fn = someView.insertSubview // ambiguous: could be any of the three methods ``` In some cases, it is possible to use type annotations to disambiguate: ```swift let fn: (UIView, Int) = someView.insertSubview // ok: uses insertSubview(_:at:) let fn: (UIView, UIView) = someView.insertSubview // error: still ambiguous! ``` To resolve the latter case, one must fall back to creating a closure: ```swift let fn: (UIView, UIView) = { view, otherView in button.insertSubview(view, aboveSubview: otherView) } ``` which is painfully tedious. One additional bit of motivation: Swift should probably get some way to ask for the Objective-C selector for a given method (rather than writing a string literal). The argument to such an operation would likely be a reference to a method, which would benefit from being able to name any method, including getters and setters. ## Proposed solution I propose to extend function naming to allow compound Swift names (e.g., `insertSubview(_:aboveSubview:)`) anywhere a name can occur. Specifically, ```swift let fn = someView.insertSubview(_:at:) let fn1 = someView.insertSubview(_:aboveSubview:) ``` The same syntax can also refer to initializers, e.g., ```swift let buttonFactory = UIButton.init(type:) ``` The "produce the Objective-C selector for the given method" operation will be the subject of a separate proposal. However, here is one possibility that illustrations how it uses the proposed syntax here: ```swift let getter = Selector(NSDictionary.insertSubview(_:aboveSubview:)) // produces insertSubview:aboveSubview:. ``` ## Detailed Design Grammatically, the *primary-expression* grammar will change from: primary-expression -> identifier generic-argument-clause[opt] to: primary-expression -> unqualified-name generic-argument-clause[opt] unqualified-name -> identifier | identifier '(' ((identifier | '_') ':')+ ')' Within the parentheses, the use of "+" is important, because it disambiguates: ```swift f() ``` as a call to `f` rather than a reference to an `f` with no arguments. Zero-argument function references will still require disambiguation via contextual type information. Note that the reference to the name must include all of the arguments present in the declaration; arguments for defaulted or variadic parameters cannot be skipped. For example: ```swift func foo(x x: Int, y: Int = 7, strings: String...) { ... } let fn1 = foo(x:y:strings:) // okay let fn2 = foo(x:) // error: no function named 'foo(x:)' ``` ## Impact on existing code This is a purely additive feature that has no impact on existing code. ## Alternatives considered * Joe Groff [notes](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/003008.html) that *lenses* are a better solution than manually retrieving getter/setter functions when the intent is to actually operate on the properties. * Bartlomiej Cichosz [suggests](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151228/004739.html) a general partial application syntax using `_` as a placeholder, e.g., ```swift aGameView.insertSubview(_, aboveSubview: playingSurfaceView) ``` When all arguments are `_`, this provides the ability to name any method: ```swift aGameView.insertSubview(_, aboveSubview: _) ``` I decided not to go with this because I don't believe we need such a general partial application syntax in Swift. Closures using the $ names are nearly as concise, and eliminate any questions about how the `_` placeholder maps to an argument of the partially-applied function: ```swift { aGameView.insertSubview($0, aboveSubview: playingSurfaceView) } ``` * We could elide the underscores in the names, e.g., ```swift let fn1 = someView.insertSubview(:aboveSubview:) ``` However, this makes it much harder to visually distinguish methods with no first argument label from methods with a first argument label, e.g., `f(x:)` vs. `f(:x:)`. Additionally, empty argument labels in function names are written using the underscores everywhere else in the system (e.g., the Clang `swift_name` attribute), and we should maintain consistency. ---------- [Previous](@previous) | [Next](@next) */
mit
e02355c11bb6deda7acc0de550d22fa7
35.6
405
0.754098
3.938918
false
false
false
false
marcosvm/tips
tips/ViewController.swift
1
2078
// // ViewController.swift // tips // // Created by Marcos Oliveira on 1/14/15. // Copyright (c) 2015 Techbinding. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var totalLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tipLabel.text = "$0.0 0" totalLabel.text = "$0.00" // self.navigationController?.setNavigationBarHidden(false, animated: true) // self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: "onSettingsButton") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { let defaults = NSUserDefaults.standardUserDefaults() let percentSetting = defaults.integerForKey("tip_percent") tipControl.selectedSegmentIndex = percentSetting self.onEditingChange(self) } @IBAction func onEditingChange(sender: AnyObject) { var tipPercentages = [0.15, 0.18, 0.2] var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] var billAmount = (billField.text as NSString).doubleValue var tip = billAmount * tipPercentage var total = billAmount + tip tipLabel.text = String(format: "%.2f", tip) totalLabel.text = String(format: "%.2f", total) } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } func onSettingsButton(sender: AnyObject) { let settingsViewController = SettingsViewController(nibName: "SettingsViewController", bundle: nil) navigationController?.pushViewController(settingsViewController, animated: true) } }
mit
2aedd866a3901ddbbe3f1607dacc214a
32.532258
142
0.676131
4.91253
false
false
false
false
Minitour/AZTabBar
Example/ContentViewController.swift
1
1748
// // ContentViewController.swift // Example // // Created by Antonio Zaitoun on 8/25/16. // Copyright © 2016 New Sound Interactive. All rights reserved. // import Foundation import UIKit class ContentViewController:UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{ public var backgroundColor:UIColor! @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.collectionView.backgroundColor = self.backgroundColor self.collectionView.delegate = self self.collectionView.dataSource = self } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.collectionView.frame.size.width/3, height: self.collectionView.frame.size.width/3) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 34 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DemoCell", for: indexPath) as! DemoCell cell.demoImage.image = nil cell.demoImage.image = UIImage(named: "demo_1") cell.demoImage.contentMode = .scaleAspectFit return cell } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.collectionView.contentOffset.y = 0 } } class DemoCell:UICollectionViewCell{ @IBOutlet weak var demoImage:UIImageView! }
mit
7441bb4d64f928ecefc2f5c67f4386dd
30.763636
160
0.709216
5.358896
false
false
false
false
iosengineer/presentations
WhatsNewInXcode6/getoffmylawn/getoffmylawn/MakeClouds.playground/section-1.swift
1
987
// Playground - noun: a place where people can play import UIKit import QuartzCore var view = UIView(frame: CGRect(x: 0, y: 0, width: 512, height: 512)) view.backgroundColor = UIColor(red: 35/255, green: 185/255, blue: 240/255, alpha: 1.0) var cloud = CAShapeLayer() view.layer.addSublayer(cloud) var circle = CGPathCreateMutable() let xOffset = 100 let yOffset = 40 cloud.path = circle cloud.fillColor = UIColor.whiteColor().CGColor view CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset, y: yOffset, width: 100, height: 100)) view CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset + 60, y: yOffset + 40, width: 100, height: 60)) view CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset - 50, y: yOffset + 54, width: 100, height: 45)) view CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset - 20, y: yOffset + 30, width: 50, height: 50)) view // CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset + 100, y: yOffset + 54, width: 100, height: 45)) view
cc0-1.0
8c73fe266d936a4e91ad3b2341639137
21.953488
102
0.718338
3.236066
false
false
false
false
BrikerMan/BMPlayer
Source/BMPlayerControlView.swift
1
27755
// // BMPlayerControlView.swift // Pods // // Created by BrikerMan on 16/4/29. // // import UIKit import NVActivityIndicatorView @objc public protocol BMPlayerControlViewDelegate: class { /** call when control view choose a definition - parameter controlView: control view - parameter index: index of definition */ func controlView(controlView: BMPlayerControlView, didChooseDefinition index: Int) /** call when control view pressed an button - parameter controlView: control view - parameter button: button type */ func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton) /** call when slider action trigged - parameter controlView: control view - parameter slider: progress slider - parameter event: action */ func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControl.Event) /** call when needs to change playback rate - parameter controlView: control view - parameter rate: playback rate */ @objc optional func controlView(controlView: BMPlayerControlView, didChangeVideoPlaybackRate rate: Float) } open class BMPlayerControlView: UIView { open weak var delegate: BMPlayerControlViewDelegate? open weak var player: BMPlayer? // MARK: Variables open var resource: BMPlayerResource? open var selectedIndex = 0 open var isFullscreen = false open var isMaskShowing = true open var totalDuration: TimeInterval = 0 open var delayItem: DispatchWorkItem? var playerLastState: BMPlayerState = .notSetURL fileprivate var isSelectDefinitionViewOpened = false // MARK: UI Components /// main views which contains the topMaskView and bottom mask view open var mainMaskView = UIView() open var topMaskView = UIView() open var bottomMaskView = UIView() /// Image view to show video cover open var maskImageView = UIImageView() /// top views open var topWrapperView = UIView() open var backButton = UIButton(type : UIButton.ButtonType.custom) open var titleLabel = UILabel() open var chooseDefinitionView = UIView() /// bottom view open var bottomWrapperView = UIView() open var currentTimeLabel = UILabel() open var totalTimeLabel = UILabel() /// Progress slider open var timeSlider = BMTimeSlider() /// load progress view open var progressView = UIProgressView() /* play button playButton.isSelected = player.isPlaying */ open var playButton = UIButton(type: UIButton.ButtonType.custom) /* fullScreen button fullScreenButton.isSelected = player.isFullscreen */ open var fullscreenButton = UIButton(type: UIButton.ButtonType.custom) open var subtitleLabel = UILabel() open var subtitleBackView = UIView() open var subtileAttribute: [NSAttributedString.Key : Any]? /// Activty Indector for loading open var loadingIndicator = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) open var seekToView = UIView() open var seekToViewImage = UIImageView() open var seekToLabel = UILabel() open var replayButton = UIButton(type: UIButton.ButtonType.custom) /// Gesture used to show / hide control view open var tapGesture: UITapGestureRecognizer! open var doubleTapGesture: UITapGestureRecognizer! // MARK: - handle player state change /** call on when play time changed, update duration here - parameter currentTime: current play time - parameter totalTime: total duration */ open func playTimeDidChange(currentTime: TimeInterval, totalTime: TimeInterval) { currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime) totalTimeLabel.text = BMPlayer.formatSecondsToString(totalTime) timeSlider.value = Float(currentTime) / Float(totalTime) if let subtitle = resource?.subtitle { showSubtile(from: subtitle, at: currentTime) } } /** change subtitle resource - Parameter subtitles: new subtitle object */ open func update(subtitles: BMSubtitles?) { resource?.subtitle = subtitles } /** call on load duration changed, update load progressView here - parameter loadedDuration: loaded duration - parameter totalDuration: total duration */ open func loadedTimeDidChange(loadedDuration: TimeInterval, totalDuration: TimeInterval) { progressView.setProgress(Float(loadedDuration)/Float(totalDuration), animated: true) } open func playerStateDidChange(state: BMPlayerState) { switch state { case .readyToPlay: hideLoader() case .buffering: showLoader() case .bufferFinished: hideLoader() case .playedToTheEnd: playButton.isSelected = false showPlayToTheEndView() controlViewAnimation(isShow: true) default: break } playerLastState = state } /** Call when User use the slide to seek function - parameter toSecound: target time - parameter totalDuration: total duration of the video - parameter isAdd: isAdd */ open func showSeekToView(to toSecound: TimeInterval, total totalDuration:TimeInterval, isAdd: Bool) { seekToView.isHidden = false seekToLabel.text = BMPlayer.formatSecondsToString(toSecound) let rotate = isAdd ? 0 : CGFloat(Double.pi) seekToViewImage.transform = CGAffineTransform(rotationAngle: rotate) let targetTime = BMPlayer.formatSecondsToString(toSecound) timeSlider.value = Float(toSecound / totalDuration) currentTimeLabel.text = targetTime } // MARK: - UI update related function /** Update UI details when player set with the resource - parameter resource: video resouce - parameter index: defualt definition's index */ open func prepareUI(for resource: BMPlayerResource, selectedIndex index: Int) { self.resource = resource self.selectedIndex = index titleLabel.text = resource.name prepareChooseDefinitionView() autoFadeOutControlViewWithAnimation() } open func playStateDidChange(isPlaying: Bool) { autoFadeOutControlViewWithAnimation() playButton.isSelected = isPlaying } /** auto fade out controll view with animtion */ open func autoFadeOutControlViewWithAnimation() { cancelAutoFadeOutAnimation() delayItem = DispatchWorkItem { [weak self] in if self?.playerLastState != .playedToTheEnd { self?.controlViewAnimation(isShow: false) } } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + BMPlayerConf.animateDelayTimeInterval, execute: delayItem!) } /** cancel auto fade out controll view with animtion */ open func cancelAutoFadeOutAnimation() { delayItem?.cancel() } /** Implement of the control view animation, override if need's custom animation - parameter isShow: is to show the controlview */ open func controlViewAnimation(isShow: Bool) { let alpha: CGFloat = isShow ? 1.0 : 0.0 self.isMaskShowing = isShow UIApplication.shared.setStatusBarHidden(!isShow, with: .fade) UIView.animate(withDuration: 0.3, animations: {[weak self] in guard let wSelf = self else { return } wSelf.topMaskView.alpha = alpha wSelf.bottomMaskView.alpha = alpha wSelf.mainMaskView.backgroundColor = UIColor(white: 0, alpha: isShow ? 0.4 : 0.0) if isShow { if wSelf.isFullscreen { wSelf.chooseDefinitionView.alpha = 1.0 } } else { wSelf.replayButton.isHidden = true wSelf.chooseDefinitionView.snp.updateConstraints { (make) in make.height.equalTo(35) } wSelf.chooseDefinitionView.alpha = 0.0 } wSelf.layoutIfNeeded() }) { [weak self](_) in if isShow { self?.autoFadeOutControlViewWithAnimation() } } } /** Implement of the UI update when screen orient changed - parameter isForFullScreen: is for full screen */ open func updateUI(_ isForFullScreen: Bool) { isFullscreen = isForFullScreen fullscreenButton.isSelected = isForFullScreen chooseDefinitionView.isHidden = !BMPlayerConf.enableChooseDefinition || !isForFullScreen if isForFullScreen { if BMPlayerConf.topBarShowInCase.rawValue == 2 { topMaskView.isHidden = true } else { topMaskView.isHidden = false } } else { if BMPlayerConf.topBarShowInCase.rawValue >= 1 { topMaskView.isHidden = true } else { topMaskView.isHidden = false } } } /** Call when video play's to the end, override if you need custom UI or animation when played to the end */ open func showPlayToTheEndView() { replayButton.isHidden = false } open func hidePlayToTheEndView() { replayButton.isHidden = true } open func showLoader() { loadingIndicator.isHidden = false loadingIndicator.startAnimating() } open func hideLoader() { loadingIndicator.isHidden = true } open func hideSeekToView() { seekToView.isHidden = true } open func showCoverWithLink(_ cover:String) { self.showCover(url: URL(string: cover)) } open func showCover(url: URL?) { if let url = url { DispatchQueue.global(qos: .default).async { [weak self] in let data = try? Data(contentsOf: url) DispatchQueue.main.async(execute: { [weak self] in guard let `self` = self else { return } if let data = data { self.maskImageView.image = UIImage(data: data) } else { self.maskImageView.image = nil } self.hideLoader() }); } } } open func hideCoverImageView() { self.maskImageView.isHidden = true } open func prepareChooseDefinitionView() { guard let resource = resource else { return } for item in chooseDefinitionView.subviews { item.removeFromSuperview() } for i in 0..<resource.definitions.count { let button = BMPlayerClearityChooseButton() if i == 0 { button.tag = selectedIndex } else if i <= selectedIndex { button.tag = i - 1 } else { button.tag = i } button.setTitle("\(resource.definitions[button.tag].definition)", for: UIControl.State()) chooseDefinitionView.addSubview(button) button.addTarget(self, action: #selector(self.onDefinitionSelected(_:)), for: UIControl.Event.touchUpInside) button.snp.makeConstraints({ [weak self](make) in guard let `self` = self else { return } make.top.equalTo(chooseDefinitionView.snp.top).offset(35 * i) make.width.equalTo(50) make.height.equalTo(25) make.centerX.equalTo(chooseDefinitionView) }) if resource.definitions.count == 1 { button.isEnabled = false button.isHidden = true } } } open func prepareToDealloc() { self.delayItem = nil } // MARK: - Action Response /** Call when some action button Pressed - parameter button: action Button */ @objc open func onButtonPressed(_ button: UIButton) { autoFadeOutControlViewWithAnimation() if let type = ButtonType(rawValue: button.tag) { switch type { case .play, .replay: if playerLastState == .playedToTheEnd { hidePlayToTheEndView() } default: break } } delegate?.controlView(controlView: self, didPressButton: button) } /** Call when the tap gesture tapped - parameter gesture: tap gesture */ @objc open func onTapGestureTapped(_ gesture: UITapGestureRecognizer) { if playerLastState == .playedToTheEnd { return } controlViewAnimation(isShow: !isMaskShowing) } @objc open func onDoubleTapGestureRecognized(_ gesture: UITapGestureRecognizer) { guard let player = player else { return } guard playerLastState == .readyToPlay || playerLastState == .buffering || playerLastState == .bufferFinished else { return } if player.isPlaying { player.pause() } else { player.play() } } // MARK: - handle UI slider actions @objc func progressSliderTouchBegan(_ sender: UISlider) { delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchDown) } @objc func progressSliderValueChanged(_ sender: UISlider) { hidePlayToTheEndView() cancelAutoFadeOutAnimation() let currentTime = Double(sender.value) * totalDuration currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime) delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .valueChanged) } @objc func progressSliderTouchEnded(_ sender: UISlider) { autoFadeOutControlViewWithAnimation() delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchUpInside) } // MARK: - private functions fileprivate func showSubtile(from subtitle: BMSubtitles, at time: TimeInterval) { if let group = subtitle.search(for: time) { subtitleBackView.isHidden = false subtitleLabel.attributedText = NSAttributedString(string: group.text, attributes: subtileAttribute) } else { subtitleBackView.isHidden = true } } @objc fileprivate func onDefinitionSelected(_ button:UIButton) { let height = isSelectDefinitionViewOpened ? 35 : resource!.definitions.count * 40 chooseDefinitionView.snp.updateConstraints { (make) in make.height.equalTo(height) } UIView.animate(withDuration: 0.3, animations: {[weak self] in self?.layoutIfNeeded() }) isSelectDefinitionViewOpened = !isSelectDefinitionViewOpened if selectedIndex != button.tag { selectedIndex = button.tag delegate?.controlView(controlView: self, didChooseDefinition: button.tag) } prepareChooseDefinitionView() } @objc fileprivate func onReplyButtonPressed() { replayButton.isHidden = true } // MARK: - Init override public init(frame: CGRect) { super.init(frame: frame) setupUIComponents() addSnapKitConstraint() customizeUIComponents() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUIComponents() addSnapKitConstraint() customizeUIComponents() } /// Add Customize functions here open func customizeUIComponents() { } func setupUIComponents() { // Subtile view subtitleLabel.numberOfLines = 0 subtitleLabel.textAlignment = .center subtitleLabel.textColor = UIColor.white subtitleLabel.adjustsFontSizeToFitWidth = true subtitleLabel.minimumScaleFactor = 0.5 subtitleLabel.font = UIFont.systemFont(ofSize: 13) subtitleBackView.layer.cornerRadius = 2 subtitleBackView.backgroundColor = UIColor.black.withAlphaComponent(0.4) subtitleBackView.addSubview(subtitleLabel) subtitleBackView.isHidden = true addSubview(subtitleBackView) // Main mask view addSubview(mainMaskView) mainMaskView.addSubview(topMaskView) mainMaskView.addSubview(bottomMaskView) mainMaskView.insertSubview(maskImageView, at: 0) mainMaskView.clipsToBounds = true mainMaskView.backgroundColor = UIColor(white: 0, alpha: 0.4 ) // Top views topMaskView.addSubview(topWrapperView) topWrapperView.addSubview(backButton) topWrapperView.addSubview(titleLabel) topWrapperView.addSubview(chooseDefinitionView) backButton.tag = BMPlayerControlView.ButtonType.back.rawValue backButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_back"), for: .normal) backButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside) titleLabel.textColor = UIColor.white titleLabel.text = "" titleLabel.font = UIFont.systemFont(ofSize: 16) chooseDefinitionView.clipsToBounds = true // Bottom views bottomMaskView.addSubview(bottomWrapperView) bottomWrapperView.addSubview(playButton) bottomWrapperView.addSubview(currentTimeLabel) bottomWrapperView.addSubview(totalTimeLabel) bottomWrapperView.addSubview(progressView) bottomWrapperView.addSubview(timeSlider) bottomWrapperView.addSubview(fullscreenButton) playButton.tag = BMPlayerControlView.ButtonType.play.rawValue playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_play"), for: .normal) playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_pause"), for: .selected) playButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside) currentTimeLabel.textColor = UIColor.white currentTimeLabel.font = UIFont.systemFont(ofSize: 12) currentTimeLabel.text = "00:00" currentTimeLabel.textAlignment = NSTextAlignment.center totalTimeLabel.textColor = UIColor.white totalTimeLabel.font = UIFont.systemFont(ofSize: 12) totalTimeLabel.text = "00:00" totalTimeLabel.textAlignment = NSTextAlignment.center timeSlider.maximumValue = 1.0 timeSlider.minimumValue = 0.0 timeSlider.value = 0.0 timeSlider.setThumbImage(BMImageResourcePath("Pod_Asset_BMPlayer_slider_thumb"), for: .normal) timeSlider.maximumTrackTintColor = UIColor.clear timeSlider.minimumTrackTintColor = BMPlayerConf.tintColor timeSlider.addTarget(self, action: #selector(progressSliderTouchBegan(_:)), for: UIControl.Event.touchDown) timeSlider.addTarget(self, action: #selector(progressSliderValueChanged(_:)), for: UIControl.Event.valueChanged) timeSlider.addTarget(self, action: #selector(progressSliderTouchEnded(_:)), for: [UIControl.Event.touchUpInside,UIControl.Event.touchCancel, UIControl.Event.touchUpOutside]) progressView.tintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6 ) progressView.trackTintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3 ) fullscreenButton.tag = BMPlayerControlView.ButtonType.fullscreen.rawValue fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_fullscreen"), for: .normal) fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_portialscreen"), for: .selected) fullscreenButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside) mainMaskView.addSubview(loadingIndicator) loadingIndicator.type = BMPlayerConf.loaderType loadingIndicator.color = BMPlayerConf.tintColor // View to show when slide to seek addSubview(seekToView) seekToView.addSubview(seekToViewImage) seekToView.addSubview(seekToLabel) seekToLabel.font = UIFont.systemFont(ofSize: 13) seekToLabel.textColor = UIColor ( red: 0.9098, green: 0.9098, blue: 0.9098, alpha: 1.0 ) seekToView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7 ) seekToView.layer.cornerRadius = 4 seekToView.layer.masksToBounds = true seekToView.isHidden = true seekToViewImage.image = BMImageResourcePath("Pod_Asset_BMPlayer_seek_to_image") addSubview(replayButton) replayButton.isHidden = true replayButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_replay"), for: .normal) replayButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside) replayButton.tag = ButtonType.replay.rawValue tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureTapped(_:))) addGestureRecognizer(tapGesture) if BMPlayerManager.shared.enablePlayControlGestures { doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onDoubleTapGestureRecognized(_:))) doubleTapGesture.numberOfTapsRequired = 2 addGestureRecognizer(doubleTapGesture) tapGesture.require(toFail: doubleTapGesture) } } func addSnapKitConstraint() { // Main mask view mainMaskView.snp.makeConstraints { [unowned self](make) in make.edges.equalTo(self) } maskImageView.snp.makeConstraints { [unowned self](make) in make.edges.equalTo(self.mainMaskView) } topMaskView.snp.makeConstraints { [unowned self](make) in make.top.left.right.equalTo(self.mainMaskView) } topWrapperView.snp.makeConstraints { [unowned self](make) in make.height.equalTo(50) if #available(iOS 11.0, *) { make.top.left.right.equalTo(self.topMaskView.safeAreaLayoutGuide) make.bottom.equalToSuperview() } else { make.top.equalToSuperview().offset(15) make.bottom.left.right.equalToSuperview() } } bottomMaskView.snp.makeConstraints { [unowned self](make) in make.bottom.left.right.equalTo(self.mainMaskView) } bottomWrapperView.snp.makeConstraints { [unowned self](make) in make.height.equalTo(50) if #available(iOS 11.0, *) { make.bottom.left.right.equalTo(self.bottomMaskView.safeAreaLayoutGuide) make.top.equalToSuperview() } else { make.edges.equalToSuperview() } } // Top views backButton.snp.makeConstraints { (make) in make.width.height.equalTo(50) make.left.bottom.equalToSuperview() } titleLabel.snp.makeConstraints { [unowned self](make) in make.left.equalTo(self.backButton.snp.right) make.centerY.equalTo(self.backButton) } chooseDefinitionView.snp.makeConstraints { [unowned self](make) in make.right.equalToSuperview().offset(-20) make.top.equalTo(self.titleLabel.snp.top).offset(-4) make.width.equalTo(60) make.height.equalTo(30) } // Bottom views playButton.snp.makeConstraints { (make) in make.width.equalTo(50) make.height.equalTo(50) make.left.bottom.equalToSuperview() } currentTimeLabel.snp.makeConstraints { [unowned self](make) in make.left.equalTo(self.playButton.snp.right) make.centerY.equalTo(self.playButton) make.width.equalTo(40) } timeSlider.snp.makeConstraints { [unowned self](make) in make.centerY.equalTo(self.currentTimeLabel) make.left.equalTo(self.currentTimeLabel.snp.right).offset(10).priority(750) make.height.equalTo(30) } progressView.snp.makeConstraints { [unowned self](make) in make.centerY.left.right.equalTo(self.timeSlider) make.height.equalTo(2) } totalTimeLabel.snp.makeConstraints { [unowned self](make) in make.centerY.equalTo(self.currentTimeLabel) make.left.equalTo(self.timeSlider.snp.right).offset(5) make.width.equalTo(40) } fullscreenButton.snp.makeConstraints { [unowned self](make) in make.width.equalTo(50) make.height.equalTo(50) make.centerY.equalTo(self.currentTimeLabel) make.left.equalTo(self.totalTimeLabel.snp.right) make.right.equalToSuperview() } loadingIndicator.snp.makeConstraints { [unowned self](make) in make.center.equalTo(self.mainMaskView) } // View to show when slide to seek seekToView.snp.makeConstraints { [unowned self](make) in make.center.equalTo(self.snp.center) make.width.equalTo(100) make.height.equalTo(40) } seekToViewImage.snp.makeConstraints { [unowned self](make) in make.left.equalTo(self.seekToView.snp.left).offset(15) make.centerY.equalTo(self.seekToView.snp.centerY) make.height.equalTo(15) make.width.equalTo(25) } seekToLabel.snp.makeConstraints { [unowned self](make) in make.left.equalTo(self.seekToViewImage.snp.right).offset(10) make.centerY.equalTo(self.seekToView.snp.centerY) } replayButton.snp.makeConstraints { [unowned self](make) in make.center.equalTo(self.mainMaskView) make.width.height.equalTo(50) } subtitleBackView.snp.makeConstraints { [unowned self](make) in make.bottom.equalTo(self.snp.bottom).offset(-5) make.centerX.equalTo(self.snp.centerX) make.width.lessThanOrEqualTo(self.snp.width).offset(-10).priority(750) } subtitleLabel.snp.makeConstraints { [unowned self](make) in make.left.equalTo(self.subtitleBackView.snp.left).offset(10) make.right.equalTo(self.subtitleBackView.snp.right).offset(-10) make.top.equalTo(self.subtitleBackView.snp.top).offset(2) make.bottom.equalTo(self.subtitleBackView.snp.bottom).offset(-2) } } fileprivate func BMImageResourcePath(_ fileName: String) -> UIImage? { let bundle = Bundle(for: BMPlayer.self) return UIImage(named: fileName, in: bundle, compatibleWith: nil) } }
mit
ff76cccd958aac9df616fb79bf844705
35.045455
132
0.618339
5.009928
false
false
false
false
diegocavalca/Studies
programming/Swift/TaskNote/TaskNote/AppDelegate.swift
1
6135
// // AppDelegate.swift // TaskNote // // Created by Diego Cavalca on 05/05/15. // Copyright (c) 2015 Diego Cavalca. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "br.com.diegocavalca.TaskNote" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("TaskNote", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TaskNote.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
cc0-1.0
f8006674e5db41c8a883705b02cacf93
54.27027
290
0.715729
5.706977
false
false
false
false
vnu/YelpMe
YelpMe/BusinessesViewController.swift
1
3101
// // BusinessesViewController.swift // Yelp // // Created by Vinu Charanya on 2/10/16. // Copyright © 2016 Vnu. All rights reserved. // import UIKit class BusinessesViewController: UIViewController { var businesses: [Business]! var searchBar:UISearchBar! let businessViewCellId = "com.vnu.BusinessViewCell" @IBOutlet var searchTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() loadBusinesses() setupSearchBar() } func setupSearchBar(){ searchBar = UISearchBar() searchBar?.sizeToFit() navigationItem.titleView = searchBar searchBar.delegate = self } func loadBusinesses(searchText: String = "Restaurants"){ YelpAPI.sharedInstance.searchWithTerm(searchText, completion: { (businesses: [Business]!, error: NSError!) -> Void in self.businesses = businesses self.searchTableView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension BusinessesViewController:FiltersViewControllerDelegate{ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let navigationController = segue.destinationViewController as! UINavigationController let filtersViewController = navigationController.topViewController as! FiltersViewController filtersViewController.delegate = self } func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: [String : AnyObject]) { let categories = filters["Categories"] as? [String] var sort = "0" var distance = "1609" var deals = false if let sortFilter = filters["Sort"] as? [String]{ sort = sortFilter[0] } if let distanceFilter = filters["Distance"] as? [String]{ distance = distanceFilter[0] } if let _ = filters["Deals"]{ deals = true } YelpAPI.sharedInstance.searchWithTerm("Restaurants", sort: sort, categories: categories, deals: deals, distance: distance) { (businesses: [Business]!, error: NSError!) -> Void in self.businesses = businesses self.searchTableView.reloadData() } } } extension BusinessesViewController:UISearchBarDelegate{ func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if !searchText.isEmpty{ loadBusinesses(searchText) } } } extension BusinessesViewController: UITableViewDataSource, UITableViewDelegate{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.businesses != nil ? self.businesses.count : 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(businessViewCellId) as! BusinessTableViewCell cell.business = businesses[indexPath.row] return cell } }
apache-2.0
676086255fefb19aab7c3a8e250b5aff
31.291667
186
0.675161
5.210084
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Preview/PPPReview.swift
3
3307
@objc(MWMPPPReview) final class PPPReview: MWMTableViewCell { @IBOutlet private weak var ratingSummaryView: RatingSummaryView! @IBOutlet private weak var reviewsLabel: UILabel! { didSet { reviewsLabel.font = UIFont.regular14() reviewsLabel.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var pricingLabel: UILabel! { didSet { pricingLabel.font = UIFont.regular14() } } @IBOutlet private weak var addReviewButton: UIButton! { didSet { addReviewButton.backgroundColor = UIColor.linkBlue() addReviewButton.setTitle("+ \(L("leave_a_review"))", for: .normal) addReviewButton.setTitleColor(UIColor.white, for: .normal) addReviewButton.titleLabel?.font = UIFont.bold12() } } @IBOutlet private weak var discountView: UIView! @IBOutlet private weak var discountLabel: UILabel! @IBOutlet private weak var priceConstraint: NSLayoutConstraint! typealias OnAddReview = () -> () private var onAddReview: OnAddReview? @objc func config(rating: UGCRatingValueType, canAddReview: Bool, isReviewedByUser: Bool, reviewsCount: UInt, ratingsCount: UInt, price: String, discount: Int, smartDeal: Bool, onAddReview: OnAddReview?) { self.onAddReview = onAddReview pricingLabel.text = price if discount > 0 { priceConstraint.priority = .defaultLow discountView.isHidden = false discountLabel.text = "-\(discount)%" } else if smartDeal { priceConstraint.priority = .defaultLow discountView.isHidden = false discountLabel.text = "%" } else { priceConstraint.priority = .defaultHigh discountView.isHidden = true } ratingSummaryView.textFont = UIFont.bold12() ratingSummaryView.value = rating.value ratingSummaryView.type = rating.type ratingSummaryView.backgroundOpacity = 0.05 if canAddReview && !isReviewedByUser { addReviewButton.isHidden = false addReviewButton.layer.cornerRadius = addReviewButton.height / 2 } else { addReviewButton.isHidden = true } pricingLabel.isHidden = true reviewsLabel.isHidden = false if rating.type == .noValue { if isReviewedByUser { ratingSummaryView.noValueImage = #imageLiteral(resourceName: "ic_12px_radio_on") ratingSummaryView.noValueColor = UIColor.linkBlue() reviewsLabel.text = L("placepage_reviewed") pricingLabel.isHidden = false } else { ratingSummaryView.noValueImage = #imageLiteral(resourceName: "ic_12px_rating_normal") ratingSummaryView.noValueColor = UIColor.blackSecondaryText() reviewsLabel.text = reviewsCount == 0 ? L("placepage_no_reviews") : "" } } else { ratingSummaryView.defaultConfig() reviewsLabel.text = ratingsCount > 0 ? String(format:L("placepage_summary_rating_description"), ratingsCount) : "" pricingLabel.isHidden = false } } @IBAction private func addReview() { onAddReview?() } override func layoutSubviews() { super.layoutSubviews() let inset = width / 2 separatorInset = UIEdgeInsetsMake(0, inset, 0, inset) } }
apache-2.0
51da202674ba59f89a50c707d95d47df
32.744898
93
0.660417
4.51776
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Schedule/Feedback/SessionFeedbackViewController.swift
1
7044
// // Copyright (c) 2017 Google Inc. // // 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 MaterialComponents class SessionFeedbackViewController: BaseCollectionViewController { let viewModel: SessionFeedbackViewModel let submitButton = UIBarButtonItem(title: NSLocalizedString("Submit", comment: "Submit button"), style: .done, target: self, action: #selector(submitButtonPressed(_:))) let cancelButton = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: "Cancel button"), style: .plain, target: self, action: #selector(cancelButtonPressed(_:))) fileprivate var survey = FeedbackSurvey() convenience init(sessionID: String, title: String, userState: PersistentUserState) { let viewModel = SessionFeedbackViewModel(sessionID: sessionID, title: title, userState: userState) self.init(viewModel: viewModel) } required init(viewModel: SessionFeedbackViewModel) { self.viewModel = viewModel let layout = MDCCollectionViewFlowLayout() layout.minimumLineSpacing = 8 super.init(collectionViewLayout: layout) } @objc override func setupViews() { super.setupViews() collectionView.backgroundColor = .white collectionView.register( SessionFeedbackCollectionViewCell.self, forCellWithReuseIdentifier: SessionFeedbackCollectionViewCell.reuseIdentifier() ) collectionView.register(FeedbackHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FeedbackHeader.identifier) self.title = NSLocalizedString("Rate Session", comment: "Rate Session screen title") navigationItem.leftBarButtonItem = cancelButton navigationItem.rightBarButtonItem = submitButton submitButton.isEnabled = false } @objc override func setupAppBar() -> MDCAppBarViewController { let bar = super.setupAppBar() let statusBarHeight = UIApplication.shared.statusBarFrame.height bar.headerView.minimumHeight = statusBarHeight + 40 bar.headerView.maximumHeight = statusBarHeight + 60 return bar } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported for controller of type \(SessionFeedbackViewController.self)") } } // MARK: - Submitting feedback extension SessionFeedbackViewController: SessionFeedbackRatingDelegate { @objc func cancelButtonPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } @objc func submitButtonPressed(_ sender: Any) { viewModel.submitFeedback(survey, presentingController: self) } func cell(_ cell: SessionFeedbackCollectionViewCell, didChangeRating rating: Int?, for feedbackQuestion: FeedbackQuestion) { survey.answers[feedbackQuestion] = rating submitButton.isEnabled = canSubmitFeedback } var canSubmitFeedback: Bool { return survey.isComplete } } // MARK: - UICollectionViewDataSource extension SessionFeedbackViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return survey.questions.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let reuseIdentifier = SessionFeedbackCollectionViewCell.reuseIdentifier() // swiftlint:disable force_cast let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SessionFeedbackCollectionViewCell // swiftlint:enable force_cast let question = survey.questions[indexPath.row] let rating = survey.answers[question] cell.populate(question: question, rating: rating, delegate: self, didSubmitFeedback: viewModel.didSubmitFeedback) return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // swiftlint:disable force_cast let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FeedbackHeader.identifier, for: indexPath) as! FeedbackHeader // swiftlint:enable force_cast view.populate(title: viewModel.sessionTitle, feedbackSubmitted: viewModel.didSubmitFeedback) return view } override func collectionView(_ collectionView: UICollectionView, shouldHideItemSeparatorAt indexPath: IndexPath) -> Bool { return true } } // MARK: - UICollectionViewDelegateFlowLayout extension SessionFeedbackViewController { override func collectionView(_ collectionView: UICollectionView, cellHeightAt indexPath: IndexPath) -> CGFloat { let question = survey.questions[indexPath.row] return SessionFeedbackCollectionViewCell.heightForCell(withTitle: question.body, maxWidth: view.frame.width) } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let width = self.view.frame.width let height = FeedbackHeader.height(withTitle: viewModel.sessionTitle, maxWidth: width, submittedFeedback: viewModel.didSubmitFeedback) return CGSize(width: width, height: height) } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) } }
apache-2.0
37b119a286ce603e659c42e6b045506e
38.351955
113
0.658291
5.989796
false
false
false
false
mikaoj/BSImagePicker
Sources/Presentation/Zoom/ZoomAnimator.swift
1
4374
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 final class ZoomAnimator : NSObject, UIViewControllerAnimatedTransitioning { enum Mode { case expand case shrink } var sourceImageView: UIImageView? var destinationImageView: UIImageView? let mode: Mode init(mode: Mode) { self.mode = mode super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.25 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // Get to and from view controller if let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let sourceImageView = sourceImageView, let destinationImageView = destinationImageView { let containerView = transitionContext.containerView // Setup views sourceImageView.isHidden = true destinationImageView.isHidden = true containerView.backgroundColor = toViewController.view.backgroundColor // Setup scaling image let scalingFrame = containerView.convert(sourceImageView.frame, from: sourceImageView.superview) let scalingImage = ImageView(frame: scalingFrame) scalingImage.contentMode = sourceImageView.contentMode scalingImage.clipsToBounds = true if mode == .expand { toViewController.view.alpha = 0.0 fromViewController.view.alpha = 1.0 scalingImage.image = destinationImageView.image ?? sourceImageView.image } else { scalingImage.image = sourceImageView.image ?? destinationImageView.image } // Add views to container view containerView.addSubview(toViewController.view) containerView.addSubview(scalingImage) // Convert destination frame let destinationFrame = containerView.convert(destinationImageView.bounds, from: destinationImageView.superview) // Animate UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: [], animations: { () -> Void in // Fade in fromViewController.view.alpha = 0.0 toViewController.view.alpha = 1.0 scalingImage.frame = destinationFrame scalingImage.contentMode = destinationImageView.contentMode }, completion: { (finished) -> Void in scalingImage.removeFromSuperview() // Unhide destinationImageView.isHidden = false fromViewController.view.alpha = 1.0 // Finish transition transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } } }
mit
b1e94114b45650633b7e83e3b0381677
43.622449
315
0.649211
6.040055
false
false
false
false
CosmicMind/Motion
Sources/Transition/MotionTransition+Start.swift
3
7082
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit extension MotionTransition { /// Starts the transition animation. func start() { guard .notified == state else { return } state = .starting prepareViewFrame() prepareViewControllers() prepareSnapshotView() preparePlugins() preparePreprocessors() prepareAnimators() for v in plugins { preprocessors.append(v) animators.append(v) } prepareTransitionContainer() prepareContainer() prepareContext() prepareViewHierarchy() prepareAnimatingViews() prepareToView() processPreprocessors() processAnimation() } } fileprivate extension MotionTransition { /// Prepares the views frames. func prepareViewFrame() { guard let fv = fromView else { return } guard let tv = toView else { return } if let toViewController = toViewController, let transitionContext = transitionContext { tv.frame = transitionContext.finalFrame(for: toViewController) } else { tv.frame = fv.frame } tv.setNeedsLayout() tv.layoutIfNeeded() } /// Prepares the from and to view controllers. func prepareViewControllers() { processStartTransitionDelegation(transitionContext: transitionContext, fromViewController: fromViewController, toViewController: toViewController) } /// Prepares the snapshot view, which hides any flashing that may occur. func prepareSnapshotView() { fullScreenSnapshot = transitionContainer?.window?.snapshotView(afterScreenUpdates: false) ?? fromView?.snapshotView(afterScreenUpdates: false) if let v = fullScreenSnapshot { (transitionContainer?.window ?? transitionContainer)?.addSubview(v) } if let v = fromViewController?.motionStoredSnapshot { v.removeFromSuperview() fromViewController?.motionStoredSnapshot = nil } if let v = toViewController?.motionStoredSnapshot { v.removeFromSuperview() toViewController?.motionStoredSnapshot = nil } } /// Prepares the plugins. func preparePlugins() { plugins = MotionTransition.enabledPlugins.map { return $0.init() } } /// Prepares the preprocessors. func preparePreprocessors() { preprocessors = [IgnoreSubviewTransitionsPreprocessor(), ConditionalPreprocessor(), TransitionPreprocessor(), MatchPreprocessor(), SourcePreprocessor(), CascadePreprocessor()] } /// Prepares the animators. func prepareAnimators() { animators = [MotionCoreAnimator<MotionCoreAnimationViewContext>()] if #available(iOS 10, tvOS 10, *) { animators.append(MotionCoreAnimator<MotionViewPropertyViewContext>()) } } /// Prepares the transition container. func prepareTransitionContainer() { transitioningViewController?.view.isUserInteractionEnabled = isUserInteractionEnabled transitionContainer?.isUserInteractionEnabled = isUserInteractionEnabled } /// Prepares the view that holds all the animating views. func prepareContainer() { container = UIView(frame: transitionContainer?.bounds ?? .zero) if !toOverFullScreen && !fromOverFullScreen { container.backgroundColor = containerBackgroundColor } transitionContainer?.addSubview(container) } /// Prepares the MotionContext instance. func prepareContext() { context = MotionContext(container: container) for v in preprocessors { v.motion = self } for v in animators { v.motion = self } guard let tv = toView else { return } guard let fv = fromView else { return } context.loadViewAlpha(rootView: tv) container.addSubview(tv) context.loadViewAlpha(rootView: fv) container.addSubview(fv) tv.setNeedsUpdateConstraints() tv.updateConstraintsIfNeeded() tv.setNeedsLayout() tv.layoutIfNeeded() context.set(fromViews: fv.flattenedViewHierarchy, toViews: tv.flattenedViewHierarchy) } /// Prepares the view hierarchy. func prepareViewHierarchy() { if (.auto == viewOrderStrategy && !isPresenting && !isTabBarController) || .sourceViewOnTop == viewOrderStrategy { context.insertToViewFirst = true } for v in preprocessors { v.process(fromViews: context.fromViews, toViews: context.toViews) } } /// Prepares the transition fromView & toView pairs. func prepareAnimatingViews() { animatingFromViews = context.fromViews.filter { (view) -> Bool in for animator in animators { if animator.canAnimate(view: view, isAppearing: false) { return true } } return false } animatingToViews = context.toViews.filter { (view) -> Bool in for animator in animators { if animator.canAnimate(view: view, isAppearing: true) { return true } } return false } } /// Prepares the to view. func prepareToView() { guard let tv = toView else { return } context.hide(view: tv) } } fileprivate extension MotionTransition { /// Executes the preprocessors' process function. func processPreprocessors() { for v in preprocessors { v.process(fromViews: context.fromViews, toViews: context.toViews) } } /// Processes the animations. func processAnimation() { #if os(tvOS) animate() #else if isNavigationController { // When animating within navigationController, we have to dispatch later into the main queue. // otherwise snapshots will be pure white. Possibly a bug with UIKit Motion.async { [weak self] in self?.animate() } } else { animate() } #endif } }
mit
c43a048eec1c986362cdbc4b564702e5
26.772549
150
0.671138
4.997883
false
false
false
false
xwu/swift
libswift/Sources/SIL/Type.swift
1
826
//===--- Type.swift - Value type ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SILBridging public struct Type { var bridged: BridgedType public var isAddress: Bool { SILType_isAddress(bridged) != 0 } public var isObject: Bool { !isAddress } public func isTrivial(in function: Function) -> Bool { return SILType_isTrivial(bridged, function.bridged) != 0 } }
apache-2.0
09433f543cd7eee819440b384bcee943
33.416667
80
0.605327
4.614525
false
false
false
false
XQS6LB3A/LyricsX
LyricsX/View/KaraokeLabel.swift
2
8079
// // KaraokeLabel.swift // LyricsX - https://github.com/ddddxxx/LyricsX // // 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 https://mozilla.org/MPL/2.0/. // import Cocoa import SwiftCF import CoreGraphicsExt import CoreTextExt class KaraokeLabel: NSTextField { @objc dynamic var isVertical = false { didSet { clearCache() invalidateIntrinsicContentSize() } } @objc dynamic var drawFurigana = false { didSet { clearCache() invalidateIntrinsicContentSize() } } override var attributedStringValue: NSAttributedString { didSet { clearCache() } } override var stringValue: String { didSet { clearCache() } } @objc override dynamic var font: NSFont? { didSet { clearCache() } } @objc override dynamic var textColor: NSColor? { didSet { clearCache() } } private func clearCache() { _attrString = nil _ctFrame = nil needsLayout = true needsDisplay = true removeProgressAnimation() } private var _attrString: NSAttributedString? private var attrString: NSAttributedString { if let attrString = _attrString { return attrString } let attrString = NSMutableAttributedString(attributedString: attributedStringValue) let string = attrString.string as NSString let shouldDrawFurigana = drawFurigana && string.dominantLanguage == "ja" let tokenizer = CFStringTokenizer.create(string: .from(string)) for tokenType in IteratorSequence(tokenizer) where tokenType.contains(.isCJWordMask) { if isVertical { let tokenRange = tokenizer.currentTokenRange() let attr: [NSAttributedString.Key: Any] = [ .verticalGlyphForm: true, .baselineOffset: (font?.pointSize ?? 24) * 0.25, ] attrString.addAttributes(attr, range: tokenRange.asNS) } guard shouldDrawFurigana else { continue } if let (furigana, range) = tokenizer.currentFuriganaAnnotation(in: string) { var attr: [CFAttributedString.Key: Any] = [.ctRubySizeFactor: 0.5] attr[.ctForegroundColor] = textColor let annotation = CTRubyAnnotation.create(furigana, attributes: attr) attrString.addAttribute(.cf(.ctRubyAnnotation), value: annotation, range: range) } } textColor?.do { attrString.addAttributes([.foregroundColor: $0], range: attrString.fullRange) } _attrString = attrString return attrString } private var _ctFrame: CTFrame? private var ctFrame: CTFrame { if let ctFrame = _ctFrame { return ctFrame } layoutSubtreeIfNeeded() let progression: CTFrameProgression = isVertical ? .rightToLeft : .topToBottom let frameAttr: [CTFrame.AttributeKey: Any] = [.progression: progression.rawValue as NSNumber] let framesetter = CTFramesetter.create(attributedString: attrString) let (suggestSize, fitRange) = framesetter.suggestFrameSize(constraints: bounds.size, frameAttributes: frameAttr) let path = CGPath(rect: CGRect(origin: .zero, size: suggestSize), transform: nil) let ctFrame = framesetter.frame(stringRange: fitRange, path: path, frameAttributes: frameAttr) _ctFrame = ctFrame return ctFrame } override var intrinsicContentSize: NSSize { let progression: CTFrameProgression = isVertical ? .rightToLeft : .topToBottom let frameAttr: [CTFrame.AttributeKey: Any] = [.progression: progression.rawValue as NSNumber] let framesetter = CTFramesetter.create(attributedString: attrString) let constraints = CGSize(width: CGFloat.infinity, height: .infinity) return framesetter.suggestFrameSize(constraints: constraints, frameAttributes: frameAttr).size } override func draw(_ dirtyRect: NSRect) { let context = NSGraphicsContext.current!.cgContext context.textMatrix = .identity context.translateBy(x: 0, y: bounds.height) context.scaleBy(x: 1.0, y: -1.0) CTFrameDraw(ctFrame, context) } // MARK: - Progress // TODO: multi-line private lazy var progressLayer: CALayer = { let pLayer = CALayer() wantsLayer = true layer?.addSublayer(pLayer) return pLayer }() @objc dynamic var progressColor: NSColor? { get { return progressLayer.backgroundColor.flatMap(NSColor.init) } set { progressLayer.backgroundColor = newValue?.cgColor } } func setProgressAnimation(color: NSColor, progress: [(TimeInterval, Int)]) { removeProgressAnimation() guard let line = ctFrame.lines.first, let origin = ctFrame.lineOrigins(range: CFRange(location: 0, length: 1)).first else { return } var lineBounds = line.bounds() var transform = CGAffineTransform.translate(x: origin.x, y: origin.y) if isVertical { transform.transform(by: .swap() * .translate(y: -lineBounds.width)) transform *= .flip(height: bounds.height) } lineBounds.apply(t: transform) progressLayer.anchorPoint = isVertical ? CGPoint(x: 0.5, y: 0) : CGPoint(x: 0, y: 0.5) progressLayer.frame = lineBounds progressLayer.backgroundColor = color.cgColor let mask = CALayer() mask.frame = progressLayer.bounds let img = NSImage(size: progressLayer.bounds.size, flipped: false) { _ in let context = NSGraphicsContext.current!.cgContext let ori = lineBounds.applying(.flip(height: self.bounds.height)).origin context.concatenate(.translate(x: -ori.x, y: -ori.y)) CTFrameDraw(self.ctFrame, context) return true } mask.contents = img.cgImage(forProposedRect: nil, context: nil, hints: nil) progressLayer.mask = mask guard let index = progress.firstIndex(where: { $0.0 > 0 }) else { return } var map = progress.map { ($0.0, line.offset(charIndex: $0.1).primary) } if index > 0 { let progress = map[index - 1].1 + CGFloat(map[index - 1].0) * (map[index].1 - map[index - 1].1) / CGFloat(map[index].0 - map[index - 1].0) map.replaceSubrange(..<index, with: [(0, progress)]) } let duration = map.last!.0 let animation = CAKeyframeAnimation() animation.keyTimes = map.map { ($0.0 / duration) as NSNumber } animation.values = map.map { $0.1 } animation.keyPath = isVertical ? "bounds.size.height" : "bounds.size.width" animation.duration = duration progressLayer.add(animation, forKey: "inlineProgress") } func pauseProgressAnimation() { let pausedTime = progressLayer.convertTime(CACurrentMediaTime(), from: nil) progressLayer.speed = 0 progressLayer.timeOffset = pausedTime } func resumeProgressAnimation() { let pausedTime = progressLayer.timeOffset progressLayer.speed = 1 progressLayer.timeOffset = 0 progressLayer.beginTime = 0 let timeSincePause = progressLayer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime progressLayer.beginTime = timeSincePause } func removeProgressAnimation() { CATransaction.begin() CATransaction.setDisableActions(true) progressLayer.speed = 1 progressLayer.timeOffset = 0 progressLayer.removeAnimation(forKey: "inlineProgress") progressLayer.frame = .zero CATransaction.commit() } }
gpl-3.0
4a838b13b8c8425d454866c392e44b46
36.752336
150
0.620869
4.769185
false
false
false
false
kunwang/absnetwork
ABSNetwork/Sources/ABSRequestorJoiner.swift
1
2307
// // ABSRequestorJoiner.swift // ABSNetwork // // Created by abstractwang on 2017/10/9. // Copyright © 2017年 com.abswang. All rights reserved. // import Foundation public protocol ABSRequestorJoinerDelegate: class { func allRequestFinished(_ allSuccessed: Bool, joiner: ABSRequestorJoiner) } public extension ABSRequestorJoinerDelegate { func allRequestFinished(_ allSuccessed: Bool, joiner: ABSRequestorJoinerDelegate) { // default do nothing } } public class ABSRequestorJoiner { private var _identifier: Int? public var requestors = [ABSRequestor]() public weak var delegate: ABSRequestorJoinerDelegate? public var allRequestFinishedCallback: ((Bool, ABSRequestorJoiner)->())? public init() { } public var identifier: Int? { return _identifier } public func identifier(_ identifier: Int?) -> ABSRequestorJoiner { _identifier = identifier return self } @discardableResult public func join(_ requestor: ABSRequestor) -> ABSRequestorJoiner { requestor.requestProcessFinish = {[weak self]() in self?.requestorProcessFinish()} self.requestors.append(requestor) return self } @discardableResult public func delegate(_ delegate: ABSRequestorJoinerDelegate) -> ABSRequestorJoiner { self.delegate = delegate return self } public func execute() { for requestor in requestors { requestor.execute() } } public func requestorProcessFinish() { var ret = true var allSuccessed = true for requestor in requestors { ret = ret && requestor.requestProcessFinished allSuccessed = allSuccessed && requestor.requestSuccessed } if ret { if let theDelegate = self.delegate { theDelegate.allRequestFinished(allSuccessed, joiner: self) } else { allRequestFinishedCallback?(allSuccessed, self) } } } public func cancel() { for requestor in self.requestors { requestor.cancel() } } public func clean() { cancel() requestors.removeAll() } }
mit
ad89fc79aa96ff9be8161ff184251a5b
24.318681
90
0.615451
4.840336
false
false
false
false
safx/TypetalkApp
TypetalkApp/OSX/Views/AttachmentView.swift
1
3414
// // AttachmentView.swift // TypetalkApp // // Created by Safx Developer on 2015/02/08. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import Cocoa import TypetalkKit import yavfl import RxSwift class AttachmentView: NSView { private var thumbnailImage: NSImageView? private var iconImage: NSImageView? private var fileInfoLabel: NSXLabel? private let disposeBag = DisposeBag() private(set) var model: URLAttachment? { didSet { modelDidSet() } } init(attachment: URLAttachment) { super.init(frame: NSMakeRect(0, 0, 0, 0)) // FIXME:RX self.model = attachment modelDidSet() } override init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func modelDidSet() { if let m = model { if m.attachment.isImageFile { thumbnailImage = NSImageView() //thumbnail.contentMode = .ScaleAspectFit self.addSubview(thumbnailImage!) visualFormat(thumbnailImage!) { thumbnail in .H ~ |-0-[thumbnail]-0-|; .V ~ |-0-[thumbnail]-0-|; } if let downloadRequest = DownloadAttachment(url: m.apiUrl, attachmentType: AttachmentView.resolveAttachmentType(m)) { let s = TypetalkAPI.rx_sendRequest(downloadRequest) s.subscribe( onNext: { res in Swift.print("** \(m.attachment.fileName)") dispatch_async(dispatch_get_main_queue(), { () in self.thumbnailImage!.image = NSImage(data: res) }) }, onError: { err in Swift.print("E \(err)") }, onCompleted:{ () in }) .addDisposableTo(disposeBag) } } else { fileInfoLabel = NSXLabel() let name = m.attachment.fileName let size = NSByteCountFormatter.stringFromByteCount(Int64(m.attachment.fileSize), countStyle: .File) let attr = [ NSForegroundColorAttributeName: NSColor.blueColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue ] let text = NSAttributedString(string: "\(name) (\(size))", attributes: attr) fileInfoLabel?.attributedStringValue = text self.addSubview(fileInfoLabel!) visualFormat(fileInfoLabel!) { label in .H ~ |-64-[label]-0-|; .V ~ |-0-[label]-0-|; } } } } class func viewHeight(a: URLAttachment) -> Int { let margin = 8 if !a.thumbnails.isEmpty { return a.thumbnails[0].height + margin } return a.attachment.isImageFile ? 200 : 30 + margin } class private func resolveAttachmentType(a: URLAttachment) -> AttachmentType? { if !a.thumbnails.isEmpty { return a.thumbnails[0].type // FIXME } return nil } }
mit
64ad07402dd04fd474796ed9335f12e3
33.12
133
0.520809
5.177542
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Honeycode/Honeycode_Shapes.swift
1
13015
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension Honeycode { // MARK: Enums public enum Format: String, CustomStringConvertible, Codable { case accounting = "ACCOUNTING" case auto = "AUTO" case contact = "CONTACT" case currency = "CURRENCY" case date = "DATE" case dateTime = "DATE_TIME" case number = "NUMBER" case percentage = "PERCENTAGE" case rowlink = "ROWLINK" case text = "TEXT" case time = "TIME" public var description: String { return self.rawValue } } // MARK: Shapes public struct ColumnMetadata: AWSDecodableShape { /// The format of the column. public let format: Format /// The name of the column. public let name: String public init(format: Format, name: String) { self.format = format self.name = name } private enum CodingKeys: String, CodingKey { case format case name } } public struct DataItem: AWSDecodableShape { /// The formatted value of the data. e.g. John Smith. public let formattedValue: String? /// The overrideFormat is optional and is specified only if a particular row of data has a different format for the data than the default format defined on the screen or the table. public let overrideFormat: Format? /// The raw value of the data. e.g. [email protected] public let rawValue: String? public init(formattedValue: String? = nil, overrideFormat: Format? = nil, rawValue: String? = nil) { self.formattedValue = formattedValue self.overrideFormat = overrideFormat self.rawValue = rawValue } private enum CodingKeys: String, CodingKey { case formattedValue case overrideFormat case rawValue } } public struct GetScreenDataRequest: AWSEncodableShape { /// The ID of the app that contains the screem. public let appId: String /// The number of results to be returned on a single page. Specify a number between 1 and 100. The maximum value is 100. This parameter is optional. If you don't specify this parameter, the default page size is 100. public let maxResults: Int? /// This parameter is optional. If a nextToken is not specified, the API returns the first page of data. Pagination tokens expire after 1 hour. If you use a token that was returned more than an hour back, the API will throw ValidationException. public let nextToken: String? /// The ID of the screen. public let screenId: String /// Variables are optional and are needed only if the screen requires them to render correctly. Variables are specified as a map where the key is the name of the variable as defined on the screen. The value is an object which currently has only one property, rawValue, which holds the value of the variable to be passed to the screen. public let variables: [String: VariableValue]? /// The ID of the workbook that contains the screen. public let workbookId: String public init(appId: String, maxResults: Int? = nil, nextToken: String? = nil, screenId: String, variables: [String: VariableValue]? = nil, workbookId: String) { self.appId = appId self.maxResults = maxResults self.nextToken = nextToken self.screenId = screenId self.variables = variables self.workbookId = workbookId } public func validate(name: String) throws { try self.validate(self.appId, name: "appId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.screenId, name: "screenId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") try self.validate(self.workbookId, name: "workbookId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") } private enum CodingKeys: String, CodingKey { case appId case maxResults case nextToken case screenId case variables case workbookId } } public struct GetScreenDataResult: AWSDecodableShape { /// Provides the pagination token to load the next page if there are more results matching the request. If a pagination token is not present in the response, it means that all data matching the query has been loaded. public let nextToken: String? /// A map of all the rows on the screen keyed by block name. public let results: [String: ResultSet] /// Indicates the cursor of the workbook at which the data returned by this workbook is read. Workbook cursor keeps increasing with every update and the increments are not sequential. public let workbookCursor: Int64 public init(nextToken: String? = nil, results: [String: ResultSet], workbookCursor: Int64) { self.nextToken = nextToken self.results = results self.workbookCursor = workbookCursor } private enum CodingKeys: String, CodingKey { case nextToken case results case workbookCursor } } public struct InvokeScreenAutomationRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "appId", location: .uri(locationName: "appId")), AWSMemberEncoding(label: "screenAutomationId", location: .uri(locationName: "automationId")), AWSMemberEncoding(label: "screenId", location: .uri(locationName: "screenId")), AWSMemberEncoding(label: "workbookId", location: .uri(locationName: "workbookId")) ] /// The ID of the app that contains the screen automation. public let appId: String /// The request token for performing the automation action. Request tokens help to identify duplicate requests. If a call times out or fails due to a transient error like a failed network connection, you can retry the call with the same request token. The service ensures that if the first call using that request token is successfully performed, the second call will return the response of the previous call rather than performing the action again. Note that request tokens are valid only for a few minutes. You cannot use request tokens to dedupe requests spanning hours or days. public let clientRequestToken: String? /// The row ID for the automation if the automation is defined inside a block with source or list. public let rowId: String? /// The ID of the automation action to be performed. public let screenAutomationId: String /// The ID of the screen that contains the screen automation. public let screenId: String /// Variables are optional and are needed only if the screen requires them to render correctly. Variables are specified as a map where the key is the name of the variable as defined on the screen. The value is an object which currently has only one property, rawValue, which holds the value of the variable to be passed to the screen. public let variables: [String: VariableValue]? /// The ID of the workbook that contains the screen automation. public let workbookId: String public init(appId: String, clientRequestToken: String? = nil, rowId: String? = nil, screenAutomationId: String, screenId: String, variables: [String: VariableValue]? = nil, workbookId: String) { self.appId = appId self.clientRequestToken = clientRequestToken self.rowId = rowId self.screenAutomationId = screenAutomationId self.screenId = screenId self.variables = variables self.workbookId = workbookId } public func validate(name: String) throws { try self.validate(self.appId, name: "appId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 64) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 32) try self.validate(self.rowId, name: "rowId", parent: name, pattern: "row:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") try self.validate(self.screenAutomationId, name: "screenAutomationId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") try self.validate(self.screenId, name: "screenId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") try self.validate(self.workbookId, name: "workbookId", parent: name, pattern: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") } private enum CodingKeys: String, CodingKey { case clientRequestToken case rowId case variables } } public struct InvokeScreenAutomationResult: AWSDecodableShape { /// The updated workbook cursor after performing the automation action. public let workbookCursor: Int64 public init(workbookCursor: Int64) { self.workbookCursor = workbookCursor } private enum CodingKeys: String, CodingKey { case workbookCursor } } public struct ResultRow: AWSDecodableShape { /// List of all the data cells in a row. public let dataItems: [DataItem] /// The ID for a particular row. public let rowId: String? public init(dataItems: [DataItem], rowId: String? = nil) { self.dataItems = dataItems self.rowId = rowId } private enum CodingKeys: String, CodingKey { case dataItems case rowId } } public struct ResultSet: AWSDecodableShape { /// List of headers for all the data cells in the block. The header identifies the name and default format of the data cell. Data cells appear in the same order in all rows as defined in the header. The names and formats are not repeated in the rows. If a particular row does not have a value for a data cell, a blank value is used. For example, a task list that displays the task name, due date and assigned person might have headers [ { "name": "Task Name"}, {"name": "Due Date", "format": "DATE"}, {"name": "Assigned", "format": "CONTACT"} ]. Every row in the result will have the task name as the first item, due date as the second item and assigned person as the third item. If a particular task does not have a due date, that row will still have a blank value in the second element and the assigned person will still be in the third element. public let headers: [ColumnMetadata] /// List of rows returned by the request. Each row has a row Id and a list of data cells in that row. The data cells will be present in the same order as they are defined in the header. public let rows: [ResultRow] public init(headers: [ColumnMetadata], rows: [ResultRow]) { self.headers = headers self.rows = rows } private enum CodingKeys: String, CodingKey { case headers case rows } } public struct VariableValue: AWSEncodableShape { /// Raw value of the variable. public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } private enum CodingKeys: String, CodingKey { case rawValue } } }
apache-2.0
f158a759a4ab71526e6d3dc009f443cd
50.85259
858
0.639262
4.261624
false
false
false
false
nerdishbynature/octokit.swift
Tests/OctoKitTests/StatusesTests.swift
1
7354
import OctoKit import XCTest class StatusesTests: XCTestCase { // MARK: Actual Request tests func testCreateCommitStatus() { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", expectedHTTPMethod: "POST", jsonFile: "status", statusCode: 201) let task = Octokit().createCommitStatus(session, owner: "octocat", repository: "Hello-World", sha: "6dcb09b5b57875f334f61aebed695e2e4193db5e", state: .success, targetURL: "https://example.com/build/status", description: "The build succeeded!", context: "continuous-integration/jenkins") { response in switch response { case let .success(status): XCTAssertEqual(status.id, 1) XCTAssertEqual(status.url, "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e") XCTAssertEqual(status.avatarURL, "https://github.com/images/error/hubot_happy.gif") XCTAssertEqual(status.nodeId, "MDY6U3RhdHVzMQ==") XCTAssertEqual(status.state, Status.State.success) XCTAssertEqual(status.description, "Build has completed successfully") XCTAssertEqual(status.targetURL, "https://ci.example.com/1000/output") XCTAssertEqual(status.context, "continuous-integration/jenkins") XCTAssertEqual(status.creator?.login, "octocat") case let .failure(error): XCTAssertNil(error) } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testCreateCommitStatusAsync() async throws { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", expectedHTTPMethod: "POST", jsonFile: "status", statusCode: 201) let status = try await Octokit().createCommitStatus(session, owner: "octocat", repository: "Hello-World", sha: "6dcb09b5b57875f334f61aebed695e2e4193db5e", state: .success, targetURL: "https://example.com/build/status", description: "The build succeeded!", context: "continuous-integration/jenkins") XCTAssertEqual(status.id, 1) XCTAssertEqual(status.url, "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e") XCTAssertEqual(status.avatarURL, "https://github.com/images/error/hubot_happy.gif") XCTAssertEqual(status.nodeId, "MDY6U3RhdHVzMQ==") XCTAssertEqual(status.state, Status.State.success) XCTAssertEqual(status.description, "Build has completed successfully") XCTAssertEqual(status.targetURL, "https://ci.example.com/1000/output") XCTAssertEqual(status.context, "continuous-integration/jenkins") XCTAssertEqual(status.creator?.login, "octocat") XCTAssertTrue(session.wasCalled) } #endif func testListCommitStatuses() { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/statuses", expectedHTTPMethod: "GET", jsonFile: "statuses", statusCode: 200) let task = Octokit().listCommitStatuses(session, owner: "octocat", repository: "Hello-World", ref: "6dcb09b5b57875f334f61aebed695e2e4193db5e") { response in switch response { case let .success(statuses): XCTAssertEqual(statuses.count, 1) XCTAssertEqual(statuses.first?.id, 1) XCTAssertEqual(statuses.first?.url, "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e") XCTAssertEqual(statuses.first?.avatarURL, "https://github.com/images/error/hubot_happy.gif") XCTAssertEqual(statuses.first?.nodeId, "MDY6U3RhdHVzMQ==") XCTAssertEqual(statuses.first?.state, Status.State.success) XCTAssertEqual(statuses.first?.description, "Build has completed successfully") XCTAssertEqual(statuses.first?.targetURL, "https://ci.example.com/1000/output") XCTAssertEqual(statuses.first?.context, "continuous-integration/jenkins") XCTAssertEqual(statuses.first?.creator?.login, "octocat") case let .failure(error): XCTAssertNil(error) } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testListCommitStatusesAsync() async throws { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/statuses", expectedHTTPMethod: "GET", jsonFile: "statuses", statusCode: 200) let statuses = try await Octokit().listCommitStatuses(session, owner: "octocat", repository: "Hello-World", ref: "6dcb09b5b57875f334f61aebed695e2e4193db5e") XCTAssertEqual(statuses.count, 1) XCTAssertEqual(statuses.first?.id, 1) XCTAssertEqual(statuses.first?.url, "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e") XCTAssertEqual(statuses.first?.avatarURL, "https://github.com/images/error/hubot_happy.gif") XCTAssertEqual(statuses.first?.nodeId, "MDY6U3RhdHVzMQ==") XCTAssertEqual(statuses.first?.state, Status.State.success) XCTAssertEqual(statuses.first?.description, "Build has completed successfully") XCTAssertEqual(statuses.first?.targetURL, "https://ci.example.com/1000/output") XCTAssertEqual(statuses.first?.context, "continuous-integration/jenkins") XCTAssertEqual(statuses.first?.creator?.login, "octocat") XCTAssertTrue(session.wasCalled) } #endif }
mit
a08214aa34b10bfc3426ede61380682b
61.322034
166
0.579413
4.6339
false
true
false
false
tattn/SPAJAM2017-Final
SPAJAM2017Final/UI/EpisodeVC.swift
1
1219
// // EpisodeVC.swift // SPAJAM2017Final // // Created by 熊本 和正 on 2017/07/09. // Copyright © 2017年 tattn. All rights reserved. // import UIKit import Instantiate import InstantiateStandard final class EpisodeVC: UIViewController { @IBOutlet weak var episodeLabel: UILabel! static var instantiateSource: InstantiateSource { return .identifier(className) } override func viewDidLoad() { super.viewDidLoad() let lineHeight: CGFloat = 25.0 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight let attributedText = NSMutableAttributedString(string: episodeLabel.text!) attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedText.length)) episodeLabel.attributedText = attributedText } } extension EpisodeVC: StoryboardInstantiatable { struct Dependency { let title: String // let id: String } func inject(_ dependency: Dependency) { title = dependency.title // dependency.id } }
mit
1dd5e76db46b97aa03ac4b84f84957cc
26.409091
135
0.681592
5.131915
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCDomain/Analytics/AnalyticsEvents+Verification.swift
1
1017
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import PlatformKit import ToolKit extension AnalyticsEvents.New { public enum Verification: AnalyticsEvent { public var type: AnalyticsEventType { .nabu } case verificationSubmissionFailed( failureReason: FailureReason, provider: Provider, tier: Int ) } public enum FailureReason: String, StringRawRepresentable { case localError = "LOCAL_ERROR" case networkError = "NETWORK_ERROR" case serverError = "SERVER_ERROR" case uploadError = "UPLOAD_ERROR" case videoFailed = "VIDEO_FAILED" case unknown = "UNKNOWN" } public enum Provider: String, StringRawRepresentable { case blockchain = "BLOCKCHAIN" case manual = "MANUAL" case onfido = "ONFIDO" case rdc = "RDC" case rdcMedia = "RDC_MEDIA" case rdcPep = "RDC_PEP" case veriff = "VERIFF" } }
lgpl-3.0
6482f3d0a50a966dfec4246338594478
26.459459
63
0.627953
4.45614
false
false
false
false
modocache/swift
test/IDE/coloring.swift
1
20532
// RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s // RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s // XFAIL: broken_std_regex #line 17 "abc.swift" // CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str> @available(iOS 8.0, OSX 10.10, *) // CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *) func foo() { // CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>} if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"} } enum List<T> { case Nil // rdar://21927124 // CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List) indirect case Cons(T, List) } // CHECK: <kw>struct</kw> S { struct S { // CHECK: <kw>var</kw> x : <type>Int</type> var x : Int // CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type> var y : Int.Int // CHECK: <kw>var</kw> a, b : <type>Int</type> var a, b : Int } enum EnumWithDerivedEquatableConformance : Int { // CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} { case CaseA // CHECK-NEXT: <kw>case</kw> CaseA case CaseB, CaseC // CHECK-NEXT: <kw>case</kw> CaseB, CaseC case CaseD = 30, CaseE // CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE } // CHECK-NEXT: } // CHECK: <kw>class</kw> MyCls { class MyCls { // CHECK: <kw>var</kw> www : <type>Int</type> var www : Int // CHECK: <kw>func</kw> foo(x: <type>Int</type>) {} func foo(x: Int) {} // CHECK: <kw>var</kw> aaa : <type>Int</type> { var aaa : Int { // CHECK: <kw>get</kw> {} get {} // CHECK: <kw>set</kw> {} set {} } // CHECK: <kw>var</kw> bbb : <type>Int</type> { var bbb : Int { // CHECK: <kw>set</kw> { set { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } } // CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> { subscript (i : Int, j : Int) -> Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> i + j return i + j } // CHECK: <kw>set</kw>(v) { set(v) { // CHECK: v + i - j v + i - j } } // CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {} func multi(_ name: Int, otherpart x: Int) {} } // CHECK-LABEL: <kw>class</kw> Attributes { class Attributes { // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type> @IBOutlet var v0: Int // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @IBOutlet var v1: String // CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type> @objc @IBOutlet var v2: String // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @objc var v3: String // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {} @available(*, unavailable) func f1() {} // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {} @available(*, unavailable) @IBAction func f2() {} // CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {} @IBAction @available(*, unavailable) func f3() {} // CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {} mutating func func_mutating_1() {} // CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {} nonmutating func func_mutating_2() {} } func stringLikeLiterals() { // CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str> var us1: UnicodeScalar = "a" // CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str> var us2: UnicodeScalar = "ы" // CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str> var ch1: Character = "a" // CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str> var ch2: Character = "あ" // CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str> var s1 = "abc абвгд あいうえお" } // CHECK: <kw>var</kw> globComp : <type>Int</type> var globComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> <int>0</int> return 0 } } // CHECK: <comment-block>/* foo is the best */</comment-block> /* foo is the best */ // CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> { func foo(n: Float) -> Int { // CHECK: <kw>var</kw> fnComp : <type>Int</type> var fnComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> a: <type>Int</type> // CHECK: <kw>return</kw> <int>0</int> var a: Int return 0 } } // CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}() var q = MyCls() // CHECK: <kw>var</kw> ee = <str>"yoo"</str>; var ee = "yoo"; // CHECK: <kw>return</kw> <int>100009</int> return 100009 } ///- returns: single-line, no space // CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space /// - returns: single-line, 1 space // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space /// - returns: single-line, 2 spaces // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces /// - returns: single-line, more spaces // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces // CHECK: <kw>protocol</kw> Prot { protocol Prot { // CHECK: <kw>typealias</kw> Blarg typealias Blarg // CHECK: <kw>func</kw> protMeth(x: <type>Int</type>) func protMeth(x: Int) // CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> } var protocolProperty1: Int { get } // CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> } var protocolProperty2: Int { get set } } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}} infix operator *-* : FunnyPrecedence // CHECK: <kw>precedencegroup</kw> FunnyPrecedence // CHECK-NEXT: <kw>associativity</kw>: left{{$}} // CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence precedencegroup FunnyPrecedence { associativity: left higherThan: MultiplicationPrecedence } // CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence infix operator *-+* : FunnyPrecedence // CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-+*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}} infix operator *--* // CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *--*(l: Int, r: Int) -> Int { return l } // CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {} protocol Prot2 : Prot {} // CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {} class SubCls : MyCls, Prot {} // CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}} func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {} func f(x: Int) -> Int { // CHECK: <comment-line>// string interpolation is the best</comment-line> // string interpolation is the best // CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str> "This is string \(genFn({(a:Int -> Int) in a})) interpolation" } // CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) { func bar(x: Int) -> (Int, Float) { // CHECK: foo({{(<type>)?}}Float{{(</type>)?}}()) foo(Float()) } class GenC<T1,T2> {} func test() { // CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>() var x = GenC<Int, Float>() } // CHECK: <kw>typealias</kw> MyInt = <type>Int</type> typealias MyInt = Int func test2(x: Int) { // CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str> "\(x)" } // CHECK: <kw>class</kw> Observers { class Observers { // CHECK: <kw>var</kw> p1 : <type>Int</type> { var p1 : Int { // CHECK: <kw>willSet</kw>(newValue) {} willSet(newValue) {} // CHECK: <kw>didSet</kw> {} didSet {} } // CHECK: <kw>var</kw> p2 : <type>Int</type> { var p2 : Int { // CHECK: <kw>didSet</kw> {} didSet {} // CHECK: <kw>willSet</kw> {} willSet {} } } // CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) { func test3(o: AnyObject) { // CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type> let x = o as! MyCls } // CHECK: <kw>func</kw> test4(inout a: <type>Int</type>) {{{$}} func test4(inout a: Int) { // CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}} if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}} // CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}} func test4b(a: inout Int) { } // CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> { class MySubClass : MyCls { // CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {} override func foo(x: Int) {} // CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {} convenience init(a: Int) {} } // CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> } var g1 = { (x: Int) -> Int in return 0 } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ { infix operator ~~ {} // CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ { prefix operator *~~ {} // CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* { postfix operator ~~* {} func test_defer() { defer { // CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int> let x : Int = 0 } } // FIXME: blah. // FIXME: blah blah // Something something, FIXME: blah // CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line> // CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line> /* FIXME: blah*/ // CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block> /* * FIXME: blah * Blah, blah. */ // CHECK: <comment-block>/* // CHECK: * <comment-marker>FIXME: blah</comment-marker> // CHECK: * Blah, blah. // CHECK: */</comment-block> // TODO: blah. // TTODO: blah. // MARK: blah. // CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line> // CHECK: <kw>func</kw> test5() -> <type>Int</type> { func test5() -> Int { // CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line> // TODO: something, something. // CHECK: <kw>return</kw> <int>0</int> return 0 } func test6<T : Prot>(x: T) {} // CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}} // http://whatever.com?ee=2&yy=1 and radar://123456 /* http://whatever.com FIXME: see in http://whatever.com/fixme http://whatever.com */ // CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line> // CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker> // CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block> // CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line> // http://whatever.com/what-ever // CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {} func <#test1#> () {} /// Brief. /// /// Simple case. /// /// - parameter x: A number /// - parameter y: Another number /// - returns: `x + y` func foo(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /// Brief. /// /// Simple case. /// /// - Parameters: /// - x: A number /// - y: Another number /// ///- note: NOTE1 /// /// - NOTE: NOTE2 /// - note: Not a Note field (not at top level) /// - returns: `x + y` func bar(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>: // CHECK: </doc-comment-line><doc-comment-line>/// - x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /** Does pretty much nothing. Not a parameter list: improper indentation. - Parameters: sdfadsf - WARNING: - WARNING: Should only have one field - $$$: Not a field. Empty field, OK: */ func baz() {} // CHECK: <doc-comment-block>/** // CHECK: Does pretty much nothing. // CHECK: Not a parameter list: improper indentation. // CHECK: - Parameters: sdfadsf // CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field // CHECK: - $$$: Not a field. // CHECK: Empty field, OK: // CHECK: */</doc-comment-block> // CHECK: <kw>func</kw> baz() {} /***/ func emptyDocBlockComment() {} // CHECK: <doc-comment-block>/***/</doc-comment-block> // CHECK: <kw>func</kw> emptyDocBlockComment() {} /** */ func emptyDocBlockComment2() {} // CHECK: <doc-comment-block>/** // CHECK: */ // CHECK: <kw>func</kw> emptyDocBlockComment2() {} /** */ func emptyDocBlockComment3() {} // CHECK: <doc-comment-block>/** */ // CHECK: <kw>func</kw> emptyDocBlockComment3() {} /**/ func malformedBlockComment(f : () throws -> ()) rethrows {} // CHECK: <doc-comment-block>/**/</doc-comment-block> // CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {} //: playground doc comment line func playgroundCommentLine(f : () throws -> ()) rethrows {} // CHECK: <comment-line>//: playground doc comment line</comment-line> /*: playground doc comment multi-line */ func playgroundCommentMultiLine(f : () throws -> ()) rethrows {} // CHECK: <comment-block>/*: // CHECK: playground doc comment multi-line // CHECK: */</comment-block> /// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings) // CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url> func funcTakingFor(for internalName: Int) {} // CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {} func funcTakingIn(in internalName: Int) {} // CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {} _ = 123 // CHECK: <int>123</int> _ = -123 // CHECK: <int>-123</int> _ = -1 // CHECK: <int>-1</int> _ = -0x123 // CHECK: <int>-0x123</int> _ = -3.1e-5 // CHECK: <float>-3.1e-5</float> /** aaa - returns: something */ // CHECK: - <doc-comment-field>returns</doc-comment-field>: something let filename = #file // CHECK: <kw>let</kw> filename = <kw>#file</kw> let line = #line // CHECK: <kw>let</kw> line = <kw>#line</kw> let column = #column // CHECK: <kw>let</kw> column = <kw>#column</kw> let function = #function // CHECK: <kw>let</kw> function = <kw>#function</kw> let image = #imageLiteral(resourceName: "cloud.png") // CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal> let file = #fileLiteral(resourceName: "cloud.png") // CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal> let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) // CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal> let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1), #colorLiteral(red: 0, green: 1, blue: 0, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)] // CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>, // CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>, // CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>] "--\"\(x) --" // CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str> func keywordAsLabel1(in: Int) {} // CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {} func keywordAsLabel2(for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {} func keywordAsLabel3(if: Int, for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {} func keywordAsLabel4(_: Int) {} // CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {} func keywordAsLabel5(_: Int, for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {} func keywordAsLabel6(if let: Int) {} // CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {} func foo1() { // CHECK: <kw>func</kw> foo1() { keywordAsLabel1(in: 1) // CHECK: keywordAsLabel1(in: <int>1</int>) keywordAsLabel2(for: 1) // CHECK: keywordAsLabel2(for: <int>1</int>) keywordAsLabel3(if: 1, for: 2) // CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>) keywordAsLabel5(1, for: 2) // CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>) _ = (if: 0, for: 2) // CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>) _ = (_: 0, _: 2) // CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>) } func foo2(O1 : Int?, O2: Int?, O3: Int?) { guard let _ = O1, var _ = O2, let _ = O3 else { } // CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { } if let _ = O1, var _ = O2, let _ = O3 {} // CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {} } // Keep this as the last test /** Trailing off ... func unterminatedBlockComment() {} // CHECK: <comment-line>// Keep this as the last test</comment-line> // CHECK: <doc-comment-block>/** // CHECK: Trailing off ... // CHECK: func unterminatedBlockComment() {} // CHECK: </doc-comment-block>
apache-2.0
461d5fce7c634ce39d2fbe5452b0bdac
35.404973
178
0.600215
2.861371
false
false
false
false
tikhop/TPKit
Pod/Sources/Date+Extension.swift
1
2397
// // NSDate+Extension.swift // Alias // // Created by Pavel Tikhonenko on 13/04/15. // Copyright (c) 2015 Pavel Tikhonenko. All rights reserved. // import Foundation public extension Date { func isSame(to date: Date) -> Bool { let calendar = Calendar.current let comp1 = (calendar as NSCalendar).components([NSCalendar.Unit.month, NSCalendar.Unit.day, NSCalendar.Unit.year], from: self) let comp2 = (calendar as NSCalendar).components([NSCalendar.Unit.month, NSCalendar.Unit.day, NSCalendar.Unit.year], from: date) return (comp1.day == comp2.day) && (comp1.month == comp2.month) && (comp1.year == comp2.year) } func isDateToday() -> Bool { let otherDay = (Calendar.current as NSCalendar).components([.era, .year, .month, .day], from: self) let today = (Calendar.current as NSCalendar).components([.era, .year, .month, .day], from: Date()) let isToday = (today.day == otherDay.day && today.month == otherDay.month && today.year == otherDay.year && today.era == otherDay.era) return isToday } func isDateWithinWeek() -> Bool { return isDateWithinDaysBefore(7) } func isDateWithinDaysBefore(_ days: Int) -> Bool { let now = Date() let calendar = Calendar.current let beforeDate = calendar.date(byAdding: .day, value: -days, to: now, wrappingComponents: false) if(self.compare(beforeDate!) == .orderedDescending) { if(self.compare(now) == .orderedAscending) { return true } } return false } func formatedString(dateFormat: String = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'", timeZone: TimeZone = TimeZone.autoupdatingCurrent) -> String? { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = timeZone return formatter.string(from: self) } } public extension String { func date(dateFormat: String, timeZone: TimeZone = TimeZone.autoupdatingCurrent) -> Date? { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = timeZone let date = formatter.date(from: self) return date } }
mit
19817fc4a9df9735b8e8a3607bff1788
28.9625
142
0.59491
4.257549
false
false
false
false
getsentry/sentry-swift
Samples/tvOS-Swift/tvOS-SBSwift/ActionCell.swift
1
1652
import Foundation import UIKit class ActionCell: UICollectionViewCell { var titleLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder: NSCoder) { super.init(coder: coder) initialize() } private func initialize() { layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowRadius = 4 contentView.layer.cornerRadius = 20 contentView.layer.masksToBounds = true titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.textAlignment = .center titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) let constraints = [ titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 32), titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -32), titleLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 32), titleLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -32) ] NSLayoutConstraint.activate(constraints) } override func layoutSubviews() { super.layoutSubviews() UIView.animate(withDuration: 0.2) { self.contentView.backgroundColor = self.isFocused ? UIColor(white: 0.3, alpha: 1) : UIColor.black self.layer.shadowOffset = self.isFocused ? CGSize(width: 6, height: 3) : CGSize(width: 2, height: 1) } } }
mit
7631d13a68c084b87e3c70203d86e8d8
31.392157
112
0.633777
5.194969
false
false
false
false
tjw/swift
test/multifile/keypath.swift
4
209
// RUN: %target-swift-frontend -emit-ir %S/Inputs/keypath.swift -primary-file %s func f<T>(_: T) { _ = \C<T>.b _ = \C<T>[0] _ = \D<T>.b _ = \D<T>[0] _ = \P.b // FIXME: crashes // _ = \P[0] }
apache-2.0
30bb600330285b53ebc4da42dc6c88ac
13.928571
80
0.449761
2.111111
false
false
false
false
apple/swift
test/decl/protocol/special/coding/class_codable_simple_conditional_final_separate.swift
36
1603
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4 final class Conditional<T> { var x: T var y: T? init() { fatalError() } func foo() { // They should receive a synthesized CodingKeys enum. let _ = Conditional.CodingKeys.self // The enum should have a case for each of the vars. let _ = Conditional.CodingKeys.x let _ = Conditional.CodingKeys.y // Static vars should not be part of the CodingKeys enum. let _ = Conditional.CodingKeys.z // expected-error {{type 'Conditional<T>.CodingKeys' has no member 'z'}} } } extension Conditional: Encodable where T: Encodable { // expected-note {{where 'T' = 'OnlyDec'}} } extension Conditional: Decodable where T: Decodable { // expected-note {{where 'T' = 'OnlyEnc'}} } struct OnlyEnc: Encodable {} struct OnlyDec: Decodable {} // They should receive synthesized init(from:) and an encode(to:). let _ = Conditional<OnlyDec>.init(from:) let _ = Conditional<OnlyEnc>.encode(to:) // but only for the appropriately *codable parameters. let _ = Conditional<OnlyEnc>.init(from:) // expected-error {{referencing initializer 'init(from:)' on 'Conditional' requires that 'OnlyEnc' conform to 'Decodable'}} let _ = Conditional<OnlyDec>.encode(to:) // expected-error {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'OnlyDec' conform to 'Encodable'}} // The synthesized CodingKeys type should not be accessible from outside the // struct. let _ = Conditional<Int>.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
e3e6cfad8a6a46f0df709dc3565cc891
37.166667
168
0.708671
3.967822
false
false
false
false
JarlRyan/IOSNote
Swift/EmptyTableView/EmptyTableView/RootViewController.swift
1
1460
// // RootViewController.swift // EmptyTableView // // Created by bingoogol on 14-6-17. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class RootViewController : UIViewController,UITableViewDataSource,UITableViewDelegate { var dataArr = NSMutableArray() var _tableView:UITableView? override func viewDidLoad() { super.viewDidLoad() for index in 1 ... 50 { dataArr.addObject("row \(index)") } _tableView = UITableView(frame:CGRect(x:10,y:10,width:200,height:400)) _tableView!.delegate = self _tableView!.dataSource = self self.view.addSubview(_tableView) } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return dataArr.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cellid = "my cell id" var cell = tableView.dequeueReusableCellWithIdentifier(cellid) as? UITableViewCell if !cell { cell = UITableViewCell(style: .Default, reuseIdentifier: cellid) } var data = dataArr.objectAtIndex(indexPath.row) as? String cell!.textLabel.text = data return cell } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { println("点击了\(indexPath.row)") } }
apache-2.0
a3de7622a468eedd82af74c1818097d3
29.893617
112
0.646006
4.922034
false
false
false
false
uasys/swift
tools/SwiftSyntax/SyntaxData.swift
6
8012
//===-------------------- SyntaxData.swift - Syntax Data ------------------===// // // 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 Foundation /// A unique identifier for a node in the tree. /// Currently, this is an index path from the current node to the root of the /// tree. It's an implementation detail and shouldn't be /// exposed to clients. typealias NodeIdentifier = [Int] /// SyntaxData is the underlying storage for each Syntax node. /// It's modelled as an array that stores and caches a SyntaxData for each raw /// syntax node in its layout. It is up to the specific Syntax nodes to maintain /// the correct layout of their SyntaxData backing stores. /// /// SyntaxData is an implementation detail, and should not be exposed to clients /// of libSyntax. /// /// The following relationships are preserved: /// parent.cachedChild(at: indexInParent) === self /// raw.layout.count == childCaches.count /// pathToRoot.first === indexInParent final class SyntaxData: Equatable { let raw: RawSyntax let indexInParent: Int weak var parent: SyntaxData? let childCaches: [AtomicCache<SyntaxData>] /// Creates a SyntaxData with the provided raw syntax, pointing to the /// provided index, in the provided parent. /// - Parameters: /// - raw: The raw syntax underlying this node. /// - indexInParent: The index in the parent's layout where this node will /// reside. /// - parent: The parent of this node, or `nil` if this node is the root. required init(raw: RawSyntax, indexInParent: Int = 0, parent: SyntaxData? = nil) { self.raw = raw self.indexInParent = indexInParent self.parent = parent self.childCaches = raw.layout.map { _ in AtomicCache<SyntaxData>() } } /// The index path from this node to the root. This can be used to uniquely /// identify this node in the tree. lazy private(set) var pathToRoot: NodeIdentifier = { var path = [Int]() var node = self while let parent = node.parent { path.append(node.indexInParent) node = parent } return path }() /// Returns the child data at the provided index in this data's layout. /// This child is cached and will be used in subsequent accesses. /// - Note: This function traps if the index is out of the bounds of the /// data's layout. /// /// - Parameter index: The index to create and cache. /// - Returns: The child's data at the provided index. func cachedChild(at index: Int) -> SyntaxData { return childCaches[index].value { realizeChild(index) } } /// Returns the child data at the provided cursor in this data's layout. /// This child is cached and will be used in subsequent accesses. /// - Note: This function traps if the cursor is out of the bounds of the /// data's layout. /// /// - Parameter cursor: The cursor to create and cache. /// - Returns: The child's data at the provided cursor. func cachedChild<CursorType: RawRepresentable>( at cursor: CursorType) -> SyntaxData where CursorType.RawValue == Int { return cachedChild(at: cursor.rawValue) } /// Walks up the provided node's parent tree looking for the receiver. /// - parameter data: The potential child data. /// - returns: `true` if the receiver exists in the parent chain of the /// provided data. /// - seealso: isDescendent(of:) func isAncestor(of data: SyntaxData) -> Bool { return data.isDescendent(of: self) } /// Walks up the receiver's parent tree looking for the provided node. /// - parameter data: The potential ancestor data. /// - returns: `true` if the data exists in the parent chain of the receiver. /// - seealso: isAncestor(of:) func isDescendent(of data: SyntaxData) -> Bool { if data == self { return true } var node = self while let parent = node.parent { if parent == data { return true } node = parent } return false } /// Creates a copy of `self` and recursively creates `SyntaxData` nodes up to /// the root. /// - parameter newRaw: The new RawSyntax that will back the new `Data` /// - returns: A tuple of both the new root node and the new data with the raw /// layout replaced. func replacingSelf( _ newRaw: RawSyntax) -> (root: SyntaxData, newValue: SyntaxData) { // If we have a parent already, then ask our current parent to copy itself // recursively up to the root. if let parent = parent { let (root, newParent) = parent.replacingChild(newRaw, at: indexInParent) let newMe = newParent.cachedChild(at: indexInParent) return (root: root, newValue: newMe) } else { // Otherwise, we're already the root, so return the new data as both the // new root and the new data. let newMe = SyntaxData(raw: newRaw, indexInParent: indexInParent, parent: nil) return (root: newMe, newValue: newMe) } } /// Creates a copy of `self` with the child at the provided index replaced /// with a new SyntaxData containing the raw syntax provided. /// /// - Parameters: /// - child: The raw syntax for the new child to replace. /// - index: The index pointing to where in the raw layout to place this /// child. /// - Returns: The new root node created by this operation, and the new child /// syntax data. /// - SeeAlso: replacingSelf(_:) func replacingChild(_ child: RawSyntax, at index: Int) -> (root: SyntaxData, newValue: SyntaxData) { let newRaw = raw.replacingChild(index, with: child) return replacingSelf(newRaw) } /// Creates a copy of `self` with the child at the provided cursor replaced /// with a new SyntaxData containing the raw syntax provided. /// /// - Parameters: /// - child: The raw syntax for the new child to replace. /// - cursor: A cursor that points to the index of the child you wish to /// replace /// - Returns: The new root node created by this operation, and the new child /// syntax data. /// - SeeAlso: replacingSelf(_:) func replacingChild<CursorType: RawRepresentable>(_ child: RawSyntax, at cursor: CursorType) -> (root: SyntaxData, newValue: SyntaxData) where CursorType.RawValue == Int { return replacingChild(child, at: cursor.rawValue) } /// Creates the child's syntax data for the provided cursor. /// /// - Parameter cursor: The cursor pointing into the raw syntax's layout for /// the child you're creating. /// - Returns: A new SyntaxData for the specific child you're /// creating, whose parent is pointing to self. func realizeChild<CursorType: RawRepresentable>( _ cursor: CursorType) -> SyntaxData where CursorType.RawValue == Int { return realizeChild(cursor.rawValue) } /// Creates the child's syntax data for the provided index. /// /// - Parameter cursor: The cursor pointing into the raw syntax's layout for /// the child you're creating. /// - Returns: A new SyntaxData for the specific child you're /// creating, whose parent is pointing to self. func realizeChild(_ index: Int) -> SyntaxData { return SyntaxData(raw: raw.layout[index], indexInParent: index, parent: self) } /// Tells whether two SyntaxData nodes have the same identity. /// This is not structural equality. /// - Returns: True if both datas are exactly the same. static func ==(lhs: SyntaxData, rhs: SyntaxData) -> Bool { return lhs === rhs } }
apache-2.0
4398cce0d1e4341c58b69375bfcca8de
39.261307
80
0.652896
4.277629
false
false
false
false
gservera/ScheduleKit
ScheduleKit/Model/SCKDayPoint.swift
1
3936
/* * SCKDayPoint.swift * ScheduleKit * * Created: Guillem Servera on 31/12/2014. * Copyright: © 2014-2019 Guillem Servera (https://github.com/gservera) * * 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 /// A type that represents an abstract time point within a day. public struct SCKDayPoint { /// The absolute number of seconds this point represents. let dayOffset: TimeInterval let hour: Int let minute: Int let second: Int /// Returns a `SCKDayPoint` object with all properties set to zero. static var zero: SCKDayPoint { return self.init(hour: 0, minute: 0, second: 0) } /// Convenience initializer. Creates a new SCKDayPoint object with hour, minute and /// second extracted from an Date object. /// /// - parameter date: The Date object from which to get h/m/s parameters. /// /// - returns: The initialized SCKDayPoint. public init(date: Date) { let components = sharedCalendar.dateComponents([.hour, .minute, .second], from: date) self.init(hour: components.hour!, minute: components.minute!, second: components.second!) } /// Initializes a new `SCKDayPoint` object with hour, minute and second set to the /// specified values. If any parameter is less than 0 or more than 60, it gets passed /// to the higher unit if possible. /// /// - parameter hour: The point's hour. /// - parameter minute: The point's minute. If less than 0 or greater than 60 it gets passed to hour. /// - parameter second: The point's second. If less than 0 or greater than 60 it gets passed to minute. /// /// - returns: The initialized SCKDayPoint. public init(hour: Int, minute: Int, second: Int) { var zHour = hour, zMinute = minute, zSecond = second while zSecond >= 60 { zSecond -= 60; zMinute += 1 } while zSecond <= -60 { zSecond += 60; zMinute -= 1 } if zSecond < 0 { zSecond = 60 + zSecond; zMinute -= 1 } while zMinute >= 60 { zMinute -= 60; zHour += 1 } while zMinute <= -60 { zMinute += 60; zHour -= 1 } if zMinute < 0 { zMinute = 60 + zMinute; zHour -= 1 } self.hour = zHour self.minute = zMinute self.second = zSecond dayOffset = Double(zSecond) + Double(zMinute * 60) + Double (zHour * 3600) } } extension SCKDayPoint: Comparable { public static func == (lhs: SCKDayPoint, rhs: SCKDayPoint) -> Bool { return lhs.dayOffset == rhs.dayOffset } public static func < (lhs: SCKDayPoint, rhs: SCKDayPoint) -> Bool { return lhs.dayOffset < rhs.dayOffset } } extension SCKDayPoint: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(dayOffset) } }
mit
c0f93aaa6f20239ac1bfb3448b862d67
36.122642
107
0.650572
4.031762
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Core/Initializers/MirgrationInitializer.swift
1
1414
// Copyright DApps Platform Inc. All rights reserved. import Foundation import RealmSwift import TrustCore final class MigrationInitializer: Initializer { let account: WalletInfo lazy var config: Realm.Configuration = { return RealmConfiguration.configuration(for: account) }() init( account: WalletInfo ) { self.account = account } func perform() { config.schemaVersion = Config.dbMigrationSchemaVersion config.migrationBlock = { migration, oldSchemaVersion in switch oldSchemaVersion { case 0...32: migration.enumerateObjects(ofType: TokenObject.className()) { oldObject, newObject in guard let oldObject = oldObject else { return } guard let newObject = newObject else { return } guard let value = oldObject["contract"] as? String else { return } guard let address = EthereumAddress(string: value) else { return } newObject["contract"] = address.description } fallthrough case 33...49: migration.deleteData(forType: Transaction.className) fallthrough case 50...52: migration.deleteData(forType: CoinTicker.className) default: break } } } }
gpl-3.0
4553e217ee20217bcc0490fcc64ad99d
30.422222
101
0.580622
5.81893
false
true
false
false
Mrwerdo/QuickShare
QuickShare/Sender/main.swift
1
2597
// // main.swift // QuickShare // // Copyright (c) 2016 Andrew Thompson // // 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 Communication import Core import Dispatch // The purpose of this program is to mimic a group of quick share applications // so the application in development can be simulated. var filePath: String? = "/Users/mrwerdo/Library/Developer/Xcode/DerivedData/QuickShare-gcplsydslisswsfhocbcflxscnkj/Build/Products/Debug/Sender.zip" // FIXEME: This is not correct and will crash in Xcode. // This program must be ran from the command line. if let path = Process.arguments.dropFirst().first { filePath = path } else { print("no file name given") } if let filePath = filePath { let multicast_address = "nerds" let interface = convertShareGroupNameToIPAddress(multicast_address) let group1: ShareGroup group1 = try ShareGroup(groupName: multicast_address, username: "Mr Mail Man", interface: interface!) group1.user.isController = true let center1 = try MessageCenter() center1.add(group: group1, controller: nil) let otherqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) let time = dispatch_time(DISPATCH_TIME_NOW, 3 * Int64(bitPattern: NSEC_PER_SEC)) dispatch_after(time, otherqueue) { let name: [Character] = filePath.characters.reverse().map({$0}).split("/").first!.reverse().map({$0}) let f = try! FileMetadata(path: filePath, filename: String(name)) group1.requestFileTransfer(f) } center1.doTheWork() }
mit
d339547ed0607592a27e865e25125a8f
40.238095
148
0.729688
3.983129
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Error.swift
28
1117
// // Error.swift // Rx // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation let RxErrorDomain = "RxErrorDomain" let RxCompositeFailures = "RxCompositeFailures" /** Generic Rx error codes. - Unknown: Unknown error occured - Cast: Error during Casting - Disposed: Performing an action on disposed object */ public enum RxErrorCode : Int { case Unknown = 0 case Cast = 2 case Disposed = 3 } /** Singleton instances of RxErrors */ public struct RxError { /** Singleton instance of Unknown Error */ public static let UnknownError = NSError(domain: RxErrorDomain, code: RxErrorCode.Unknown.rawValue, userInfo: nil) /** Singleton instance of error during casting */ public static let CastError = NSError(domain: RxErrorDomain, code: RxErrorCode.Cast.rawValue, userInfo: nil) /** Singleton instance of doing something on a disposed object */ public static let DisposedError = NSError(domain: RxErrorDomain, code: RxErrorCode.Disposed.rawValue, userInfo: nil) }
gpl-3.0
1461f6fa08e613d710e58cfad3bb2fce
23.304348
120
0.700985
4.091575
false
false
false
false
joemcbride/outlander-osx
src/Outlander/JsonSerializer.swift
1
10283
/*The MIT License (MIT) Copyright (c) 2015 Peter Helstrup Jensen 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 /// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries. public class JSONSerializer { /** Errors that indicates failures of JSONSerialization - JsonIsNotDictionary: - - JsonIsNotArray: - - JsonIsNotValid: - */ public enum JSONSerializerError: ErrorType { case JsonIsNotDictionary case JsonIsNotArray case JsonIsNotValid } //http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary /** Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"]. - parameter jsonString: JSON string to be converted to a NSDictionary. - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects. - returns: A NSDictionary representation of the JSON string. */ public static func toDictionary(jsonString: String) throws -> NSDictionary { if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary { return dictionary } else { throw JSONSerializerError.JsonIsNotDictionary } } /** Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary. - parameter jsonString: The JSON string to be converted to an NSArray - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object. - returns: NSArray representation of the JSON objects. */ public static func toArray(jsonString: String) throws -> NSArray { if let array = try jsonToAnyObject(jsonString) as? NSArray { return array } else { throw JSONSerializerError.JsonIsNotArray } } /** Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray. - parameter jsonString: JSON string to be converted to AnyObject - throws: Throws error of type JSONSerializerError. - returns: Returns the JSON string as AnyObject */ private static func jsonToAnyObject(jsonString: String) throws -> AnyObject? { var any: AnyObject? if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) { do { any = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) } catch let error as NSError { let sError = String(error) NSLog(sError) throw JSONSerializerError.JsonIsNotValid } } return any } /** Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented. - parameter object: The instantiation of any custom class to be represented as JSON. - returns: A string JSON representation of the object. */ public static func toJson(object: Any, prettify: Bool = false) -> String { var json = "{" 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)! children += randomCollection currentMirror = currentMirror.superclassMirror()! } var filteredChildren = [(label: String?, value: Any)]() for (optionalPropertyName, value) in children { if !optionalPropertyName!.containsString("notMapped_") { filteredChildren += [(optionalPropertyName, value)] } } var skip = false let size = filteredChildren.count var index = 0 for (optionalPropertyName, value) in filteredChildren { skip = false let propertyName = optionalPropertyName! let property = Mirror(reflecting: value) var handledValue = String() if propertyName == "Some" && property.displayStyle == Mirror.DisplayStyle.Struct { handledValue = toJson(value) skip = true } else if (value is Int || value is Double || value is Float || value is Bool) && property.displayStyle != Mirror.DisplayStyle.Optional { handledValue = String(value ?? "null") } else if let array = value as? [Int?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Double?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Float?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Bool?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [String?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? "\"\(value!)\"" : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [String] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += "\"\(value)\"" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? NSArray { handledValue += "[" for (index, value) in array.enumerate() { if !(value is Int) && !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) { handledValue += toJson(value) } else { handledValue += "\(value)" } handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if property.displayStyle == Mirror.DisplayStyle.Class || property.displayStyle == Mirror.DisplayStyle.Struct || String(value.dynamicType).containsString("#") { handledValue = toJson(value) } else if property.displayStyle == Mirror.DisplayStyle.Optional { let str = String(value) if str != "nil" { handledValue = String(str).substringWithRange(str.startIndex.advancedBy(9)..<str.endIndex.advancedBy(-1)) } else { handledValue = "null" } } else { handledValue = String(value) != "nil" ? "\"\(value)\"" : "null" } if !skip { json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "") } else { json = "\(handledValue)" + (index < size-1 ? ", " : "") } index += 1 } if !skip { json += "}" } if prettify { let jsonData = json.dataUsingEncoding(NSUTF8StringEncoding)! let jsonObject:AnyObject = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: []) let prettyJsonData = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted) json = NSString(data: prettyJsonData, encoding: NSUTF8StringEncoding)! as String } return json } }
mit
5af1eb6fccf4f3efb88f242ade92b6e2
42.944444
193
0.575999
5.361314
false
false
false
false
mo3bius/My-Simple-Instagram
My-Simple-Instagram/Configurations/AppConfig.swift
1
781
// // AppConfig.swift // My-Simple-Instagram // // Created by Luigi Aiello on 30/10/17. // Copyright © 2017 Luigi Aiello. All rights reserved. // import Foundation class AppConfig { // MARK: - Singleton instance static let sharedInstance = AppConfig() static let INSTAGRAM_AUTHURL = "https://api.instagram.com/oauth/authorize/" static let INSTAGRAM_CLIENT_ID = "2662b83c8a6d4b1a910c677cc638bc2d" static let INSTAGRAM_CLIENTSERCRET = "dab1cc77151446858ffad168ebd2981b" static let INSTAGRAM_REDIRECT_URI = "http://www.luigiaiello.org" static let INSTAGRAM_ACCESS_TOKEN = "access_token" static let INSTAGRAM_SCOPE = "follower_list+public_content" /* add whatever scope you need https://www.instagram.com/developer/authorization/ */ }
mit
d18d657ce71c450f93a6cb0e7dc26aee
32.913043
148
0.725641
3.333333
false
true
false
false
IngmarStein/swift
test/stdlib/TestDateInterval.swift
4
8074
// 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: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation #if FOUNDATION_XCTEST import XCTest class TestDateIntervalSuper : XCTestCase { } #else import StdlibUnittest class TestDateIntervalSuper { } #endif class TestDateInterval : TestDateIntervalSuper { func dateWithString(_ str: String) -> Date { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .gregorian) formatter.locale = Locale(identifier: "en_US") formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" return formatter.date(from: str)! as Date } func test_compareDateIntervals() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration: TimeInterval = 10000000.0 let testInterval1 = DateInterval(start: start, duration: duration) let testInterval2 = DateInterval(start: start, duration: duration) expectEqual(testInterval1, testInterval2) expectEqual(testInterval2, testInterval1) expectEqual(testInterval1.compare(testInterval2), ComparisonResult.orderedSame) let testInterval3 = DateInterval(start: start, duration: 10000000000.0) expectTrue(testInterval1 < testInterval3) expectTrue(testInterval3 > testInterval1) let earlierStart = dateWithString("2009-05-17 14:49:47 -0700") let testInterval4 = DateInterval(start: earlierStart, duration: duration) expectTrue(testInterval4 < testInterval1) expectTrue(testInterval1 > testInterval4) } } func test_isEqualToDateInterval() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let testInterval1 = DateInterval(start: start, duration: duration) let testInterval2 = DateInterval(start: start, duration: duration) expectEqual(testInterval1, testInterval2) let testInterval3 = DateInterval(start: start, duration: 100.0) expectNotEqual(testInterval1, testInterval3) } } func test_checkIntersection() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start1 = dateWithString("2010-05-17 14:49:47 -0700") let end1 = dateWithString("2010-08-17 14:49:47 -0700") let testInterval1 = DateInterval(start: start1, end: end1) let start2 = dateWithString("2010-02-17 14:49:47 -0700") let end2 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval2 = DateInterval(start: start2, end: end2) expectTrue(testInterval1.intersects(testInterval2)) let start3 = dateWithString("2010-10-17 14:49:47 -0700") let end3 = dateWithString("2010-11-17 14:49:47 -0700") let testInterval3 = DateInterval(start: start3, end: end3) expectFalse(testInterval1.intersects(testInterval3)) } } func test_validIntersections() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start1 = dateWithString("2010-05-17 14:49:47 -0700") let end1 = dateWithString("2010-08-17 14:49:47 -0700") let testInterval1 = DateInterval(start: start1, end: end1) let start2 = dateWithString("2010-02-17 14:49:47 -0700") let end2 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval2 = DateInterval(start: start2, end: end2) let start3 = dateWithString("2010-05-17 14:49:47 -0700") let end3 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval3 = DateInterval(start: start3, end: end3) let intersection1 = testInterval2.intersection(with: testInterval1) expectNotNil(intersection1) expectEqual(testInterval3, intersection1) let intersection2 = testInterval1.intersection(with: testInterval2) expectNotNil(intersection2) expectEqual(intersection1, intersection2) } } func test_containsDate() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let testInterval = DateInterval(start: start, duration: duration) let containedDate = dateWithString("2010-05-17 20:49:47 -0700") expectTrue(testInterval.contains(containedDate)) let earlierStart = dateWithString("2009-05-17 14:49:47 -0700") expectFalse(testInterval.contains(earlierStart)) } } func test_AnyHashableContainingDateInterval() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let values: [DateInterval] = [ DateInterval(start: start, duration: duration), DateInterval(start: start, duration: duration / 2), DateInterval(start: start, duration: duration / 2), ] let anyHashables = values.map(AnyHashable.init) expectEqual(DateInterval.self, type(of: anyHashables[0].base)) expectEqual(DateInterval.self, type(of: anyHashables[1].base)) expectEqual(DateInterval.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } } func test_AnyHashableCreatedFromNSDateInterval() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let values: [NSDateInterval] = [ NSDateInterval(start: start, duration: duration), NSDateInterval(start: start, duration: duration / 2), NSDateInterval(start: start, duration: duration / 2), ] let anyHashables = values.map(AnyHashable.init) expectEqual(DateInterval.self, type(of: anyHashables[0].base)) expectEqual(DateInterval.self, type(of: anyHashables[1].base)) expectEqual(DateInterval.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } } } #if !FOUNDATION_XCTEST var DateIntervalTests = TestSuite("TestDateInterval") DateIntervalTests.test("test_compareDateIntervals") { TestDateInterval().test_compareDateIntervals() } DateIntervalTests.test("test_isEqualToDateInterval") { TestDateInterval().test_isEqualToDateInterval() } DateIntervalTests.test("test_checkIntersection") { TestDateInterval().test_checkIntersection() } DateIntervalTests.test("test_validIntersections") { TestDateInterval().test_validIntersections() } DateIntervalTests.test("test_AnyHashableContainingDateInterval") { TestDateInterval().test_AnyHashableContainingDateInterval() } DateIntervalTests.test("test_AnyHashableCreatedFromNSDateInterval") { TestDateInterval().test_AnyHashableCreatedFromNSDateInterval() } runAllTests() #endif
apache-2.0
21483c6541288c197ae2d2c34ec0c5d9
44.106145
134
0.624721
4.47561
false
true
false
false
stomp1128/TIY-Assignments
12-InDueTimeRedux/12-InDueTimeRedux/ListTableViewController.swift
1
5349
// // ListTableViewController.swift // 12-InDueTimeRedux // // Created by Chris Stomp on 12/1/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData class ListTableViewController: UITableViewController, UITextFieldDelegate { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var list = [List]() override func viewDidLoad() { super.viewDidLoad() title = "Todo List" let fetchRequest = NSFetchRequest(entityName: "List") do { let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [List] list = fetchResults! } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return list.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ListCell", forIndexPath: indexPath) as! ListCell let listItem = list[indexPath.row] if listItem.item == nil { cell.item.becomeFirstResponder() } else { cell.item.text = listItem.item } return cell } //MARK: Action Handlers @IBAction func addListItem(sender: UIBarButtonItem) { let aList = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: managedObjectContext) as! List list.append(aList) tableView.reloadData() } //MARK: UITextField Delegate func textfieldShouldReturn(textField: UITextField) -> Bool { var rc = false if textField.text != "" { rc = true let contentView = textField.superview let cell = contentView?.superview as! ListCell let indexPath = tableView.indexPathForCell(cell) let aList = list[indexPath!.row] aList.item = textField.text textField.resignFirstResponder() saveContext() } return rc } //Mark: Private func saveContext() { do{ try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let aList = list[indexPath.row] list.removeAtIndex(indexPath.row) managedObjectContext.deleteObject(aList) saveContext() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc0-1.0
1f120afeef6faf0def9fd48b6ee08656
30.64497
157
0.637622
5.671262
false
false
false
false
jonatascb/Calculadora
Calculadora/CalculatorGraphViewController.swift
1
914
// // CalculatorGraphViewController.swift // Calculadora // // Created by Computação Gráfica 2 on 21/05/15. // Copyright (c) 2015 DCC UFRJ. All rights reserved. // import UIKit class CalculatorGraphViewController : UIViewController { @IBOutlet weak var graphView: GraphView! { didSet { graphView.calculatorGraphView = self } } private var brain = CalculatorBrain() typealias PropertyList = AnyObject var program: PropertyList { get { return brain.program } set { brain.program = newValue } } func calcularFuncao(x: CGFloat) -> CGFloat? { brain.variaveis["M"] = Double(x) if let valorFuncao = brain.avaliar() { return CGFloat(valorFuncao) } return nil } }
mit
dab6f7943dbb9740327403a8253707aa
17.24
54
0.540066
4.509901
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/view/widget/MD2LabelWidget.swift
1
3962
// // MD2LabelWidget.swift // md2-ios-library // // Created by Christoph Rieger on 29.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // import UIKit /// A stylable text output element. class MD2LabelWidget: MD2SingleWidget, MD2StylableWidget { /// Unique widget identification. let widgetId: MD2WidgetMapping /// The view element value. Using a property observer, external changes trigger a UI control update. var value: MD2Type { didSet { updateElement() } } /// Inner dimensions of the screen occupied by the widget var dimensions: MD2Dimension? /// The native UI control. var widgetElement: UILabel /// The color as hex string. var color: MD2String? /// The font size as multiplicatve scaling factor (similar to 'em' in CSS). var fontSize: MD2Float? = MD2Float(1.0) /// The text style. var textStyle: MD2WidgetTextStyle = MD2WidgetTextStyle.Normal /// Width of the widget as specified by the model (percentage of the availale width) var width: Float? /** Default initializer. :param: widgetId Widget identifier */ init(widgetId: MD2WidgetMapping) { self.widgetId = widgetId self.value = MD2String() self.widgetElement = UILabel() } /** Render the view element, i.e. specifying the position and appearance of the widget. :param: view The surrounding view element. :param: controller The responsible view controller. */ func render(view: UIView, controller: UIViewController) { if dimensions == nil { // Element is not specified in layout. Maybe grid with not enough cells?! return } // Set value updateElement() // Set default styles //widgetElement.textAlignment = .Center widgetElement.numberOfLines = 2 widgetElement.lineBreakMode = .ByWordWrapping // Set custom styles if color?.isSet() == true { widgetElement.textColor = UIColor(rgba: color!.platformValue!) } widgetElement.font = UIFont(name: textStyle.rawValue, size: CGFloat(Float(MD2ViewConfig.FONT_SIZE) * fontSize!.platformValue!)) // Add to surrounding view view.addSubview(widgetElement) } /** Calculate the dimensions of the widget based on the available bounds. The occupied space of the widget is returned. *NOTICE* The occupied space may surpass the bounds (and thus the visible screen), if the height of the element is not sufficient. This is not a problem as the screen will scroll automatically. *NOTICE* The occupied space usually differs from the dimensions property as it refers to the *outer* dimensions in contrast to the dimensions property referring to *inner* dimensions. The difference represents the gutter included in the widget positioning process. :param: bounds The available screen space. :returns: The occupied outer dimensions of the widget. */ func calculateDimensions(bounds: MD2Dimension) -> MD2Dimension { let outerDimensions = MD2Dimension( x: bounds.x, y: bounds.y, width: bounds.width, height: MD2ViewConfig.DIMENSION_LABEL_HEIGHT) // Add gutter dimensions = MD2UIUtil.innerDimensionsWithGutter(outerDimensions) widgetElement.frame = MD2UIUtil.dimensionToCGRect(dimensions!) return outerDimensions } /// Enable the view element. func enable() { self.widgetElement.enabled = true } /// Disable the view element. func disable() { self.widgetElement.enabled = false } func updateElement() { self.widgetElement.text = value.toString() } }
apache-2.0
b12eb1c291c10303d08ce95be49a8992
31.219512
272
0.636547
4.909542
false
false
false
false
fanticqq/ZLayout
ZLayout/ZLayoutTests/ZLayoutTestsAlignAndFillVertical.swift
1
2523
// // ZLayoutTestsAlignAndFillVertical.swift // ZLayout // // Created by Igor Zarubin on 20/05/2017. // Copyright © 2017 Igor Zarubin. All rights reserved. // import XCTest class ZLayoutTestsAlignAndFillVertical: XCTestCase { lazy var rootView: UIView = { let view = UIView(frame: UIScreen.main.bounds) return view }() lazy var view1: UIView = { let root = UIScreen.main.bounds let side: CGFloat = root.size.width / 4 let rect = CGRect(x: (root.width / 2) - side / 2, y: 0, width: side, height: side) let view = UIView(frame: rect) return view }() lazy var view2: UIView = { let root = UIScreen.main.bounds let side: CGFloat = root.size.width / 4 let rect = CGRect(x: (root.width / 2) - side / 2, y: root.height - side, width: side, height: side) let view = UIView(frame: rect) return view }() lazy var alignmentView: UIView = { let view = UIView() return view }() let alignmentViewSize: CGSize = CGSize(width: 20, height: 20) override func setUp() { super.setUp() rootView.addSubview(view1) rootView.addSubview(view2) rootView.addSubview(alignmentView) alignmentView.frame = CGRect(origin: CGPoint.zero, size: alignmentViewSize) } func testAlignAndFillTop() { alignmentView.alignAndFill(on: .top, relativeTo: view2, withGravity: .center, stretchTo: view1) XCTAssert(alignmentView.minY == view1.maxY) XCTAssert(alignmentView.maxY == view2.minY) } func testAlignAndFillBottom() { alignmentView.alignAndFill(on: .bottom, relativeTo: view1, withGravity: .center, stretchTo: view2) XCTAssert(alignmentView.minY == view1.maxY) XCTAssert(alignmentView.maxY == view2.minY) } func testAlignAndFillTopToSuperview() { alignmentView.alignAndFill(on: .top, relativeTo: view2, withGravity: .center) XCTAssert(alignmentView.minY == 0) XCTAssert(alignmentView.maxY == view2.minY) } func testAlignAndFillBottomToSuperview() { alignmentView.alignAndFill(on: .bottom, relativeTo: view1, withGravity: .center) XCTAssert(alignmentView.minY == view1.maxY) XCTAssert(alignmentView.maxY == rootView.maxY) } }
mit
661e1ad5546ce034f87ce540ae915280
31.333333
106
0.59437
4.210351
false
true
false
false
ashikahmad/SugarAnchor
Example/SugarAnchor/Example1VC.swift
1
1594
// // Example1VC.swift // SugarAnchor // // Created by ashikahmad on 05/09/2017. // Copyright (c) 2017 ashikahmad. All rights reserved. // import UIKit import SugarAnchor class Example1VC: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let redView = addedView(.red) let greenView = addedView(.green) let blueView = addedView(.blue) redView.leadingAnchor =*= view.leadingAnchor + 20 redView.topAnchor =*= topLayoutGuide.bottomAnchor + 10 redView.widthAnchor =*= redView.heightAnchor greenView.leadingAnchor =*= redView.trailingAnchor + 8 greenView.topAnchor =*= redView.topAnchor greenView.trailingAnchor =*= view.trailingAnchor - 20 greenView.heightAnchor =*= 30 blueView.leadingAnchor =*= greenView.leadingAnchor blueView.topAnchor =*= greenView.bottomAnchor + 5 blueView.widthAnchor =*= greenView.widthAnchor / 2 + 15 blueView.heightAnchor =*= greenView.heightAnchor blueView.bottomAnchor =*= redView.bottomAnchor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addedView(_ color: UIColor)-> UIView { let newView = UIView() newView.translatesAutoresizingMaskIntoConstraints = false newView.backgroundColor = color view.addSubview(newView) return newView } }
mit
63afca4d38424f46354f23d4e593c02f
30.88
80
0.660602
5.313333
false
false
false
false
jwfriese/Fleet
Fleet/CoreExtensions/Navigation/NavBar/UINavigationBar+Fleet.swift
1
1916
extension Fleet { enum NavBarError: FleetErrorDefinition { case noNavBarItems case titleNotFound(_ title: String) var errorMessage: String { get { switch self { case .noNavBarItems: return "No nav bar items found in the view controller." case .titleNotFound(let title): return "No item with title '\(title)' found in nav bar." } } } var name: NSExceptionName { get { NSExceptionName(rawValue: "Fleet.NavBarError") } } } } extension UINavigationBar { /** Mimics a tap on an item with the given title from the navigation bar's top item, firing any associated behavior. - parameters: - title: The title of the item to tap - throws: A `FleetError` if a navigation bar item with the given title cannot be found, if there in the are no items in the navigation bar, or if the item's action is not properly set up. */ public func tapTopItem(withTitle title: String) { guard let navBarItem = topItem else { FleetError(Fleet.NavBarError.noNavBarItems).raise() return } var allButtonItems: [UIBarButtonItem] = [] if let rightItems = navBarItem.rightBarButtonItems { allButtonItems.append(contentsOf: rightItems) } if let leftItems = navBarItem.leftBarButtonItems { allButtonItems.append(contentsOf: leftItems) } let matchingNavBarItemOpt = allButtonItems.first() { item in item.title == title } guard let matchingNavBarItem = matchingNavBarItemOpt else { FleetError(Fleet.NavBarError.titleNotFound(title)).raise() return } matchingNavBarItem.tap() } }
apache-2.0
5dc5f4c8356c61731704837536a6ef33
29.903226
98
0.582463
4.950904
false
false
false
false
JGiola/swift-package-manager
Sources/PackageGraph/PackageGraphRoot.swift
2
4711
/* 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 Basic import Utility import PackageModel import SourceControl /// Represents the input to the package graph root. public struct PackageGraphRootInput { public typealias PackageDependency = PackageGraphRoot.PackageDependency /// The list of root packages. public let packages: [AbsolutePath] /// Top level dependencies to the graph. public let dependencies: [PackageDependency] /// Create a package graph root. public init(packages: [AbsolutePath], dependencies: [PackageDependency] = []) { self.packages = packages self.dependencies = dependencies } } /// Represents the inputs to the package graph. public struct PackageGraphRoot { // FIXME: We can kill this now. // /// Represents a top level package dependencies. public struct PackageDependency { public typealias Requirement = PackageModel.PackageDependencyDescription.Requirement // Location of this dependency. // // Opaque location object which will be included in any diagnostics // related to this dependency. Clients can use this identify where this // dependency is declared. public let location: String /// The URL of the package. public let url: String /// The requirement of the package. public let requirement: Requirement /// Create the package reference object for the dependency. public func createPackageRef(config: SwiftPMConfig) -> PackageReference { let effectiveURL = config.mirroredURL(forURL: self.url) return PackageReference( identity: PackageReference.computeIdentity(packageURL: effectiveURL), path: effectiveURL, isLocal: (requirement == .localPackage) ) } public init( url: String, requirement: Requirement, location: String ) { // FIXME: SwiftPM can't handle file URLs with file:// scheme so we need to // strip that. We need to design a URL data structure for SwiftPM. let filePrefix = "file://" if url.hasPrefix(filePrefix) { self.url = AbsolutePath(String(url.dropFirst(filePrefix.count))).asString } else { self.url = url } self.requirement = requirement self.location = location } } /// The list of root manifests. public let manifests: [Manifest] /// The root package references. public let packageRefs: [PackageReference] /// The top level dependencies. public let dependencies: [PackageDependency] /// Create a package graph root. public init(input: PackageGraphRootInput, manifests: [Manifest]) { self.packageRefs = zip(input.packages, manifests).map { (path, manifest) in PackageReference(identity: manifest.name.lowercased(), path: path.asString, isLocal: true) } self.manifests = manifests self.dependencies = input.dependencies } /// Returns the constraints imposed by root manifests + dependencies. public func constraints(config: SwiftPMConfig) -> [RepositoryPackageConstraint] { let constraints = packageRefs.map({ RepositoryPackageConstraint(container: $0, requirement: .unversioned) }) return constraints + dependencies.map({ RepositoryPackageConstraint( container: $0.createPackageRef(config: config), requirement: $0.requirement.toConstraintRequirement() ) }) } } extension PackageDependencyDescription.Requirement { /// Returns the constraint requirement representation. public func toConstraintRequirement() -> RepositoryPackageConstraint.Requirement { switch self { case .range(let range): return .versionSet(.range(range)) case .revision(let identifier): assert(Git.checkRefFormat(ref: identifier)) return .revision(identifier) case .branch(let identifier): assert(Git.checkRefFormat(ref: identifier)) return .revision(identifier) case .exact(let version): return .versionSet(.exact(version)) case .localPackage: return .unversioned } } }
apache-2.0
8fb6769744706773959c788f933ad88c
31.944056
102
0.647633
5.222838
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Library/LibraryPanelContextMenu.swift
2
4046
// 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 Storage import Shared protocol LibraryPanelContextMenu { func getSiteDetails(for indexPath: IndexPath) -> Site? func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonRowActions]? func presentContextMenu(for indexPath: IndexPath) func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) } extension LibraryPanelContextMenu { func presentContextMenu(for indexPath: IndexPath) { guard let site = getSiteDetails(for: indexPath) else { return } presentContextMenu(for: site, with: indexPath, completionHandler: { return self.contextMenu(for: site, with: indexPath) }) } func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? { guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil } let viewModel = PhotonActionSheetViewModel(actions: [actions], site: site, modalStyle: .overFullScreen) let contextMenu = PhotonActionSheet(viewModel: viewModel) contextMenu.modalTransitionStyle = .crossDissolve let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() return contextMenu } func getRecentlyClosedTabContexMenuActions(for site: Site, recentlyClosedPanelDelegate: RecentlyClosedPanelDelegate?) -> [PhotonRowActions]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = SingleActionViewModel(title: .OpenInNewTabContextMenuTitle, iconString: ImageIdentifiers.newTab) { _ in recentlyClosedPanelDelegate?.openRecentlyClosedSiteInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = SingleActionViewModel(title: .OpenInNewPrivateTabContextMenuTitle, iconString: ImageIdentifiers.newPrivateTab) { _ in recentlyClosedPanelDelegate?.openRecentlyClosedSiteInNewTab(siteURL, isPrivate: true) } return [PhotonRowActions(openInNewTabAction), PhotonRowActions(openInNewPrivateTabAction)] } func getRemoteTabContexMenuActions(for site: Site, remotePanelDelegate: RemotePanelDelegate?) -> [PhotonRowActions]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = SingleActionViewModel(title: .OpenInNewTabContextMenuTitle, iconString: ImageIdentifiers.newTab) { _ in remotePanelDelegate?.remotePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = SingleActionViewModel(title: .OpenInNewPrivateTabContextMenuTitle, iconString: ImageIdentifiers.newPrivateTab) { _ in remotePanelDelegate?.remotePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } return [PhotonRowActions(openInNewTabAction), PhotonRowActions(openInNewPrivateTabAction)] } func getDefaultContextMenuActions(for site: Site, libraryPanelDelegate: LibraryPanelDelegate?) -> [PhotonRowActions]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = SingleActionViewModel(title: .OpenInNewTabContextMenuTitle, iconString: ImageIdentifiers.newTab) { _ in libraryPanelDelegate?.libraryPanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) }.items let openInNewPrivateTabAction = SingleActionViewModel(title: .OpenInNewPrivateTabContextMenuTitle, iconString: ImageIdentifiers.newPrivateTab) { _ in libraryPanelDelegate?.libraryPanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) }.items return [openInNewTabAction, openInNewPrivateTabAction] } }
mpl-2.0
2de8559093c5911321d8f3a09a245f8e
49.575
157
0.722936
5.642957
false
false
false
false
benlangmuir/swift
test/Sema/implicit-import-typealias.swift
1
4802
// RUN: %empty-directory(%t) // RUN: split-file %s %t // RUN: %target-swift-emit-module-interface(%t/Original.swiftinterface) %t/Original.swift // RUN: %target-swift-typecheck-module-from-interface(%t/Original.swiftinterface) // RUN: %target-swift-emit-module-interface(%t/Aliases.swiftinterface) %t/Aliases.swift -I %t // RUN: %target-swift-typecheck-module-from-interface(%t/Aliases.swiftinterface) -I %t // RUN: %target-swift-frontend -typecheck -verify %t/UsesAliasesNoImport.swift -I %t // RUN: %target-swift-frontend -typecheck -verify %t/UsesAliasesImplementationOnlyImport.swift -I %t // RUN: %target-swift-frontend -typecheck -verify %t/UsesAliasesWithImport.swift -I %t /// The swiftinterface is broken by the missing import without the workaround. // RUN: %target-swift-emit-module-interface(%t/UsesAliasesNoImport.swiftinterface) %t/UsesAliasesNoImport.swift -I %t \ // RUN: -disable-print-missing-imports-in-module-interface // RUN: not %target-swift-typecheck-module-from-interface(%t/UsesAliasesNoImport.swiftinterface) -I %t /// The swiftinterface parses fine with the workaround adding the missing imports. // RUN: %target-swift-emit-module-interface(%t/UsesAliasesNoImportFixed.swiftinterface) %t/UsesAliasesNoImport.swift -I %t // RUN: %target-swift-typecheck-module-from-interface(%t/UsesAliasesNoImportFixed.swiftinterface) -I %t /// The module with an implementation-only import is not affected by the workaround and remains broken. // RUN: %target-swift-emit-module-interface(%t/UsesAliasesImplementationOnlyImport.swiftinterface) %t/UsesAliasesImplementationOnlyImport.swift -I %t \ // RUN: -disable-print-missing-imports-in-module-interface // RUN: not %target-swift-typecheck-module-from-interface(%t/UsesAliasesImplementationOnlyImport.swiftinterface) -I %t //--- Original.swift open class Clazz {} public protocol Proto { func requirement() } public struct Struct { public init() {} } @propertyWrapper public struct Wrapper<T> { public var wrappedValue: T public init(wrappedValue: T) { self.wrappedValue = wrappedValue } } //--- Aliases.swift import Original public typealias ClazzAlias = Clazz public typealias ProtoAlias = Proto public typealias StructAlias = Struct public typealias WrapperAlias = Wrapper //--- UsesAliasesNoImport.swift import Aliases // expected-warning@+2 {{'ClazzAlias' aliases 'Original.Clazz' and cannot be used here because 'Original' was not imported by this file; this is an error in Swift 6}} // expected-note@+1 {{The missing import of module 'Original' will be added implicitly}} public class InheritsFromClazzAlias: ClazzAlias {} @inlinable public func inlinableFunc() { // expected-warning@+2 {{'StructAlias' aliases 'Original.Struct' and cannot be used in an '@inlinable' function because 'Original' was not imported by this file; this is an error in Swift 6}} // expected-note@+1 {{The missing import of module 'Original' will be added implicitly}} _ = StructAlias.self } // expected-warning@+2 {{'ProtoAlias' aliases 'Original.Proto' and cannot be used here because 'Original' was not imported by this file; this is an error in Swift 6}} // expected-note@+1 {{The missing import of module 'Original' will be added implicitly}} public func takesGeneric<T: ProtoAlias>(_ t: T) {} public struct HasMembers { // expected-warning@+2 {{'WrapperAlias' aliases 'Original.Wrapper' and cannot be used as property wrapper here because 'Original' was not imported by this file; this is an error in Swift 6}} // expected-note@+1 {{The missing import of module 'Original' will be added implicitly}} @WrapperAlias public var wrapped: Int } // expected-warning@+2 {{'StructAlias' aliases 'Original.Struct' and cannot be used in an extension with public or '@usableFromInline' members because 'Original' was not imported by this file; this is an error in Swift 6}} // expected-note@+1 {{The missing import of module 'Original' will be added implicitly}} extension StructAlias { public func someFunc() {} } //--- UsesAliasesImplementationOnlyImport.swift import Aliases @_implementationOnly import Original @inlinable public func inlinableFunc() { // expected-warning@+1 {{'StructAlias' aliases 'Original.Struct' and cannot be used in an '@inlinable' function because 'Original' has been imported as implementation-only; this is an error in Swift 6}} _ = StructAlias.self } // expected-warning@+1 {{'ProtoAlias' aliases 'Original.Proto' and cannot be used here because 'Original' has been imported as implementation-only; this is an error in Swift 6}} public func takesGeneric<T: ProtoAlias>(_ t: T) {} //--- UsesAliasesWithImport.swift import Aliases import Original @inlinable public func inlinableFunc() { _ = StructAlias.self } public func takesGeneric<T: ProtoAlias>(_ t: T) {}
apache-2.0
14d9b2470504b2cfff507a1aa5053d54
41.495575
222
0.756768
3.844676
false
false
false
false
hujewelz/modelSwift
ModelSwift/Classes/Type.swift
1
3820
// // Type.swift // Pods // // Created by jewelz on 2017/3/24. // // import Foundation public enum Type<Value> { case some(Value) case array(Value) case int case string case double case float case bool case none public var value: Any.Type? { switch self { case .some(let v): return v as? Any.Type case .int: return Int.self case .float: return Float.self case .double: return Double.self case .string: return String.self case .bool: return Bool.self case .none: return nil case .array(let v): if v is String.Type { return String.self } else if v is Int.Type { return Int.self } else if v is Float.Type { return Float.self } else if v is Double.Type { return Double.self } else if v is Bool.Type { return Bool.self } else { return v as? Any.Type } } } } public struct Image { public let subject: Any /// type of the reflecting subject public var subjectType: Type<Any> { let mirror = Mirror(reflecting: subject) return typeOf(mirror.subjectType) } /// An element of the reflected instance's structure. The optional /// `label` may be used to represent the name /// of a stored property, and `type` is the stored property`s type. public typealias Child = (label: String?, type: Type<Any>) public typealias Children = [Child] public init(reflecting subject: Any) { self.subject = subject } /// A collection of `Child` elements describing the structure of the /// reflected subject. public var children: Children { var results = [Child]() let mirror = Mirror(reflecting: self.subject) for (lab, value) in mirror.children { let v = (lab, self.subjectType(of: value)) results.append(v) } return results } private func subjectType(of subject: Any) -> Type<Any> { let mirror = Mirror(reflecting: subject) let subjectType = mirror.subjectType return typeOf(subjectType) } private func typeOf(_ subjectType: Any.Type) -> Type<Any> { //print("subject type: \(subjectType)") if subjectType is Int.Type || subjectType is Optional<Int>.Type { return .int } else if subjectType is String.Type || subjectType is Optional<String>.Type { return .string } else if subjectType is Float.Type || subjectType is Optional<Float>.Type { return .float } else if subjectType is Double.Type || subjectType is Optional<Double>.Type { return .double } else if subjectType is Bool.Type || subjectType is Optional<Bool>.Type { return .bool } else if subjectType is Array<String>.Type || subjectType is Optional<Array<String>>.Type { return .array(String.self) } else if subjectType is Array<Int>.Type || subjectType is Optional<Array<Int>>.Type { return .array(Int.self) } else if subjectType is Array<Float>.Type || subjectType is Optional<Array<Float>>.Type { return .array(Float.self) } else if subjectType is Array<Bool>.Type || subjectType is Optional<Array<Bool>>.Type { return .array(Bool.self) } else if subjectType is Array<Double>.Type || subjectType is Optional<Array<Double>>.Type { return .array(Double.self) } return .some(subjectType) } }
mit
9907ce6f6a216077e6334873a6a302aa
29.07874
100
0.56466
4.558473
false
false
false
false
kay-kim/stitch-examples
todo/ios/Pods/FacebookCore/Sources/Core/AppEvents/AppEvent.swift
19
4267
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation /** Represents a single application event that can be logged to Facebook Analytics. */ public struct AppEvent: AppEventLoggable { public typealias ParametersDictionary = [AppEventParameterName : AppEventParameterValueType] /// Name of the application event. public let name: AppEventName /// Arbitrary parameter dictionary of characteristics of an event. public var parameters: ParametersDictionary /** Amount to be aggregated into all events of this eventName. App Insights will report the cumulative and average value of this amount. */ public var valueToSum: Double? /** Creates an app event. - parameter name: App event name. - parameter parameters: Parameters dictionary. Default: empty. - parameter valueToSum: Optional value to sum. Default: `nil`. */ public init(name: AppEventName, parameters: ParametersDictionary = [:], valueToSum: Double? = nil) { self.name = name self.parameters = parameters self.valueToSum = valueToSum } } extension AppEvent { /** Creates an app event. - parameter name: String representation of app event name. - parameter parameters: Parameters dictionary. Default: empty. - parameter valueToSum: Optional value to sum. Default: `nil`. */ public init(name: String, parameters: ParametersDictionary = [:], valueToSum: Double? = nil) { self.init(name: AppEventName(name), parameters: parameters, valueToSum: valueToSum) } } /** Protocol that describes a single application event that can be logged to Facebook Analytics. */ public protocol AppEventLoggable { /// Name of the application event. var name: AppEventName { get } /// Arbitrary parameter dictionary of characteristics of an event. var parameters: AppEvent.ParametersDictionary { get } /// Amount to be aggregated into all events of this eventName. var valueToSum: Double? { get } } /** Conforming types that can be logged as a parameter value of `AppEventLoggable`. By default implemented for `NSNumber`, `String`, `IntegerLiteralType` and `FloatLiteralType`. Should only return either a `String` or `NSNumber`. */ public protocol AppEventParameterValueType { /// Object value. Can be either `NSNumber` or `String`. var appEventParameterValue: Any { get } } extension NSNumber: AppEventParameterValueType { /// An object representation of `self`, suitable for parameter value of `AppEventLoggable`. public var appEventParameterValue: Any { return self } } extension IntegerLiteralType: AppEventParameterValueType { /// An object representation of `self`, suitable for parameter value of `AppEventLoggable`. public var appEventParameterValue: Any { return self as NSNumber } } extension FloatLiteralType: AppEventParameterValueType { /// An object representation of `self`, suitable for parameter value of `AppEventLoggable`. public var appEventParameterValue: Any { return self as NSNumber } } extension String: AppEventParameterValueType { /// An object representation of `self`, suitable for parameter value of `AppEventLoggable`. public var appEventParameterValue: Any { return self } }
apache-2.0
4d76685a78d31e97984bde8d14d6359d
36.429825
102
0.747363
4.578326
false
false
false
false
j-chao/venture
source/venture/Globals.swift
1
3081
// // Globals.swift // venture // // Created by Justin Chao on 3/22/17. // Copyright © 2017 Group1. All rights reserved. // import Foundation import Firebase var tripLength:Int = 1 var passedTrip:String = "" var timeFormat:String = "regular" var background:Int = 1 func dateFromString (dateString:String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy" dateFormatter.locale = Locale(identifier: "en_US") let dateObj = dateFormatter.date(from: dateString) return (dateObj)! } func stringFromDate (date:Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/YYYY" return dateFormatter.string(from: date) } func flightDatefromDate (date:Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY-MM-dd" return dateFormatter.string(from: date) } func stringLongFromDate (date:Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE MMM dd" return dateFormatter.string(from: date) } func dateFromStringLong (dateString:String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE MMM dd" dateFormatter.locale = Locale(identifier: "en_US") let dateObj = dateFormatter.date(from: dateString) return (dateObj)! } func stringTimefromDate (date:Date) -> String { let dateFormatter = DateFormatter() if timeFormat == "regular" { dateFormatter.dateFormat = "h:mm a" } else if timeFormat == "military" { dateFormatter.dateFormat = "HH:mm" } return dateFormatter.string(from: date) } func stringTimefromDateToFIR (date:Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.string(from: date) } func timeFromStringTime (timeStr:String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.date(from: timeStr)! } func timeFromString (timeStr:String) -> Date { let dateFormatter = DateFormatter() if timeFormat == "regular" { dateFormatter.dateFormat = "h:mm a" } else if timeFormat == "military" { dateFormatter.dateFormat = "HH:mm" } return dateFormatter.date(from: timeStr)! } func militaryToRegular (timeStr:String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.date(from: timeStr) dateFormatter.dateFormat = "h:mm a" return dateFormatter.string(from: date!) } func calculateDays(start: Date, end: Date) -> Int { let currentCalendar = Calendar.current guard let start = currentCalendar.ordinality(of: .day, in: .era, for: start) else { return 0 } guard let end = currentCalendar.ordinality(of: .day, in: .era, for: end) else { return 0 } return (end - start) } func minutesToHoursMinutes (minutes: Int) -> String { let hours = minutes / 60 let min = (minutes % 60) return ("\(hours)h:\(min)m") }
mit
5e97f4aa47a003587f2f0c38c25f7b17
27.518519
87
0.682792
3.958869
false
false
false
false
ygorshenin/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/TaxiCell/PlacePageTaxiCell.swift
2
1533
@objc(MWMPlacePageTaxiCell) final class PlacePageTaxiCell: MWMTableViewCell { @IBOutlet private weak var icon: UIImageView! @IBOutlet private weak var title: UILabel! { didSet { title.font = UIFont.bold14() title.textColor = UIColor.blackPrimaryText() } } @IBOutlet private weak var orderButton: UIButton! { didSet { let l = orderButton.layer l.cornerRadius = 8 l.borderColor = UIColor.linkBlue().cgColor l.borderWidth = 1 orderButton.setTitle(L("taxi_order"), for: .normal) orderButton.setTitleColor(UIColor.white, for: .normal) orderButton.titleLabel?.font = UIFont.bold14() orderButton.backgroundColor = UIColor.linkBlue() } } private weak var delegate: MWMPlacePageButtonsProtocol! private var type: MWMPlacePageTaxiProvider! @objc func config(type: MWMPlacePageTaxiProvider, delegate: MWMPlacePageButtonsProtocol) { self.delegate = delegate self.type = type switch type { case .taxi: icon.image = #imageLiteral(resourceName: "icTaxiTaxi") title.text = L("taxi") case .uber: icon.image = #imageLiteral(resourceName: "icTaxiUber") title.text = L("uber") case .yandex: icon.image = #imageLiteral(resourceName: "ic_taxi_logo_yandex") title.text = L("yandex_taxi_title") case .maxim: icon.image = #imageLiteral(resourceName: "ic_taxi_logo_maksim") title.text = L("maxim_taxi_title") } } @IBAction func orderAction() { delegate.orderTaxi(type) } }
apache-2.0
aa3e2f0cc46995c91a8972b0bdae0b8a
30.285714
92
0.676451
4.066313
false
false
false
false
toggl/superday
teferi/UI/Modules/Daily Summary/Views/DailySummaryTableViewCell.swift
1
925
import UIKit class DailySummaryTableViewCell: UITableViewCell { @IBOutlet weak var dot: UIView! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var percentageLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! private let hourMask = "%02d h %02d min" private let minuteMask = "%02d min" func setup(with activity: Activity, totalDuration: TimeInterval) { dot.backgroundColor = activity.category.color dot.layer.cornerRadius = dot.bounds.width / 2 categoryLabel.text = activity.category.description percentageLabel.text = "\(Int(activity.duration / totalDuration * 100))%" let minutes = (Int(activity.duration) / 60) % 60 let hours = Int(activity.duration / 3600) durationLabel.text = hours > 0 ? String(format: hourMask, hours, minutes) : String(format: minuteMask, minutes) } }
bsd-3-clause
073719a5eb5d588c3228acec2416ee20
34.576923
119
0.664865
4.579208
false
false
false
false
almazrafi/Metatron
Sources/Types/MediaRegistry.swift
1
3550
// // MediaRegistry.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 MediaRegistry { // MARK: Type Properties public static let regular = MediaRegistry() // MARK: Instance Properties public private(set) var medias: [String: MediaFormat] // MARK: Initializers private init() { self.medias = ["mp3": MPEGMediaFormat.regular] } // MARK: Instance Methods @discardableResult public func registerMedia(format: MediaFormat, fileExtension: String) -> Bool { guard !fileExtension.isEmpty else { return false } let key = fileExtension.lowercased() guard self.medias[key] == nil else { return false } self.medias[key] = format return true } public func identifyFilePath(_ filePath: String) -> MediaFormat? { guard let extensionStart = filePath.range(of: ".", options: String.CompareOptions.backwards) else { return nil } guard extensionStart.lowerBound > filePath.startIndex else { return nil } guard extensionStart.upperBound < filePath.endIndex else { return nil } return self.medias[filePath.substring(from: extensionStart.upperBound).lowercased()] } } public func createMedia(fromStream stream: Stream) throws -> Media { for (_, format) in MediaRegistry.regular.medias { do { return try format.createMedia(fromStream: stream) } catch MediaError.invalidFormat { } } throw MediaError.invalidFormat } public func createMedia(fromFilePath filePath: String, readOnly: Bool) throws -> Media { if let format = MediaRegistry.regular.identifyFilePath(filePath) { return try format.createMedia(fromFilePath: filePath, readOnly: readOnly) } for (_, format) in MediaRegistry.regular.medias { do { return try format.createMedia(fromFilePath: filePath, readOnly: readOnly) } catch MediaError.invalidFormat { } } throw MediaError.invalidFormat } public func createMedia(fromData data: [UInt8], readOnly: Bool) throws -> Media { for (_, format) in MediaRegistry.regular.medias { do { return try format.createMedia(fromData: data, readOnly: readOnly) } catch MediaError.invalidFormat { } } throw MediaError.invalidFormat }
mit
2e8db09396ea6694746ce8b21f0c5110
29.869565
107
0.676901
4.60441
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/Lyrics3/Lyrics3TagAlbumTest.swift
1
5108
// // Lyrics3TagAlbumTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 Metatron class Lyrics3TagAlbumTest: XCTestCase { // MARK: Instance Methods func test() { let textEncoding = ID3v1Latin1TextEncoding.regular let tag = Lyrics3Tag() do { let value = "" tag.album = value XCTAssert(tag.album == value.prefix(250)) let field = tag.appendField(Lyrics3FieldID.eal) XCTAssert(field.stuff == nil) do { tag.version = Lyrics3Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = Lyrics3Version.v2 XCTAssert(tag.toData() == nil) } field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = value XCTAssert(tag.album == value.prefix(250)) } do { let value = "Abc 123" tag.album = value XCTAssert(tag.album == value.prefix(250)) let field = tag.appendField(Lyrics3FieldID.eal) XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == value.prefix(250)) do { tag.version = Lyrics3Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = Lyrics3Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = Lyrics3Tag(fromData: data) else { return XCTFail() } XCTAssert(other.album == value.deencoded(with: textEncoding).prefix(250)) } field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = value XCTAssert(tag.album == value.prefix(250)) } do { let value = "Абв 123" tag.album = value XCTAssert(tag.album == value.prefix(250)) let field = tag.appendField(Lyrics3FieldID.eal) XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == value.prefix(250)) do { tag.version = Lyrics3Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = Lyrics3Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = Lyrics3Tag(fromData: data) else { return XCTFail() } XCTAssert(other.album == value.deencoded(with: textEncoding).prefix(250)) } field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = value XCTAssert(tag.album == value.prefix(250)) } do { let value = Array<String>(repeating: "Abc", count: 123).joined(separator: "\n") tag.album = value XCTAssert(tag.album == value.prefix(250)) let field = tag.appendField(Lyrics3FieldID.eal) XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == value.prefix(250)) do { tag.version = Lyrics3Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = Lyrics3Version.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = Lyrics3Tag(fromData: data) else { return XCTFail() } XCTAssert(other.album == value.deencoded(with: textEncoding).prefix(250)) } field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = value XCTAssert(tag.album == value.prefix(250)) } } }
mit
6bafab6d88de7710614fdf07707c4027
28.005682
109
0.570225
4.674908
false
false
false
false
gdaniele/StackViewPhotoCollage
StackViewPhotoCollage/ImageFeedViewController.swift
1
4461
// // ImageFeedViewController.swift // StackViewPhotoCollage // // Created by Giancarlo on 7/4/15. // Copyright (c) 2015 Giancarlo. All rights reserved. // import UIKit import AVFoundation // Inspired by: RayWenderlich.com pinterest-basic-layout class ImageFeedViewController: UICollectionViewController { // MARK: Layout Concerns private let cellStyle = BeigeRoundedPhotoCaptionCellStyle() private let reuseIdentifier = "PhotoCaptionCell" private let collectionViewBottomInset: CGFloat = 10 private let collectionViewSideInset: CGFloat = 5 private let collectionViewTopInset: CGFloat = UIApplication.sharedApplication().statusBarFrame.height private var numberOfColumns: Int = 1 // MARK: Data private let photos = Photo.allPhotos() required init() { let layout = MultipleColumnLayout() super.init(collectionViewLayout: layout) layout.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setUpUI() } override func viewWillTransitionToSize( size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) guard let collectionView = collectionView, let layout = collectionView.collectionViewLayout as? MultipleColumnLayout else { return } layout.clearCache() layout.invalidateLayout() } // MARK: Private private func setUpUI() { // Set background if let patternImage = UIImage(named: "pattern") { view.backgroundColor = UIColor(patternImage: patternImage) } // Set title title = "Variable height layout" // Set generic styling collectionView?.backgroundColor = UIColor.clearColor() collectionView?.contentInset = UIEdgeInsetsMake( collectionViewTopInset, collectionViewSideInset, collectionViewBottomInset, collectionViewSideInset) // Set layout guard let layout = collectionViewLayout as? MultipleColumnLayout else { return } layout.cellPadding = collectionViewSideInset layout.numberOfColumns = numberOfColumns // Register cell identifier self.collectionView?.registerClass(PhotoCaptionCell.self, forCellWithReuseIdentifier: self.reuseIdentifier) } } // MARK: UICollectionViewDelegate extension ImageFeedViewController { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath ) -> UICollectionViewCell { guard let cell = collectionView .dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as? PhotoCaptionCell else { fatalError("Could not dequeue cell") } cell.setUpWithImage(photos[indexPath.item].image, title: photos[indexPath.item].caption, style: BeigeRoundedPhotoCaptionCellStyle()) return cell } } // MARK: MultipleColumnLayoutDelegate extension ImageFeedViewController: MultipleColumnLayoutDelegate { func collectionView(collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat { let photo = photos[indexPath.item] let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT)) return AVMakeRectWithAspectRatioInsideRect(photo.image.size, boundingRect).height } func collectionView(collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat { let rect = NSString(string: photos[indexPath.item].caption) .boundingRectWithSize( CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: cellStyle.titleFont], context: nil) return ceil(rect.height + cellStyle.titleInsets.top + cellStyle.titleInsets.bottom) } }
mit
9ac23b068467b2c90be0a5ddb20c3fca
31.093525
91
0.691997
5.555417
false
false
false
false
patrick-gleeson/thinginess_swift
ThinginessSwift/Classes/ThingRegistry.swift
1
711
// // ThingRegistry.swift // Pods // // Created by Patrick Gleeson on 16/09/2016. // // public class ThingRegistry { public static let sharedInstance = ThingRegistry() public func thingsOfType(type :String) -> ThingSet { return ThingSet(things: (registry[type] ?? [])) } func register(thing: BaseThing, with_types types: Array<String>) { types.forEach { ( type : String) -> () in if var subregistry = registry[type] { subregistry.append(thing) } else { var subregistry = [thing] registry[type] = subregistry } } } private var registry = [String:Array<BaseThing>]() }
mit
32e49a60b6ad855d42fd7e43ecad7bb9
23.517241
70
0.565401
4.086207
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyer/Jobs/JobGroupHeaderView.swift
1
1221
import UIKit class JobGroupHeaderView: UITableViewHeaderFooterView { private var containerView: UIView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let viewPackage = Bundle.main.loadNibNamed("JobGroupHeaderView", owner: self, options: nil) guard let loadedView = viewPackage?.first as? UIView else { print("Failed to load nib with name 'JobGroupHeaderView'") return } containerView = loadedView addSubview(containerView) containerView.bounds = bounds autoresizesSubviews = true autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] backgroundColor = UIColor.clear containerView.backgroundColor = UIColor.clear } private weak var cachedNameLabel: UILabel? weak var nameLabel: UILabel? { get { if cachedNameLabel != nil { return cachedNameLabel } let nameLabel = containerView.subviews.filter { subview in return subview.isKind(of: UILabel.self) }.first as? UILabel cachedNameLabel = nameLabel return cachedNameLabel } } }
apache-2.0
799ef0926ba291c4c44faf3ae08d7d0d
32
99
0.652744
5.652778
false
false
false
false
tbajis/Bop
Photo.swift
1
768
// // Photo+CoreDataClass.swift // Bop // // Created by Thomas Manos Bajis on 4/24/17. // Copyright © 2017 Thomas Manos Bajis. All rights reserved. // import Foundation import CoreData // MARK: - Photo: NSManagedObject class Photo: NSManagedObject { // MARK: Initializer convenience init(id: String?, height: Double, width: Double, mediaURL: String, context: NSManagedObjectContext) { if let ent = NSEntityDescription.entity(forEntityName: "Photo", in: context) { self.init(entity: ent, insertInto: context) self.id = id self.mediaURL = mediaURL self.width = width self.height = height } else { fatalError("Unable to find Entity Photo") } } }
apache-2.0
b452eedeec078c7933ab0b39eb932d94
26.392857
117
0.6206
4.237569
false
false
false
false
mayongl/MyNews
MyNews/MyNews/NewsViewController+TableViewDataSource.swift
1
1103
// // NewsViewController+TableViewDataSource.swift // MyNews // // Created by Yong Lin Ma on 26/04/2017. // Copyright © 2017 Sixlivesleft. All rights reserved. // import UIKit extension NewsViewController : UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //let cell = tableView.dequeueReusableCell(withIdentifier: "NewsImageCell", for: indexPath) var cell : UITableViewCell // Configure the cell... if indexPath.row == 1 { cell = tableView.dequeueReusableCell(withIdentifier: "NewsImageCell", for: indexPath) } else { cell = tableView.dequeueReusableCell(withIdentifier: "NewsStandardCell", for: indexPath) } return cell } }
mit
7f554f54497cf9c675ba4f2a3518e855
26.55
100
0.622505
5.455446
false
false
false
false