repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
mrgerych/Cuckoo
Tests/Matching/ParameterMatcherTest.swift
2
859
// // ParameterMatcherTest.swift // Cuckoo // // Created by Filip Dolnik on 05.07.16. // Copyright © 2016 Brightify. All rights reserved. // import XCTest import Cuckoo class ParameterMatcherTest: XCTestCase { func testMatches() { let matcher = ParameterMatcher { $0 == 5 } XCTAssertTrue(matcher.matches(5)) XCTAssertFalse(matcher.matches(4)) } func testOr() { let matcher = ParameterMatcher { $0 == 5 }.or(ParameterMatcher { $0 == 4 }) XCTAssertTrue(matcher.matches(5)) XCTAssertTrue(matcher.matches(4)) XCTAssertFalse(matcher.matches(3)) } func testAnd() { let matcher = ParameterMatcher { $0 > 3 }.and(ParameterMatcher { $0 < 5 }) XCTAssertTrue(matcher.matches(4)) XCTAssertFalse(matcher.matches(3)) } }
mit
iOSreverse/DWWB
DWWB/DWWB/Classes/Home(首页)/HomeModel/User.swift
1
661
// // User.swift // DWWB // // Created by xmg on 16/4/9. // Copyright © 2016年 NewDee. All rights reserved. // import UIKit class User: NSObject { // MARK: - 属性 var profile_image_url : String? // 用户的头像 var screen_name : String? // 用户的昵称 var verified_type : Int = -1 // 用户的认证类型 var mbrank : Int = 0 // 用户的会员等级 // MARK: - 自定义构造函数 init(dict : [String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} }
apache-2.0
JGiola/swift
test/Interop/Cxx/operators/member-inline.swift
1
8987
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop) // // REQUIRES: executable_test // TODO: Fix CxxShim for Windows. // XFAIL: OS=windows-msvc import MemberInline import StdlibUnittest var OperatorsTestSuite = TestSuite("Operators") #if !os(Windows) // SR-13129 OperatorsTestSuite.test("LoadableIntWrapper.minus (inline)") { var lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let result = lhs - rhs expectEqual(19, result.value) } OperatorsTestSuite.test("AddressOnlyIntWrapper.minus") { let lhs = AddressOnlyIntWrapper(42) let rhs = AddressOnlyIntWrapper(23) let result = lhs - rhs expectEqual(19, result.value) } #endif OperatorsTestSuite.test("LoadableIntWrapper.equal (inline)") { let lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 42) let result = lhs == rhs expectTrue(result) } OperatorsTestSuite.test("LoadableIntWrapper.unaryMinus (inline)") { let lhs = LoadableIntWrapper(value: 42) let inverseLhs = -lhs; expectEqual(-42, inverseLhs.value) } OperatorsTestSuite.test("LoadableIntWrapper.call (inline)") { var wrapper = LoadableIntWrapper(value: 42) let resultNoArgs = wrapper() let resultOneArg = wrapper(23) let resultTwoArgs = wrapper(3, 5) expectEqual(42, resultNoArgs) expectEqual(65, resultOneArg) expectEqual(57, resultTwoArgs) } OperatorsTestSuite.test("LoadableIntWrapper.successor() (inline)") { var wrapper = LoadableIntWrapper(value: 42) let result1 = wrapper.successor() expectEqual(43, result1.value) expectEqual(42, wrapper.value) // Calling `successor()` should not mutate `wrapper`. let result2 = result1.successor() expectEqual(44, result2.value) expectEqual(43, result1.value) expectEqual(42, wrapper.value) } #if !os(Windows) // SR-13129 OperatorsTestSuite.test("LoadableBoolWrapper.exclaim (inline)") { var wrapper = LoadableBoolWrapper(value: true) let resultExclaim = !wrapper expectEqual(false, resultExclaim.value) } #endif OperatorsTestSuite.test("AddressOnlyIntWrapper.call (inline)") { var wrapper = AddressOnlyIntWrapper(42) let resultNoArgs = wrapper() let resultOneArg = wrapper(23) let resultTwoArgs = wrapper(3, 5) expectEqual(42, resultNoArgs) expectEqual(65, resultOneArg) expectEqual(57, resultTwoArgs) } OperatorsTestSuite.test("AddressOnlyIntWrapper.successor() (inline)") { var wrapper = AddressOnlyIntWrapper(0) let result1 = wrapper.successor() expectEqual(1, result1.value) expectEqual(0, wrapper.value) // Calling `successor()` should not mutate `wrapper`. let result2 = result1.successor() expectEqual(2, result2.value) expectEqual(1, result1.value) expectEqual(0, wrapper.value) } OperatorsTestSuite.test("HasPreIncrementOperatorWithAnotherReturnType.successor() (inline)") { var wrapper = HasPreIncrementOperatorWithAnotherReturnType() let result1 = wrapper.successor() expectEqual(1, result1.value) expectEqual(0, wrapper.value) // Calling `successor()` should not mutate `wrapper`. let result2 = result1.successor() expectEqual(2, result2.value) expectEqual(1, result1.value) expectEqual(0, wrapper.value) } OperatorsTestSuite.test("HasPreIncrementOperatorWithVoidReturnType.successor() (inline)") { var wrapper = HasPreIncrementOperatorWithVoidReturnType() let result1 = wrapper.successor() expectEqual(1, result1.value) expectEqual(0, wrapper.value) // Calling `successor()` should not mutate `wrapper`. let result2 = result1.successor() expectEqual(2, result2.value) expectEqual(1, result1.value) expectEqual(0, wrapper.value) } OperatorsTestSuite.test("DerivedFromAddressOnlyIntWrapper.call (inline, base class)") { var wrapper = DerivedFromAddressOnlyIntWrapper(42) let resultNoArgs = wrapper() let resultOneArg = wrapper(23) let resultTwoArgs = wrapper(3, 5) expectEqual(42, resultNoArgs) expectEqual(65, resultOneArg) expectEqual(57, resultTwoArgs) } OperatorsTestSuite.test("ReadWriteIntArray.subscript (inline)") { var arr = ReadWriteIntArray() let resultBefore = arr[1] expectEqual(2, resultBefore) arr[1] = 234 let resultAfter = arr[1] expectEqual(234, resultAfter) } OperatorsTestSuite.test("DerivedFromReadWriteIntArray.subscript (inline, base class)") { var arr = DerivedFromReadWriteIntArray() let resultBefore = arr[1] expectEqual(2, resultBefore) arr[1] = 234 let resultAfter = arr[1] expectEqual(234, resultAfter) } OperatorsTestSuite.test("ReadOnlyIntArray.subscript (inline)") { let arr = ReadOnlyIntArray(1) let result0 = arr[0] let result2 = arr[2] let result4 = arr[4] expectEqual(1, result0) expectEqual(3, result2) expectEqual(5, result4) } OperatorsTestSuite.test("WriteOnlyIntArray.subscript (inline)") { var arr = WriteOnlyIntArray() let resultBefore = arr[0] expectEqual(1, resultBefore) arr[0] = 654 let resultAfter = arr[0] expectEqual(654, resultAfter) } OperatorsTestSuite.test("DifferentTypesArray.subscript (inline)") { let arr = DifferentTypesArray() let resultInt: Int32 = arr[2] let resultDouble: Double = arr[0.1] expectEqual(3, resultInt) expectEqual(1.5.rounded(.down), resultDouble.rounded(.down)) expectEqual(1.5.rounded(.up), resultDouble.rounded(.up)) } OperatorsTestSuite.test("IntArrayByVal.subscript (inline)") { var arr = IntArrayByVal() let result0 = arr[0] let result1 = arr[1] let result2 = arr[2] expectEqual(1, result0) expectEqual(2, result1) expectEqual(3, result2) arr.setValueAtIndex(42, 2) let result3 = arr[2] expectEqual(42, result3) } OperatorsTestSuite.test("NonTrivialIntArrayByVal.subscript (inline)") { var arr = NonTrivialIntArrayByVal(1) let result0 = arr[0] let result2 = arr[2] let result4 = arr[4] expectEqual(1, result0) expectEqual(3, result2) expectEqual(5, result4) arr.setValueAtIndex(42, 2) let result5 = arr[2] expectEqual(42, result5) } OperatorsTestSuite.test("DifferentTypesArrayByVal.subscript (inline)") { var arr = DifferentTypesArrayByVal() let resultInt: Int32 = arr[2] let resultDouble: Double = arr[0.1] expectEqual(3, resultInt) expectEqual(1.5.rounded(.down), resultDouble.rounded(.down)) expectEqual(1.5.rounded(.up), resultDouble.rounded(.up)) } #if !os(Windows) // SR-13129 OperatorsTestSuite.test("NonTrivialArrayByVal.subscript (inline)") { var arr = NonTrivialArrayByVal() let NonTrivialByVal = arr[0]; let cStr = NonTrivialByVal.Str! expectEqual("Non-Trivial", String(cString: cStr)) expectEqual(1, NonTrivialByVal.a) expectEqual(2, NonTrivialByVal.b) expectEqual(3, NonTrivialByVal.c) expectEqual(4, NonTrivialByVal.d) expectEqual(5, NonTrivialByVal.e) expectEqual(6, NonTrivialByVal.f) } OperatorsTestSuite.test("DerivedFromNonTrivialArrayByVal.subscript (inline, base class)") { var arr = DerivedFromNonTrivialArrayByVal() let NonTrivialByVal = arr[0]; let cStr = NonTrivialByVal.Str! expectEqual("Non-Trivial", String(cString: cStr)) expectEqual(1, NonTrivialByVal.a) expectEqual(2, NonTrivialByVal.b) expectEqual(3, NonTrivialByVal.c) expectEqual(4, NonTrivialByVal.d) expectEqual(5, NonTrivialByVal.e) expectEqual(6, NonTrivialByVal.f) } #endif OperatorsTestSuite.test("PtrByVal.subscript (inline)") { var arr = PtrByVal() expectEqual(64, arr[0]![0]) arr[0]![0] = 23 expectEqual(23, arr[0]![0]) } OperatorsTestSuite.test("ConstOpPtrByVal.subscript (inline)") { var arr = ConstOpPtrByVal() expectEqual(64, arr[0]![0]) } OperatorsTestSuite.test("ConstPtrByVal.subscript (inline)") { var arr = ConstPtrByVal() expectEqual(64, arr[0]![0]) } OperatorsTestSuite.test("RefToPtr.subscript (inline)") { var arr = RefToPtr() let ptr: UnsafeMutablePointer<Int32> = UnsafeMutablePointer<Int32>.allocate(capacity: 64) ptr[0] = 23 expectEqual(64, arr[0]![0]) arr[0] = ptr expectEqual(23, arr[0]![0]) } OperatorsTestSuite.test("PtrToPtr.subscript (inline)") { var arr = PtrToPtr() let ptr: UnsafeMutablePointer<Int32> = UnsafeMutablePointer<Int32>.allocate(capacity: 64) ptr[0] = 23 expectEqual(64, arr[0]![0]![0]) arr[0]![0] = ptr expectEqual(23, arr[0]![0]![0]) } // TODO: this causes a crash (does it also crash on main?) //OperatorsTestSuite.test("TemplatedSubscriptArrayByVal.subscript (inline)") { // let ptr: UnsafeMutablePointer<Int32> = // UnsafeMutablePointer<Int32>.allocate(capacity: 64) // ptr[0] = 23 // var arr = TemplatedSubscriptArrayByVal(ptr: ptr) // expectEqual(23, arr[0]) //} OperatorsTestSuite.test("Iterator.pointee") { var iter = Iterator() let res = iter.pointee expectEqual(123, res) } OperatorsTestSuite.test("ConstIterator.pointee") { let iter = ConstIterator() let res = iter.pointee expectEqual(234, res) } OperatorsTestSuite.test("ConstIteratorByVal.pointee") { let iter = ConstIteratorByVal() let res = iter.pointee expectEqual(456, res) } runAllTests()
apache-2.0
vbicer/RealmStore
Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftObjectInterfaceTests.swift
2
11354
//////////////////////////////////////////////////////////////////////////// // // 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 Foundation class OuterClass { class InnerClass { } } class SwiftStringObjectSubclass : SwiftStringObject { @objc dynamic var stringCol2 = "" } class SwiftSelfRefrencingSubclass: SwiftStringObject { @objc dynamic var objects = RLMArray<SwiftSelfRefrencingSubclass>(objectClassName: SwiftSelfRefrencingSubclass.className()) } class SwiftDefaultObject: RLMObject { @objc dynamic var intCol = 1 @objc dynamic var boolCol = true override class func defaultPropertyValues() -> [AnyHashable : Any]? { return ["intCol": 2] } } class SwiftOptionalNumberObject: RLMObject { @objc dynamic var intCol: NSNumber? = 1 @objc dynamic var floatCol: NSNumber? = 2.2 as Float as NSNumber @objc dynamic var doubleCol: NSNumber? = 3.3 @objc dynamic var boolCol: NSNumber? = true } class SwiftObjectInterfaceTests: RLMTestCase { // Swift models func testSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = SwiftObject() realm.add(obj) obj.boolCol = true obj.intCol = 1234 obj.floatCol = 1.1 obj.doubleCol = 2.2 obj.stringCol = "abcd" obj.binaryCol = "abcd".data(using: String.Encoding.utf8) obj.dateCol = Date(timeIntervalSince1970: 123) obj.objectCol = SwiftBoolObject() obj.objectCol.boolCol = true obj.arrayCol.add(obj.objectCol) try! realm.commitWriteTransaction() let data = "abcd".data(using: String.Encoding.utf8) let firstObj = SwiftObject.allObjects(in: realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, true, "should be true") XCTAssertEqual(firstObj.intCol, 1234, "should be 1234") XCTAssertEqual(firstObj.floatCol, Float(1.1), "should be 1.1") XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2") XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, Date(timeIntervalSince1970: 123), "should be epoch + 123") XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true") XCTAssertEqual(obj.arrayCol.count, UInt(1), "array count should be 1") XCTAssertEqual(obj.arrayCol.firstObject()!.boolCol, true, "should be true") } func testDefaultValueSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() realm.add(SwiftObject()) try! realm.commitWriteTransaction() let data = "a".data(using: String.Encoding.utf8) let firstObj = SwiftObject.allObjects(in: realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, false, "should be false") XCTAssertEqual(firstObj.intCol, 123, "should be 123") XCTAssertEqual(firstObj.floatCol, Float(1.23), "should be 1.23") XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3") XCTAssertEqual(firstObj.stringCol, "a", "should be a") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, Date(timeIntervalSince1970: 1), "should be epoch + 1") XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false") XCTAssertEqual(firstObj.arrayCol.count, UInt(0), "array count should be zero") } func testMergedDefaultValuesSwiftObject() { let realm = self.realmWithTestPath() realm.beginWriteTransaction() _ = SwiftDefaultObject.create(in: realm, withValue: NSDictionary()) try! realm.commitWriteTransaction() let object = SwiftDefaultObject.allObjects(in: realm).firstObject() as! SwiftDefaultObject XCTAssertEqual(object.intCol, 2, "defaultPropertyValues should override native property default value") XCTAssertEqual(object.boolCol, true, "native property default value should be used if defaultPropertyValues doesn't contain that key") } func testSubclass() { // test className methods XCTAssertEqual("SwiftStringObject", SwiftStringObject.className()) XCTAssertEqual("SwiftStringObjectSubclass", SwiftStringObjectSubclass.className()) let realm = RLMRealm.default() realm.beginWriteTransaction() _ = SwiftStringObject.createInDefaultRealm(withValue: ["string"]) _ = SwiftStringObjectSubclass.createInDefaultRealm(withValue: ["string", "string2"]) try! realm.commitWriteTransaction() // ensure creation in proper table XCTAssertEqual(UInt(1), SwiftStringObjectSubclass.allObjects().count) XCTAssertEqual(UInt(1), SwiftStringObject.allObjects().count) try! realm.transaction { // create self referencing subclass let sub = SwiftSelfRefrencingSubclass.createInDefaultRealm(withValue: ["string", []]) let sub2 = SwiftSelfRefrencingSubclass() sub.objects.add(sub2) } } func testOptionalNSNumberProperties() { let realm = realmWithTestPath() let no = SwiftOptionalNumberObject() XCTAssertEqual([.int, .float, .double, .bool], no.objectSchema.properties.map { $0.type }) XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float as NSNumber, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(true, no.boolCol!) try! realm.transaction { realm.add(no) no.intCol = nil no.floatCol = nil no.doubleCol = nil no.boolCol = nil } XCTAssertNil(no.intCol) XCTAssertNil(no.floatCol) XCTAssertNil(no.doubleCol) XCTAssertNil(no.boolCol) try! realm.transaction { no.intCol = 1.1 no.floatCol = 2.2 as Float as NSNumber no.doubleCol = 3.3 no.boolCol = false } XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float as NSNumber, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(false, no.boolCol!) } func testOptionalSwiftProperties() { let realm = realmWithTestPath() try! realm.transaction { realm.add(SwiftOptionalObject()) } let firstObj = SwiftOptionalObject.allObjects(in: realm).firstObject() as! SwiftOptionalObject XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optNSStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) try! realm.transaction { firstObj.optObjectCol = SwiftBoolObject() firstObj.optObjectCol!.boolCol = true firstObj.optStringCol = "Hi!" firstObj.optNSStringCol = "Hi!" firstObj.optBinaryCol = Data(bytes: "hi", count: 2) firstObj.optDateCol = Date(timeIntervalSinceReferenceDate: 10) } XCTAssertTrue(firstObj.optObjectCol!.boolCol) XCTAssertEqual(firstObj.optStringCol!, "Hi!") XCTAssertEqual(firstObj.optNSStringCol!, "Hi!") XCTAssertEqual(firstObj.optBinaryCol!, Data(bytes: "hi", count: 2)) XCTAssertEqual(firstObj.optDateCol!, Date(timeIntervalSinceReferenceDate: 10)) try! realm.transaction { firstObj.optObjectCol = nil firstObj.optStringCol = nil firstObj.optNSStringCol = nil firstObj.optBinaryCol = nil firstObj.optDateCol = nil } XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optNSStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) } func testSwiftClassNameIsDemangled() { XCTAssertEqual(SwiftObject.className(), "SwiftObject", "Calling className() on Swift class should return demangled name") } // Objective-C models // Note: Swift doesn't support custom accessor names // so we test to make sure models with custom accessors can still be accessed func testCustomAccessors() { let realm = realmWithTestPath() realm.beginWriteTransaction() let ca = CustomAccessorsObject.create(in: realm, withValue: ["name", 2]) XCTAssertEqual(ca.name!, "name", "name property should be name.") ca.age = 99 XCTAssertEqual(ca.age, Int32(99), "age property should be 99") try! realm.commitWriteTransaction() } func testClassExtension() { let realm = realmWithTestPath() realm.beginWriteTransaction() let bObject = BaseClassStringObject() bObject.intCol = 1 bObject.stringCol = "stringVal" realm.add(bObject) try! realm.commitWriteTransaction() let objectFromRealm = BaseClassStringObject.allObjects(in: realm)[0] as! BaseClassStringObject XCTAssertEqual(objectFromRealm.intCol, Int32(1), "Should be 1") XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal") } func testCreateOrUpdate() { let realm = RLMRealm.default() realm.beginWriteTransaction() _ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["string", 1]) let objects = SwiftPrimaryStringObject.allObjects(); XCTAssertEqual(objects.count, UInt(1), "Should have 1 object"); XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 1, "Value should be 1"); _ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["stringCol": "string2", "intCol": 2]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") _ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["string", 3]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 3, "Value should be 3"); try! realm.commitWriteTransaction() } // if this fails (and you haven't changed the test module name), the checks // for swift class names and the demangling logic need to be updated func testNSStringFromClassDemangledTopLevelClassNames() { XCTAssertEqual(NSStringFromClass(OuterClass.self), "Tests.OuterClass") } // if this fails (and you haven't changed the test module name), the prefix // check in RLMSchema initialization needs to be updated func testNestedClassNameMangling() { XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC5Tests10OuterClass10InnerClass") } }
mit
kstaring/swift
test/Constraints/ErrorBridging.swift
4
1950
// RUN: %target-swift-frontend %clang-importer-sdk -parse %s -verify // REQUIRES: objc_interop import Foundation enum FooError: HairyError, Runcible { case A var hairiness: Int { return 0 } func runce() {} } protocol HairyError : Error { var hairiness: Int { get } } protocol Runcible { func runce() } let foo = FooError.A let error: Error = foo let subError: HairyError = foo let compo: HairyError & Runcible = foo // Error-conforming concrete or existential types can be coerced explicitly // to NSError. let ns1 = foo as NSError let ns2 = error as NSError let ns3 = subError as NSError var ns4 = compo as NSError // NSError conversion must be explicit. // TODO: fixit to insert 'as NSError' ns4 = compo // expected-error{{cannot assign value of type 'HairyError & Runcible' to type 'NSError'}} let e1 = ns1 as? FooError let e1fix = ns1 as FooError // expected-error{{did you mean to use 'as!'}} {{17-19=as!}} let esub = ns1 as Error let esub2 = ns1 as? Error // expected-warning{{conditional cast from 'NSError' to 'Error' always succeeds}} // SR-1562 / rdar://problem/26370984 enum MyError : Error { case failed } func concrete1(myError: MyError) -> NSError { return myError as NSError } func concrete2(myError: MyError) -> NSError { return myError // expected-error{{cannot convert return expression of type 'MyError' to return type 'NSError'}} } func generic<T : Error>(error: T) -> NSError { return error as NSError } extension Error { var asNSError: NSError { return self as NSError } var asNSError2: NSError { return self // expected-error{{cannot convert return expression of type 'Self' to return type 'NSError'}} } } // rdar://problem/27543121 func throwErrorCode() throws { throw FictionalServerError.meltedDown // expected-error{{thrown error code type 'FictionalServerError.Code' does not conform to 'Error'; construct an 'FictionalServerError' instance}}{{29-29=(}}{{40-40=)}} }
apache-2.0
practicalswift/swift
test/stdlib/CoreGraphics.swift
15
470
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import CoreGraphics import StdlibUnittest let CoreGraphicsTests = TestSuite("CoreGraphics") CoreGraphicsTests.test("CGColor/_ExpressibleByColorLiteral") { let color: CGColor = #colorLiteral( red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0) // we primarilly care that the code above does not crash expectEqual([0.5, 0.5, 0.5, 1.0], color.components ?? []) } runAllTests()
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/11079-swift-sourcemanager-getmessage.swift
11
239
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func g( = [ { var : { class A { { } func a { { { } } { } class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/08383-swift-sourcemanager-getmessage.swift
11
225
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for c : { let b { { } class c { struct d { class case ,
mit
avtr/bluejay
Bluejay/BluejayDemo/AppDelegate.swift
1
2188
// // AppDelegate.swift // BluejayDemo // // Created by Jeremy Chiang on 2017-02-07. // Copyright © 2017 Steamclock Software. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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:. } }
mit
yuriy-tolstoguzov/ScaledCenterCarousel
Swift/Example/ScaledCenterCarouselSwiftExample/ScaledCenterCarouselSwiftExample/ViewController.swift
1
1118
// // ViewController.swift // ScaledCenterCarouselSwiftExample // // Created by Yuriy Tolstoguzov on 10/20/19. // Copyright © 2019 Yuriy Tolstoguzov. All rights reserved. // import UIKit import ScaledCenterCarousel class ViewController: UIViewController, ScaledCenterCarouselPaginatorDelegate { @IBOutlet weak var collectionView: UICollectionView? let collectionViewDataSource = CarouselDataSource() lazy var paginator = ScaledCenterCarouselPaginator(collectionView: collectionView!, delegate: self) override func viewDidLoad() { super.viewDidLoad() guard let collectionView = collectionView else { return } collectionView.dataSource = collectionViewDataSource paginator = ScaledCenterCarouselPaginator(collectionView: collectionView, delegate: self) } // MARK: - CarouselCenterPagerDelegate func carousel(_ collectionView: UICollectionView, didSelectElementAt index: UInt) { } func carousel(_ collectionView: UICollectionView, didScrollTo visibleCells: [UICollectionViewCell]) { } }
mit
mightydeveloper/swift
validation-test/compiler_crashers/27561-swift-functiontype-get.swift
9
339
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B{ let a=0 func b{class B<T where B:a{struct b{ struct Q<T{ struct B{ struct A{ class A struct A{{ }var b=A{
apache-2.0
paleksandrs/APCoreDataKit
APCoreDataKit/NSManagedObjectContext+StackSetup.swift
1
1401
// // Created by Aleksandrs Proskurins // // License // Copyright © 2016 Aleksandrs Proskurins // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreData public extension NSManagedObjectContext { public convenience init(model: ManagedObjectModel, storeType: PersistentStoreType, concurrencyType: NSManagedObjectContextConcurrencyType = .mainQueueConcurrencyType) { self.init(concurrencyType: concurrencyType) persistentStoreCoordinator = getPersistentStoreCoordinator(withModel: model, storeType: storeType) } fileprivate func getPersistentStoreCoordinator(withModel model: ManagedObjectModel, storeType: PersistentStoreType) -> NSPersistentStoreCoordinator{ let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model.managedObjectModel) let url = storeType.storePath() do { try coordinator.addPersistentStore(ofType: storeType.type, configurationName: nil, at: url as URL?, options: nil) } catch { fatalError("*** Failed to initialize the application's saved data ***") } return coordinator } func child() -> NSManagedObjectContext { let child = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) child.parent = self return child } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0794-swift-typebase-isspecialized.swift
13
988
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func e<l { enum e { func p() { p d> Bool { } protocol f : b { func b } func a<g>func s<s : m, v : m u v.v == s> (m: v) { } func s<v l k : a { } protocol g { } struct n : g { } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } } k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) { struct d<f : e, g: e where g.h == f.h> {{ } struct B<T : A> { } protocol C { ty } } struct d<f : e, g: e where g.h ==ay) { } } extension NSSet { convenience init<T>(array: Array<T>) { } } class A { class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { } class e: k{ clq) { } } T) { } } } class A { class func a() -> Self { } } func b<T>(t: AnyObject.Type) -> T! { } class A { } class k: h{ class func r {} var k = 1
apache-2.0
yutmr/Refresher
Sources/Refresher.swift
1
3334
// // Refresher.swift // // Created by Yu Tamura on 2016/06/05. // Copyright © 2016 Yu Tamura. All rights reserved. // import UIKit @objc public enum RefreshState: Int { case stable, refreshing, ready } @objc public protocol RefresherDelegate { /// Notice current refresh state. /// - parameter refreshView: A view for display refresh state. /// - parameter state: Current refreesh state. /// - parameter percent: Percent of reached refresh threshold. func updateRefreshView(refreshView: UIView, state: RefreshState, percent: Float) /// Notify refresh timing. func startRefreshing() } @objcMembers final public class Refresher: NSObject { private let refreshView: UIView private let scrollView: UIScrollView public weak var delegate: RefresherDelegate? public private(set) var state: RefreshState = .stable { didSet (oldValue) { let percent = Float(-scrollView.contentOffset.y / refreshView.frame.height) delegate?.updateRefreshView(refreshView: refreshView, state: state, percent: percent) if oldValue != .refreshing && state == .refreshing { delegate?.startRefreshing() } } } public var animateDuration: TimeInterval = 0.3 private var isDragging = false public init(refreshView: UIView, scrollView: UIScrollView) { refreshView.frame = CGRect(x: 0, y: -refreshView.frame.height, width: scrollView.frame.width, height: refreshView.frame.height) scrollView.addSubview(refreshView) self.refreshView = refreshView self.scrollView = scrollView super.init() scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil) } deinit { scrollView.removeObserver(self, forKeyPath: "contentOffset") } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let scrollView = object as? UIScrollView else { return } if isDragging && !scrollView.isDragging { didEndDragging() } isDragging = scrollView.isDragging didScroll() } private func didScroll() { let height = refreshView.frame.height let offsetY = scrollView.contentOffset.y switch state { case .stable: // Switch state if below threshold state = (height < -offsetY) ? .ready : .stable case .ready: // Switch state if above threshold state = (height > -offsetY) ? .stable : .ready case .refreshing: // Set contentInset to refreshView visible UIView.animate(withDuration: animateDuration) { [weak self] in self?.scrollView.contentInset = UIEdgeInsets(top: height, left: 0, bottom: 0, right: 0) } } } private func didEndDragging() { if state == .ready { // Start Refreshing state = .refreshing } } public func finishRefreshing() { // End Refreshing state = .stable UIView.animate(withDuration: animateDuration) { self.scrollView.contentInset = .zero } } }
mit
erkekin/FormSpeech
FormSpeech/FormSpeech.swift
1
3434
// // FormSpeech.swift // FormSpeech // // Created by Erk Ekin on 16/11/2016. // Copyright © 2016 Erk Ekin. All rights reserved. // import Foundation typealias Pair = [Field:String] protocol Iteratable {} protocol FormSpeechDelegate { func valueParsed(parser: Parser, forValue value:String, andKey key:Field) } class Parser { var delegate:FormSpeechDelegate? let words = Field.rawValues() var iteration = 0 var text = ""{ didSet{ let secondIndex = iteration + 1 let secondWord:String? = secondIndex == words.count ? nil: words[secondIndex] let first = words[iteration] let second = secondWord if let value = text.getSubstring(substring1: first, substring2: second), let key = Field(rawValue: first){ let value = value.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) iteration += secondIndex == words.count ? 0 : 1 delegate?.valueParsed(parser: self, forValue: value, andKey: key) } } } } extension RawRepresentable where Self: RawRepresentable { static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafePointer(to: &i) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } if next.hashValue != i { return nil } i += 1 return next } } } extension Iteratable where Self: RawRepresentable, Self: Hashable { static func hashValues() -> AnyIterator<Self> { return iterateEnum(self) } static func rawValues() -> [Self.RawValue] { return hashValues().map({$0.rawValue}) } } extension String{ func getSubstring(substring1: String, substring2:String?) -> String?{ guard let range1 = self.range(of: substring1) else{return nil} let lo = self.index(range1.upperBound, offsetBy: 0) if let sub = substring2 { if let range2 = self.range(of: sub){ let hi = self.index(range2.lowerBound, offsetBy: 0) let subRange = lo ..< hi return self[subRange] }else{ return nil } }else { let hi = self.endIndex let subRange = lo ..< hi return self[subRange] } } // func parse() -> Pair?{ need for a full sentence parse. // // let words = Field.rawValues() // var output:Pair = [:] // // for (index, word) in words.enumerated() { // // let secondIndex = index + 1 // let secondWord:String? = secondIndex == words.count ? nil: words[secondIndex] // // if let value = getSubstring(substring1: word, substring2: secondWord), // let key = Field(rawValue: word){ // // output[key] = value.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) // // }else { // return nil // } // } // // return output.count == 0 ? nil:output // // } }
gpl-3.0
samnm/material-components-ios
components/TextFields/tests/unit/TextFieldControllerLegacyTests.swift
2
17909
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length // swiftlint:disable type_body_length import XCTest import MaterialComponents.MaterialMath import MaterialComponents.MaterialPalettes import MaterialComponents.MaterialTextFields class TextFieldControllerDefaultLegacyTests: XCTestCase { func testCopyingLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) controller.characterCountMax = 49 controller.characterCountViewMode = .always controller.disabledColor = .orange controller.isFloatingEnabled = false controller.floatingPlaceholderNormalColor = .purple controller.floatingPlaceholderScale = 0.1 controller.placeholderText = "Placeholder" controller.helperText = "Helper" controller.inlinePlaceholderColor = .green controller.activeColor = .blue controller.normalColor = .white controller.underlineViewMode = .always controller.leadingUnderlineLabelTextColor = .yellow controller.trailingUnderlineLabelTextColor = .orange if let controllerCopy = controller.copy() as? MDCTextInputControllerLegacyDefault { XCTAssertEqual(controller.characterCountMax, controllerCopy.characterCountMax) XCTAssertEqual(controller.characterCountViewMode, controllerCopy.characterCountViewMode) XCTAssertEqual(controller.disabledColor, controllerCopy.disabledColor) XCTAssertEqual(controller.isFloatingEnabled, controllerCopy.isFloatingEnabled) XCTAssertEqual(controller.floatingPlaceholderNormalColor, controllerCopy.floatingPlaceholderNormalColor) XCTAssertEqual(controller.floatingPlaceholderScale, controllerCopy.floatingPlaceholderScale) XCTAssertEqual(controller.placeholderText, controllerCopy.placeholderText) XCTAssertEqual(controller.helperText, controllerCopy.helperText) XCTAssertEqual(controller.inlinePlaceholderColor, controllerCopy.inlinePlaceholderColor) XCTAssertEqual(controller.activeColor, controllerCopy.activeColor) XCTAssertEqual(controller.normalColor, controllerCopy.normalColor) XCTAssertEqual(controller.underlineViewMode, controllerCopy.underlineViewMode) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, controllerCopy.leadingUnderlineLabelTextColor) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, controllerCopy.trailingUnderlineLabelTextColor) } else { XCTFail("No copy or copy is wrong class") } } func testCopyingLegacyFullWidth() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) controller.characterCountMax = 49 controller.characterCountViewMode = .always controller.disabledColor = .yellow controller.placeholderText = "Placeholder" controller.helperText = "Helper" controller.inlinePlaceholderColor = .green controller.activeColor = .blue controller.normalColor = .white controller.underlineViewMode = .always controller.trailingUnderlineLabelTextColor = .purple if let controllerCopy = controller.copy() as? MDCTextInputControllerLegacyFullWidth { XCTAssertEqual(controller.characterCountMax, controllerCopy.characterCountMax) XCTAssertEqual(controller.characterCountViewMode, controllerCopy.characterCountViewMode) XCTAssertEqual(controller.disabledColor, controllerCopy.disabledColor) XCTAssertEqual(controller.placeholderText, controllerCopy.placeholderText) XCTAssertEqual(controller.helperText, controllerCopy.helperText) XCTAssertEqual(controller.inlinePlaceholderColor, controllerCopy.inlinePlaceholderColor) XCTAssertEqual(controller.activeColor, controllerCopy.activeColor) XCTAssertEqual(controller.normalColor, controllerCopy.normalColor) XCTAssertEqual(controller.underlineViewMode, controllerCopy.underlineViewMode) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, controllerCopy.trailingUnderlineLabelTextColor) } else { XCTFail("No copy or copy is wrong class") } } func testDynamicTypeLegacyDefault() { let textField = MDCTextField() XCTAssertFalse(textField.mdc_adjustsFontForContentSizeCategory) textField.mdc_adjustsFontForContentSizeCategory = true XCTAssertTrue(textField.mdc_adjustsFontForContentSizeCategory) let controller = MDCTextInputControllerLegacyDefault(textInput: textField) XCTAssertNotNil(controller.textInput) controller.mdc_adjustsFontForContentSizeCategory = true XCTAssertTrue(controller.mdc_adjustsFontForContentSizeCategory) // The controller takes over listening for dynamic type size changes. XCTAssertFalse(textField.mdc_adjustsFontForContentSizeCategory) } func testDynamicTypeLegacyFullWidth() { let textField = MDCTextField() XCTAssertFalse(textField.mdc_adjustsFontForContentSizeCategory) textField.mdc_adjustsFontForContentSizeCategory = true XCTAssertTrue(textField.mdc_adjustsFontForContentSizeCategory) let controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) XCTAssertNotNil(controller.textInput) controller.mdc_adjustsFontForContentSizeCategory = true XCTAssertTrue(controller.mdc_adjustsFontForContentSizeCategory) // The controller takes over listening for dynamic type size changes. XCTAssertFalse(textField.mdc_adjustsFontForContentSizeCategory) } func testCharacterMaxLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) let altLeading = "Alternative Helper Test" controller.helperText = altLeading controller.characterCountMax = 50 // By setting the folowing text with is 51 characters when the max is set to 50 characters, it // should trigger an error state. textField.text = "Lorem ipsum dolor sit amet, consectetuer adipiscing" XCTAssertTrue("51 / 50".isEqual(textField.trailingUnderlineLabel.text)) XCTAssertEqual(MDCPalette.red.accent400, textField.underline?.color) XCTAssertEqual(MDCPalette.red.accent400, textField.trailingUnderlineLabel.textColor) } func testCharacterMaxLegacyFullWidth() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) let altLeading = "Alternative Helper Test" controller.helperText = altLeading controller.characterCountMax = 50 // By setting the folowing text with is 51 characters when the max is set to 50 characters, it // should trigger an error state. textField.text = "Lorem ipsum dolor sit amet, consectetuer adipiscing" XCTAssertTrue("51 / 50".isEqual(textField.trailingUnderlineLabel.text)) XCTAssertEqual(MDCPalette.red.accent400, textField.trailingUnderlineLabel.textColor) } func testErrorsLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) // Helper text is shown on the leading underline label. Make sure the color and content are as // expected. let altLeading = "Alternative Helper Test" controller.helperText = altLeading controller.leadingUnderlineLabelTextColor = .green XCTAssertEqual(.green, textField.leadingUnderlineLabel.textColor) XCTAssertEqual(altLeading, textField.leadingUnderlineLabel.text) controller.trailingUnderlineLabelTextColor = .white XCTAssertEqual(textField.trailingUnderlineLabel.textColor, .white) XCTAssertNil(controller.errorText) // Setting error text should change the color and content of the leading underline label let error = "Error Test" controller.setErrorText(error, errorAccessibilityValue: nil) XCTAssertNotEqual(altLeading, textField.leadingUnderlineLabel.text) XCTAssertEqual(error, textField.leadingUnderlineLabel.text) XCTAssertEqual(error, controller.errorText) let newError = "Different Error Test" let altErrorAccessibilityValue = "Not the default" controller.setErrorText(newError, errorAccessibilityValue: altErrorAccessibilityValue) XCTAssertEqual(newError, controller.errorText) XCTAssertEqual(newError, textField.leadingUnderlineLabel.text) XCTAssertNotEqual(error, controller.errorText) XCTAssertNotEqual(error, textField.leadingUnderlineLabel.text) // Setting an error should change the leading label's text color. XCTAssertNotEqual(.green, textField.leadingUnderlineLabel.textColor) // Setting error color should change the color of the underline, leading, and trailing colors. controller.errorColor = .blue XCTAssertEqual(.blue, controller.errorColor) XCTAssertNotEqual(MDCPalette.red.accent400, textField.leadingUnderlineLabel.textColor) XCTAssertNotEqual(MDCPalette.red.accent400, textField.trailingUnderlineLabel.textColor) XCTAssertNotEqual(MDCPalette.red.accent400, textField.underline?.color) XCTAssertEqual(.blue, textField.leadingUnderlineLabel.textColor) XCTAssertEqual(.blue, textField.trailingUnderlineLabel.textColor) XCTAssertEqual(.blue, textField.underline?.color) // If the controller is also in a character max error state, the leading label should still be // showing the text from the error that was set. controller.setErrorText(error, errorAccessibilityValue: nil) controller.characterCountMax = 50 textField.text = "Lorem ipsum dolor sit amet, consectetuer adipiscing" XCTAssertEqual(error, textField.leadingUnderlineLabel.text) // Removing the error should set the leading text back to its previous text. controller.setErrorText(nil, errorAccessibilityValue: nil) XCTAssertNotEqual(error, textField.leadingUnderlineLabel.text) XCTAssertEqual(altLeading, textField.leadingUnderlineLabel.text) // Test error text being reset but character max still exceded. XCTAssertEqual(.blue, textField.leadingUnderlineLabel.textColor) XCTAssertEqual(.blue, textField.trailingUnderlineLabel.textColor) XCTAssertEqual(.blue, textField.underline?.color) // Removing the text should remove the error state from character max and therefore remove // anything from showing the error color. textField.text = nil XCTAssertNotEqual(.blue, textField.leadingUnderlineLabel.textColor) XCTAssertNotEqual(.blue, textField.trailingUnderlineLabel.textColor) XCTAssertNotEqual(.blue, textField.underline?.color) } func testFloatingPlaceholderLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) textField.sizeToFit() controller.placeholderText = "Placeholder" textField.text = "Set Text" textField.setNeedsLayout() textField.layoutIfNeeded() let estimatedTextFrame = UIEdgeInsetsInsetRect(textField.bounds, controller.textInsets(UIEdgeInsets())) XCTAssertFalse(textField.placeholderLabel.frame.intersects(estimatedTextFrame)) } func testLabelsLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) let placeholderString = "Placeholder" controller.placeholderText = placeholderString XCTAssertEqual(controller.placeholderText, placeholderString) XCTAssertEqual(textField.placeholder, controller.placeholderText) let helperString = "Helper" controller.helperText = helperString XCTAssertEqual(controller.helperText, helperString) XCTAssertEqual(textField.leadingUnderlineLabel.text, controller.helperText) } func testLabelsLegacyFullWidth() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) let placeholderString = "Placeholder" controller.placeholderText = placeholderString XCTAssertEqual(controller.placeholderText, placeholderString) XCTAssertEqual(textField.placeholder, controller.placeholderText) controller.helperText = "Helper" XCTAssertEqual(controller.helperText, nil) } func testPresentationLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) XCTAssertEqual(controller.isFloatingEnabled, true) controller.isFloatingEnabled = false XCTAssertEqual(controller.isFloatingEnabled, false) controller.isFloatingEnabled = true textField.sizeToFit() XCTAssertEqual(textField.frame.height, 70) controller.helperText = "Helper" textField.sizeToFit() XCTAssertTrue(MDCCGFloatEqual(MDCCeil(textField.frame.height), 85.0)) controller.characterCountViewMode = .never XCTAssertEqual(.clear, textField.trailingUnderlineLabel.textColor) controller.characterCountViewMode = .always XCTAssertNotEqual(.clear, textField.trailingUnderlineLabel.textColor) controller.underlineViewMode = .never XCTAssertEqual(.lightGray, textField.underline?.color) controller.underlineViewMode = .always XCTAssertEqual(MDCPalette.blue.accent700, textField.underline?.color) } func testPresentationLegacyFullWidth() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) textField.sizeToFit() XCTAssertEqual(textField.frame.height, 57) controller.characterCountViewMode = .never XCTAssertEqual(.clear, textField.trailingUnderlineLabel.textColor) controller.characterCountViewMode = .always XCTAssertNotEqual(.clear, textField.trailingUnderlineLabel.textColor) controller.underlineViewMode = .never XCTAssertEqual(.clear, textField.underline?.color) controller.underlineViewMode = .always XCTAssertEqual(.clear, textField.underline?.color) controller.disabledColor = .red XCTAssertEqual(controller.disabledColor, .clear) } func testSerializationLegacyDefault() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyDefault(textInput: textField) controller.characterCountMax = 25 controller.characterCountViewMode = .always controller.disabledColor = .yellow controller.isFloatingEnabled = false controller.floatingPlaceholderNormalColor = .purple controller.floatingPlaceholderScale = 0.1 controller.helperText = "Helper" controller.inlinePlaceholderColor = .green controller.activeColor = .blue controller.normalColor = .white controller.underlineViewMode = .always let serializedController = NSKeyedArchiver.archivedData(withRootObject: controller) XCTAssertNotNil(serializedController) let unserializedController = NSKeyedUnarchiver.unarchiveObject(with: serializedController) as? MDCTextInputControllerLegacyDefault XCTAssertNotNil(unserializedController) unserializedController?.textInput = textField XCTAssertEqual(controller.characterCountMax, unserializedController?.characterCountMax) XCTAssertEqual(controller.characterCountViewMode, unserializedController?.characterCountViewMode) XCTAssertEqual(controller.disabledColor, unserializedController?.disabledColor) XCTAssertEqual(controller.isFloatingEnabled, unserializedController?.isFloatingEnabled) XCTAssertEqual(controller.floatingPlaceholderNormalColor, unserializedController?.floatingPlaceholderNormalColor) XCTAssertEqual(controller.floatingPlaceholderScale, unserializedController?.floatingPlaceholderScale) XCTAssertEqual(controller.helperText, unserializedController?.helperText) XCTAssertEqual(controller.inlinePlaceholderColor, unserializedController?.inlinePlaceholderColor) XCTAssertEqual(controller.activeColor, unserializedController?.activeColor) XCTAssertEqual(controller.normalColor, unserializedController?.normalColor) XCTAssertEqual(controller.underlineViewMode, unserializedController?.underlineViewMode) } func testSerializationLegacyFullWidth() { let textField = MDCTextField() let controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) controller.characterCountMax = 25 controller.characterCountViewMode = .always controller.disabledColor = .yellow controller.errorColor = .blue controller.inlinePlaceholderColor = .green let serializedController = NSKeyedArchiver.archivedData(withRootObject: controller) XCTAssertNotNil(serializedController) let unserializedController = NSKeyedUnarchiver.unarchiveObject(with: serializedController) as? MDCTextInputControllerLegacyFullWidth XCTAssertNotNil(unserializedController) unserializedController?.textInput = textField XCTAssertEqual(controller.characterCountMax, unserializedController?.characterCountMax) XCTAssertEqual(controller.characterCountViewMode, unserializedController?.characterCountViewMode) XCTAssertEqual(unserializedController?.disabledColor, .clear) XCTAssertEqual(controller.errorColor, unserializedController?.errorColor) XCTAssertEqual(controller.helperText, unserializedController?.helperText) XCTAssertEqual(controller.inlinePlaceholderColor, unserializedController?.inlinePlaceholderColor) } }
apache-2.0
qq456cvb/DeepLearningKitForiOS
DeepLearningKitFortvOS/DeepLearningKitFortvOS/MetalUtilityFunctions.swift
7
7757
// // MetalUtilFunctions.swift // MemkiteMetal // // Created by Amund Tveit & Torb Morland on 24/11/15. // Copyright © 2015 Memkite. All rights reserved. // import Foundation import Metal func createComplexNumbersArray(count: Int) -> [MetalComplexNumberType] { let zeroComplexNumber = MetalComplexNumberType() return [MetalComplexNumberType](count: count, repeatedValue: zeroComplexNumber) } func createFloatNumbersArray(count: Int) -> [Float] { return [Float](count: count, repeatedValue: 0.0) } func createFloatMetalBuffer(var vector: [Float], let metalDevice:MTLDevice) -> MTLBuffer { let byteLength = vector.count*sizeof(Float) // future: MTLResourceStorageModePrivate return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createComplexMetalBuffer(var vector:[MetalComplexNumberType], let metalDevice:MTLDevice) -> MTLBuffer { let byteLength = vector.count*sizeof(MetalComplexNumberType) // or size of and actual 1st element object? return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createShaderParametersMetalBuffer(var shaderParameters:MetalShaderParameters, metalDevice:MTLDevice) -> MTLBuffer { let byteLength = sizeof(MetalShaderParameters) return metalDevice.newBufferWithBytes(&shaderParameters, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createMatrixShaderParametersMetalBuffer(var params: MetalMatrixVectorParameters, metalDevice: MTLDevice) -> MTLBuffer { let byteLength = sizeof(MetalMatrixVectorParameters) return metalDevice.newBufferWithBytes(&params, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createPoolingParametersMetalBuffer(var params: MetalPoolingParameters, metalDevice: MTLDevice) -> MTLBuffer { let byteLength = sizeof(MetalPoolingParameters) return metalDevice.newBufferWithBytes(&params, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createConvolutionParametersMetalBuffer(var params: MetalConvolutionParameters, metalDevice: MTLDevice) -> MTLBuffer { let byteLength = sizeof(MetalConvolutionParameters) return metalDevice.newBufferWithBytes(&params, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func createTensorDimensionsVectorMetalBuffer(var vector: [MetalTensorDimensions], metalDevice: MTLDevice) -> MTLBuffer { let byteLength = vector.count * sizeof(MetalTensorDimensions) return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func setupShaderInMetalPipeline(shaderName:String, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice) -> (shader:MTLFunction!, computePipelineState:MTLComputePipelineState!, computePipelineErrors:NSErrorPointer!) { let shader = metalDefaultLibrary.newFunctionWithName(shaderName) let computePipeLineDescriptor = MTLComputePipelineDescriptor() computePipeLineDescriptor.computeFunction = shader // var computePipelineErrors = NSErrorPointer() // let computePipelineState:MTLComputePipelineState = metalDevice.newComputePipelineStateWithFunction(shader!, completionHandler: {(}) let computePipelineErrors = NSErrorPointer() var computePipelineState:MTLComputePipelineState? = nil do { computePipelineState = try metalDevice.newComputePipelineStateWithFunction(shader!) } catch { print("catching..") } return (shader, computePipelineState, computePipelineErrors) } func createMetalBuffer(var vector:[Float], metalDevice:MTLDevice) -> MTLBuffer { let byteLength = vector.count*sizeof(Float) return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache) } func preLoadMetalShaders(metalDevice: MTLDevice, metalDefaultLibrary: MTLLibrary) { let shaders = ["avg_pool", "max_pool", "rectifier_linear", "convolution_layer", "im2col"] for shader in shaders { setupShaderInMetalPipeline(shader, metalDefaultLibrary: metalDefaultLibrary,metalDevice: metalDevice) // TODO: this returns stuff } } func createOrReuseFloatMetalBuffer(name:String, data: [Float], inout cache:[Dictionary<String,MTLBuffer>], layer_number:Int, metalDevice:MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { print("found key = \(name) in cache") result = tmpval } else { print("didnt find key = \(name) in cache") result = createFloatMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result // print("DEBUG: cache = \(cache)") } return result } func createOrReuseConvolutionParametersMetalBuffer(name:String, data: MetalConvolutionParameters, inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { print("found key = \(name) in cache") result = tmpval } else { print("didnt find key = \(name) in cache") result = createConvolutionParametersMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result } func createOrReuseTensorDimensionsVectorMetalBuffer(name:String, data:[MetalTensorDimensions],inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { print("found key = \(name) in cache") result = tmpval } else { print("didnt find key = \(name) in cache") result = createTensorDimensionsVectorMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result } // //let sizeParamMetalBuffer = createShaderParametersMetalBuffer(size_params, metalDevice: metalDevice) //let poolingParamMetalBuffer = createPoolingParametersMetalBuffer(pooling_params, metalDevice: metalDevice) func createOrReuseShaderParametersMetalBuffer(name:String, data:MetalShaderParameters,inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { // print("found key = \(name) in cache") result = tmpval } else { // print("didnt find key = \(name) in cache") result = createShaderParametersMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result } func createOrReusePoolingParametersMetalBuffer(name:String, data:MetalPoolingParameters,inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer { var result:MTLBuffer if let tmpval = cache[layer_number][name] { // print("found key = \(name) in cache") result = tmpval } else { // print("didnt find key = \(name) in cache") result = createPoolingParametersMetalBuffer(data, metalDevice: metalDevice) cache[layer_number][name] = result //print("DEBUG: cache = \(cache)") } return result }
apache-2.0
robinmonjo/TFImagePickerController
Library/TFImagePickerControllerDelegate.swift
1
437
// // FBImagePickerDelegateProtocol.swift // FBImagePicker // // Created by Robin Monjo on 07/09/14. // Copyright (c) 2014 Robin Monjo. All rights reserved. // import UIKit protocol TFImagePickerControllerDelegate { func imagePickerController(controller: TFImagePickerController!, didPickImage image: UIImage, withMetadata metadata:[String:AnyObject]) func imagePickerControllerDidCancel(controller: TFImagePickerController!) }
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/26513-swift-constraints-constraintsystem-getconstraintlocator.swift
65
474
// 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 // RUN: not %target-swift-frontend %s -typecheck if true{ } class A{ let d{class e{{ } struct S{var d{ struct A{ class case,
apache-2.0
schrismartin/dont-shoot-the-messenger
Sources/Library/Controllers/CNDumbParse.swift
1
449
import Foundation public func parse(input: [String],player: Player, area: Area){ for message in input { console.log("NEW MESSAGE\n") let lower = message.lowercased() let splitArray = lower.characters.split(separator:" ").map{ String($0)} for i in 0..<splitArray.count{ console.log("\(i) = \(splitArray[i])") if (findAction(index: i, parsedText: splitArray,player: player, area: area)){ break; } } } }
mit
netguru/inbbbox-ios
Unit Tests/AutoScrollableShotsDataSourceSpec.swift
1
3800
// // AutoScrollableShotsDataSourceSpec.swift // Inbbbox // // Created by Patryk Kaczmarek on 30/12/15. // Copyright © 2015 Netguru Sp. z o.o. All rights reserved. // import Quick import Nimble @testable import Inbbbox class AutoScrollableShotsDataSourceSpec: QuickSpec { override func spec() { var sut: AutoScrollableShotsDataSource! describe("when initializing with content and collection view") { var collectionView: UICollectionView! let content = [ UIImage.referenceImageWithColor(.green), UIImage.referenceImageWithColor(.yellow), UIImage.referenceImageWithColor(.red) ] beforeEach { collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout()) sut = AutoScrollableShotsDataSource(collectionView: collectionView, content: content) } afterEach { sut = nil collectionView = nil } it("collection view should be same") { expect(sut!.collectionView).to(equal(collectionView)) } it("collection view datasource should be properly set") { expect(sut.collectionView.dataSource!) === sut } it("collection view delegate should be properly set") { expect(sut.collectionView.delegate!) === sut } it("collection view item size should be correct") { expect(sut.itemSize).to(equal(CGSize(width: 100, height: 100))) } it("collection view should have exactly 1 section") { expect(sut.collectionView.numberOfSections).to(equal(1)) } it("collection view should have proper cell class") { let indexPath = IndexPath(item: 0, section: 0) expect(sut.collectionView.dataSource!.collectionView(sut.collectionView, cellForItemAt: indexPath)).to(beAKindOf(AutoScrollableCollectionViewCell.self)) } describe("and showing content") { context("with preparing for animation") { beforeEach { sut.prepareForAnimation() } it("collection view should have exactly 1 section") { expect(sut.collectionView.numberOfItems(inSection: 0)).to(equal(7)) } it("extended content should be 2") { expect(sut.extendedScrollableItemsCount).to(equal(2)) } } context("without preparing for animation") { it("collection view should have exactly 1 section") { expect(sut.collectionView.numberOfItems(inSection: 0)).to(equal(content.count)) } } context("for first cell") { it("image should be same as first in content") { let indexPath = IndexPath(item: 0, section: 0) let cell = sut.collectionView.dataSource!.collectionView(sut.collectionView, cellForItemAt: indexPath) as! AutoScrollableCollectionViewCell expect(cell.imageView.image).to(equal(content.first!)) } } } } } }
gpl-3.0
ndleon09/TopApps
TopApps/AppTableViewCell.swift
1
1232
// // AppTableViewCell.swift // TopApps // // Created by Nelson Dominguez on 24/04/16. // Copyright © 2016 Nelson Dominguez. All rights reserved. // import Foundation import UIKit import BothamUI import AlamofireImage class AppTableViewCell: UITableViewCell, BothamViewCell { func configure(forItem item: App) { let size: CGSize = CGSize(width: 50.0, height: 50.0) let radius: CGFloat = 8.0 let filter = AspectScaledToFillSizeWithRoundedCornersFilter(size: size, radius: radius) let placeholder = UIImage(named: "placeholder")?.af_imageAspectScaled(toFit: size).af_imageRounded(withCornerRadius: radius) if let image = item.image { imageView?.af_setImage(withURL: URL(string: image)!, placeholderImage: placeholder, filter: filter, progress: nil, progressQueue: DispatchQueue.main, imageTransition: .crossDissolve(0.4), runImageTransitionIfCached: false, completion: nil) } else { imageView?.image = placeholder } textLabel?.text = item.name detailTextLabel?.numberOfLines = 0 detailTextLabel?.text = item.category accessibilityLabel = "\(item.id)-Identifier" } }
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/25154-swift-constraints-constraintsystem-opengeneric.swift
65
470
// 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 // RUN: not %target-swift-frontend %s -typecheck let a{struct B<T where B:C{class B{class B{{}let b=true as S}struct S<T
apache-2.0
optimizely/objective-c-sdk
OptimizelySDKCore/OptimizelySDKCoreTests/OptimizelySwiftTest.swift
1
5786
/**************************************************************************** * Copyright 2018, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ import XCTest import OptimizelySDKCore let kAttributeKeyBrowserType = "browser_type" let kAttributeKeyBrowserVersion = "browser_version" let kAttributeKeyBrowserBuildNumber = "browser_build_number" let kAttributeKeyBrowserIsDefault = "browser_is_default" let kUserId = "userId" class OptimizelySwiftTest: XCTestCase { var datafile: Data? var typedAudienceDatafile:Data? var optimizely:Optimizely? var optimizelyTypedAudience:Optimizely? var attributes:[String:Any]? override func setUp() { super.setUp() self.datafile = OPTLYTestHelper.loadJSONDatafile(intoDataObject: "test_data_10_experiments") self.typedAudienceDatafile = OPTLYTestHelper.loadJSONDatafile(intoDataObject:"typed_audience_datafile") XCTAssertNotNil(self.datafile, "Data file should not be nil.") self.optimizely = Optimizely.init(builder: OPTLYBuilder.init(block: { (builder) in builder?.datafile = self.datafile builder?.logger = OPTLYLoggerDefault.init(logLevel: OptimizelyLogLevel.off) builder?.errorHandler = OPTLYErrorHandlerNoOp.init() })) XCTAssertNotNil(self.typedAudienceDatafile, "Data file should not be nil.") self.optimizelyTypedAudience = Optimizely.init(builder: OPTLYBuilder.init(block: { (builder) in builder?.datafile = self.typedAudienceDatafile builder?.logger = OPTLYLoggerDefault.init(logLevel: OptimizelyLogLevel.off) builder?.errorHandler = OPTLYErrorHandlerNoOp.init() })) XCTAssertNotNil(self.optimizely, "Optimizely should not be nil"); XCTAssertNotNil(self.optimizelyTypedAudience, " Typed Optimizely should not be nil"); self.attributes = [ kAttributeKeyBrowserType : "firefox", kAttributeKeyBrowserVersion : 68.1, kAttributeKeyBrowserBuildNumber : 106, kAttributeKeyBrowserIsDefault : true] } override func tearDown() { super.tearDown() self.datafile = nil self.optimizely = nil self.typedAudienceDatafile = nil } func testVariationWithAudience() { let experimentKey = "testExperimentWithFirefoxAudience"; let experiment = self.optimizely?.config?.getExperimentForKey(experimentKey) XCTAssertNotNil(experiment); var variation:OPTLYVariation? let attributesWithUserNotInAudience = ["browser_type" : "chrome"] let attributesWithUserInAudience = ["browser_type" : "firefox"] // test get experiment without attributes variation = self.optimizely?.variation(experimentKey, userId:kUserId) XCTAssertNil(variation); // test get experiment with bad attributes variation = self.optimizely?.variation(experimentKey, userId:kUserId, attributes:attributesWithUserNotInAudience) XCTAssertNil(variation); // test get experiment with good attributes variation = self.optimizely?.variation(experimentKey, userId:kUserId, attributes:attributesWithUserInAudience) XCTAssertNotNil(variation); } func testVariationWithAudienceTypeInteger() { let experimentKey = "testExperimentWithFirefoxAudience" let experiment = self.optimizely?.config?.getExperimentForKey(experimentKey) XCTAssertNotNil(experiment) var variation:OPTLYVariation? let attributesWithUserNotInAudience = [kAttributeKeyBrowserBuildNumber : 601] let attributesWithUserInAudience = [kAttributeKeyBrowserBuildNumber : 106] // test get experiment without attributes variation = self.optimizely?.variation(experimentKey, userId:kUserId) XCTAssertNil(variation); // test get experiment with bad attributes variation = self.optimizely?.variation(experimentKey, userId:kUserId, attributes:attributesWithUserNotInAudience) XCTAssertNil(variation); // test get experiment with good attributes variation = self.optimizely?.variation(experimentKey, userId:kUserId, attributes:attributesWithUserInAudience) XCTAssertNotNil(variation); } func testOptimizelyInitWithBuilder() { XCTAssertNotNil(self.datafile, "Data file should not be nil.") self.optimizely = Optimizely.init(builder: OPTLYBuilder.init(block: { (builder) in builder?.datafile = self.datafile builder?.logger = OPTLYLoggerDefault.init(logLevel: OptimizelyLogLevel.off) builder?.errorHandler = OPTLYErrorHandlerNoOp.init() })) XCTAssertNotNil(self.optimizely, "Optimizely should not be nil"); } }
apache-2.0
rmnblm/Mapbox-iOS-Examples
src/Examples/ClusteringViewController.swift
1
3292
// // ClusteringViewController.swift // Mapbox-iOS-Examples // // Created by Roman Blum on 21.09.16. // Copyright © 2016 rmnblm. All rights reserved. // import UIKit import Mapbox let kClusterZoomLevel: Float = 11 let kSourceName = "mcdonalds" let kIconName = "Pin" let kLayerName = "restaurants" let kLayerClusterName = "restaurants-cluster" let kLayerPointCountName = "restaurants-cluster-pointcount" class ClusteringViewController: UIViewController, MGLMapViewDelegate { @IBOutlet var mapView: MGLMapView! let layerNames = [kLayerClusterName, kLayerPointCountName, kLayerName] func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) { mapView.style?.setImage(#imageLiteral(resourceName: "Pin"), forName: kIconName) var options = [MGLShapeSourceOption : Any]() options[.clustered] = true options[.clusterRadius] = 100 options[.maximumZoomLevelForClustering] = kClusterZoomLevel let sourceURL = Bundle.main.url(forResource: kSourceName, withExtension: "geojson")! let source = MGLShapeSource(identifier: kSourceName, url: sourceURL, options: options) mapView.style?.addSource(source) let circles = MGLCircleStyleLayer(identifier: kLayerClusterName, source: source) circles.circleStrokeColor = MGLStyleValue(rawValue: UIColor.white) circles.circleStrokeWidth = MGLStyleValue(rawValue: 1) circles.circleColor = MGLStyleValue( interpolationMode: .interval, sourceStops: [ 0: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 76/255.0, green: 217/255.0, blue: 100/255.0, alpha: 1)), 100: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 255/255.0, green: 204/255.0, blue: 0/255.0, alpha: 1)), 300: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 255/255.0, green: 149/255.0, blue: 0/255.0, alpha: 1)), 1000: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1))], attributeName: "point_count", options: nil) circles.circleRadius = MGLStyleValue( interpolationMode: .interval, sourceStops: [ 0: MGLStyleValue(rawValue: 12), 100: MGLStyleValue(rawValue: 15), 300: MGLStyleValue(rawValue: 18), 1000: MGLStyleValue(rawValue: 20)], attributeName: "point_count", options: nil) circles.predicate = NSPredicate(format: "%K == YES", argumentArray: ["cluster"]) mapView.style?.addLayer(circles) var symbols = MGLSymbolStyleLayer(identifier: kLayerPointCountName, source: source) symbols.text = MGLStyleValue(rawValue: "{point_count}") symbols.textColor = MGLStyleValue(rawValue: UIColor.white) mapView.style?.addLayer(symbols) symbols = MGLSymbolStyleLayer(identifier: kLayerName, source: source) symbols.iconImageName = MGLStyleValue.init(rawValue: NSString(string: kIconName)) symbols.iconAllowsOverlap = MGLStyleValue(rawValue: NSNumber(value: true)) symbols.predicate = NSPredicate(format: "%K != YES", argumentArray: ["cluster"]) mapView.style?.addLayer(symbols) } }
mit
twtstudio/WePeiYang-iOS
WePeiYang/Read/View/Search.swift
1
7755
// // Search.swift // YouTube // // Created by Haik Aslanyan on 7/4/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // protocol SearchDelegate { func hideSearchView(status : Bool) func saveResult(result: [Librarian.SearchResult]) } import UIKit enum LabelContent: String { case NotFound = "没有找到相关书籍👀" case Morning = "早上好~ (。・∀・)ノ゙" case Afternoon = "下午好~ (๑•̀ㅂ•́)و✧" case Evening = "晚上好~ <(  ̄^ ̄)" } class Search: UIView, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { var result: [Librarian.SearchResult] = [] //MARK: Properties let label = UILabel() var notFoundView:UIView! let statusView: UIView = { let st = UIView.init(frame: UIApplication.sharedApplication().statusBarFrame) st.backgroundColor = UIColor.blackColor() st.alpha = 0.15 return st }() lazy var searchView: UIView = { let sv = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.width, height: 68)) sv.backgroundColor = UIColor.whiteColor() sv.alpha = 0 return sv }() lazy var backgroundView: UIView = { let bv = UIView.init(frame: self.frame) bv.backgroundColor = UIColor.blackColor() bv.alpha = 0 return bv }() lazy var backButton: UIButton = { let bb = UIButton.init(frame: CGRect.init(x: 0, y: 20, width: 48, height: 48)) bb.setBackgroundImage(UIImage.init(named: "back"), forState: []) bb.addTarget(self, action: #selector(Search.dismiss), forControlEvents: .TouchUpInside) return bb }() lazy var searchField: UITextField = { let sf = UITextField.init(frame: CGRect.init(x: 48, y: 20, width: self.frame.width - 50, height: 48)) sf.placeholder = "查询书籍在馆记录" sf.autocapitalizationType = .None sf.clearsOnBeginEditing = true sf.returnKeyType = .Go // sf.keyboardAppearance = UIKeyboardAppearance.Dark return sf }() lazy var tableView: UITableView = { let tv: UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 68, width: self.frame.width, height: self.frame.height - 68)) return tv }() var items = [String]() var delegate:SearchDelegate? //MARK: Methods func customization() { self.addSubview(self.backgroundView) self.backgroundView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(Search.dismiss))) self.addSubview(self.searchView) self.searchView.addSubview(self.searchField) self.searchView.addSubview(self.backButton) self.tableView.delegate = self self.tableView.dataSource = self self.tableView.tableFooterView = UIView() self.tableView.backgroundColor = UIColor.clearColor() self.searchField.delegate = self self.addSubview(self.statusView) self.addSubview(self.tableView) self.tableView.estimatedRowHeight = 80 self.tableView.rowHeight = UITableViewAutomaticDimension notFoundView = UIView(frame: CGRect.init(x: 0, y: 68, width: self.frame.width, height: 50)) notFoundView.backgroundColor = UIColor.whiteColor() notFoundView.addSubview(self.label) self.addSubview(notFoundView) //UIApplication.sharedApplication().keyWindow?.addSubview(notFoundView) self.label.sizeToFit() self.label.snp_makeConstraints { make in make.center.equalTo(notFoundView) } self.refreshLabel() } func refreshLabel() { let date = NSDate() let timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "HH" let strNowTime = timeFormatter.stringFromDate(date) as String let hour = Int(strNowTime)! var str: LabelContent = .Morning switch hour { case 5...11: str = .Morning case 12...18: str = .Afternoon case 19...24, 0...4: str = .Evening default: break; } label.text = str.rawValue } func animate() { UIView.animateWithDuration(0.2, animations: { self.backgroundView.alpha = 0.5 self.searchView.alpha = 1 // self.searchField.becomeFirstResponder() }) } func dismiss() { self.searchField.text = "" self.items.removeAll() self.tableView.removeFromSuperview() // self.notFoundView.removeFromSuperview() // 没有动画 // UIView.animateWithDuration(0.0, animations: { // self.backgroundView.alpha = 0 // self.searchView.alpha = 0 self.searchField.resignFirstResponder() self.searchView.removeFromSuperview() self.removeFromSuperview() // }, completion: {(Bool) in self.delegate?.hideSearchView(true) // }) } //MARK: 搜索 func textFieldShouldReturn(textField: UITextField) -> Bool { guard let str = textField.text else { return true } //self.notFoundView.removeFromSuperview() result.removeAll() self.tableView.reloadData() Librarian.searchBook(withString: str) { searchResult in self.result = searchResult self.delegate?.saveResult(self.result) if self.result.count == 0 { self.tableView.tableHeaderView = self.notFoundView self.label.text = LabelContent.NotFound.rawValue self.notFoundView.frame = CGRectMake(0, 68, self.frame.width, 50) //self.addSubview(self.notFoundView) } self.searchField.resignFirstResponder() //UIApplication.sharedApplication().keyWindow?.addSubview(self.notFoundView) self.tableView.reloadData() } return true } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { self.result.removeAll() self.tableView.reloadData() self.notFoundView.frame = CGRectMake(0, 0, 0, 0) label.text = "" return true } //MARK: TableView Delegates and Datasources func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return result.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = SearchResultCell(model: result[indexPath.row]) return cell } func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.searchField.resignFirstResponder() } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView.deselectRowAtIndexPath(indexPath, animated: true) let vc = BookDetailViewController(bookID: "\(result[indexPath.row].bookID)") self.removeFromSuperview() //print(self.tableView.contentOffset) // only push once if !(UIViewController.currentViewController().navigationController?.topViewController is BookDetailViewController){ UIViewController.currentViewController().navigationController?.showViewController(vc, sender: nil) } // UIViewController.currentViewController().navigationController?.pushViewController(vc, animated: true) } //MARK: Inits override init(frame: CGRect) { super.init(frame: frame) customization() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
tuanan94/FRadio-ios
SwiftRadioUITests/SwiftRadioUITests.swift
1
4865
// // SwiftRadioUITests.swift // SwiftRadioUITests // // Created by Jonah Stiennon on 12/3/15. // Copyright © 2015 CodeMarket.io. All rights reserved. // import XCTest class SwiftRadioUITests: XCTestCase { let app = XCUIApplication() let stations = XCUIApplication().cells let hamburgerMenu = XCUIApplication().navigationBars["Swift Radio"].buttons["icon hamburger"] let pauseButton = XCUIApplication().buttons["btn pause"] let playButton = XCUIApplication().buttons["btn play"] let volume = XCUIApplication().sliders.element(boundBy: 0) 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() // wait for the main view to load self.expectation( for: NSPredicate(format: "self.count > 0"), evaluatedWith: stations, handler: nil) self.waitForExpectations(timeout: 10.0, handler: nil) // 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 assertStationsPresent() { let numStations:UInt = 4 XCTAssertEqual(stations.count, Int(numStations)) let texts = stations.staticTexts.count XCTAssertEqual(texts, Int(numStations * 2)) } func assertHamburgerContent() { XCTAssertTrue(app.staticTexts["Created by: Matthew Fecher"].exists) } func assertAboutContent() { XCTAssertTrue(app.buttons["email me"].exists) XCTAssertTrue(app.buttons["matthewfecher.com"].exists) } func assertPaused() { XCTAssertFalse(pauseButton.isEnabled) XCTAssertTrue(playButton.isEnabled) XCTAssertTrue(app.staticTexts["Station Paused..."].exists); } func assertPlaying() { XCTAssertTrue(pauseButton.isEnabled) XCTAssertFalse(playButton.isEnabled) XCTAssertFalse(app.staticTexts["Station Paused..."].exists); } func assertStationOnMenu(_ stationName:String) { let button = app.buttons["nowPlaying"]; let label:String = button.label if label != "" { XCTAssertTrue(label.contains(stationName)) } else { XCTAssertTrue(false) } } func assertStationInfo() { let textView = app.textViews.element(boundBy: 0) if let value = textView.value { XCTAssertGreaterThan((value as AnyObject).length, 10) } else { XCTAssertTrue(false) } } func waitForStationToLoad() { self.expectation( for: NSPredicate(format: "exists == 0"), evaluatedWith: app.staticTexts["Loading Station..."], handler: nil) self.waitForExpectations(timeout: 25.0, handler: nil) } func testMainStationsView() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. assertStationsPresent() hamburgerMenu.tap() assertHamburgerContent() app.buttons["About"].tap() assertAboutContent() app.buttons["Okay"].tap() app.buttons["btn close"].tap() assertStationsPresent() let firstStation = stations.element(boundBy: 0) let stationName:String = firstStation.children(matching: .staticText).element(boundBy: 0).label assertStationOnMenu("Choose") firstStation.tap() waitForStationToLoad(); pauseButton.tap() assertPaused() playButton.tap() assertPlaying() app.navigationBars["Sub Pop Radio"].buttons["Back"].tap() assertStationOnMenu(stationName) app.navigationBars["Swift Radio"].buttons["btn nowPlaying"].tap() waitForStationToLoad() volume.adjust(toNormalizedSliderPosition: 0.2) volume.adjust(toNormalizedSliderPosition: 0.8) volume.adjust(toNormalizedSliderPosition: 0.5) app.buttons["More Info"].tap() assertStationInfo() app.buttons["Okay"].tap() app.buttons["logo"].tap() assertAboutContent() app.buttons["Okay"].tap() } }
mit
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/SubtractBlend.swift
9
153
public class SubtractBlend: BasicOperation { public init() { super.init(fragmentShader:SubtractBlendFragmentShader, numberOfInputs:2) } }
mit
kousun12/RxSwift
RxSwift/Disposables/CompositeDisposable.swift
8
3481
// // CompositeDisposable.swift // Rx // // Created by Krunoslav Zaher on 2/20/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a group of disposable resources that are disposed together. */ public class CompositeDisposable : DisposeBase, Disposable, Cancelable { public typealias DisposeKey = Bag<Disposable>.KeyType private var _lock = SpinLock() // state private var _disposables: Bag<Disposable>? = Bag() public var disposed: Bool { get { _lock.lock(); defer { _lock.unlock() } return _disposables == nil } } public override init() { } /** Initializes a new instance of composite disposable with the specified number of disposables. */ public init(_ disposable1: Disposable, _ disposable2: Disposable) { _disposables!.insert(disposable1) _disposables!.insert(disposable2) } /** Initializes a new instance of composite disposable with the specified number of disposables. */ public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { _disposables!.insert(disposable1) _disposables!.insert(disposable2) _disposables!.insert(disposable3) } /** Initializes a new instance of composite disposable with the specified number of disposables. */ public init(disposables: [Disposable]) { for disposable in disposables { _disposables!.insert(disposable) } } /** Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. - parameter disposable: Disposable to add. - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already disposed `nil` will be returned. */ public func addDisposable(disposable: Disposable) -> DisposeKey? { let key = _addDisposable(disposable) if key == nil { disposable.dispose() } return key } private func _addDisposable(disposable: Disposable) -> DisposeKey? { _lock.lock(); defer { _lock.unlock() } return _disposables?.insert(disposable) } /** - returns: Gets the number of disposables contained in the `CompositeDisposable`. */ public var count: Int { get { _lock.lock(); defer { _lock.unlock() } return _disposables?.count ?? 0 } } /** Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. - parameter disposeKey: Key used to identify disposable to be removed. */ public func removeDisposable(disposeKey: DisposeKey) { _removeDisposable(disposeKey)?.dispose() } private func _removeDisposable(disposeKey: DisposeKey) -> Disposable? { _lock.lock(); defer { _lock.unlock() } return _disposables?.removeKey(disposeKey) } /** Disposes all disposables in the group and removes them from the group. */ public func dispose() { if let disposables = _dispose() { disposeAllIn(disposables) } } private func _dispose() -> Bag<Disposable>? { _lock.lock(); defer { _lock.unlock() } let disposeBag = _disposables _disposables = nil return disposeBag } }
mit
XiaHaozheJose/swift3_wb
sw3_wb/sw3_wb/Classes/Tools/Extension/UIColor-Extension.swift
1
2538
// // UIColor-Extension.swift // pageView // // Copyright © 2017年 浩哲 夏. All rights reserved. // import Foundation import UIKit // MARK: - 随机颜色 extension UIColor{ class func randomColor()->UIColor{ return UIColor.init(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0) } // MARK: - RGB值 convenience init(r:CGFloat,g:CGFloat,b:CGFloat,alpha:CGFloat = 1.0) { self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha) } // MARK: - 处理16进制 convenience init?(hexString:String) { //处理16进制 0x 0X # guard hexString.characters.count > 6 else {return nil } var hexTempString = hexString.uppercased() as NSString //判断0X if hexTempString.hasPrefix("0X") || hexTempString.hasPrefix("##"){ hexTempString = hexTempString.substring(from: 2) as NSString // hexTempString = hexTempString.substring(from: hexTempString.index(hexString.startIndex, offsetBy: 2)) } //判断# if hexTempString.hasPrefix("#"){ hexTempString = hexTempString.substring(from: 1) as NSString } //截取R:FF G:00 B:11 var range = NSRange.init(location: 0, length: 2) let rHex = hexTempString.substring(with: range) var red : UInt32 = 0 Scanner(string: rHex).scanHexInt32(&red) range.location = 2 let gHex = hexTempString.substring(with: range) var green : UInt32 = 0 Scanner(string: gHex).scanHexInt32(&green) range.location = 4 let bHex = hexTempString.substring(with: range) var blue : UInt32 = 0 Scanner(string: bHex).scanHexInt32(&blue) self.init(r: CGFloat(red), g: CGFloat(green), b: CGFloat(blue)) } } // MARK: - 从颜色中获取RGB extension UIColor{ ///通过RGB值通道 获取RGB func getRGBWithRGBColor()->(CGFloat,CGFloat,CGFloat){ guard let cmps = cgColor.components else { fatalError("MUST BE RGB COLOR") } return (cmps[0] * 255,cmps[1] * 255,cmps[2] * 255) } ///通过颜色直接获取RGB func getRGBWithColor()->(CGFloat,CGFloat,CGFloat){ var red : CGFloat = 0 var green : CGFloat = 0 var blue : CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: nil) return (red * 255, green * 255, blue * 255) } }
mit
apple/swift-package-manager
Fixtures/Miscellaneous/Plugins/PluginCanBeReferencedByProductName/Sources/PluginCanBeReferencedByProductName/PluginCanBeReferencedByProductName.swift
2
130
public struct PluginCanBeReferencedByProductName { public private(set) var text = stringConstant public init() { } }
apache-2.0
EugeneVegner/sws-copyleaks-sdk-test
Example/PlagiarismChecker/MainViewController.swift
1
5931
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ import UIKit import PlagiarismChecker class MainViewController: UIViewController { //@IBOutlet weak var navigationItem: UINavigationItem! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var currentProcess: AnyObject? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.backBarButtonItem = nil self.navigationItem.leftBarButtonItem = nil self.navigationItem.title = "Main" } //createByUrl @IBAction func createByUrlAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let cloud = CopyleaksCloud(.Businesses) cloud.allowPartialScan = true cloud.createByUrl(NSURL(string: "https://google.com")!) { (result) in self.activityIndicator.stopAnimating() self.showProcessResult(result) } } @IBAction func createByTextAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let cloud = CopyleaksCloud(.Businesses) cloud.createByText("Test me") { (result) in self.activityIndicator.stopAnimating() self.showProcessResult(result) } } @IBAction func createByFileAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let imagePath: String = NSBundle.mainBundle().pathForResource("doc_test", ofType: "txt")! let cloud = CopyleaksCloud(.Businesses) cloud.allowPartialScan = true cloud.createByFile(fileURL: NSURL(string: imagePath)!, language: "English") { (result) in self.activityIndicator.stopAnimating() self.showProcessResult(result) } } @IBAction func createByOCRAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let imagePath: String = NSBundle.mainBundle().pathForResource("ocr_test", ofType: "png")! let cloud = CopyleaksCloud(.Businesses) cloud.allowPartialScan = true cloud.createByOCR(fileURL: NSURL(string: imagePath)!, language: "English") { (result) in self.activityIndicator.stopAnimating() self.showProcessResult(result) } } @IBAction func countCreditsAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let cloud = CopyleaksCloud(.Businesses) cloud.countCredits { (result) in self.activityIndicator.stopAnimating() if result.isSuccess { let val = result.value?["Amount"] as? Int ?? 0 Alert("Amount", message: "\(val)") } else { Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error") } } } @IBAction func logoutAction(sender: AnyObject) { Copyleaks.logout { self.navigationController?.popViewControllerAnimated(true) } } // MARK: - helpers func showProcessResult(result: PlagiarismChecker.CopyleaksResult<AnyObject, NSError>) { currentProcess = nil if result.isSuccess { currentProcess = result.value self.performSegueWithIdentifier("showDetails", sender: nil) } else { Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error") } } // MARK: - Memory override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetails" { if let processId: String = currentProcess?["ProcessId"] as? String, created: String = currentProcess?["CreationTimeUTC"] as? String { let vc: ProcessDetailsViewController = segue.destinationViewController as! ProcessDetailsViewController vc.processId = processId vc.processCreated = created vc.processStatus = "Progress" } else { Alert("Error", message: "No process data") } } } }
mit
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Core/Services/3rd Party/ThirdPartyManagerProtocol.swift
1
243
// // ThirdPartyManagerProtocol.swift // AsciiArtPlayer // // Created by Sergey Teryokhin on 20/12/2016. // Copyright © 2016 iMacDev. All rights reserved. // import Foundation protocol ThirdPartyManagerProtocol { func configure() }
mit
ctinnell/swift-reflection
SwiftReflect.playground/section-1.swift
1
591
// Playground - noun: a place where people can play import UIKit class animal { let animalName: String let color: String init(animalName: String, color: String) { self.animalName = animalName self.color = color } } let dog = animal(animalName: "Fido", color: "white") let dogProperties = reflect(dog) dogProperties.count for index in 0...dogProperties.count-1 { let (name, child) = dogProperties[0] if child.valueType is String.Type { println("\(name) is a string") } else { println("It isn't a string") } }
mit
javibm/fastlane
fastlane/swift/LaneFileProtocol.swift
1
3735
// // LaneFileProtocol.swift // FastlaneSwiftRunner // // Created by Joshua Liebowitz on 8/4/17. // Copyright © 2017 Joshua Liebowitz. All rights reserved. // import Foundation public protocol LaneFileProtocol: class { var fastlaneVersion: String { get } static func runLane(named: String) func recordLaneDescriptions() func beforeAll() func afterAll(currentLane: String) func onError(currentLane: String, errorInfo: String) } public extension LaneFileProtocol { var fastlaneVersion: String { return "" } // default "" because that means any is fine func beforeAll() { } // no op by default func afterAll(currentLane: String) { } // no op by default func onError(currentLane: String, errorInfo: String) {} // no op by default func recordLaneDescriptions() { } // no op by default } @objcMembers public class LaneFile: NSObject, LaneFileProtocol { private(set) static var fastfileInstance: Fastfile? // Called before any lane is executed. private func setupAllTheThings() { // Step 1, add lange descriptions (self as! Fastfile).recordLaneDescriptions() // Step 2, run beforeAll() function LaneFile.fastfileInstance!.beforeAll() } public static var lanes: [String : String] { var laneToMethodName: [String : String] = [:] var methodCount: UInt32 = 0 let methodList = class_copyMethodList(self, &methodCount) for i in 0..<Int(methodCount) { let selName = sel_getName(method_getName(methodList![i])) let name = String(cString: selName) let lowercasedName = name.lowercased() guard lowercasedName.hasSuffix("lane") else { continue } laneToMethodName[lowercasedName] = name let lowercasedNameNoLane = String(lowercasedName.prefix(lowercasedName.count - 4)) laneToMethodName[lowercasedNameNoLane] = name } return laneToMethodName } public static func loadFastfile() { if self.fastfileInstance == nil { let fastfileType: AnyObject.Type = NSClassFromString(self.className())! let fastfileAsNSObjectType: NSObject.Type = fastfileType as! NSObject.Type let currentFastfileInstance: Fastfile? = fastfileAsNSObjectType.init() as? Fastfile self.fastfileInstance = currentFastfileInstance } } public static func runLane(named: String) { log(message: "Running lane: \(named)") self.loadFastfile() guard let fastfileInstance: Fastfile = self.fastfileInstance else { let message = "Unable to instantiate class named: \(self.className())" log(message: message) fatalError(message) } // call all methods that need to be called before we start calling lanes fastfileInstance.setupAllTheThings() let currentLanes = self.lanes let lowerCasedLaneRequested = named.lowercased() guard let laneMethod = currentLanes[lowerCasedLaneRequested] else { let message = "unable to find lane named: \(named)" log(message: message) fatalError(message) } // We need to catch all possible errors here and display a nice message _ = fastfileInstance.perform(NSSelectorFromString(laneMethod)) // only call on success fastfileInstance.afterAll(currentLane: named) log(message: "Done running lane: \(named) 🚀") } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.1]
mit
think-dev/MadridBUS
MadridBUS/Source/Data/Network/StringRequest.swift
1
848
import Foundation import Alamofire import ObjectMapper class StringRequest: Request { typealias ResponseType = String var group: DispatchGroup = DispatchGroup() var stringURL: String var method: HTTPMethod var parameter: Mappable var encoding: ParameterEncoding? var response: Response<ResponseType> var skippableKey: String? required init(url: String, method: HTTPMethod, parameter: Mappable, encoding: ParameterEncoding?, skippableKey: String?) { self.stringURL = url self.method = method self.parameter = parameter self.response = Response<ResponseType>() self.encoding = encoding self.skippableKey = skippableKey } func addSuccessResponse(_ data: Data) { response.dataResponse = String(data: data, encoding: .utf8) } }
mit
zbw209/-
StudyNotes/Pods/Alamofire/Source/Protector.swift
5
5274
// // Protector.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 // MARK: - /// An `os_unfair_lock` wrapper. final class UnfairLock { private let unfairLock: os_unfair_lock_t init() { unfairLock = .allocate(capacity: 1) unfairLock.initialize(to: os_unfair_lock()) } deinit { unfairLock.deinitialize(count: 1) unfairLock.deallocate() } private func lock() { os_unfair_lock_lock(unfairLock) } private func unlock() { os_unfair_lock_unlock(unfairLock) } /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to run. /// /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure() } /// Execute a closure while acquiring the lock. /// /// - Parameter closure: The closure to run. func around(_ closure: () -> Void) { lock(); defer { unlock() } return closure() } } /// A thread-safe wrapper around a value. final class Protector<T> { private let lock = UnfairLock() private var value: T init(_ value: T) { self.value = value } /// The contained value. Unsafe for anything more than direct read or write. var directValue: T { get { return lock.around { value } } set { lock.around { value = newValue } } } /// Synchronously read or transform the contained value. /// /// - Parameter closure: The closure to execute. /// /// - Returns: The return value of the closure passed. func read<U>(_ closure: (T) -> U) -> U { return lock.around { closure(self.value) } } /// Synchronously modify the protected value. /// /// - Parameter closure: The closure to execute. /// /// - Returns: The modified value. @discardableResult func write<U>(_ closure: (inout T) -> U) -> U { return lock.around { closure(&self.value) } } } extension Protector where T: RangeReplaceableCollection { /// Adds a new element to the end of this protected collection. /// /// - Parameter newElement: The `Element` to append. func append(_ newElement: T.Element) { write { (ward: inout T) in ward.append(newElement) } } /// Adds the elements of a sequence to the end of this protected collection. /// /// - Parameter newElements: The `Sequence` to append. func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } /// Add the elements of a collection to the end of the protected collection. /// /// - Parameter newElements: The `Collection` to append. func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } } extension Protector where T == Data? { /// Adds the contents of a `Data` value to the end of the protected `Data`. /// /// - Parameter data: The `Data` to be appended. func append(_ data: Data) { write { (ward: inout T) in ward?.append(data) } } } extension Protector where T == Request.MutableState { /// Attempts to transition to the passed `State`. /// /// - Parameter state: The `State` to attempt transition to. /// /// - Returns: Whether the transition occurred. func attemptToTransitionTo(_ state: Request.State) -> Bool { return lock.around { guard value.state.canTransitionTo(state) else { return false } value.state = state return true } } /// Perform a closure while locked with the provided `Request.State`. /// /// - Parameter perform: The closure to perform while locked. func withState(perform: (Request.State) -> Void) { lock.around { perform(value.state) } } }
mit
vlaminck/LD33
LD33/LD33/MyUtils.swift
1
2396
// // MyUtils.swift // ZombieConga // // Created by Main Account on 10/22/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import Foundation import CoreGraphics func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func += (inout left: CGPoint, right: CGPoint) { left = left + right } func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } func -= (inout left: CGPoint, right: CGPoint) { left = left - right } func * (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x * right.x, y: left.y * right.y) } func *= (inout left: CGPoint, right: CGPoint) { left = left * right } func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } func *= (inout point: CGPoint, scalar: CGFloat) { point = point * scalar } func / (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x / right.x, y: left.y / right.y) } func /= (inout left: CGPoint, right: CGPoint) { left = left / right } func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } func /= (inout point: CGPoint, scalar: CGFloat) { point = point / scalar } #if !(arch(x86_64) || arch(arm64)) func atan2(y: CGFloat, x: CGFloat) -> CGFloat { return CGFloat(atan2f(Float(y), Float(x))) } func sqrt(a: CGFloat) -> CGFloat { return CGFloat(sqrtf(Float(a))) } #endif extension CGPoint { func length() -> CGFloat { return sqrt(x*x + y*y) } func normalized() -> CGPoint { return self / length() } var angle: CGFloat { return atan2(y, x) } } let π = CGFloat(M_PI) func shortestAngleBetween(angle1: CGFloat, angle2: CGFloat) -> CGFloat { let twoπ = π * 2.0 var angle = (angle2 - angle1) % twoπ if (angle >= π) { angle = angle - twoπ } if (angle <= -π) { angle = angle + twoπ } return angle } extension CGFloat { func sign() -> CGFloat { return (self >= 0.0) ? 1.0 : -1.0 } } extension CGFloat { static func random() -> CGFloat { return CGFloat(Float(arc4random()) / Float(UInt32.max)) } static func random(min min: CGFloat, max: CGFloat) -> CGFloat { assert(min < max) return CGFloat.random() * (max - min) + min } }
mit
lorentey/swift
validation-test/stdlib/Slice/Slice_Of_DefaultedMutableRangeReplaceableBidirectionalCollection_WithPrefixAndSuffix.swift
16
4046
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [-9999, -9998, -9997, -9996, -9995] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<DefaultedMutableRangeReplaceableBidirectionalCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = DefaultedMutableRangeReplaceableBidirectionalCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<DefaultedMutableRangeReplaceableBidirectionalCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = DefaultedMutableRangeReplaceableBidirectionalCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<DefaultedMutableRangeReplaceableBidirectionalCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = DefaultedMutableRangeReplaceableBidirectionalCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addRangeReplaceableBidirectionalSliceTests( "Slice_Of_DefaultedMutableRangeReplaceableBidirectionalCollection_WithPrefixAndSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 ) SliceTests.addMutableBidirectionalCollectionTests( "Slice_Of_DefaultedMutableRangeReplaceableBidirectionalCollection_WithPrefixAndSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) runAllTests()
apache-2.0
tgrf/swiftBluetoothSerial
Classes/BluetoothSerial.swift
1
10504
// // BluetoothSerial.swift (originally DZBluetoothSerialHandler.swift) // HM10 Serial // // Created by Alex on 09-08-15. // Copyright (c) 2015 Balancing Rock. All rights reserved. // // IMPORTANT: Don't forget to set the variable 'writeType' or else the whole thing might not work. // import UIKit import CoreBluetooth /// Global serial handler, don't forget to initialize it with init(delgate:) var serial: BluetoothSerial! // Delegate functions public protocol BluetoothSerialDelegate { // ** Required ** /// Called when de state of the CBCentralManager changes (e.g. when bluetooth is turned on/off) func serialDidChangeState() /// Called when a peripheral disconnected func serialDidDisconnect(_ peripheral: CBPeripheral, error: NSError?) // ** Optionals ** /// Called when a message is received func serialDidReceiveString(_ message: String) /// Called when a message is received func serialDidReceiveBytes(_ bytes: [UInt8]) /// Called when a message is received func serialDidReceiveData(_ data: Data) /// Called when the RSSI of the connected peripheral is read func serialDidReadRSSI(_ rssi: NSNumber) /// Called when a new peripheral is discovered while scanning. Also gives the RSSI (signal strength) func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?) /// Called when a peripheral is connected (but not yet ready for cummunication) func serialDidConnect(_ peripheral: CBPeripheral) /// Called when a pending connection failed func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?) /// Called when a peripheral is ready for communication func serialIsReady(_ peripheral: CBPeripheral) } // Make some of the delegate functions optional public extension BluetoothSerialDelegate { func serialDidReceiveString(_ message: String) {} func serialDidReceiveBytes(_ bytes: [UInt8]) {} func serialDidReceiveData(_ data: Data) {} func serialDidReadRSSI(_ rssi: NSNumber) {} func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?) {} func serialDidConnect(_ peripheral: CBPeripheral) {} func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?) {} func serialIsReady(_ peripheral: CBPeripheral) {} } public final class BluetoothSerial: NSObject { //MARK: Variables /// The delegate object the BluetoothDelegate methods will be called upon public var delegate: BluetoothSerialDelegate! /// The CBCentralManager this bluetooth serial handler uses for... well, everything really var centralManager: CBCentralManager! /// The peripheral we're trying to connect to (nil if none) public var pendingPeripheral: CBPeripheral? /// The connected peripheral (nil if none is connected) public var connectedPeripheral: CBPeripheral? /// The characteristic 0xFFE1 we need to write to, of the connectedPeripheral weak var writeCharacteristic: CBCharacteristic? /// Whether this serial is ready to send and receive data public var isReady: Bool { get { return centralManager.state == .poweredOn && connectedPeripheral != nil && writeCharacteristic != nil } } /// Whether to write to the HM10 with or without response. /// Legit HM10 modules (from JNHuaMao) require 'Write without Response', /// while fake modules (e.g. from Bolutek) require 'Write with Response'. public var writeType: CBCharacteristicWriteType = .withoutResponse //MARK: functions /// Always use this to initialize an instance public init(delegate: BluetoothSerialDelegate) { super.init() self.delegate = delegate centralManager = CBCentralManager(delegate: self, queue: nil) } /// Start scanning for peripherals public func startScan() { guard centralManager.state == .poweredOn else { return } // start scanning for peripherals with correct service UUID let uuid = CBUUID(string: "FFE0") centralManager.scanForPeripherals(withServices: [uuid], options: nil) // retrieve peripherals that are already connected // see this stackoverflow question http://stackoverflow.com/questions/13286487 let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [uuid]) for peripheral in peripherals { delegate.serialDidDiscoverPeripheral(peripheral, RSSI: nil) } } /// Stop scanning for peripherals public func stopScan() { centralManager.stopScan() } /// Try to connect to the given peripheral public func connectToPeripheral(_ peripheral: CBPeripheral) { pendingPeripheral = peripheral centralManager.connect(peripheral, options: nil) } /// Disconnect from the connected peripheral or stop connecting to it public func disconnect() { if let p = connectedPeripheral { centralManager.cancelPeripheralConnection(p) } else if let p = pendingPeripheral { centralManager.cancelPeripheralConnection(p) //TODO: Test whether its neccesary to set p to nil } } /// The didReadRSSI delegate function will be called after calling this function public func readRSSI() { guard isReady else { return } connectedPeripheral!.readRSSI() } /// Send a string to the device public func sendMessageToDevice(_ message: String) { guard isReady else { return } if let data = message.data(using: String.Encoding.utf8) { connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType) } } /// Send an array of bytes to the device public func sendBytesToDevice(_ bytes: [UInt8]) { guard isReady else { return } let data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType) } /// Send data to the device public func sendDataToDevice(_ data: Data) { guard isReady else { return } connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType) } } extension BluetoothSerial: CBCentralManagerDelegate, CBPeripheralDelegate { //MARK: CBCentralManagerDelegate functions public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // just send it to the delegate delegate.serialDidDiscoverPeripheral(peripheral, RSSI: RSSI) } public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { // set some stuff right peripheral.delegate = self pendingPeripheral = nil connectedPeripheral = peripheral // send it to the delegate delegate.serialDidConnect(peripheral) // Okay, the peripheral is connected but we're not ready yet! // First get the 0xFFE0 service // Then get the 0xFFE1 characteristic of this service // Subscribe to it & create a weak reference to it (for writing later on), // and then we're ready for communication peripheral.discoverServices([CBUUID(string: "FFE0")]) } public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { connectedPeripheral = nil pendingPeripheral = nil // send it to the delegate delegate.serialDidDisconnect(peripheral, error: error as NSError?) } public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { pendingPeripheral = nil // just send it to the delegate delegate.serialDidFailToConnect(peripheral, error: error as NSError?) } public func centralManagerDidUpdateState(_ central: CBCentralManager) { // note that "didDisconnectPeripheral" won't be called if BLE is turned off while connected connectedPeripheral = nil pendingPeripheral = nil // send it to the delegate delegate.serialDidChangeState() } //MARK: CBPeripheralDelegate functions public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { // discover the 0xFFE1 characteristic for all services (though there should only be one) for service in peripheral.services! { peripheral.discoverCharacteristics([CBUUID(string: "FFE1")], for: service) } } public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { // check whether the characteristic we're looking for (0xFFE1) is present - just to be sure for characteristic in service.characteristics! { if characteristic.uuid == CBUUID(string: "FFE1") { // subscribe to this value (so we'll get notified when there is serial data for us..) peripheral.setNotifyValue(true, for: characteristic) // keep a reference to this characteristic so we can write to it writeCharacteristic = characteristic // notify the delegate we're ready for communication delegate.serialIsReady(peripheral) } } } public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { // notify the delegate in different ways // if you don't use one of these, just comment it (for optimum efficiency :]) let data = characteristic.value guard data != nil else { return } // first the data delegate.serialDidReceiveData(data!) // then the string if let str = String(data: data!, encoding: String.Encoding.utf8) { delegate.serialDidReceiveString(str) } else { //print("Received an invalid string!") uncomment for debugging } // now the bytes array var bytes = [UInt8](repeating: 0, count: data!.count / MemoryLayout<UInt8>.size) (data! as NSData).getBytes(&bytes, length: data!.count) delegate.serialDidReceiveBytes(bytes) } public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { delegate.serialDidReadRSSI(RSSI) } }
mit
noppoMan/aws-sdk-swift
Sources/Soto/Services/IAM/IAM_Paginator.swift
1
84620
//===----------------------------------------------------------------------===// // // 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 SotoCore // MARK: Paginators extension IAM { /// Retrieves information about all IAM users, groups, roles, and policies in your AWS account, including their relationships to one another. Use this API to obtain a snapshot of the configuration of IAM permissions (users, groups, roles, and policies) in your account. Policies returned by this API are URL-encoded compliant with RFC 3986. You can use a URL decoding method to convert the policy back to plain JSON text. For example, if you use Java, you can use the decode method of the java.net.URLDecoder utility class in the Java SDK. Other languages and SDKs provide similar functionality. You can optionally filter the results using the Filter parameter. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getAccountAuthorizationDetailsPaginator<Result>( _ input: GetAccountAuthorizationDetailsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetAccountAuthorizationDetailsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getAccountAuthorizationDetails, tokenKey: \GetAccountAuthorizationDetailsResponse.marker, moreResultsKey: \GetAccountAuthorizationDetailsResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getAccountAuthorizationDetailsPaginator( _ input: GetAccountAuthorizationDetailsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetAccountAuthorizationDetailsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getAccountAuthorizationDetails, tokenKey: \GetAccountAuthorizationDetailsResponse.marker, moreResultsKey: \GetAccountAuthorizationDetailsResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Returns a list of IAM users that are in the specified IAM group. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getGroupPaginator<Result>( _ input: GetGroupRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetGroupResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getGroup, tokenKey: \GetGroupResponse.marker, moreResultsKey: \GetGroupResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getGroupPaginator( _ input: GetGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetGroupResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getGroup, tokenKey: \GetGroupResponse.marker, moreResultsKey: \GetGroupResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Returns information about the access key IDs associated with the specified IAM user. If there is none, the operation returns an empty list. Although each user is limited to a small number of keys, you can still paginate the results using the MaxItems and Marker parameters. If the UserName field is not specified, the user name is determined implicitly based on the AWS access key ID used to sign the request. This operation works for access keys under the AWS account. Consequently, you can use this operation to manage AWS account root user credentials even if the AWS account has no associated users. To ensure the security of your AWS account, the secret access key is accessible only during key and user creation. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAccessKeysPaginator<Result>( _ input: ListAccessKeysRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAccessKeysResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAccessKeys, tokenKey: \ListAccessKeysResponse.marker, moreResultsKey: \ListAccessKeysResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAccessKeysPaginator( _ input: ListAccessKeysRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAccessKeysResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAccessKeys, tokenKey: \ListAccessKeysResponse.marker, moreResultsKey: \ListAccessKeysResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the account alias associated with the AWS account (Note: you can have only one). For information about using an AWS account alias, see Using an Alias for Your AWS Account ID in the IAM User Guide. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAccountAliasesPaginator<Result>( _ input: ListAccountAliasesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAccountAliasesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAccountAliases, tokenKey: \ListAccountAliasesResponse.marker, moreResultsKey: \ListAccountAliasesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAccountAliasesPaginator( _ input: ListAccountAliasesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAccountAliasesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAccountAliases, tokenKey: \ListAccountAliasesResponse.marker, moreResultsKey: \ListAccountAliasesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists all managed policies that are attached to the specified IAM group. An IAM group can also have inline policies embedded with it. To list the inline policies for a group, use the ListGroupPolicies API. For information about policies, see Managed Policies and Inline Policies in the IAM User Guide. You can paginate the results using the MaxItems and Marker parameters. You can use the PathPrefix parameter to limit the list of policies to only those matching the specified path prefix. If there are no policies attached to the specified group (or none that match the specified path prefix), the operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAttachedGroupPoliciesPaginator<Result>( _ input: ListAttachedGroupPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAttachedGroupPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAttachedGroupPolicies, tokenKey: \ListAttachedGroupPoliciesResponse.marker, moreResultsKey: \ListAttachedGroupPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAttachedGroupPoliciesPaginator( _ input: ListAttachedGroupPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAttachedGroupPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAttachedGroupPolicies, tokenKey: \ListAttachedGroupPoliciesResponse.marker, moreResultsKey: \ListAttachedGroupPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists all managed policies that are attached to the specified IAM role. An IAM role can also have inline policies embedded with it. To list the inline policies for a role, use the ListRolePolicies API. For information about policies, see Managed Policies and Inline Policies in the IAM User Guide. You can paginate the results using the MaxItems and Marker parameters. You can use the PathPrefix parameter to limit the list of policies to only those matching the specified path prefix. If there are no policies attached to the specified role (or none that match the specified path prefix), the operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAttachedRolePoliciesPaginator<Result>( _ input: ListAttachedRolePoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAttachedRolePoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAttachedRolePolicies, tokenKey: \ListAttachedRolePoliciesResponse.marker, moreResultsKey: \ListAttachedRolePoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAttachedRolePoliciesPaginator( _ input: ListAttachedRolePoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAttachedRolePoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAttachedRolePolicies, tokenKey: \ListAttachedRolePoliciesResponse.marker, moreResultsKey: \ListAttachedRolePoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists all managed policies that are attached to the specified IAM user. An IAM user can also have inline policies embedded with it. To list the inline policies for a user, use the ListUserPolicies API. For information about policies, see Managed Policies and Inline Policies in the IAM User Guide. You can paginate the results using the MaxItems and Marker parameters. You can use the PathPrefix parameter to limit the list of policies to only those matching the specified path prefix. If there are no policies attached to the specified group (or none that match the specified path prefix), the operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAttachedUserPoliciesPaginator<Result>( _ input: ListAttachedUserPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAttachedUserPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAttachedUserPolicies, tokenKey: \ListAttachedUserPoliciesResponse.marker, moreResultsKey: \ListAttachedUserPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAttachedUserPoliciesPaginator( _ input: ListAttachedUserPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAttachedUserPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAttachedUserPolicies, tokenKey: \ListAttachedUserPoliciesResponse.marker, moreResultsKey: \ListAttachedUserPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists all IAM users, groups, and roles that the specified managed policy is attached to. You can use the optional EntityFilter parameter to limit the results to a particular type of entity (users, groups, or roles). For example, to list only the roles that are attached to the specified policy, set EntityFilter to Role. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listEntitiesForPolicyPaginator<Result>( _ input: ListEntitiesForPolicyRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListEntitiesForPolicyResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listEntitiesForPolicy, tokenKey: \ListEntitiesForPolicyResponse.marker, moreResultsKey: \ListEntitiesForPolicyResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listEntitiesForPolicyPaginator( _ input: ListEntitiesForPolicyRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListEntitiesForPolicyResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listEntitiesForPolicy, tokenKey: \ListEntitiesForPolicyResponse.marker, moreResultsKey: \ListEntitiesForPolicyResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the names of the inline policies that are embedded in the specified IAM group. An IAM group can also have managed policies attached to it. To list the managed policies that are attached to a group, use ListAttachedGroupPolicies. For more information about policies, see Managed Policies and Inline Policies in the IAM User Guide. You can paginate the results using the MaxItems and Marker parameters. If there are no inline policies embedded with the specified group, the operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listGroupPoliciesPaginator<Result>( _ input: ListGroupPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListGroupPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listGroupPolicies, tokenKey: \ListGroupPoliciesResponse.marker, moreResultsKey: \ListGroupPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listGroupPoliciesPaginator( _ input: ListGroupPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListGroupPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroupPolicies, tokenKey: \ListGroupPoliciesResponse.marker, moreResultsKey: \ListGroupPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the IAM groups that have the specified path prefix. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listGroupsPaginator<Result>( _ input: ListGroupsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listGroups, tokenKey: \ListGroupsResponse.marker, moreResultsKey: \ListGroupsResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listGroupsPaginator( _ input: ListGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListGroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroups, tokenKey: \ListGroupsResponse.marker, moreResultsKey: \ListGroupsResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the IAM groups that the specified IAM user belongs to. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listGroupsForUserPaginator<Result>( _ input: ListGroupsForUserRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListGroupsForUserResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listGroupsForUser, tokenKey: \ListGroupsForUserResponse.marker, moreResultsKey: \ListGroupsForUserResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listGroupsForUserPaginator( _ input: ListGroupsForUserRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListGroupsForUserResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroupsForUser, tokenKey: \ListGroupsForUserResponse.marker, moreResultsKey: \ListGroupsForUserResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the instance profiles that have the specified path prefix. If there are none, the operation returns an empty list. For more information about instance profiles, go to About Instance Profiles. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listInstanceProfilesPaginator<Result>( _ input: ListInstanceProfilesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListInstanceProfilesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listInstanceProfiles, tokenKey: \ListInstanceProfilesResponse.marker, moreResultsKey: \ListInstanceProfilesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listInstanceProfilesPaginator( _ input: ListInstanceProfilesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListInstanceProfilesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listInstanceProfiles, tokenKey: \ListInstanceProfilesResponse.marker, moreResultsKey: \ListInstanceProfilesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the instance profiles that have the specified associated IAM role. If there are none, the operation returns an empty list. For more information about instance profiles, go to About Instance Profiles. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listInstanceProfilesForRolePaginator<Result>( _ input: ListInstanceProfilesForRoleRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListInstanceProfilesForRoleResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listInstanceProfilesForRole, tokenKey: \ListInstanceProfilesForRoleResponse.marker, moreResultsKey: \ListInstanceProfilesForRoleResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listInstanceProfilesForRolePaginator( _ input: ListInstanceProfilesForRoleRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListInstanceProfilesForRoleResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listInstanceProfilesForRole, tokenKey: \ListInstanceProfilesForRoleResponse.marker, moreResultsKey: \ListInstanceProfilesForRoleResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the MFA devices for an IAM user. If the request includes a IAM user name, then this operation lists all the MFA devices associated with the specified user. If you do not specify a user name, IAM determines the user name implicitly based on the AWS access key ID signing the request for this API. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listMFADevicesPaginator<Result>( _ input: ListMFADevicesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListMFADevicesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listMFADevices, tokenKey: \ListMFADevicesResponse.marker, moreResultsKey: \ListMFADevicesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listMFADevicesPaginator( _ input: ListMFADevicesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListMFADevicesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listMFADevices, tokenKey: \ListMFADevicesResponse.marker, moreResultsKey: \ListMFADevicesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists all the managed policies that are available in your AWS account, including your own customer-defined managed policies and all AWS managed policies. You can filter the list of policies that is returned using the optional OnlyAttached, Scope, and PathPrefix parameters. For example, to list only the customer managed policies in your AWS account, set Scope to Local. To list only AWS managed policies, set Scope to AWS. You can paginate the results using the MaxItems and Marker parameters. For more information about managed policies, see Managed Policies and Inline Policies in the IAM User Guide. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPoliciesPaginator<Result>( _ input: ListPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPolicies, tokenKey: \ListPoliciesResponse.marker, moreResultsKey: \ListPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPoliciesPaginator( _ input: ListPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPolicies, tokenKey: \ListPoliciesResponse.marker, moreResultsKey: \ListPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists information about the versions of the specified managed policy, including the version that is currently set as the policy's default version. For more information about managed policies, see Managed Policies and Inline Policies in the IAM User Guide. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPolicyVersionsPaginator<Result>( _ input: ListPolicyVersionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPolicyVersionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPolicyVersions, tokenKey: \ListPolicyVersionsResponse.marker, moreResultsKey: \ListPolicyVersionsResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPolicyVersionsPaginator( _ input: ListPolicyVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPolicyVersionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPolicyVersions, tokenKey: \ListPolicyVersionsResponse.marker, moreResultsKey: \ListPolicyVersionsResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the names of the inline policies that are embedded in the specified IAM role. An IAM role can also have managed policies attached to it. To list the managed policies that are attached to a role, use ListAttachedRolePolicies. For more information about policies, see Managed Policies and Inline Policies in the IAM User Guide. You can paginate the results using the MaxItems and Marker parameters. If there are no inline policies embedded with the specified role, the operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRolePoliciesPaginator<Result>( _ input: ListRolePoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRolePoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRolePolicies, tokenKey: \ListRolePoliciesResponse.marker, moreResultsKey: \ListRolePoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRolePoliciesPaginator( _ input: ListRolePoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRolePoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRolePolicies, tokenKey: \ListRolePoliciesResponse.marker, moreResultsKey: \ListRolePoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the IAM roles that have the specified path prefix. If there are none, the operation returns an empty list. For more information about roles, go to Working with Roles. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRolesPaginator<Result>( _ input: ListRolesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRolesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRoles, tokenKey: \ListRolesResponse.marker, moreResultsKey: \ListRolesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRolesPaginator( _ input: ListRolesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRolesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRoles, tokenKey: \ListRolesResponse.marker, moreResultsKey: \ListRolesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Returns information about the SSH public keys associated with the specified IAM user. If none exists, the operation returns an empty list. The SSH public keys returned by this operation are used only for authenticating the IAM user to an AWS CodeCommit repository. For more information about using SSH keys to authenticate to an AWS CodeCommit repository, see Set up AWS CodeCommit for SSH Connections in the AWS CodeCommit User Guide. Although each user is limited to a small number of keys, you can still paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSSHPublicKeysPaginator<Result>( _ input: ListSSHPublicKeysRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSSHPublicKeysResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSSHPublicKeys, tokenKey: \ListSSHPublicKeysResponse.marker, moreResultsKey: \ListSSHPublicKeysResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSSHPublicKeysPaginator( _ input: ListSSHPublicKeysRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSSHPublicKeysResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSSHPublicKeys, tokenKey: \ListSSHPublicKeysResponse.marker, moreResultsKey: \ListSSHPublicKeysResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the server certificates stored in IAM that have the specified path prefix. If none exist, the operation returns an empty list. You can paginate the results using the MaxItems and Marker parameters. For more information about working with server certificates, see Working with Server Certificates in the IAM User Guide. This topic also includes a list of AWS services that can use the server certificates that you manage with IAM. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listServerCertificatesPaginator<Result>( _ input: ListServerCertificatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListServerCertificatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listServerCertificates, tokenKey: \ListServerCertificatesResponse.marker, moreResultsKey: \ListServerCertificatesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listServerCertificatesPaginator( _ input: ListServerCertificatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListServerCertificatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listServerCertificates, tokenKey: \ListServerCertificatesResponse.marker, moreResultsKey: \ListServerCertificatesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Returns information about the signing certificates associated with the specified IAM user. If none exists, the operation returns an empty list. Although each user is limited to a small number of signing certificates, you can still paginate the results using the MaxItems and Marker parameters. If the UserName field is not specified, the user name is determined implicitly based on the AWS access key ID used to sign the request for this API. This operation works for access keys under the AWS account. Consequently, you can use this operation to manage AWS account root user credentials even if the AWS account has no associated users. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSigningCertificatesPaginator<Result>( _ input: ListSigningCertificatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSigningCertificatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSigningCertificates, tokenKey: \ListSigningCertificatesResponse.marker, moreResultsKey: \ListSigningCertificatesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSigningCertificatesPaginator( _ input: ListSigningCertificatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSigningCertificatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSigningCertificates, tokenKey: \ListSigningCertificatesResponse.marker, moreResultsKey: \ListSigningCertificatesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the names of the inline policies embedded in the specified IAM user. An IAM user can also have managed policies attached to it. To list the managed policies that are attached to a user, use ListAttachedUserPolicies. For more information about policies, see Managed Policies and Inline Policies in the IAM User Guide. You can paginate the results using the MaxItems and Marker parameters. If there are no inline policies embedded with the specified user, the operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listUserPoliciesPaginator<Result>( _ input: ListUserPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListUserPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listUserPolicies, tokenKey: \ListUserPoliciesResponse.marker, moreResultsKey: \ListUserPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listUserPoliciesPaginator( _ input: ListUserPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListUserPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUserPolicies, tokenKey: \ListUserPoliciesResponse.marker, moreResultsKey: \ListUserPoliciesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the IAM users that have the specified path prefix. If no path prefix is specified, the operation returns all users in the AWS account. If there are none, the operation returns an empty list. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listUsersPaginator<Result>( _ input: ListUsersRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListUsersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listUsers, tokenKey: \ListUsersResponse.marker, moreResultsKey: \ListUsersResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listUsersPaginator( _ input: ListUsersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListUsersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUsers, tokenKey: \ListUsersResponse.marker, moreResultsKey: \ListUsersResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Lists the virtual MFA devices defined in the AWS account by assignment status. If you do not specify an assignment status, the operation returns a list of all virtual MFA devices. Assignment status can be Assigned, Unassigned, or Any. You can paginate the results using the MaxItems and Marker parameters. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listVirtualMFADevicesPaginator<Result>( _ input: ListVirtualMFADevicesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListVirtualMFADevicesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listVirtualMFADevices, tokenKey: \ListVirtualMFADevicesResponse.marker, moreResultsKey: \ListVirtualMFADevicesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listVirtualMFADevicesPaginator( _ input: ListVirtualMFADevicesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListVirtualMFADevicesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listVirtualMFADevices, tokenKey: \ListVirtualMFADevicesResponse.marker, moreResultsKey: \ListVirtualMFADevicesResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Simulate how a set of IAM policies and optionally a resource-based policy works with a list of API operations and AWS resources to determine the policies' effective permissions. The policies are provided as strings. The simulation does not perform the API operations; it only checks the authorization to determine if the simulated policies allow or deny the operations. If you want to simulate existing policies that are attached to an IAM user, group, or role, use SimulatePrincipalPolicy instead. Context keys are variables that are maintained by AWS and its services and which provide details about the context of an API query request. You can use the Condition element of an IAM policy to evaluate context keys. To get the list of context keys that the policies require for correct simulation, use GetContextKeysForCustomPolicy. If the output is long, you can use MaxItems and Marker parameters to paginate the results. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func simulateCustomPolicyPaginator<Result>( _ input: SimulateCustomPolicyRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, SimulatePolicyResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: simulateCustomPolicy, tokenKey: \SimulatePolicyResponse.marker, moreResultsKey: \SimulatePolicyResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func simulateCustomPolicyPaginator( _ input: SimulateCustomPolicyRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (SimulatePolicyResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: simulateCustomPolicy, tokenKey: \SimulatePolicyResponse.marker, moreResultsKey: \SimulatePolicyResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Simulate how a set of IAM policies attached to an IAM entity works with a list of API operations and AWS resources to determine the policies' effective permissions. The entity can be an IAM user, group, or role. If you specify a user, then the simulation also includes all of the policies that are attached to groups that the user belongs to. You can optionally include a list of one or more additional policies specified as strings to include in the simulation. If you want to simulate only policies specified as strings, use SimulateCustomPolicy instead. You can also optionally include one resource-based policy to be evaluated with each of the resources included in the simulation. The simulation does not perform the API operations; it only checks the authorization to determine if the simulated policies allow or deny the operations. Note: This API discloses information about the permissions granted to other users. If you do not want users to see other user's permissions, then consider allowing them to use SimulateCustomPolicy instead. Context keys are variables maintained by AWS and its services that provide details about the context of an API query request. You can use the Condition element of an IAM policy to evaluate context keys. To get the list of context keys that the policies require for correct simulation, use GetContextKeysForPrincipalPolicy. If the output is long, you can use the MaxItems and Marker parameters to paginate the results. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func simulatePrincipalPolicyPaginator<Result>( _ input: SimulatePrincipalPolicyRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, SimulatePolicyResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: simulatePrincipalPolicy, tokenKey: \SimulatePolicyResponse.marker, moreResultsKey: \SimulatePolicyResponse.isTruncated, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func simulatePrincipalPolicyPaginator( _ input: SimulatePrincipalPolicyRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (SimulatePolicyResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: simulatePrincipalPolicy, tokenKey: \SimulatePolicyResponse.marker, moreResultsKey: \SimulatePolicyResponse.isTruncated, on: eventLoop, onPage: onPage ) } } extension IAM.GetAccountAuthorizationDetailsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.GetAccountAuthorizationDetailsRequest { return .init( filter: self.filter, marker: token, maxItems: self.maxItems ) } } extension IAM.GetGroupRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.GetGroupRequest { return .init( groupName: self.groupName, marker: token, maxItems: self.maxItems ) } } extension IAM.ListAccessKeysRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListAccessKeysRequest { return .init( marker: token, maxItems: self.maxItems, userName: self.userName ) } } extension IAM.ListAccountAliasesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListAccountAliasesRequest { return .init( marker: token, maxItems: self.maxItems ) } } extension IAM.ListAttachedGroupPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListAttachedGroupPoliciesRequest { return .init( groupName: self.groupName, marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix ) } } extension IAM.ListAttachedRolePoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListAttachedRolePoliciesRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix, roleName: self.roleName ) } } extension IAM.ListAttachedUserPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListAttachedUserPoliciesRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix, userName: self.userName ) } } extension IAM.ListEntitiesForPolicyRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListEntitiesForPolicyRequest { return .init( entityFilter: self.entityFilter, marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix, policyArn: self.policyArn, policyUsageFilter: self.policyUsageFilter ) } } extension IAM.ListGroupPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListGroupPoliciesRequest { return .init( groupName: self.groupName, marker: token, maxItems: self.maxItems ) } } extension IAM.ListGroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListGroupsRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix ) } } extension IAM.ListGroupsForUserRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListGroupsForUserRequest { return .init( marker: token, maxItems: self.maxItems, userName: self.userName ) } } extension IAM.ListInstanceProfilesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListInstanceProfilesRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix ) } } extension IAM.ListInstanceProfilesForRoleRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListInstanceProfilesForRoleRequest { return .init( marker: token, maxItems: self.maxItems, roleName: self.roleName ) } } extension IAM.ListMFADevicesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListMFADevicesRequest { return .init( marker: token, maxItems: self.maxItems, userName: self.userName ) } } extension IAM.ListPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListPoliciesRequest { return .init( marker: token, maxItems: self.maxItems, onlyAttached: self.onlyAttached, pathPrefix: self.pathPrefix, policyUsageFilter: self.policyUsageFilter, scope: self.scope ) } } extension IAM.ListPolicyVersionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListPolicyVersionsRequest { return .init( marker: token, maxItems: self.maxItems, policyArn: self.policyArn ) } } extension IAM.ListRolePoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListRolePoliciesRequest { return .init( marker: token, maxItems: self.maxItems, roleName: self.roleName ) } } extension IAM.ListRolesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListRolesRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix ) } } extension IAM.ListSSHPublicKeysRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListSSHPublicKeysRequest { return .init( marker: token, maxItems: self.maxItems, userName: self.userName ) } } extension IAM.ListServerCertificatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListServerCertificatesRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix ) } } extension IAM.ListSigningCertificatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListSigningCertificatesRequest { return .init( marker: token, maxItems: self.maxItems, userName: self.userName ) } } extension IAM.ListUserPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListUserPoliciesRequest { return .init( marker: token, maxItems: self.maxItems, userName: self.userName ) } } extension IAM.ListUsersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListUsersRequest { return .init( marker: token, maxItems: self.maxItems, pathPrefix: self.pathPrefix ) } } extension IAM.ListVirtualMFADevicesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.ListVirtualMFADevicesRequest { return .init( assignmentStatus: self.assignmentStatus, marker: token, maxItems: self.maxItems ) } } extension IAM.SimulateCustomPolicyRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.SimulateCustomPolicyRequest { return .init( actionNames: self.actionNames, callerArn: self.callerArn, contextEntries: self.contextEntries, marker: token, maxItems: self.maxItems, permissionsBoundaryPolicyInputList: self.permissionsBoundaryPolicyInputList, policyInputList: self.policyInputList, resourceArns: self.resourceArns, resourceHandlingOption: self.resourceHandlingOption, resourceOwner: self.resourceOwner, resourcePolicy: self.resourcePolicy ) } } extension IAM.SimulatePrincipalPolicyRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> IAM.SimulatePrincipalPolicyRequest { return .init( actionNames: self.actionNames, callerArn: self.callerArn, contextEntries: self.contextEntries, marker: token, maxItems: self.maxItems, permissionsBoundaryPolicyInputList: self.permissionsBoundaryPolicyInputList, policyInputList: self.policyInputList, policySourceArn: self.policySourceArn, resourceArns: self.resourceArns, resourceHandlingOption: self.resourceHandlingOption, resourceOwner: self.resourceOwner, resourcePolicy: self.resourcePolicy ) } }
apache-2.0
ChristianDeckert/CDTools
CDTools/Foundation/CDAppCache.swift
1
6106
// // CDAppCache.swift // CDTools // // Created by Christian Deckert on 06.07.16. // Copyright © 2016 Christian Deckert. All rights reserved. // import Foundation // MARK: - CDAppCache: a simple singelton to cache and persist stuff public typealias WatchAppCacheObserverCallback = (_ object: AnyObject?, _ key: String) -> Void let _appCacheInstance = CDAppCache() open class CDAppCache { fileprivate var cache = Dictionary<String, AnyObject>() open var suitName: String? = nil { didSet { if let suitName = self.suitName { userDefaults = UserDefaults(suiteName: suitName)! } else { userDefaults = UserDefaults.standard } } } open var userDefaults: UserDefaults = UserDefaults.standard open static func sharedCache() -> CDAppCache { return _appCacheInstance } open func clear() { _appCacheInstance.clear() } open func add(objectToCache object: AnyObject, forKey: String) -> Bool { cache[forKey] = object notifyObservers(forKey) return true } open func objectForKey(_ key: String) -> AnyObject? { return cache[key] } open func stringForKey(_ key: String) -> String? { return objectForKey(key) as? String } open func integerForKey(_ key: String) -> Int? { return objectForKey(key) as? Int } open func doubleForKey(_ key: String) -> Double? { return objectForKey(key) as? Double } open func dictionaryForKey(_ key: String) -> Dictionary<String, AnyObject>? { return objectForKey(key) as? Dictionary<String, AnyObject> } open func remove(_ key: String) { cache[key] = nil notifyObservers(key) } // MARK: - Oberserver fileprivate var observers = Array<_WatchAppCacheObserver>() // MARK: Private Helper Class _WatchAppCacheObserver fileprivate class _WatchAppCacheObserver: NSObject { weak var observer: NSObject? var keys = Array<String>() var callback: WatchAppCacheObserverCallback? = nil func isObservingKey(_ key: String) -> Bool { for k in keys { if key == k { return true } } return false } init(observer: NSObject) { self.observer = observer } } open func addObserver(_ observer: NSObject, forKeys keys: Array<String>, callback: @escaping WatchAppCacheObserverCallback) { let (internalObserverIndex, internalObserver) = findObserver(observer) let newObserver: _WatchAppCacheObserver if let internalObserver = internalObserver { newObserver = internalObserver } else { newObserver = _WatchAppCacheObserver(observer: observer) } newObserver.keys.append(contentsOf: keys) newObserver.callback = callback if -1 == internalObserverIndex { self.observers.append(newObserver) self.notifyObserver(newObserver, keys: keys) } } open func removeObserver(_ observer: NSObject) -> Bool { let (internalObserverIndex, _) = findObserver(observer) if -1 != internalObserverIndex { self.observers.remove(at: internalObserverIndex) return true } return false } fileprivate func findObserver(_ observer: NSObject) -> (Int, _WatchAppCacheObserver?) { for (index, o) in self.observers.enumerated() { if let obs = o.observer, obs == observer { return (index, o) } } return (-1, nil) } fileprivate func notifyObservers(_ key: String) { for internalObserver in self.observers { self.notifyObserver(internalObserver, key: key) } } fileprivate func notifyObserver(_ observer: _WatchAppCacheObserver, keys: [String]) { for key in keys { self.notifyObserver(observer, key: key) } } fileprivate func notifyObserver(_ observer: _WatchAppCacheObserver, key: String) { if observer.isObservingKey(key) { observer.callback?(self.objectForKey(key), key) } } } public extension CDAppCache { public func persistObject(objectToPersist object: AnyObject, forKey key: String) { userDefaults.set(object, forKey: key) userDefaults.synchronize() } public func persistImage(imageToPersist image: UIImage, forKey: String) { let persistBase64: (Data) -> Void = { (imageData) in let base64image = imageData.base64EncodedString(options: NSData.Base64EncodingOptions()) self.userDefaults.set(base64image, forKey: forKey) self.userDefaults.synchronize() } if let imageData = UIImagePNGRepresentation(image) { persistBase64(imageData) } else if let imageData = UIImageJPEGRepresentation(image, 1.0) { persistBase64(imageData) } } public func unpersistImage(_ forKey: String) { self.removePersistedObject(forKey) } public func removePersistedObject(_ forKey: String) { userDefaults.removeObject(forKey: forKey) userDefaults.synchronize() } public func persistedObject(_ forKey: String) -> AnyObject? { return userDefaults.object(forKey: forKey) as AnyObject } public func persistedImage(_ forKey: String) -> UIImage? { if let base64string = persistedObject(forKey) as? String { if let imageData = Data.init(base64Encoded: base64string, options: NSData.Base64DecodingOptions()) { return UIImage(data: imageData) } } return nil } public func persistedInt(_ forKey: String) -> Int? { return persistedObject(forKey) as? Int } }
mit
urbanthings/urbanthings-sdk-apple
UTAPIObjCAdapter/Public/TransitDetailedRouteInfo.swift
1
883
// // TransitDetailedRouteInfo.swift // UrbanThingsAPI // // Created by Mark Woollard on 15/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation import UTAPI /// Contains detailed information for a transit route. /// /// Extends `TransitRouteInfo` @objc public protocol TransitDetailedRouteInfo : TransitRouteInfo { /// Detailed description of the route, optional. var routeDescription:String? { get } } @objc public class UTTransitDetailedRouteInfo : UTTransitRouteInfo, TransitDetailedRouteInfo { var transitDetailedRouteInfo: UTAPI.TransitDetailedRouteInfo { return self.adapted as! UTAPI.TransitDetailedRouteInfo } public init?(adapt: UTAPI.TransitDetailedRouteInfo) { super.init(adapt: adapt) } public var routeDescription: String? { return self.transitDetailedRouteInfo.routeDescription } }
apache-2.0
charlymr/JTAppleCalendar
Example/JTAppleCalendar/CodeWhiteSectionHeaderView.swift
1
945
// // CodeWhiteSectionHeaderView.swift // JTAppleCalendar // // Created by Jeron Thomas on 2016-07-15. // Copyright © 2016 CocoaPods. All rights reserved. // import JTAppleCalendar class CodeWhiteSectionHeaderView: JTAppleHeaderView { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.setFillColor(red: 1.0, green: 2.5, blue: 0.3, alpha: 1.0); let r1 = CGRect(x: 0 , y: 0, width: 25, height: 25); // Size context.addRect(r1); context.fillPath(); context.setStrokeColor(red: 1.0, green: 1.0, blue: 0.5, alpha: 1.0); context.addEllipse(inRect: CGRect(x: 0 , y: 0, width: 25, height: 25)); context.strokePath(); } }
mit
Incipia/Goalie
Goalie/GoalieKerningButton.swift
1
5617
// // GoalieKerningButton.swift // Goalie // // Created by Gregory Klein on 1/2/16. // Copyright © 2016 Incipia. All rights reserved. // import UIKit /*** IMPORTANT NOTE: This class is meant to be used for labels in a storyboard or XIB file ***/ class GoalieKerningButton: UIButton { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) guard let label = titleLabel else { return } let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.alignment = NSTextAlignment.center let attributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor, NSKernAttributeName : 3, NSParagraphStyleAttributeName : paragraphStyle ] as [String : Any] let highlightedAttributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5), NSKernAttributeName : 3, NSParagraphStyleAttributeName : paragraphStyle ] as [String : Any] let attributedString = NSAttributedString(string: label.text ?? "", attributes: attributes) let highlightedAttributedString = NSAttributedString(string: label.text ?? "", attributes: highlightedAttributes) UIView.performWithoutAnimation { () -> Void in self.setAttributedTitle(attributedString, for: UIControlState()) self.setAttributedTitle(highlightedAttributedString, for: .highlighted) } } func updateText(_ text: String, color: UIColor) { guard let label = titleLabel else { return } let attributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : color, NSKernAttributeName : 3, ] as [String : Any] let highlightedAttributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5), NSKernAttributeName : 3, ] as [String : Any] let attributedString = NSAttributedString(string: text, attributes: attributes) let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes) UIView.performWithoutAnimation { () -> Void in self.setAttributedTitle(attributedString, for: UIControlState()) self.setAttributedTitle(highlightedAttributedString, for: .highlighted) self.layoutIfNeeded() } } func updateText(_ text: String) { guard let label = titleLabel else { return } let attributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor, NSKernAttributeName : 1.5, ] as [String : Any] let highlightedAttributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5), NSKernAttributeName : 1.5, ] as [String : Any] let attributedString = NSAttributedString(string: text, attributes: attributes) let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes) UIView.performWithoutAnimation { () -> Void in self.setAttributedTitle(attributedString, for: UIControlState()) self.setAttributedTitle(highlightedAttributedString, for: .highlighted) self.layoutIfNeeded() } } func updateTextColor(_ color: UIColor) { guard let label = titleLabel else { return } guard let text = label.text else { return } let attributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : color, NSKernAttributeName : 3 ] as [String : Any] let highlightedAttributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5), NSKernAttributeName : 3 ] as [String : Any] let attributedString = NSAttributedString(string: text, attributes: attributes) let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes) UIView.performWithoutAnimation { () -> Void in self.setAttributedTitle(attributedString, for: UIControlState()) self.setAttributedTitle(highlightedAttributedString, for: .highlighted) self.layoutIfNeeded() } } func updateKerningValue(_ value: CGFloat) { guard let label = titleLabel else { return } guard let text = label.text else { return } let attributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor, NSKernAttributeName : value ] as [String : Any] let highlightedAttributes = [ NSFontAttributeName : label.font, NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5), NSKernAttributeName : value ] as [String : Any] let attributedString = NSAttributedString(string: text, attributes: attributes) let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes) UIView.performWithoutAnimation { () -> Void in self.setAttributedTitle(attributedString, for: UIControlState()) self.setAttributedTitle(highlightedAttributedString, for: .highlighted) self.layoutIfNeeded() } } }
apache-2.0
syershov/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Cian/PPCianCarouselCell.swift
1
3412
@objc(MWMPPCianCarouselCell) final class PPCianCarouselCell: MWMTableViewCell { @IBOutlet private weak var title: UILabel! { didSet { title.text = L("subtitle_rent") title.font = UIFont.bold14() title.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var more: UIButton! { didSet { more.setImage(#imageLiteral(resourceName: "logo_cian"), for: .normal) more.titleLabel?.font = UIFont.regular17() more.setTitleColor(UIColor.linkBlue(), for: .normal) } } @IBOutlet private weak var collectionView: UICollectionView! var data: [CianItemModel]? { didSet { updateCollectionView { [weak self] in self?.collectionView.reloadSections(IndexSet(integer: 0)) } } } fileprivate let kMaximumNumberOfElements = 5 fileprivate var delegate: MWMPlacePageButtonsProtocol? func config(delegate d: MWMPlacePageButtonsProtocol?) { delegate = d collectionView.contentOffset = .zero collectionView.delegate = self collectionView.dataSource = self collectionView.register(cellClass: CianElement.self) collectionView.reloadData() isSeparatorHidden = true backgroundColor = UIColor.clear } fileprivate func isLastCell(_ indexPath: IndexPath) -> Bool { return indexPath.item == collectionView.numberOfItems(inSection: indexPath.section) - 1 } override func didMoveToSuperview() { super.didMoveToSuperview() updateCollectionView(nil) } private func updateCollectionView(_ updates: (() -> Void)?) { guard let sv = superview else { return } let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let screenSize = { sv.size.width - layout.sectionInset.left - layout.sectionInset.right } let itemHeight: CGFloat = 136 let itemWidth: CGFloat if let data = data { if data.isEmpty { itemWidth = screenSize() } else { itemWidth = 160 } } else { itemWidth = screenSize() } layout.itemSize = CGSize(width: itemWidth, height: itemHeight) collectionView.performBatchUpdates(updates, completion: nil) } @IBAction fileprivate func onMore() { delegate?.openSponsoredURL(nil) } } extension PPCianCarouselCell: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withCellClass: CianElement.self, indexPath: indexPath) as! CianElement if let data = data { if data.isEmpty { cell.state = .error(onButtonAction: onMore) } else { let model = isLastCell(indexPath) ? nil : data[indexPath.item] cell.state = .offer(model: model, onButtonAction: { [unowned self] model in self.delegate?.openSponsoredURL(model?.pageURL) }) } } else { cell.state = .pending(onButtonAction: onMore) } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let data = data { if data.isEmpty { return 1 } else { return min(data.count, kMaximumNumberOfElements) + 1 } } else { return 1 } } }
apache-2.0
OrangeJam/iSchool
iSchoolTests/DataStoreTest.swift
1
3440
// // DataStoreTest.swift // iSchool // // Created by Kári Helgason on 08/09/14. // Copyright (c) 2014 OrangeJam. All rights reserved. // import UIKit import XCTest class DataStoreTests: XCTestCase { class DataStoreMock: DataStore { // Fetch classes from test page instead of the real page override func fetchClasses() { let testDataPath = NSBundle(forClass: ParserTests.self).pathForResource("timetable_normal", ofType: "html")! let data = NSData(contentsOfFile: testDataPath) classes = Parser.parseClasses(data!) } } override func setUp() { let filePath = NSBundle(forClass: self.dynamicType).pathForResource("TestCredentials", ofType:"plist") let credentials = NSDictionary(contentsOfFile:filePath!)! let username = credentials.valueForKey("Username") as String let password = credentials.valueForKey("Password") as String CredentialManager.sharedInstance.storeCredentials(username, password) super.setUp() } override func tearDown() { super.tearDown() } func testPostsNotificationOnFetchAssignments() { let notificationExpectation = expectationWithDescription("Should recieve notification") let observer = NSNotificationCenter.defaultCenter().addObserverForName( Notification.assignment.rawValue, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { _ in notificationExpectation.fulfill() } ) DataStore.sharedInstance.fetchAssignments() waitForExpectationsWithTimeout(10, handler: { _ in }) NSNotificationCenter.defaultCenter().removeObserver(observer) } func testGetClassesForDay() { let STOR = "Stöðuvélar og reiknanleiki" let ANDR = "App Development - Android" let dataStore = DataStoreMock() dataStore.fetchClasses() let classes = dataStore.getClassesForDay(WeekDay.Monday) XCTAssertEqual(classes.count, 5, "Classes for day not fetched correctly") if classes.count == 5 { XCTAssertEqual(classes[0].course, STOR, "First class on Monday should be STOR") XCTAssertEqual(classes[1].course, STOR, "Second class on Monday should be STOR") XCTAssertEqual(classes[2].course, ANDR, "Third class on Monday should be ANDR") XCTAssertEqual(classes[3].course, ANDR, "Fourth class on Monday should be ANDR") XCTAssertEqual(classes[4].course, ANDR, "Fifth class on Monday should be ANDR") } else { XCTFail("Could not check individual classes in testGetClassesForDay") } } func testGetClassesForToday() { let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! let components = calendar.components(.WeekdayCalendarUnit, fromDate: NSDate()) let today = components.weekday let dataStore = DataStoreMock() dataStore.fetchClasses() let classes = dataStore.getClassesForToday() for c in classes { let classComponents = calendar.components(.WeekdayCalendarUnit, fromDate: c.startDate) let classDay = classComponents.weekday XCTAssertEqual(today, classDay, "getClassesForToday does not return the correct classes") } } }
bsd-3-clause
kylebshr/ElegantPresentations
ElegantPresentationsTests/ElegantPresentationsTests.swift
1
1023
// // ElegantPresentationsTests.swift // ElegantPresentationsTests // // Created by Kyle Bashour on 2/21/16. // Copyright © 2016 Kyle Bashour. All rights reserved. // import XCTest @testable import ElegantPresentations class ElegantPresentationsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
RobotPajamas/ble113-ota-ios
ble113-ota/DeviceListViewController.swift
1
3111
// // ViewController.swift // ble113-ota // // Created by Suresh Joshi on 2016-06-13. // Copyright © 2016 Robot Pajamas. All rights reserved. // import UIKit import LGBluetooth class DeviceListViewController: UITableViewController { private static let cellIdentifier = "cellIdentifier" var scannedPeripherals = [BluegigaPeripheral]() override func viewDidLoad() { super.viewDidLoad() setupUi() initCoreBluetooth() } func setupUi() { self.refreshControl = UIRefreshControl() self.refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh") self.refreshControl!.addTarget(self, action: #selector(DeviceListViewController.scanForDevices), forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(refreshControl!) } // This is a nothing function, strictly here to initialize CoreBluetooth func initCoreBluetooth() { let callback: LGCentralManagerDiscoverPeripheralsCallback = { peripherals in NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(DeviceListViewController.scanForDevices), userInfo: nil, repeats: false) } LGCentralManager.sharedInstance().scanForPeripheralsByInterval(1, completion: callback) } // The bulk of the advertising data is done here func scanForDevices() { let callback: LGCentralManagerDiscoverPeripheralsCallback = { peripherals in self.refreshControl!.endRefreshing() for peripheral in peripherals { let p = peripheral as! LGPeripheral if p.name?.lowercaseString.containsString("robot pajamas") == true { let bluegigaPeripheral = BluegigaPeripheral(fromPeripheral: p) self.scannedPeripherals.append(bluegigaPeripheral) } } self.tableView.reloadData() } print("Start scanning...") scannedPeripherals.removeAll() LGCentralManager.sharedInstance().scanForPeripheralsByInterval(5, completion: callback) } // MARK: UITableViewDataSource methods override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return scannedPeripherals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(DeviceListViewController.cellIdentifier) let peripheral = scannedPeripherals[indexPath.row] cell!.textLabel?.text = peripheral.name return cell! } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "goToFirmwareUpdate" { let path = self.tableView.indexPathForSelectedRow! let peripheral = scannedPeripherals[path.row] let destination = segue.destinationViewController as! FirmwareUpdateViewController destination.peripheral = peripheral } } }
mit
njdehoog/Spelt
Sources/Spelt/SiteServer.swift
1
894
import GCDWebServers public class SiteServer { private lazy var server = GCDWebServer()! let directoryPath: String let indexFilename: String public init(directoryPath: String, indexFilename: String = "index.html") { self.directoryPath = directoryPath self.indexFilename = indexFilename // log only warnings, errors and exceptions GCDWebServer.setLogLevel(3) server.addGETHandler(forBasePath: "/", directoryPath: directoryPath, indexFilename: indexFilename , cacheAge: 0, allowRangeRequests: true) } deinit { server.stop() } open func run() throws { try server.run(options: [:]) } open func start(port: Int = 0) throws -> (URL, UInt) { try server.start(options: [GCDWebServerOption_Port : port]) return (server.serverURL!, server.port) } }
mit
arrrnas/vinted-ab-ios
Carthage/Checkouts/CryptoSwift/Tests/CryptoSwiftTests/RandomBytesSequenceTests.swift
2
556
// // RandomBytesSequenceTests.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 10/10/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // import XCTest @testable import CryptoSwift class RandomBytesSequenceTests: XCTestCase { func testSequence() { XCTAssertNil(RandomBytesSequence(size: 0).makeIterator().next()) for value in RandomBytesSequence(size: 100) { XCTAssertTrue(value <= UInt8.max) } } static let allTests = [ ("testSequence", testSequence), ] }
mit
XWJACK/Music
Music/Modules/Player/PlayerModel.swift
1
965
// // PlayerModel.swift // Music // // Created by Jack on 3/16/17. // Copyright © 2017 Jack. All rights reserved. // import UIKit //struct MusicPlayerResponse { // // struct Music { //// var data = Data() // var response: ((Data) -> ())? = nil // var progress: ((Progress) -> ())? = nil // // init(response: ((Data) -> ())? = nil, // progress: ((Progress) -> ())? = nil) { // // self.response = response // self.progress = progress // } // } // // struct Lyric { // var success: ((String) -> ())? = nil // init(success: ((String) -> ())? = nil) { // // self.success = success // } // } // // var music: Music // var lyric: Lyric // // var failed: ((Error) -> ())? = nil // // init(music: Music, lyric: Lyric) { // self.music = music // self.lyric = lyric // } //}
mit
shajrawi/swift
stdlib/public/core/UTF8.swift
1
12373
//===--- UTF8.swift -------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Unicode { @_frozen public enum UTF8 { case _swift3Buffer(Unicode.UTF8.ForwardParser) } } extension Unicode.UTF8 { /// Returns the number of code units required to encode the given Unicode /// scalar. /// /// Because a Unicode scalar value can require up to 21 bits to store its /// value, some Unicode scalars are represented in UTF-8 by a sequence of up /// to 4 code units. The first code unit is designated a *lead* byte and the /// rest are *continuation* bytes. /// /// let anA: Unicode.Scalar = "A" /// print(anA.value) /// // Prints "65" /// print(UTF8.width(anA)) /// // Prints "1" /// /// let anApple: Unicode.Scalar = "🍎" /// print(anApple.value) /// // Prints "127822" /// print(UTF8.width(anApple)) /// // Prints "4" /// /// - Parameter x: A Unicode scalar value. /// - Returns: The width of `x` when encoded in UTF-8, from `1` to `4`. @_alwaysEmitIntoClient public static func width(_ x: Unicode.Scalar) -> Int { switch x.value { case 0..<0x80: return 1 case 0x80..<0x0800: return 2 case 0x0800..<0x1_0000: return 3 default: return 4 } } } extension Unicode.UTF8 : _UnicodeEncoding { public typealias CodeUnit = UInt8 public typealias EncodedScalar = _ValidUTF8Buffer @inlinable public static var encodedReplacementCharacter : EncodedScalar { return EncodedScalar.encodedReplacementCharacter } @inline(__always) @inlinable public static func _isScalar(_ x: CodeUnit) -> Bool { return isASCII(x) } /// Returns whether the given code unit represents an ASCII scalar @_alwaysEmitIntoClient @inline(__always) public static func isASCII(_ x: CodeUnit) -> Bool { return x & 0b1000_0000 == 0 } @inline(__always) @inlinable public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { switch source.count { case 1: return Unicode.Scalar(_unchecked: source._biasedBits &- 0x01) case 2: let bits = source._biasedBits &- 0x0101 var value = (bits & 0b0_______________________11_1111__0000_0000) &>> 8 value |= (bits & 0b0________________________________0001_1111) &<< 6 return Unicode.Scalar(_unchecked: value) case 3: let bits = source._biasedBits &- 0x010101 var value = (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 16 value |= (bits & 0b0_______________________11_1111__0000_0000) &>> 2 value |= (bits & 0b0________________________________0000_1111) &<< 12 return Unicode.Scalar(_unchecked: value) default: _internalInvariant(source.count == 4) let bits = source._biasedBits &- 0x01010101 var value = (bits & 0b0_11_1111__0000_0000__0000_0000__0000_0000) &>> 24 value |= (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 10 value |= (bits & 0b0_______________________11_1111__0000_0000) &<< 4 value |= (bits & 0b0________________________________0000_0111) &<< 18 return Unicode.Scalar(_unchecked: value) } } @inline(__always) @inlinable public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { var c = source.value if _fastPath(c < (1&<<7)) { return EncodedScalar(_containing: UInt8(c)) } var o = c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<5)) { return EncodedScalar(_biasedBits: (o | c) &+ 0b0__1000_0001__1100_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<4)) { return EncodedScalar( _biasedBits: (o | c) &+ 0b0__1000_0001__1000_0001__1110_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 return EncodedScalar( _biasedBits: (o | c ) &+ 0b0__1000_0001__1000_0001__1000_0001__1111_0001) } @inlinable @inline(__always) public static func transcode<FromEncoding : _UnicodeEncoding>( _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type ) -> EncodedScalar? { if _fastPath(FromEncoding.self == UTF16.self) { let c = _identityCast(content, to: UTF16.EncodedScalar.self) var u0 = UInt16(truncatingIfNeeded: c._storage) if _fastPath(u0 < 0x80) { return EncodedScalar(_containing: UInt8(truncatingIfNeeded: u0)) } var r = UInt32(u0 & 0b0__11_1111) r &<<= 8 u0 &>>= 6 if _fastPath(u0 < (1&<<5)) { return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1100_0001) } r |= UInt32(u0 & 0b0__11_1111) r &<<= 8 if _fastPath(u0 & (0xF800 &>> 6) != (0xD800 &>> 6)) { u0 &>>= 6 return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1000_0001__1110_0001) } } else if _fastPath(FromEncoding.self == UTF8.self) { return _identityCast(content, to: UTF8.EncodedScalar.self) } return encode(FromEncoding.decode(content)) } @_fixed_layout public struct ForwardParser { public typealias _Buffer = _UIntBuffer<UInt8> @inline(__always) @inlinable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } @_fixed_layout public struct ReverseParser { public typealias _Buffer = _UIntBuffer<UInt8> @inline(__always) @inlinable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } } extension UTF8.ReverseParser : Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @inlinable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1110_0000__1100_0000 == 0b0__1100_0000__1000_0000 { // 2-byte sequence. Top 4 bits of decoded result must be nonzero let top4Bits = _buffer._storage & 0b0__0001_1110__0000_0000 if _fastPath(top4Bits != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1111_0000__1100_0000__1100_0000 == 0b0__1110_0000__1000_0000__1000_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000__0000_0000 if _fastPath( top5Bits != 0 && top5Bits != 0b0__1101__0010_0000__0000_0000) { return (true, 3*8) } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000__1000_0000 { // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000__0000_0000 if _fastPath( top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that ends with the LSB of /// buffer. @inline(never) @usableFromInline internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1111_0000__1100_0000 == 0b0__1110_0000__1000_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000 if top5Bits != 0 && top5Bits != 0b0__1101__0010_0000 { return 2 } } else if _buffer._storage & 0b1111_1000__1100_0000 == 0b1111_0000__1000_0000 { // 2-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000 { return 2 } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000 { // 3-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000 { return 3 } } return 1 } @inline(__always) @inlinable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(truncatingIfNeeded: _buffer._storage.byteSwapped) let shift = 32 &- bitCount return Encoding.EncodedScalar(_biasedBits: (x &+ 0x01010101) &>> shift) } } extension Unicode.UTF8.ForwardParser : Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @inlinable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1100_0000__1110_0000 == 0b0__1000_0000__1100_0000 { // 2-byte sequence. At least one of the top 4 bits of the decoded result // must be nonzero. if _fastPath(_buffer._storage & 0b0_0001_1110 != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1111_0000 == 0b0__1000_0000__1000_0000__1110_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0___0010_0000__0000_1111 if _fastPath(top5Bits != 0 && top5Bits != 0b0___0010_0000__0000_1101) { return (true, 3*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1100_0000__1111_1000 == 0b0__1000_0000__1000_0000__1000_0000__1111_0000 { // 4-byte sequence. The top 5 bits of the decoded result must be nonzero // and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if _fastPath( top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that starts with the LSB of /// buffer. @inline(never) @usableFromInline internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if _buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 { return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } @inlinable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(_buffer._storage) &+ 0x01010101 return _ValidUTF8Buffer(_biasedBits: x & ._lowBits(bitCount)) } }
apache-2.0
doncl/shortness-of-pants
BBPTable/BBPTable/BBPTableViewController.swift
1
7746
// // ViewController.swift // BBPTable // // Created by Don Clore on 8/3/15. // Copyright (c) 2015 Beer Barrel Poker Studios. All rights reserved. // import UIKit enum TableLoadMode { case defaultView case createView } class BBPTableViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { //MARK: properties var tableProperties: TableProperties? var model: BBPTableModel? var nonFixedView: UICollectionView? var fixedView: UICollectionView? var fixedModel: BBPTableModel? var nonFixedModel: BBPTableModel? var loadMode: TableLoadMode var viewWidth: CGFloat? //MARK: Initialization init(loadMode: TableLoadMode) { self.loadMode = loadMode super.init(nibName: nil, bundle: nil) } convenience init(loadMode: TableLoadMode, width: CGFloat) { self.init(loadMode: loadMode) viewWidth = width } required init?(coder aDecoder: NSCoder) { loadMode = .defaultView super.init(coder: aDecoder) } override func loadView() { BBPTableCell.initializeCellProperties(tableProperties!) BBPTableModel.buildFixedAndNonFixedModels(model!, fixedColumnModel: &fixedModel, nonFixedColumnModel: &nonFixedModel, fixedColumnCount: tableProperties!.fixedColumns!) let fixedLayout = BBPTableLayout() fixedLayout.calculateCellSizes(fixedModel!) let nonFixedLayout = BBPTableLayout() nonFixedLayout.calculateCellSizes(nonFixedModel!) if loadMode == .defaultView { super.loadView() // Go ahead and call superclass to get a plain vanilla UIView. } else { let frame = CGRect(x: 0, y:0, width:viewWidth!, height: fixedLayout.tableHeight!) self.view = UIView(frame: frame) } fixedView = createCollectionView(view, layout: fixedLayout, x: 0.0, width: fixedLayout.tableWidth!, fixed: true) let nonFixedX = view.frame.origin.x + fixedLayout.tableWidth! let nonFixedWidth = view.frame.size.width - nonFixedX nonFixedView = createCollectionView(view, layout: nonFixedLayout, x: nonFixedX, width: nonFixedWidth, fixed: false) nonFixedView!.isScrollEnabled = true nonFixedView!.showsHorizontalScrollIndicator = true } fileprivate func createCollectionView(_ parentView: UIView, layout: BBPTableLayout, x: CGFloat, width: CGFloat, fixed: Bool) -> UICollectionView { // N.B. There's some hackery here to compensate for the fact that this control wasn't // written with autolayout (more's the pity). It was early on - I'd only been doing // iOS for about 5 months, and I shied away from doing AutoLayout in code. There's // some tech debt here - I've just patched it up well enough to work for now. var tabBarOffset : CGFloat = 0.0 var navBarOffset : CGFloat = 0.0 if let nav = navigationController { navBarOffset += nav.navigationBar.frame.height } if let tab = tabBarController { tabBarOffset += tab.tabBar.frame.height } let statusBarOffset = UIApplication.shared.statusBarFrame.height let height = parentView.frame.height - (navBarOffset + tabBarOffset + statusBarOffset) let frame = CGRect(x: x, y:parentView.frame.origin.y + navBarOffset + statusBarOffset, width:width, height: height) let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) parentView.addSubview(collectionView) collectionView.bounces = false collectionView.showsVerticalScrollIndicator = false collectionView.delegate = self collectionView.dataSource = self collectionView.register(BBPTableCell.self, forCellWithReuseIdentifier: "cellIdentifier") collectionView.backgroundColor = UIColor.white collectionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.topAnchor), collectionView.leftAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.leftAnchor, constant: x), collectionView.bottomAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.bottomAnchor), ]) if fixed { collectionView.widthAnchor.constraint(equalToConstant: width).isActive = true } else { collectionView.rightAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.rightAnchor).isActive = true } return collectionView } //MARK: Handling synchronized scrolling. func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == fixedView! { matchScrollView(nonFixedView!, second:fixedView!) } else { matchScrollView(fixedView!, second: nonFixedView!) } } fileprivate func matchScrollView(_ first: UIScrollView, second: UIScrollView) { var offset = first.contentOffset offset.y = second.contentOffset.y first.setContentOffset(offset, animated:false) } //MARK: UICollectionViewDataSource methods func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let model = getModel(collectionView) return model.numberOfColumns } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let model = getModel(collectionView) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath) as! BBPTableCell let layout = collectionView.collectionViewLayout as! BBPTableLayout let columnIdx = indexPath.row let rowIdx = indexPath.section let cellData = model.dataAtLocation(rowIdx, column: columnIdx) let cellType = getCellType(indexPath) cell.setupCellInfo(cellType) cell.setCellText(cellData) let columnWidth = layout.columnWidths[columnIdx] cell.contentView.bounds = CGRect(x:0, y:0, width:columnWidth, height: layout.rowHeight!) return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { let model = getModel(collectionView) return model.numberOfRows } fileprivate func getCellType(_ indexPath: IndexPath) -> CellType { var cellType: CellType if indexPath.section == 0 { cellType = .columnHeading } else if ((indexPath.section + 1) % 2) == 0 { cellType = .dataEven } else { cellType = .dataOdd } return cellType } fileprivate func getModel(_ view: UICollectionView) -> BBPTableModel { if (view == fixedView!) { return fixedModel! } else { return nonFixedModel! } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) guard let nonFixed = nonFixedView, let fixed = fixedView else { return } nonFixed.collectionViewLayout.invalidateLayout() fixed.collectionViewLayout.invalidateLayout() coordinator.animate(alongsideTransition: { ctxt in nonFixed.layoutIfNeeded() fixed.layoutIfNeeded() }, completion: nil) } }
mit
telip007/ChatFire
ChatFire/Modals/User.swift
1
1293
// // User.swift // ChatFire // // Created by Talip Göksu on 05.09.16. // Copyright © 2016 ChatFire. All rights reserved. // import Firebase import Foundation private let userCache = NSCache() class User: NSObject { var email: String? var username: String? var partners: [String: AnyObject]? var chats: [String: AnyObject]? var profile_image: String? var uid: String? class func userFromId(id: String, user: (User) -> ()){ if let cachedUser = userCache.objectForKey(id) as? User{ user(cachedUser) } else{ let userRef = ref?.child("users/\(id)") userRef?.observeSingleEventOfType(.Value, withBlock: { (data) in if let userData = data.value as? [String: AnyObject]{ let retUser = User() retUser.setValuesForKeysWithDictionary(userData) userCache.setObject(retUser, forKey: id) user(retUser) } else{ fatalError("What went wrong here ?") } }) } } class func getCurrentUser(data: (User) -> ()){ userFromId(currentUser!.uid) { (user) in data(user) } } }
apache-2.0
Moya/Moya
Package.swift
1
2989
// swift-tools-version:5.3 import PackageDescription let rocketIfNeeded: [Package.Dependency] #if os(OSX) || os(Linux) rocketIfNeeded = [ .package(url: "https://github.com/shibapm/Rocket", .upToNextMajor(from: "1.2.0")) // dev ] #else rocketIfNeeded = [] #endif let package = Package( name: "Moya", platforms: [ .macOS(.v10_12), .iOS(.v10), .tvOS(.v10), .watchOS(.v3) ], products: [ .library(name: "Moya", targets: ["Moya"]), .library(name: "CombineMoya", targets: ["CombineMoya"]), .library(name: "ReactiveMoya", targets: ["ReactiveMoya"]), .library(name: "RxMoya", targets: ["RxMoya"]) ], dependencies: [ .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.0.0")), .package(url: "https://github.com/ReactiveCocoa/ReactiveSwift.git", .upToNextMajor(from: "6.0.0")), .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.0.0")), .package(url: "https://github.com/Quick/Quick.git", .upToNextMajor(from: "4.0.0")), // dev .package(url: "https://github.com/Quick/Nimble.git", .upToNextMajor(from: "9.0.0")), // dev .package(url: "https://github.com/AliSoftware/OHHTTPStubs.git", .upToNextMajor(from: "9.0.0")) // dev ] + rocketIfNeeded, targets: [ .target( name: "Moya", dependencies: [ .product(name: "Alamofire", package: "Alamofire") ], exclude: [ "Supporting Files/Info.plist" ] ), .target( name: "CombineMoya", dependencies: [ "Moya" ] ), .target( name: "ReactiveMoya", dependencies: [ "Moya", .product(name: "ReactiveSwift", package: "ReactiveSwift") ] ), .target( name: "RxMoya", dependencies: [ "Moya", .product(name: "RxSwift", package: "RxSwift") ] ), .testTarget( // dev name: "MoyaTests", // dev dependencies: [ // dev "Moya", // dev "CombineMoya", // dev "ReactiveMoya", // dev "RxMoya", // dev .product(name: "Quick", package: "Quick"), // dev .product(name: "Nimble", package: "Nimble"), // dev .product(name: "OHHTTPStubsSwift", package: "OHHTTPStubs") // dev ] // dev ) // dev ] ) #if canImport(PackageConfig) import PackageConfig let config = PackageConfiguration([ "rocket": [ "before": [ "scripts/update_changelog.sh", "scripts/update_podspec.sh" ], "after": [ "rake create_release\\[\"$VERSION\"\\]", "scripts/update_docs_website.sh" ] ] ]).write() #endif
mit
IngmarStein/swift
benchmark/single-source/Phonebook.swift
4
2427
//===--- Phonebook.swift --------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // This test is based on util/benchmarks/Phonebook, with modifications // for performance measuring. import TestsUtils var words = [ "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony", "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott", "Justin", "Raymond", "Brandon", "Gregory", "Samuel", "Patrick", "Benjamin", "Jack", "Dennis", "Jerry", "Alexander", "Tyler", "Douglas", "Henry", "Peter", "Walter", "Aaron", "Jose", "Adam", "Harold", "Zachary", "Nathan", "Carl", "Kyle", "Arthur", "Gerald", "Lawrence", "Roger", "Albert", "Keith", "Jeremy", "Terry", "Joe", "Sean", "Willie", "Jesse", "Ralph", "Billy", "Austin", "Bruce", "Christian", "Roy", "Bryan", "Eugene", "Louis", "Harry", "Wayne", "Ethan", "Jordan", "Russell", "Alan", "Philip", "Randy", "Juan", "Howard", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Craig" ] // This is a phone book record. struct Record : Comparable { var first: String var last: String init(_ first_ : String,_ last_ : String) { first = first_ last = last_ } } func ==(lhs: Record, rhs: Record) -> Bool { return lhs.last == rhs.last && lhs.first == rhs.first } func <(lhs: Record, rhs: Record) -> Bool { if lhs.last < rhs.last { return true } if lhs.last > rhs.last { return false } if lhs.first < rhs.first { return true } return false } @inline(never) public func run_Phonebook(_ N: Int) { // The list of names in the phonebook. var Names : [Record] = [] for first in words { for last in words { Names.append(Record(first, last)) } } for _ in 1...N { var t = Names t.sort() } }
apache-2.0
tobiasstraub/bwinf-releases
BwInf 34 (2015-2016)/Runde 2/Aufgabe 2/Marian/Source/main.swift
2
1885
import Foundation import Darwin let task = TaskReader().read() // Asynchron die Befehle abfragen: dispatch_async(dispatch_queue_create("missglueckte_drohnenlieferung_commands", DISPATCH_QUEUE_CONCURRENT)) { print("Verwende 'help' für eine Übersicht der Befehle.") while true { if let input = readLine() { if input == "h" || input == "help" { print("help / h - Hilfeübersicht anzeigen") print("quit / q - Programm beenden") print("info / i - Aktuell beste Schrittanzahl anzeigen") print("save / s - Bisher beste Lösung speichern") } else if input == "q" || input == "quit" { exit(0) } else if input == "i" || input == "info" { if let bestSolution = task.bestSolution { print("Die beste gefundene Lösung benötigt \(bestSolution.moves[0][0].characters.count) Schritte.") } else { print("Es wurde noch keine Lösung gefunden.") } } else if input == "s" || input == "save" { if let bestSolution = task.bestSolution { do { try bestSolution.solutionString.writeToFile("solution.txt", atomically: false, encoding: NSUTF8StringEncoding) print("Die zurzeit beste Lösung wurde in der Datei 'solution.txt' gespeichert.") } catch { print("Die Datei konnte nicht erstellt werden.") } } else { print("Es wurde noch keine Lösung gefunden.") } } } } } task.run() print("Das Programm ist nun fertig. Es können weiterhin Befehle eingegeben werden.") // Endlosschleife, damit weiterhin Befehle abgefragt werden können: while true {}
gpl-3.0
kperson/FSwift
FSwiftTests/Time/DateTests.swift
1
608
// // DateTests.swift // FSwift // // Created by Kelton Person on 1/17/17. // Copyright © 2017 Kelton. All rights reserved. // import XCTest class DateTest: XCTestCase { let small = Date(timeIntervalSince1970: 0) let big = Date(timeIntervalSince1970: 10) let equalSmall = Date(timeIntervalSince1970: 0) let equalBig = Date(timeIntervalSince1970: 10) func greaterThanOrEqual() { XCTAssert(big >= small) XCTAssert(big >= equalBig) } func lessThanOrEqualEqual() { XCTAssert(small <= big) XCTAssert(small <= equalSmall) } }
mit
iOSDevLog/iOSDevLog
2048-Xcode7/2048/ModelSingleton.swift
1
701
// // ModelSingleton.swift // 2048 // // Created by JiaXianhua on 15/9/14. // Copyright (c) 2015年 jiaxianhua. All rights reserved. // import UIKit class ModelSingleton: NSObject { var tiles: Dictionary<NSIndexPath, Int>! let dimension: Int = 4 let threshold: Int = 2048 class var sharedInstance : ModelSingleton { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : ModelSingleton? = nil } dispatch_once(&Static.onceToken) { Static.instance = ModelSingleton() Static.instance?.tiles = Dictionary<NSIndexPath, Int>() } return Static.instance! } }
mit
ivanbruel/TextStyle
Example/TextStyle/ViewController.swift
1
1168
// // ViewController.swift // TextStyle // // Created by Ivan Bruel on 09/01/2016. // Copyright (c) 2016 Ivan Bruel. All rights reserved. // import UIKit import TextStyle import RxSwift class ViewController: UIViewController { @IBOutlet var labels: [UILabel]! fileprivate let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let textStyles: [TextStyle] = [.title1, .title2, .headline, .subheadline, .body, .caption1, .caption2, .footnote, .callout] let texts: [String] = ["Title1", "Title2", "Headline", "Subheadline", "Body", "Caption1", "Caption2", "Footnote", "Callout"] for index in 0..<labels.count { let label = labels[index] let textStyle = textStyles[index] let text = texts[index] label.text = text textStyle.rx_font.bindTo(label.rx.font) .addDisposableTo(disposeBag) } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
johnno1962d/swift
test/SILGen/generic_closures.swift
1
6121
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s import Swift var zero: Int // CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}} func generic_nondependent_context<T>(_ x: T, y: Int) -> Int { func foo() -> Int { return y } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo() } // CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}} func generic_capture<T>(_ x: T) -> Any.Type { func foo() -> Any.Type { return T.self } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo() } // CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}} func generic_capture_cast<T>(_ x: T, y: Any) -> Bool { func foo(_ a: Any) -> Bool { return a is T } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo(y) } protocol Concept { var sensical: Bool { get } } // CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}} func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool { func foo(_ a: Concept) -> Bool { return a.sensical } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] return foo(y) } // CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}} func generic_dependent_context<T>(_ x: T, y: Int) -> T { func foo() -> T { return x } // CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T> return foo() } enum Optionable<Wrapped> { case none case some(Wrapped) } class NestedGeneric<U> { class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int { func foo() -> Int { return y } return foo() } class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T { func foo() -> T { return x } return foo() } class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U { func foo() -> U { return z } return foo() } class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) { func foo() -> (T, U) { return (x, z) } return foo() } // CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}} // CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo___XFo_iT__iT__ // CHECK: partial_apply [[REABSTRACT]]<U, T> func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> { return .some({}) } } // <rdar://problem/15417773> // Ensure that nested closures capture the generic parameters of their nested // context. // CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@in T) -> @out T // CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]] // CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T // CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]] // CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T { func nested_closure_in_generic<T>(_ x:T) -> T { return { { x }() }() } // CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties func local_properties<T>(_ t: inout T) { // CHECK: [[TBOX:%[0-9]+]] = alloc_box $T var prop: T { get { return t } set { t = newValue } } // CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER_REF]] t = prop // CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0) -> () // CHECK: apply [[SETTER_REF]] prop = t var prop2: T { get { return t } set { // doesn't capture anything } } // CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER2_REF]] t = prop2 // CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () // CHECK: apply [[SETTER2_REF]] prop2 = t } protocol Fooable { static func foo() -> Bool } // <rdar://problem/16399018> func shmassert(_ f: @autoclosure () -> Bool) {} // CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param func capture_generic_param<A: Fooable>(_ x: A) { shmassert(A.foo()) } // Make sure we use the correct convention when capturing class-constrained // member types: <rdar://problem/24470533> class Class {} protocol HasClassAssoc { associatedtype Assoc : Class } // CHECK-LABEL: sil hidden @_TF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_ // CHECK: bb0(%0 : $*T, %1 : $@callee_owned (@owned T.Assoc) -> @owned T.Assoc): // CHECK: [[GENERIC_FN:%.*]] = function_ref @_TFF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_U_FT_FQQ_5AssocS2_ // CHECK: [[CONCRETE_FN:%.*]] = partial_apply [[GENERIC_FN]]<T, T.Assoc>(%1) func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: T.Assoc -> T.Assoc) { let _: () -> T.Assoc -> T.Assoc = { f } }
apache-2.0
wuyezhiguhun/DDMusicFM
DDMusicFM/DDFound/View/DDFindStyleLiveCell.swift
1
435
// // DDFindStyleLiveCell.swift // DDMusicFM // // Created by yutongmac on 2017/9/14. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class DDFindStyleLiveCell: DDFindBaseCell { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
apache-2.0
Hyfenglin/bluehouseapp
iOS/post/post/Constant.swift
1
736
// // Constant.swift // post // // Created by Derek Li on 14-10-8. // Copyright (c) 2014年 Derek Li. All rights reserved. // import Foundation //let HTTP_PATH:String = "http://192.168.1.101:8000/" let HTTP_PATH:String = "http://127.0.0.1:8000/" class Constant{ let URL_POST_LIST:String = "\(HTTP_PATH)post/" let URL_POST_CREATE:String = "\(HTTP_PATH)post/" let URL_POST_DETAIL:String = "\(HTTP_PATH)post/" let URL_COMMENT_LIST:String = "\(HTTP_PATH)post/" let URL_COMMENT_ADD:String = "\(HTTP_PATH)post/" let URL_COMMENT_DETAIL:String = "\(HTTP_PATH)postcomment/" let URL_USER_LOGIN:String = "\(HTTP_PATH)login/" let URL_USER_REGIST:String = "\(HTTP_PATH)post/" init(){ } }
mit
swiftingio/SwiftyStrings
SwiftyStrings/String+Localized.swift
1
835
// // String+Localized.swift // LocalizedStrings // // Created by Maciej Piotrowski on 12/11/16. // Copyright © 2016 Maciej Piotrowski. All rights reserved. // import Foundation func NSLocalizedString(_ key: String) -> String { return NSLocalizedString(key, comment: "") } //MARK: Welcome Screen extension String { static let Hello = NSLocalizedString("Hello!") static let ImpressMe = NSLocalizedString("Impress Me!") static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team") static let OpsNoFeature = NSLocalizedString("Oops! It looks like this feature haven't been implemented yet :(!") static let OK = NSLocalizedString("OK") } //MARK: Another Screen extension String { static let YetAnotherString = NSLocalizedString("Yet Another String") }
mit
JasonPan/ADSSocialFeedScrollView
ADSSocialFeedScrollViewTests/ADSSocialFeedScrollViewTests.swift
1
1051
// // ADSSocialFeedScrollViewTests.swift // ADSSocialFeedScrollViewTests // // Created by Jason Pan on 21/02/2016. // Copyright © 2016 ANT Development Studios. All rights reserved. // import XCTest @testable import ADSSocialFeedScrollView class ADSSocialFeedScrollViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
hejunbinlan/Panoramic
Panoramic/Panoramic/AppDelegate.swift
1
2401
// // AppDelegate.swift // Panoramic // // Created by Sameh Mabrouk on 12/16/14. // Copyright (c) 2014 SMApps. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { var panoramaVC : PanoramaViewController? = PanoramaViewController() window = UIWindow(frame: UIScreen.mainScreen().bounds) if let window = window { window.backgroundColor = UIColor.orangeColor() window.makeKeyAndVisible() window.rootViewController = panoramaVC } 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:. } }
mit
dduan/swift
validation-test/compiler_crashers_fixed/00999-swift-parser-skipsingle.swift
11
687
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct S : NSObject { func b<h : b, e where l) -> (x: l) { func g<T { return S) { class c) { class func d) in x in a { } protocol P { convenience init() { struct d>({ [T.E == """"[1)) { _, f: b) -> V { typealias B { struct D : AnyObject.h : (x) -> (T>? = c) { enum S<T, e = b([1]] return ") } }
apache-2.0
applivery/applivery-ios-sdk
AppliveryBehaviorTests/Mocks/ConfigPersisterMock.swift
1
457
// // ConfigPersisterMock.swift // AppliverySDK // // Created by Alejandro Jiménez on 5/10/15. // Copyright © 2015 Applivery S.L. All rights reserved. // import UIKit @testable import Applivery class ConfigPersisterMock: ConfigPersister { // INPUT var config: Config? // OUTPUT var saveCalled = false override func getConfig() -> Config? { return self.config } override func saveConfig(_ config: Config) { self.saveCalled = true } }
mit
sswierczek/Helix-Movie-Guide-iOS
Helix Movie Guide/GetMovieVideosUseCase.swift
1
419
// // GetMovieVideosUseCase.swift // Helix Movie Guide // // Created by Sebastian Swierczek on 08/03/2017. // Copyright © 2017 user. All rights reserved. // import RxSwift class GetMovieVideosUseCase { private let api: MovieApi public init(api: MovieApi) { self.api = api } func execute(movieId: Int) -> Observable<[Video]> { return api.getVideos(movieId: movieId) } }
apache-2.0
Ramotion/gliding-collection
Package.swift
1
1575
// swift-tools-version:5.1 // // Package.swift // // Copyright (c) Ramotion (https://www.ramotion.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import PackageDescription let package = Package( name: "GlidingCollection", platforms: [ .iOS(.v8) ], products: [ .library(name: "GlidingCollection", targets: ["GlidingCollection"]), ], targets: [ .target(name: "GlidingCollection", path: "GlidingCollection") ], swiftLanguageVersions: [.v5] )
mit
BirdBrainTechnologies/Hummingbird-iOS-Support
BirdBlox/BirdBlox/PropertiesRequests.swift
1
1453
// // PropertiesRequests.swift // BirdBlox // // Created by Jeremy Huang on 2017-05-22. // Copyright © 2017年 Birdbrain Technologies LLC. All rights reserved. // import Foundation import UIKit //import Swifter class PropertiesManager { var heightInPoints: CGFloat = 300.0 var widthInPoints: CGFloat = 300.0 func loadRequests(server: BBTBackendServer){ server["/properties/dims"] = self.getPhysicalDims server["/properties/os"] = self.getVersion } func mmFromPoints(p:CGFloat) -> CGFloat { let mmPerPoint = BBTThisIDevice.milimetersPerPointFor(deviceModel: BBTThisIDevice.platformModelString()) return p * mmPerPoint } func getPhysicalDims(request: HttpRequest) -> HttpResponse { DispatchQueue.main.sync { let window = UIApplication.shared.delegate?.window let heightInPoints = window??.bounds.height ?? UIScreen.main.bounds.height let widthInPoints = window??.bounds.width ?? UIScreen.main.bounds.width self.heightInPoints = heightInPoints self.widthInPoints = widthInPoints } let height = mmFromPoints(p: self.heightInPoints) let width = mmFromPoints(p: self.widthInPoints) return .ok(.text("\(width),\(height)")) } func getVersion(request: HttpRequest) -> HttpResponse { let os = "iOS" let version = ProcessInfo().operatingSystemVersion return .ok(.text("\(os) " + "(\(version.majorVersion).\(version.minorVersion).\(version.patchVersion))")) } }
mit
guipanizzon/ioscreator
IOS8SwiftSliderTutorial/IOS8SwiftSliderTutorial/AppDelegate.swift
40
2104
// // AppDelegate.swift // IOS8SwiftSliderTutorial // // Created by Arthur Knopper on 15/09/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit @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:. } }
mit
sarvex/SwiftRecepies
Cloud/Storing and Synchronizing Dictionaries in iCloud/Storing and Synchronizing Dictionaries in iCloud/AppDelegate.swift
1
2040
// // AppDelegate.swift // Storing and Synchronizing Dictionaries in iCloud // // Created by vandad on 207//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? /* Checks if the user has logged into her iCloud account or not */ func isIcloudAvailable() -> Bool{ if let token = NSFileManager.defaultManager().ubiquityIdentityToken{ return true } else { return false } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { if isIcloudAvailable() == false{ println("iCloud is not available") return true } let kvoStore = NSUbiquitousKeyValueStore.defaultStore() var stringValue = "My String" let stringValueKey = "MyStringKey" var boolValue = true let boolValueKey = "MyBoolKey" var mustSynchronize = false if kvoStore.stringForKey(stringValueKey) == nil{ println("Could not find the string value in iCloud. Setting...") kvoStore.setString(stringValue, forKey: stringValueKey) mustSynchronize = true } else { stringValue = kvoStore.stringForKey(stringValueKey)! println("Found the string in iCloud = \(stringValue)") } if kvoStore.boolForKey(boolValueKey) == false{ println("Could not find the boolean value in iCloud. Setting...") kvoStore.setBool(boolValue, forKey: boolValueKey) mustSynchronize = true } else { println("Found the boolean in iCloud, getting...") boolValue = kvoStore.boolForKey(boolValueKey) } if mustSynchronize{ if kvoStore.synchronize(){ println("Successfully synchronized with iCloud.") } else { println("Failed to synchronize with iCloud.") } } return true } }
isc
JOCR10/iOS-Curso
Quices/Quiz 3/Quiz 3/EnterNumberViewController.swift
1
2078
// // EnterNumberViewController.swift // Quiz 3 // // Created by Local User on 5/23/17. // Copyright © 2017 Local User. All rights reserved. // import UIKit class EnterNumberViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var textFieldValue: UITextField! var numbers = [String]() override func viewDidLoad() { super.viewDidLoad() tableView.registerCustomCell(identifier: NumberCustomCell.getCellIdentifier()) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func buttonAction(_ sender: Any) { if((textFieldValue.text?.characters.count)! > 0 ) { numbers.append(textFieldValue.text!) tableView.reloadData() } } } extension EnterNumberViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: NumberCustomCell.getCellIdentifier()) as! NumberCustomCell let value = numbers[indexPath.row] cell.labelText?.text = "\(value)" return cell } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } }
mit
64characters/Telephone
ReceiptValidationTests/ReceiptChecksumTests.swift
1
2638
// // ReceiptChecksumTests.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import XCTest final class ReceiptChecksumTests: XCTestCase { func testCanCreate() { XCTAssertNotNil(ReceiptChecksum(sha1: Data())) } func testComputesSHA1FromConcatenatedArguments() { // $ echo -n c00010ffb105f00d000ff1ce | xxd -r -p | sha1sum -b | xxd -r -p | xxd -i XCTAssertEqual( ReceiptChecksum( guid: Data([0xc0, 0x00, 0x10, 0xff]), opaque: Data([0xb1, 0x05, 0xf0, 0x0d]), identifier: Data([0x00, 0x0f, 0xf1, 0xce]) ), ReceiptChecksum( sha1: Data( [ 0xfa, 0x47, 0x40, 0x18, 0x26, 0xc2, 0xe9, 0x76, 0x2e, 0xfa, 0x88, 0xe3, 0xa1, 0x96, 0x61, 0x74, 0x5f, 0xc8, 0x35, 0xbf ] ) ) ) // $ echo -n 000102030405060708090a0b0c0d0e0f | xxd -r -p | sha1sum -b | xxd -r -p | xxd -i XCTAssertEqual( ReceiptChecksum( guid: Data([0x00, 0x01, 0x02, 0x03, 0x04]), opaque: Data([0x05, 0x06, 0x07, 0x08]), identifier: Data([0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]) ), ReceiptChecksum( sha1: Data( [ 0x56, 0x17, 0x8b, 0x86, 0xa5, 0x7f, 0xac, 0x22, 0x89, 0x9a, 0x99, 0x64, 0x18, 0x5c, 0x2c, 0xc9, 0x6e, 0x7d, 0xa5, 0x89 ] ) ) ) // $ echo -n "" | sha1sum | xxd -r -p | xxd -i XCTAssertEqual( ReceiptChecksum(guid: Data(), opaque: Data(), identifier: Data()), ReceiptChecksum( sha1: Data( [ 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 ] ) ) ) } }
gpl-3.0
StratusHunter/JustEat-Test-Swift
Pods/RxCocoa/RxCocoa/Common/CocoaUnits/Driver/Driver+Subscription.swift
10
4094
// // Driver+Subscription.swift // Rx // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif extension DriverConvertibleType { /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ @warn_unused_result(message="http://git.io/rxs.ud") public func drive<O: ObserverType where O.E == E>(observer: O) -> Disposable { MainScheduler.ensureExecutingOnScheduler() return self.asObservable().subscribe(observer) } /** Creates new subscription and sends elements to variable. - parameter variable: Target variable for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the variable. */ @warn_unused_result(message="http://git.io/rxs.ud") public func drive(variable: Variable<E>) -> Disposable { return drive(onNext: { e in variable.value = e }) } /** Subscribes to observable sequence using custom binder function. - parameter with: Function used to bind elements from `self`. - returns: Object representing subscription. */ @warn_unused_result(message="http://git.io/rxs.ud") public func drive<R>(transformation: Observable<E> -> R) -> R { MainScheduler.ensureExecutingOnScheduler() return transformation(self.asObservable()) } /** Subscribes to observable sequence using custom binder function and final parameter passed to binder function after `self` is passed. public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return with(self)(curriedArgument) } - parameter with: Function used to bind elements from `self`. - parameter curriedArgument: Final argument passed to `binder` to finish binding process. - returns: Object representing subscription. */ @warn_unused_result(message="http://git.io/rxs.ud") public func drive<R1, R2>(with: Observable<E> -> R1 -> R2, curriedArgument: R1) -> R2 { MainScheduler.ensureExecutingOnScheduler() return with(self.asObservable())(curriedArgument) } /** Subscribes an element handler, a completion handler and disposed handler to an observable sequence. Error callback is not exposed because `Driver` can't error out. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. gracefully completed, errored, or if the generation is cancelled by disposing subscription) - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is cancelled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func drive(onNext onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { MainScheduler.ensureExecutingOnScheduler() return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) } /** Subscribes an element handler to an observable sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ @warn_unused_result(message="http://git.io/rxs.ud") public func driveNext(onNext: E -> Void) -> Disposable { MainScheduler.ensureExecutingOnScheduler() return self.asObservable().subscribeNext(onNext) } }
mit
when50/TabBarView
TabBarPageView/BaseStyle.swift
1
225
// // BaseStyle.swift // TabBarPageView // // Created by chc on 2017/6/9. // Copyright © 2017年 chc. All rights reserved. // import Foundation public protocol BaseStyle { func applyTo(_ cell: TabCollectionCell) }
mit
ortizraf/macsoftwarecenter
Mac Application Store/LabelCollectionViewItem.swift
1
5118
// // LabelCollectionViewItem.swift // Mac Software Center // // Created by Rafael Ortiz. // Copyright © 2017 Nextneo. All rights reserved. // import Cocoa class LabelCollectionViewItem: NSCollectionViewItem { @IBOutlet weak var application_label_name: NSTextField! @IBOutlet weak var application_imageview_image: NSImageView! @IBOutlet weak var application_link: NSButton! @IBOutlet weak var application_option: NSPopUpButton! @IBOutlet weak var application_category: NSTextField! var productItem: App? var buildProduct: App? { didSet{ application_label_name.stringValue = (buildProduct?.name)! if((buildProduct?.url_image?.contains("http"))! && (buildProduct?.url_image?.contains("png"))!){ application_imageview_image.image = NSImage(named: "no-image") if let checkedUrl = URL(string: (buildProduct?.url_image)!) { downloadImage(url: checkedUrl) } } else { let image = buildProduct?.url_image application_imageview_image.image = NSImage(named: image!) } application_link.target = self application_link.action = #selector(LabelCollectionViewItem.btnDownload) application_option.isEnabled = true application_option.target = self application_option.action = #selector(LabelCollectionViewItem.selectOption) application_category.stringValue = (buildProduct?.category?.name)! } } func downloadImage(url: URL) { print("Download Started", url) getDataFromUrl(url: url) { (data, response, error) in guard let data = data, error == nil else { return } print(response?.suggestedFilename ?? url.lastPathComponent) print("Download Finished", url) DispatchQueue.main.async() { () -> Void in self.application_imageview_image.image = NSImage(data: data) } } } func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) { URLSession.shared.dataTask(with: url) { (data, response, error) in completion(data, response, error) }.resume() } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } @IBAction func btnDownload(sender: NSButton){ print("Button pressed 👍 ") getDownload(downloadLink: (self.buildProduct?.download_link)!, appName: (self.buildProduct?.name)!) } @IBAction func selectOption(sender: NSPopUpButton){ print("PopUp Button pressed 👍 ") let selectedNumber = sender.indexOfSelectedItem if(selectedNumber==0){ if let url = URL(string: (self.buildProduct?.download_link)!), NSWorkspace.shared.open(url) { print("default browser was successfully opened") } } else if (selectedNumber==1) { let pasteBoard = NSPasteboard.general pasteBoard.clearContents() pasteBoard.setString((self.buildProduct?.download_link)!, forType: .string) } } func getDownload(downloadLink: String, appName: String){ self.application_link.isEnabled = false self.application_link.title = "downloading..." let downloadUrl = NSURL(string: downloadLink) let downloadService = DownloadService(url: downloadUrl!) print(downloadLink) downloadService.downloadData(completion: { (data) in let fileDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0] let fileNameUrl = NSURL(fileURLWithPath: (downloadUrl?.absoluteString)!).lastPathComponent! var fileName = fileNameUrl.removingPercentEncoding if(self.buildProduct?.file_format?.contains("zip"))!{ print("zip") fileName = appName+".zip" } else if(self.buildProduct?.file_format?.contains("dmg"))!{ fileName = appName+".dmg" } else if(!(fileName?.contains(".dmg"))! && !(fileName?.contains(".zip"))! && !(fileName?.contains(".app"))!){ print("dmg") fileName = appName+".dmg" } let fileUrl = fileDirectory.appendingPathComponent(fileName!, isDirectory: false) try? data.write(to: fileUrl) let messageService = MessageService() messageService.showNotification(title: appName, informativeText: "Download completed successfully") self.application_link.title = "download" self.application_link.isEnabled = true }) } }
gpl-3.0
victorpimentel/MarvelAPI
MarvelAPI.playground/Sources/Models/Comic.swift
1
225
import Foundation public struct Comic: Decodable { public let id: Int public let title: String? public let issueNumber: Double? public let description: String? public let pageCount: Int? public let thumbnail: Image? }
apache-2.0
TheHolyGrail/Historian
ELCache/ELCache+UIImageView.swift
2
2131
// // ELCache+UIImageView.swift // ELCache // // Created by Sam Grover on 12/27/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import UIKit import ELFoundation public extension UIImageView { internal var urlAssociationKey: String { return "com.walmartlabs.ELCache.UIImageView.NSURL" } convenience init(URL: NSURL, completion: FetchImageURLCompletionClosure) { self.init() self.setImageAt(URL, placeholder: nil, completion: completion) } func setImageAt(URL: NSURL) { setImageAt(URL, placeholder: nil, completion: {_,_ in }) } func setImageAt(URL: NSURL, placeholder: UIImage?) { setImageAt(URL, placeholder: placeholder, completion: {_,_ in }) } func setImageAt(URL: NSURL, completion: FetchImageURLCompletionClosure) { setImageAt(URL, placeholder: nil, completion: completion) } func setImageAt(URL: NSURL, placeholder: UIImage?, completion: FetchImageURLCompletionClosure) { // Use the placeholder only if the image is not valid in cache to avoid setting actual image momentarily after setting placeholder. if URLCache.sharedURLCache.validInCache(URL) != true { self.image = placeholder } URLCache.sharedURLCache.fetchImage(URL) { (image, error) -> Void in self.processURLFetch(image, error: error, completion: completion) } setAssociatedObject(self, value: URL, associativeKey: urlAssociationKey, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } func cancelURL(url: NSURL) { if let URL: NSURL = getAssociatedObject(self, associativeKey: urlAssociationKey) { URLCache.sharedURLCache.cancelFetch(URL) } } internal func processURLFetch(image: UIImage?, error: NSError?, completion: FetchImageURLCompletionClosure) { dispatch_async(dispatch_get_main_queue(), { () -> Void in if let image = image { self.image = image } completion(image, error) }) } }
mit
twostraws/HackingWithSwift
Classic/project16/Project16/AppDelegate.swift
1
2184
// // AppDelegate.swift // Project16 // // Created by Paul Hudson on 31/03/2019. // Copyright © 2019 Hacking with Swift. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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:. } }
unlicense
Monnoroch/Cuckoo
Generator/Dependencies/SourceKitten/Source/SourceKittenFramework/Parameter.swift
1
405
// // Parameter.swift // SourceKitten // // Created by JP Simard on 10/27/15. // Copyright © 2015 SourceKitten. All rights reserved. // #if SWIFT_PACKAGE import Clang_C #endif public struct Parameter { let name: String let discussion: [Text] init(comment: CXComment) { name = comment.paramName() ?? "<none>" discussion = comment.paragraph().paragraphToString() } }
mit
Houzz/PuzzleLayout
PuzzleLayout/PuzzleLayout/Layout/Utils/PuzzleCollectionViewLayout+Constants.swift
1
1571
// // PuzzleCollectionViewLayout+Constants.swift // PuzzleLayout // // Created by Yossi Avramov on 05/10/2016. // Copyright © 2016 Houzz. All rights reserved. // import UIKit /// An element kind for separator line. Shouldn't be used by 'PuzzlePieceSectionLayout' since separator lines generated by 'PuzzleCollectionViewLayout' public let PuzzleCollectionElementKindSeparatorLine = "!_SeparatorLine_!" /// An element kind for top gutter public let PuzzleCollectionElementKindSectionTopGutter = "!_SectionTopGutter_!" /// An element kind for bottom gutter public let PuzzleCollectionElementKindSectionBottomGutter = "!_SectionBottomGutter_!" /// A key used to set the view background color for separator lines & gutters. public let PuzzleCollectionColoredViewColorKey = "!_BackgroundColor_!" /// An element kind for 'PuzzleCollectionViewLayout' headers. This string is equal to the flow layout element kind for headers, which makes it easy to create header in storyboard. public let PuzzleCollectionElementKindSectionHeader: String = UICollectionView.elementKindSectionHeader /// An element kind for 'PuzzleCollectionViewLayout' footers. This string is equal to the flow layout element kind for footers, which makes it easy to create footer in storyboard. public let PuzzleCollectionElementKindSectionFooter: String = UICollectionView.elementKindSectionFooter /// A Z index of separator lines, top & bottom gutters public let PuzzleCollectionSeparatorsViewZIndex = 2 /// A Z index of pinned headers & footers public let PuzzleCollectionHeaderFooterZIndex = 4
mit
valentin7/pineapple-ios
Pineapple/DetailViewController.swift
1
5358
// // DetailViewController.swift // Pineapple // // Created by Valentin Perez on 5/23/15. // Copyright (c) 2015 Valpe Technologies. All rights reserved. // import UIKit //import MapboxGL import MapKit import AddressBook import Parse class DetailViewController: UIViewController { @IBOutlet weak var placeNameLabel: UILabel! @IBOutlet var mapView: MKMapView! @IBOutlet weak var placeImageView: UIImageView! @IBOutlet weak var descriptionLabel: UILabel! var locationManager = CLLocationManager() let regionRadius: CLLocationDistance = 200 var placeName : String = "" var placeObject : PFObject! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.hidesBarsOnSwipe = false self.navigationController?.setNavigationBarHidden(false, animated: true) if (placeObject != nil) { print("PLACE IS NOT NIL YOO") descriptionLabel.text = placeObject["description"] as? String let placeName = placeObject["name"] as! String placeNameLabel?.text = placeName let imageFile = placeObject["image"] as? PFFile let url = imageFile!.url placeImageView!.setImageWithURL(NSURL(string: url!)!) let placeLocation : PFGeoPoint = placeObject["location"] as! PFGeoPoint //let placeName = placeObject["name"] as! String let placeDescription = "Get directions"//placeObject["description"] as! String let placePin = PlaceAnnotation(title: placeName, description: placeDescription, coordinate: CLLocationCoordinate2D(latitude: placeLocation.latitude, longitude: placeLocation.longitude)) mapView.addAnnotation(placePin) mapView.delegate = self } // Do any additional setup after loading the view. } func getLocation() { if (placeObject != nil) { let geoPoint = placeObject["location"] as? PFGeoPoint let userLoc = CLLocation(latitude: geoPoint!.latitude, longitude: geoPoint!.longitude) self.centerMapOnLocation(userLoc) } else { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { let userLoc = CLLocation(latitude: geoPoint!.latitude, longitude: geoPoint!.longitude) print(" user location: \n", userLoc) self.centerMapOnLocation(userLoc) // do something with the new geoPoint } } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) checkLocationAuthorizationStatus() } func checkLocationAuthorizationStatus() { if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { mapView.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0) var placePin = MKMapPoint(x: 70, y: 90) mapView.setRegion(coordinateRegion, animated: true) } @IBAction func unwindToMainViewController (sender: UIStoryboardSegue){ // bug? exit segue doesn't dismiss so we do it manually... self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func tappedDetails(sender: AnyObject) { var vc : TweakViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tweakController") as! TweakViewController vc.place = self.placeObject vc.placeName = self.placeName self.presentViewController(vc, animated: true, completion: nil) } // func mapItem() -> MKMapItem { // let addressDictionary = [String(kABPersonAddressStreetKey): subtitle] // let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary) // // let mapItem = MKMapItem(placemark: placemark) // mapItem.name = title // // return mapItem // } // // func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, // calloutAccessoryControlTapped control: UIControl!) { // let location = view.annotation as Artwork // let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] // location.mapItem().openInMapsWithLaunchOptions(launchOptions) // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
nguyenantinhbk77/practice-swift
Views/NavigationController/Fonts/Fonts/FontListViewController.swift
2
4136
// // FontListViewController.swift // Fonts // // Created by Domenico on 23.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit class FontListViewController: UITableViewController { var fontNames: [String] = [] var showsFavorites:Bool = false private var cellPointSize: CGFloat! private let cellIdentifier = "FontName" override func viewDidLoad() { super.viewDidLoad() if showsFavorites { navigationItem.rightBarButtonItem = editButtonItem() } let preferredTableViewFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) cellPointSize = preferredTableViewFont.pointSize } // Fetch the font names func fontForDisplay(atIndexPath indexPath: NSIndexPath) -> UIFont { let fontName = fontNames[indexPath.row] return UIFont(name: fontName, size: cellPointSize)! } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if showsFavorites { fontNames = FavoritesList.sharedFavoriteList.favorites tableView.reloadData() } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fontNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.font = fontForDisplay(atIndexPath: indexPath) cell.textLabel!.text = fontNames[indexPath.row] cell.detailTextLabel?.text = fontNames[indexPath.row] return cell } // Accepted editing override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return showsFavorites } // Deleting a row override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if !showsFavorites { return } if editingStyle == UITableViewCellEditingStyle.Delete { // Delete the row from the data source let favorite = fontNames[indexPath.row] FavoritesList.sharedFavoriteList.removeFavorite(favorite) fontNames = FavoritesList.sharedFavoriteList.favorites tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) } } // Reordering function override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { FavoritesList.sharedFavoriteList.moveItem(fromIndex: sourceIndexPath.row, toIndex: destinationIndexPath.row) fontNames = FavoritesList.sharedFavoriteList.favorites } // MARK: 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. let tableViewCell = sender as! UITableViewCell let indexPath = tableView.indexPathForCell(tableViewCell)! let font = fontForDisplay(atIndexPath: indexPath) if segue.identifier == "ShowFontSizes" { let sizesVC = segue.destinationViewController as! FontSizesViewController sizesVC.title = font.fontName sizesVC.font = font } else { let infoVC = segue.destinationViewController as! FontInfoViewController infoVC.font = font infoVC.favorite = contains(FavoritesList.sharedFavoriteList.favorites, font.fontName) } } }
mit
jdbateman/VirtualTourist
VirtualTourist/VTError.swift
1
966
// // VTError.swift // VirtualTourist // // Created by john bateman on 10/6/15. // Copyright (c) 2015 John Bateman. All rights reserved. // import Foundation class VTError { var error: NSError? struct Constants { static let ERROR_DOMAIN: String = "self.VirtualTourist.Error" } enum ErrorCodes: Int { case CORE_DATA_INIT_ERROR = 9000 case JSON_PARSE_ERROR = 9001 case FLICKR_REQUEST_ERROR = 9002 case FLICKR_FILE_DOWNLOAD_ERROR = 9003 case IMAGE_CONVERSION_ERROR = 9004 case FILE_NOT_FOUND_ERROR = 9005 } init(errorString: String, errorCode: ErrorCodes) { // output to console println(errorString) // construct NSError var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = errorString error = NSError(domain: VTError.Constants.ERROR_DOMAIN, code: errorCode.rawValue, userInfo: dict) } }
mit
mirchow/HungerFreeCity
ios/Hunger Free City/Models/GooglePlace.swift
1
1435
// // GooglePlace.swift // Hunger Free City // // Created by Mirek Chowaniok on 6/26/15. // Copyright (c) 2015 Jacksonville Community. All rights reserved. // import UIKit import Foundation import CoreLocation class GooglePlace { let name: String let address: String let coordinate: CLLocationCoordinate2D let placeType: String var photoReference: String? var photo: UIImage? init(dictionary:NSDictionary, acceptedTypes: [String]) { name = dictionary["name"] as! String address = dictionary["vicinity"] as! String let location = dictionary["geometry"]?["location"] as! NSDictionary let lat = location["lat"] as! CLLocationDegrees let lng = location["lng"]as! CLLocationDegrees coordinate = CLLocationCoordinate2DMake(lat, lng) if let photos = dictionary["photos"] as? NSArray { let photo = photos.firstObject as! NSDictionary photoReference = photo["photo_reference"] as? String } var foundType = "restaurant" let possibleTypes = acceptedTypes.count > 0 ? acceptedTypes : ["bakery", "bar", "cafe", "grocery_or_supermarket", "restaurant"] for type in dictionary["types"] as! [String] { if possibleTypes.contains(type) { foundType = type break } } placeType = foundType } }
mit
project-chip/connectedhomeip
examples/tv-casting-app/darwin/TvCasting/TvCasting/ContentView.swift
1
908
/** * * Copyright (c) 2020-2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import SwiftUI struct ContentView: View { var body: some View { NavigationView { StartFromCacheView() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
18775134221/SwiftBase
SwiftTest/SwiftTest/Classes/tools/JQPhoneManagerVC.swift
2
1981
// // JQPhoneManagerVC.swift // SwiftTest // // Created by MAC on 2016/12/14. // Copyright © 2016年 MAC. All rights reserved. // import UIKit // MARK: - 拨打电话 class JQPhoneManagerVC: UIViewController { var webView: UIWebView? init () { webView = UIWebView() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.removeFromParentViewController() } override func viewDidLoad() { super.viewDidLoad() } /** * 打电话 * * @param no 电话号码 * @param inViewController 需要打电话的控制器 */ class func call(_ no: String?, _ inViewController: UIViewController?,failBlock: ()->()) { guard let _ = no else { failBlock() return } // 拨打电话 let noString: String = "tel://" + no! let url: NSURL = NSURL(string: noString)!; let canOpen: Bool? = UIApplication.shared.openURL(url as URL) guard canOpen! else { // 可选类型才可以使用可选绑定 对象才可以置空 failBlock() return } let pMVC: JQPhoneManagerVC = JQPhoneManagerVC() pMVC.view.alpha = 0 pMVC.view.frame = CGRect.zero inViewController?.addChildViewController(pMVC) inViewController?.view.addSubview(pMVC.view) let request: NSURLRequest = NSURLRequest(url: url as URL) pMVC.webView?.loadRequest(request as URLRequest) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { webView = nil print("PhoneManager已经被释放") } }
apache-2.0
Knoxantropicen/Focus-iOS
Focus/DoingTableViewCell.swift
1
1521
// // RestDoingTableViewCell.swift // Focus // // Created by TianKnox on 2017/4/16. // Copyright © 2017年 TianKnox. All rights reserved. // import UIKit class DoingTableViewCell: MGSwipeTableCell, MGSwipeTableCellDelegate { @IBOutlet weak var affairDescription: UILabel! var affair = String() { didSet { affairDescription?.text = affair affairDescription?.textColor = Style.mainTextColor settledMode.setTitleColor(Style.symbolColor, for: .normal) } } @IBOutlet weak var settledMode: UIButton! override func awakeFromNib() { super.awakeFromNib() delegate = self } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func swipeTableCellWillBeginSwiping(_ cell: MGSwipeTableCell) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "disableSwipe"), object: nil) } func swipeTableCellWillEndSwiping(_ cell: MGSwipeTableCell) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "enableSwipe"), object: nil) } override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return true } override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
mit
keyfun/DeviceStatusSample
DeviceStatusSample/DeviceStatusAction.swift
1
749
// // DeviceStatusAction.swift // DeviceStatusSample // // Created by Hui Key on 6/2/2016. // Copyright © 2016 KeyFun. All rights reserved. // import Foundation import SwiftFlux import Result class DeviceStatusAction { struct UpdateNetworkStatus: Action { typealias Payload = StatusPayload let value: StatusPayload func invoke(dispatcher: Dispatcher) { dispatcher.dispatch(self, result: Result(value: value)) } } struct UpdateBluetoothStatus: Action { typealias Payload = StatusPayload let value: StatusPayload func invoke(dispatcher: Dispatcher) { dispatcher.dispatch(self, result: Result(value: value)) } } }
mit
inacioferrarini/York
Classes/DataSyncRules/Entities/EntityDailySyncRule.swift
1
3333
// The MIT License (MIT) // // Copyright (c) 2016 Inácio Ferrarini // // 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 CoreData open class EntityDailySyncRule: EntityBaseSyncRules { open class func fetchEntityDailySyncRuleByName(_ name: String, inManagedObjectContext context: NSManagedObjectContext) -> EntityDailySyncRule? { guard name.characters.count > 0 else { return nil } let request: NSFetchRequest = NSFetchRequest<EntityDailySyncRule>(entityName: self.simpleClassName()) request.predicate = NSPredicate(format: "name = %@", name) return self.lastObjectFromRequest(request, inManagedObjectContext: context) } open class func entityDailySyncRuleByName(_ name: String, days: NSNumber?, inManagedObjectContext context: NSManagedObjectContext) -> EntityDailySyncRule? { guard name.characters.count > 0 else { return nil } var entityDailySyncRule: EntityDailySyncRule? = fetchEntityDailySyncRuleByName(name, inManagedObjectContext: context) if entityDailySyncRule == nil { let newEntityDailySyncRule = NSEntityDescription.insertNewObject(forEntityName: self.simpleClassName(), into: context) as? EntityDailySyncRule if let entity = newEntityDailySyncRule { entity.name = name } entityDailySyncRule = newEntityDailySyncRule } if let entityDailySyncRule = entityDailySyncRule { entityDailySyncRule.days = days } return entityDailySyncRule } override open func shouldRunSyncRuleWithName(_ name: String, date: Date, inManagedObjectContext context: NSManagedObjectContext) -> Bool { let lastExecution = EntitySyncHistory.fetchEntityAutoSyncHistoryByName(name, inManagedObjectContext: context) if let lastExecution = lastExecution, let lastExecutionDate = lastExecution.lastExecutionDate, let days = self.days { let elapsedTime = Date().timeIntervalSince(lastExecutionDate) let targetTime = TimeInterval(days.int32Value * 24 * 60 * 60) return elapsedTime >= targetTime } return true } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01385-swift-typedecl-getdeclaredtype.swift
1
236
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func d<b { enum A { func c { (v: c } { } } { { } } let start = b<T
mit
lpollard11/ZipCodeAPISearch
Example/Tests/Tests.swift
1
766
import UIKit import XCTest import ZipCodeAPISearch class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
szweier/SZMentionsSwift
SZMentionsSwiftTests/Internal/NSAttributedStringTests.swift
1
4102
@testable import SZMentionsSwift import XCTest private extension NSAttributedString { func attribute(_ attribute: NSAttributedString.Key, at location: Int) -> Any? { return attributes(at: location, effectiveRange: nil)[attribute] } func backgroundColor(at location: Int) -> UIColor? { return attribute(.backgroundColor, at: location) as? UIColor } func foregroundColor(at location: Int) -> UIColor? { return attribute(.foregroundColor, at: location) as? UIColor } } private final class NSAttributedStringTests: XCTestCase { var mentionAttributes: [Attribute]! var defaultAttributes: [Attribute]! var mentionAttributesClosure: ((CreateMention?) -> [AttributeContainer])! override func setUp() { super.setUp() mentionAttributes = [ Attribute(name: .backgroundColor, value: UIColor.red), Attribute(name: .foregroundColor, value: UIColor.blue), ] defaultAttributes = [Attribute(name: .foregroundColor, value: UIColor.black)] mentionAttributesClosure = { _ in self.mentionAttributes } } override func tearDown() { super.tearDown() mentionAttributes = nil defaultAttributes = nil mentionAttributesClosure = nil } func test_shouldApplyAttributesPassedToApplyFunction() { var attributedText = NSAttributedString(string: "Test string, test string, test string, test string, test string, test string, test string, test string, test string.") (attributedText, _) = attributedText |> apply(mentionAttributes, range: NSRange(location: 0, length: attributedText.length)) XCTAssertEqual(attributedText.backgroundColor(at: 0), .red) XCTAssertEqual(attributedText.foregroundColor(at: 0), .blue) } func test_shouldInsertExistingMentions() { var attributedText = NSAttributedString(string: "Test Steven Zweier") (attributedText, _) = attributedText |> apply(mentionAttributesClosure(ExampleMention(name: "Steven Zweier")), range: NSRange(location: 5, length: 13)) XCTAssertEqual(attributedText.backgroundColor(at: 5), .red) XCTAssertEqual(attributedText.foregroundColor(at: 5), .blue) } func test_shouldAddMention() { var attributedText = NSAttributedString(string: "Test @ste") (attributedText, _) = attributedText |> SZMentionsSwift.add(ExampleMention(name: "Steven Zweier"), spaceAfterMention: false, at: NSRange(location: 5, length: 4), with: mentionAttributesClosure) XCTAssertNil(attributedText.backgroundColor(at: 2)) XCTAssertNil(attributedText.foregroundColor(at: 2)) XCTAssertEqual(attributedText.backgroundColor(at: 5), .red) XCTAssertEqual(attributedText.foregroundColor(at: 5), .blue) XCTAssertEqual(attributedText.backgroundColor(at: 17), .red) XCTAssertEqual(attributedText.foregroundColor(at: 17), .blue) } func test_textViewTypingAttributes_shouldReset() { let textView = UITextView() textView.attributedText = NSAttributedString(string: "Test string, test string, test string, test string, test string, test string, test string, test string, test string.") let (text, _) = textView.attributedText |> apply(mentionAttributes, range: NSRange(location: 0, length: textView.attributedText.length)) textView.attributedText = text XCTAssertEqual(textView.typingAttributes[.backgroundColor] as? UIColor, .red) XCTAssertEqual(textView.typingAttributes[.foregroundColor] as? UIColor, .blue) textView.typingAttributes = (defaultAttributes as [AttributeContainer]).dictionary XCTAssertNil(textView.typingAttributes[.backgroundColor] as? UIColor) XCTAssertEqual(textView.typingAttributes[.foregroundColor] as? UIColor, .black) } }
mit
WeHUD/app
weHub-ios/Gzone_App/Pods/XLPagerTabStrip/Sources/TwitterPagerTabStripViewController.swift
6
10296
// TwitterPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct TwitterPagerTabStripSettings { public struct Style { public var dotColor = UIColor(white: 1, alpha: 0.4) public var selectedDotColor = UIColor.white public var portraitTitleFont = UIFont.systemFont(ofSize: 18) public var landscapeTitleFont = UIFont.systemFont(ofSize: 15) public var titleColor = UIColor.white } public var style = Style() } open class TwitterPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate { open var settings = TwitterPagerTabStripSettings() public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) pagerBehaviour = .progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) delegate = self datasource = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pagerBehaviour = .progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) delegate = self datasource = self } open override func viewDidLoad() { super.viewDidLoad() if titleView.superview == nil { navigationItem.titleView = titleView } // keep watching the frame of titleView titleView.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: nil) guard let navigationController = navigationController else { fatalError("TwitterPagerTabStripViewController should be embedded in a UINavigationController") } titleView.frame = CGRect(x: 0, y: 0, width: navigationController.navigationBar.frame.width, height: navigationController.navigationBar.frame.height) titleView.addSubview(titleScrollView) titleView.addSubview(pageControl) reloadNavigationViewItems() } open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() guard isViewLoaded else { return } reloadNavigationViewItems() setNavigationViewItemsPosition(updateAlpha: true) } // MARK: - PagerTabStripDelegate open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { // move indicator scroll view guard let distance = distanceValue else { return } var xOffset: CGFloat = 0 if fromIndex < toIndex { xOffset = distance * CGFloat(fromIndex) + distance * progressPercentage } else if fromIndex > toIndex { xOffset = distance * CGFloat(fromIndex) - distance * progressPercentage } else { xOffset = distance * CGFloat(fromIndex) } titleScrollView.contentOffset = CGPoint(x: xOffset, y: 0) // update alpha of titles setAlphaWith(offset: xOffset, andDistance: distance) // update page control page pageControl.currentPage = currentIndex } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { fatalError() } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard object as AnyObject === titleView && keyPath == "frame" && change?[NSKeyValueChangeKey.kindKey] as? UInt == NSKeyValueChange.setting.rawValue else { return } let oldRect = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue let newRect = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue if (oldRect?.equalTo(newRect!))! { titleScrollView.frame = CGRect(x: 0, y: 0, width: titleView.frame.width, height: titleScrollView.frame.height) setNavigationViewItemsPosition(updateAlpha: true) } } deinit { if isViewLoaded { titleView.removeObserver(self, forKeyPath: "frame") } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() setNavigationViewItemsPosition(updateAlpha: false) } // MARK: - Helpers private lazy var titleView: UIView = { let navigationView = UIView() navigationView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return navigationView }() private lazy var titleScrollView: UIScrollView = { [unowned self] in let titleScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44)) titleScrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleScrollView.bounces = true titleScrollView.scrollsToTop = false titleScrollView.delegate = self titleScrollView.showsVerticalScrollIndicator = false titleScrollView.showsHorizontalScrollIndicator = false titleScrollView.isPagingEnabled = true titleScrollView.isUserInteractionEnabled = false titleScrollView.alwaysBounceHorizontal = true titleScrollView.alwaysBounceVertical = false return titleScrollView }() private lazy var pageControl: FXPageControl = { [unowned self] in let pageControl = FXPageControl() pageControl.backgroundColor = .clear pageControl.dotSize = 3.8 pageControl.dotSpacing = 4.0 pageControl.dotColor = self.settings.style.dotColor pageControl.selectedDotColor = self.settings.style.selectedDotColor pageControl.isUserInteractionEnabled = false return pageControl }() private var childTitleLabels = [UILabel]() private func reloadNavigationViewItems() { // remove all child view controller header labels childTitleLabels.forEach { $0.removeFromSuperview() } childTitleLabels.removeAll() for (index, item) in viewControllers.enumerated() { let child = item as! IndicatorInfoProvider let indicatorInfo = child.indicatorInfo(for: self) let navTitleLabel : UILabel = { let label = UILabel() label.text = indicatorInfo.title label.font = UIApplication.shared.statusBarOrientation.isPortrait ? settings.style.portraitTitleFont : settings.style.landscapeTitleFont label.textColor = settings.style.titleColor label.alpha = 0 return label }() navTitleLabel.alpha = currentIndex == index ? 1 : 0 navTitleLabel.textColor = settings.style.titleColor titleScrollView.addSubview(navTitleLabel) childTitleLabels.append(navTitleLabel) } } private func setNavigationViewItemsPosition(updateAlpha: Bool) { guard let distance = distanceValue else { return } let isPortrait = UIApplication.shared.statusBarOrientation.isPortrait let navBarHeight: CGFloat = navigationController!.navigationBar.frame.size.height for (index, label) in childTitleLabels.enumerated() { if updateAlpha { label.alpha = currentIndex == index ? 1 : 0 } label.font = isPortrait ? settings.style.portraitTitleFont : settings.style.landscapeTitleFont let viewSize = label.intrinsicContentSize let originX = distance - viewSize.width/2 + CGFloat(index) * distance let originY = (CGFloat(navBarHeight) - viewSize.height) / 2 label.frame = CGRect(x: originX, y: originY - 2, width: viewSize.width, height: viewSize.height) label.tag = index } let xOffset = distance * CGFloat(currentIndex) titleScrollView.contentOffset = CGPoint(x: xOffset, y: 0) pageControl.numberOfPages = childTitleLabels.count pageControl.currentPage = currentIndex let viewSize = pageControl.sizeForNumber(ofPages: childTitleLabels.count) let originX = distance - viewSize.width / 2 pageControl.frame = CGRect(x: originX, y: navBarHeight - 10, width: viewSize.width, height: viewSize.height) } private func setAlphaWith(offset: CGFloat, andDistance distance: CGFloat) { for (index, label) in childTitleLabels.enumerated() { label.alpha = { if offset < distance * CGFloat(index) { return (offset - distance * CGFloat(index - 1)) / distance } else { return 1 - ((offset - distance * CGFloat(index)) / distance) } }() } } private var distanceValue: CGFloat? { return navigationController.map { $0.navigationBar.convert($0.navigationBar.center, to: titleView) }?.x } }
bsd-3-clause
magmajo/nmagma-ios
Sources/nOpenssl.swift
1
1920
// // nopenssl.swift // nhello // // Created by magmajo on 2017. 8. 23.. // // import Foundation public class nOpenssl { ///////////////////////////////////////////// /// Hello ///////////////////////////////////////////// public class Hello{ static var my = Hello("") var mWorld : String? = nil public init(_ world: String?) { if let world_ = world { self.mWorld = world_ } } public func world(){ print("Hello \(self.mWorld)") } } // Hello end. /** This is an extremely complicated method that concatenates the first and last name and produces the full name. - Parameter message: The first part of the full name. - Parameter file: The last part of the fullname. - Parameter function: The last part of the fullname. - Parameter line: The last part of the fullname. ### Usage Example: ### ```` nLog.log("test log") ```` * Use the `doubleValue(_:)` function to get the double value of any number. * Only ***Int*** properties are allowed. */ public static func hello(_ world: String) { print("hello \(world)") } /** This is an extremely complicated method that concatenates the first and last name and produces the full name. - Parameter message: The first part of the full name. - Parameter file: The last part of the fullname. - Parameter function: The last part of the fullname. - Parameter line: The last part of the fullname. ### Usage Example: ### ```` nLog.log("test log") ```` * Use the `doubleValue(_:)` function to get the double value of any number. * Only ***Int*** properties are allowed. */ public static func test(_ params: String){ print(params) } }
mit
fanyu/EDCCharla
EDCChat/EDCChat/EDCChatMessageCell.swift
1
4287
// // EDCChatTableViewCell.swift // EDCChat // // Created by FanYu on 10/12/2015. // Copyright © 2015 FanYu. All rights reserved. // import UIKit // MARK: - Cell Style} enum EDCChatMessageCellStyle: Int { case Unknow case Left case Right } // MARK: - Event Type enum EDCChatMessageCellEventType: Int { case Bubble case Card case Portrait } protocol EDCChatMessageCellProtocol { var style: EDCChatMessageCellStyle { set get } var enabled: Bool { set get } var message: EDCChatMessageProtocol? { set get } func systemLayoutSizeFittingSize(targetSize: CGSize) ->CGSize } @objc protocol EDCChatMessageCellDelegate: NSObjectProtocol { optional func chatCellDidCpoy(chatCell: EDCChatMessageCell) optional func chatCellDidDelete(chatCell: EDCChatMessageCell) optional func chatCellDidResend(chatCell: EDCChatMessageCell) optional func chatCellDidTap(chatCell: EDCChatMessageCell, withEvent event: EDCChatMessageCellEvent) optional func chatCellDidLongPress(chatCell: EDCChatMessageCell, withEvent event: EDCChatMessageCellEvent) } class EDCChatMessageCell: UITableViewCell, EDCChatMessageCellProtocol { private(set) static var createdCount = 0 var style: EDCChatMessageCellStyle = .Unknow var message: EDCChatMessageProtocol? { willSet { // belong to self , then right if newValue?.ownership ?? false { style = .Right } else { style = .Left } } } // use actions var enabled: Bool = false { didSet { guard oldValue != enabled else { return } if enabled { addActions() } else { removeActions() } } } // delegate weak var delegate: EDCChatMessageCellDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { self.clipsToBounds = true self.backgroundColor = UIColor.clearColor() self.selectionStyle = UITableViewCellSelectionStyle.None } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } deinit { EDCLog.trace("created count \(--self.dynamicType.createdCount)") } override func canBecomeFirstResponder() -> Bool { return true } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "chatCellDelete:" { return true } return false } // Calculate size override func systemLayoutSizeFittingSize(targetSize: CGSize) -> CGSize { // refresh self.layoutIfNeeded() // get content view size let size = contentView.systemLayoutSizeFittingSize(targetSize) // refine return CGSizeMake(size.width, size.height + 1) } func addActions() { } func removeActions() { } } // MARK: - Event class EDCChatMessageCellEvent: NSObject { var type: EDCChatMessageCellEventType var event: UIEvent? var sender: AnyObject? var extra: AnyObject? init(type: EDCChatMessageCellEventType, sender: AnyObject? = nil, event: UIEvent? = nil, extra: AnyObject? = nil) { self.type = type self.event = event self.sender = sender self.extra = extra super.init() } } //// MARK: - Event Action //extension EDCChatMessageCell { // // delete // func chatCellDelete(sender: AnyObject) { // self.delegate?.chatCellDidDelete?(self) // } // // tap // func chatCellTap(sender: EDCChatMessageCellEvent) { // self.delegate?.chatCellDidTap?(self, withEvent: sender) // } // // long press // func chatCellLongPress(sender: EDCChatMessageCellEvent) { // self.delegate?.chatCellDidLongPress?(self, withEvent: sender) // } //}
mit
Drusy/auvergne-webcams-ios
Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/SwiftTestObjects.swift
2
19399
//////////////////////////////////////////////////////////////////////////// // // 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 Foundation import RealmSwift import Realm class SwiftStringObject: Object { @objc dynamic var stringCol = "" } class SwiftBoolObject: Object { @objc dynamic var boolCol = false } class SwiftIntObject: Object { @objc dynamic var intCol = 0 } class SwiftLongObject: Object { @objc dynamic var longCol: Int64 = 0 } class SwiftObject: Object { @objc dynamic var boolCol = false @objc dynamic var intCol = 123 @objc dynamic var floatCol = 1.23 as Float @objc dynamic var doubleCol = 12.3 @objc dynamic var stringCol = "a" @objc dynamic var binaryCol = "a".data(using: String.Encoding.utf8)! @objc dynamic var dateCol = Date(timeIntervalSince1970: 1) @objc dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject() let arrayCol = List<SwiftBoolObject>() class func defaultValues() -> [String: Any] { return [ "boolCol": false, "intCol": 123, "floatCol": 1.23 as Float, "doubleCol": 12.3, "stringCol": "a", "binaryCol": "a".data(using: String.Encoding.utf8)!, "dateCol": Date(timeIntervalSince1970: 1), "objectCol": [false], "arrayCol": [] ] } } class SwiftOptionalObject: Object { @objc dynamic var optNSStringCol: NSString? @objc dynamic var optStringCol: String? @objc dynamic var optBinaryCol: Data? @objc dynamic var optDateCol: Date? let optIntCol = RealmOptional<Int>() let optInt8Col = RealmOptional<Int8>() let optInt16Col = RealmOptional<Int16>() let optInt32Col = RealmOptional<Int32>() let optInt64Col = RealmOptional<Int64>() let optFloatCol = RealmOptional<Float>() let optDoubleCol = RealmOptional<Double>() let optBoolCol = RealmOptional<Bool>() @objc dynamic var optObjectCol: SwiftBoolObject? } class SwiftOptionalPrimaryObject: SwiftOptionalObject { let id = RealmOptional<Int>() override class func primaryKey() -> String? { return "id" } } class SwiftListObject: Object { let int = List<Int>() let int8 = List<Int8>() let int16 = List<Int16>() let int32 = List<Int32>() let int64 = List<Int64>() let float = List<Float>() let double = List<Double>() let string = List<String>() let data = List<Data>() let date = List<Date>() let intOpt = List<Int?>() let int8Opt = List<Int8?>() let int16Opt = List<Int16?>() let int32Opt = List<Int32?>() let int64Opt = List<Int64?>() let floatOpt = List<Float?>() let doubleOpt = List<Double?>() let stringOpt = List<String?>() let dataOpt = List<Data?>() let dateOpt = List<Date?>() } class SwiftImplicitlyUnwrappedOptionalObject: Object { @objc dynamic var optNSStringCol: NSString! @objc dynamic var optStringCol: String! @objc dynamic var optBinaryCol: Data! @objc dynamic var optDateCol: Date! @objc dynamic var optObjectCol: SwiftBoolObject! } class SwiftOptionalDefaultValuesObject: Object { @objc dynamic var optNSStringCol: NSString? = "A" @objc dynamic var optStringCol: String? = "B" @objc dynamic var optBinaryCol: Data? = "C".data(using: String.Encoding.utf8)! as Data @objc dynamic var optDateCol: Date? = Date(timeIntervalSince1970: 10) let optIntCol = RealmOptional<Int>(1) let optInt8Col = RealmOptional<Int8>(1) let optInt16Col = RealmOptional<Int16>(1) let optInt32Col = RealmOptional<Int32>(1) let optInt64Col = RealmOptional<Int64>(1) let optFloatCol = RealmOptional<Float>(2.2) let optDoubleCol = RealmOptional<Double>(3.3) let optBoolCol = RealmOptional<Bool>(true) @objc dynamic var optObjectCol: SwiftBoolObject? = SwiftBoolObject(value: [true]) // let arrayCol = List<SwiftBoolObject?>() class func defaultValues() -> [String: Any] { return [ "optNSStringCol": "A", "optStringCol": "B", "optBinaryCol": "C".data(using: String.Encoding.utf8)!, "optDateCol": Date(timeIntervalSince1970: 10), "optIntCol": 1, "optInt8Col": 1, "optInt16Col": 1, "optInt32Col": 1, "optInt64Col": 1, "optFloatCol": 2.2 as Float, "optDoubleCol": 3.3, "optBoolCol": true ] } } class SwiftOptionalIgnoredPropertiesObject: Object { @objc dynamic var id = 0 @objc dynamic var optNSStringCol: NSString? = "A" @objc dynamic var optStringCol: String? = "B" @objc dynamic var optBinaryCol: Data? = "C".data(using: String.Encoding.utf8)! as Data @objc dynamic var optDateCol: Date? = Date(timeIntervalSince1970: 10) @objc dynamic var optObjectCol: SwiftBoolObject? = SwiftBoolObject(value: [true]) override class func ignoredProperties() -> [String] { return [ "optNSStringCol", "optStringCol", "optBinaryCol", "optDateCol", "optObjectCol" ] } } class SwiftDogObject: Object { @objc dynamic var dogName = "" let owners = LinkingObjects(fromType: SwiftOwnerObject.self, property: "dog") } class SwiftOwnerObject: Object { @objc dynamic var name = "" @objc dynamic var dog: SwiftDogObject? = SwiftDogObject() } class SwiftAggregateObject: Object { @objc dynamic var intCol = 0 @objc dynamic var floatCol = 0 as Float @objc dynamic var doubleCol = 0.0 @objc dynamic var boolCol = false @objc dynamic var dateCol = Date() @objc dynamic var trueCol = true let stringListCol = List<SwiftStringObject>() } class SwiftAllIntSizesObject: Object { @objc dynamic var int8: Int8 = 0 @objc dynamic var int16: Int16 = 0 @objc dynamic var int32: Int32 = 0 @objc dynamic var int64: Int64 = 0 } class SwiftEmployeeObject: Object { @objc dynamic var name = "" @objc dynamic var age = 0 @objc dynamic var hired = false } class SwiftCompanyObject: Object { let employees = List<SwiftEmployeeObject>() } class SwiftArrayPropertyObject: Object { @objc dynamic var name = "" let array = List<SwiftStringObject>() let intArray = List<SwiftIntObject>() } class SwiftDoubleListOfSwiftObject: Object { let array = List<SwiftListOfSwiftObject>() } class SwiftListOfSwiftObject: Object { let array = List<SwiftObject>() } class SwiftListOfSwiftOptionalObject: Object { let array = List<SwiftOptionalObject>() } class SwiftArrayPropertySubclassObject: SwiftArrayPropertyObject { let boolArray = List<SwiftBoolObject>() } class SwiftLinkToPrimaryStringObject: Object { @objc dynamic var pk = "" @objc dynamic var object: SwiftPrimaryStringObject? let objects = List<SwiftPrimaryStringObject>() override class func primaryKey() -> String? { return "pk" } } class SwiftUTF8Object: Object { // swiftlint:disable:next identifier_name @objc dynamic var 柱колоéнǢкƱаم👍 = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا" } class SwiftIgnoredPropertiesObject: Object { @objc dynamic var name = "" @objc dynamic var age = 0 @objc dynamic var runtimeProperty: AnyObject? @objc dynamic var runtimeDefaultProperty = "property" @objc dynamic var readOnlyProperty: Int { return 0 } override class func ignoredProperties() -> [String] { return ["runtimeProperty", "runtimeDefaultProperty"] } } class SwiftRecursiveObject: Object { let objects = List<SwiftRecursiveObject>() } protocol SwiftPrimaryKeyObjectType { associatedtype PrimaryKey static func primaryKey() -> String? } class SwiftPrimaryStringObject: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" @objc dynamic var intCol = 0 typealias PrimaryKey = String override class func primaryKey() -> String? { return "stringCol" } } class SwiftPrimaryOptionalStringObject: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol: String? = "" @objc dynamic var intCol = 0 typealias PrimaryKey = String? override class func primaryKey() -> String? { return "stringCol" } } class SwiftPrimaryIntObject: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" @objc dynamic var intCol = 0 typealias PrimaryKey = Int override class func primaryKey() -> String? { return "intCol" } } class SwiftPrimaryOptionalIntObject: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" let intCol = RealmOptional<Int>() typealias PrimaryKey = RealmOptional<Int> override class func primaryKey() -> String? { return "intCol" } } class SwiftPrimaryInt8Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" @objc dynamic var int8Col: Int8 = 0 typealias PrimaryKey = Int8 override class func primaryKey() -> String? { return "int8Col" } } class SwiftPrimaryOptionalInt8Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" let int8Col = RealmOptional<Int8>() typealias PrimaryKey = RealmOptional<Int8> override class func primaryKey() -> String? { return "int8Col" } } class SwiftPrimaryInt16Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" @objc dynamic var int16Col: Int16 = 0 typealias PrimaryKey = Int16 override class func primaryKey() -> String? { return "int16Col" } } class SwiftPrimaryOptionalInt16Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" let int16Col = RealmOptional<Int16>() typealias PrimaryKey = RealmOptional<Int16> override class func primaryKey() -> String? { return "int16Col" } } class SwiftPrimaryInt32Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" @objc dynamic var int32Col: Int32 = 0 typealias PrimaryKey = Int32 override class func primaryKey() -> String? { return "int32Col" } } class SwiftPrimaryOptionalInt32Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" let int32Col = RealmOptional<Int32>() typealias PrimaryKey = RealmOptional<Int32> override class func primaryKey() -> String? { return "int32Col" } } class SwiftPrimaryInt64Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" @objc dynamic var int64Col: Int64 = 0 typealias PrimaryKey = Int64 override class func primaryKey() -> String? { return "int64Col" } } class SwiftPrimaryOptionalInt64Object: Object, SwiftPrimaryKeyObjectType { @objc dynamic var stringCol = "" let int64Col = RealmOptional<Int64>() typealias PrimaryKey = RealmOptional<Int64> override class func primaryKey() -> String? { return "int64Col" } } class SwiftIndexedPropertiesObject: Object { @objc dynamic var stringCol = "" @objc dynamic var intCol = 0 @objc dynamic var int8Col: Int8 = 0 @objc dynamic var int16Col: Int16 = 0 @objc dynamic var int32Col: Int32 = 0 @objc dynamic var int64Col: Int64 = 0 @objc dynamic var boolCol = false @objc dynamic var dateCol = Date() @objc dynamic var floatCol: Float = 0.0 @objc dynamic var doubleCol: Double = 0.0 @objc dynamic var dataCol = Data() override class func indexedProperties() -> [String] { return ["stringCol", "intCol", "int8Col", "int16Col", "int32Col", "int64Col", "boolCol", "dateCol"] } } class SwiftIndexedOptionalPropertiesObject: Object { @objc dynamic var optionalStringCol: String? = "" let optionalIntCol = RealmOptional<Int>() let optionalInt8Col = RealmOptional<Int8>() let optionalInt16Col = RealmOptional<Int16>() let optionalInt32Col = RealmOptional<Int32>() let optionalInt64Col = RealmOptional<Int64>() let optionalBoolCol = RealmOptional<Bool>() @objc dynamic var optionalDateCol: Date? = Date() let optionalFloatCol = RealmOptional<Float>() let optionalDoubleCol = RealmOptional<Double>() @objc dynamic var optionalDataCol: Data? = Data() override class func indexedProperties() -> [String] { return ["optionalStringCol", "optionalIntCol", "optionalInt8Col", "optionalInt16Col", "optionalInt32Col", "optionalInt64Col", "optionalBoolCol", "optionalDateCol"] } } class SwiftCustomInitializerObject: Object { @objc dynamic var stringCol: String init(stringVal: String) { stringCol = stringVal super.init() } required init() { stringCol = "" super.init() } required init(realm: RLMRealm, schema: RLMObjectSchema) { stringCol = "" super.init(realm: realm, schema: schema) } required init(value: Any, schema: RLMSchema) { stringCol = "" super.init(value: value, schema: schema) } } class SwiftConvenienceInitializerObject: Object { @objc dynamic var stringCol = "" convenience init(stringCol: String) { self.init() self.stringCol = stringCol } } class SwiftObjectiveCTypesObject: Object { @objc dynamic var stringCol: NSString? @objc dynamic var dateCol: NSDate? @objc dynamic var dataCol: NSData? @objc dynamic var numCol: NSNumber? = 0 } class SwiftComputedPropertyNotIgnoredObject: Object { // swiftlint:disable:next identifier_name @objc dynamic var _urlBacking = "" // Dynamic; no ivar @objc dynamic var dynamicURL: URL? { get { return URL(string: _urlBacking) } set { _urlBacking = newValue?.absoluteString ?? "" } } // Non-dynamic; no ivar var url: URL? { get { return URL(string: _urlBacking) } set { _urlBacking = newValue?.absoluteString ?? "" } } } @objc(SwiftObjcRenamedObject) class SwiftObjcRenamedObject: Object { @objc dynamic var stringCol = "" } @objc(SwiftObjcRenamedObjectWithTotallyDifferentName) class SwiftObjcArbitrarilyRenamedObject: Object { @objc dynamic var boolCol = false } class SwiftCircleObject: Object { @objc dynamic var obj: SwiftCircleObject? let array = List<SwiftCircleObject>() } // Exists to serve as a superclass to `SwiftGenericPropsOrderingObject` class SwiftGenericPropsOrderingParent: Object { var implicitlyIgnoredComputedProperty: Int { return 0 } let implicitlyIgnoredReadOnlyProperty: Int = 1 let parentFirstList = List<SwiftIntObject>() @objc dynamic var parentFirstNumber = 0 func parentFunction() -> Int { return parentFirstNumber + 1 } @objc dynamic var parentSecondNumber = 1 var parentComputedProp: String { return "hello world" } } // Used to verify that Swift properties (generic and otherwise) are detected properly and // added to the schema in the correct order. class SwiftGenericPropsOrderingObject: SwiftGenericPropsOrderingParent { func myFunction() -> Int { return firstNumber + secondNumber + thirdNumber } @objc dynamic var dynamicComputed: Int { return 999 } var firstIgnored = 999 @objc dynamic var dynamicIgnored = 999 @objc dynamic var firstNumber = 0 // Managed property class func myClassFunction(x: Int, y: Int) -> Int { return x + y } var secondIgnored = 999 lazy var lazyIgnored = 999 let firstArray = List<SwiftStringObject>() // Managed property @objc dynamic var secondNumber = 0 // Managed property var computedProp: String { return "\(firstNumber), \(secondNumber), and \(thirdNumber)" } let secondArray = List<SwiftStringObject>() // Managed property override class func ignoredProperties() -> [String] { return ["firstIgnored", "dynamicIgnored", "secondIgnored", "thirdIgnored", "lazyIgnored", "dynamicLazyIgnored"] } let firstOptionalNumber = RealmOptional<Int>() // Managed property var thirdIgnored = 999 @objc dynamic lazy var dynamicLazyIgnored = 999 let firstLinking = LinkingObjects(fromType: SwiftGenericPropsOrderingHelper.self, property: "first") let secondLinking = LinkingObjects(fromType: SwiftGenericPropsOrderingHelper.self, property: "second") @objc dynamic var thirdNumber = 0 // Managed property let secondOptionalNumber = RealmOptional<Int>() // Managed property } // Only exists to allow linking object properties on `SwiftGenericPropsNotLastObject`. class SwiftGenericPropsOrderingHelper: Object { @objc dynamic var first: SwiftGenericPropsOrderingObject? @objc dynamic var second: SwiftGenericPropsOrderingObject? } class SwiftRenamedProperties1: Object { @objc dynamic var propA = 0 @objc dynamic var propB = "" let linking1 = LinkingObjects(fromType: LinkToSwiftRenamedProperties1.self, property: "linkA") let linking2 = LinkingObjects(fromType: LinkToSwiftRenamedProperties2.self, property: "linkD") override class func _realmObjectName() -> String { return "Swift Renamed Properties" } override class func _realmColumnNames() -> [String: String] { return ["propA": "prop 1", "propB": "prop 2"] } } class SwiftRenamedProperties2: Object { @objc dynamic var propC = 0 @objc dynamic var propD = "" let linking1 = LinkingObjects(fromType: LinkToSwiftRenamedProperties1.self, property: "linkA") let linking2 = LinkingObjects(fromType: LinkToSwiftRenamedProperties2.self, property: "linkD") override class func _realmObjectName() -> String { return "Swift Renamed Properties" } override class func _realmColumnNames() -> [String: String] { return ["propC": "prop 1", "propD": "prop 2"] } } class LinkToSwiftRenamedProperties1: Object { @objc dynamic var linkA: SwiftRenamedProperties1? @objc dynamic var linkB: SwiftRenamedProperties2? let array1 = List<SwiftRenamedProperties1>() override class func _realmObjectName() -> String { return "Link To Swift Renamed Properties" } override class func _realmColumnNames() -> [String: String] { return ["linkA": "link 1", "linkB": "link 2", "array1": "array"] } } class LinkToSwiftRenamedProperties2: Object { @objc dynamic var linkC: SwiftRenamedProperties1? @objc dynamic var linkD: SwiftRenamedProperties2? let array2 = List<SwiftRenamedProperties2>() override class func _realmObjectName() -> String { return "Link To Swift Renamed Properties" } override class func _realmColumnNames() -> [String: String] { return ["linkC": "link 1", "linkD": "link 2", "array2": "array"] } }
apache-2.0