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
IMcD23/Proton
Source/Core/View/Hairline.swift
1
514
// // Hairline.swift // Pods // // Created by McDowell, Ian J [ITACD] on 4/11/16. // // public enum Direction { case Vertical, Horizontal } public class Hairline: View<UIView> { public init(color: UIColor = UIColor.lightGrayColor(), direction: Direction = .Horizontal) { super.init() switch direction { case .Vertical: self.width(1) case .Horizontal: self.height(1) } self.view.backgroundColor = color } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16820-no-stacktrace.swift
11
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { protocol P { extension NSData { enum b { func b { ( [Void{ } { class case ,
mit
FunctioningFunctionalist/ramda.swift
Example/Tests/allTests.swift
1
360
import Foundation import XCTest import Ramda class AllTests: XCTestCase { func testAllReturnsTrue() { let fn = R.equals(3) let result = R.all(fn) XCTAssertTrue(result([3, 3, 3])) } func testAllReturnsFalse() { let fn = R.equals(3) let result = R.all(fn) XCTAssertFalse(result([3, 4, 3])) } }
mit
stevehe-campray/uidynamic-swift
uidynamic学习/uidynamic学习Tests/uidynamic__Tests.swift
1
991
// // uidynamic__Tests.swift // uidynamic学习Tests // // Created by hejingjin on 16/6/21. // Copyright © 2016年 Chinahr. All rights reserved. // import XCTest @testable import uidynamic__ class uidynamic__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. // 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
mightydeveloper/swift
test/ClangModules/objc_parse.swift
9
21426
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify // REQUIRES: objc_interop import AppKit import AVFoundation import objc_ext import TestProtocols import ObjCParseExtras import ObjCParseExtrasToo import ObjCParseExtrasSystem func markUsed<T>(t: T) {} func testAnyObject(obj: AnyObject) { _ = obj.nsstringProperty } // Construction func construction() { _ = B() } // Subtyping func treatBAsA(b: B) -> A { return b } // Instance method invocation func instanceMethods(b: B) { var i = b.method(1, withFloat:2.5) i = i + b.method(1, withDouble:2.5) // BOOL b.setEnabled(true) // SEL b.performSelector("isEqual:", withObject:b) if let result = b.performSelector("getAsProto", withObject:nil) { _ = result.takeUnretainedValue() } // Renaming of redundant parameters. b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}} b.performAdd(1, withValue:2, withValue:4, withValue2: 3) b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }} // Both class and instance methods exist. b.description b.instanceTakesObjectClassTakesFloat(b) b.instanceTakesObjectClassTakesFloat(2.0) // expected-error{{cannot convert value of type 'Double' to expected argument type 'AnyObject!'}} // Instance methods with keyword components var obj = NSObject() var prot = NSObjectProtocol.self b.`protocol`(prot, hasThing:obj) b.doThing(obj, `protocol`: prot) } // Class method invocation func classMethods(b: B, other: NSObject) { var i = B.classMethod() i += B.classMethod(1) i += B.classMethod(1, withInt:2) i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}} // Both class and instance methods exist. B.description() B.instanceTakesObjectClassTakesFloat(2.0) B.instanceTakesObjectClassTakesFloat(other) // expected-error{{cannot convert value of type 'NSObject' to expected argument type 'Float'}} // Call an instance method of NSObject. var c: AnyClass = B.myClass() // no-warning c = b.myClass() // no-warning } // Instance method invocation on extensions func instanceMethodsInExtensions(b: B) { b.method(1, onCat1:2.5) b.method(1, onExtA:2.5) b.method(1, onExtB:2.5) b.method(1, separateExtMethod:3.5) let m1 = b.method:onCat1: m1(1, onCat1: 2.5) let m2 = b.method:onExtA: m2(1, onExtA: 2.5) let m3 = b.method:onExtB: m3(1, onExtB: 2.5) let m4 = b.method:separateExtMethod: m4(1, separateExtMethod: 2.5) } func dynamicLookupMethod(b: AnyObject) { // FIXME: Syntax will be replaced. if let m5 = b.method:separateExtMethod: { m5(1, separateExtMethod: 2.5) } } // Properties func properties(b: B) { var i = b.counter b.counter = i + 1 i = i + b.readCounter b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}} b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}} // Informal properties in Objective-C map to methods, not variables. b.informalProp() // An informal property cannot be made formal in a subclass. The // formal property is simply ignored. b.informalMadeFormal() b.informalMadeFormal = i // expected-error{{cannot assign to property: 'b' is a 'let' constant}} b.setInformalMadeFormal(5) b.overriddenProp = 17 // Dynamic properties. var obj : AnyObject = b var optStr = obj.nsstringProperty if optStr != nil { var s : String = optStr! } // Properties that are Swift keywords var prot = b.`protocol` } // Construction. func newConstruction(a: A, aproxy: AProxy) { var b : B = B() b = B(int: 17) b = B(int:17) b = B(double:17.5, 3.14159) b = B(BBB:b) b = B(forWorldDomination:()) b = B(int: 17, andDouble : 3.14159) b = B.newWithA(a) B.alloc()._initFoo() b.notAnInit() // init methods are not imported by themselves. b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}} // init methods on non-NSObject-rooted classes AProxy(int: 5) // expected-warning{{unused}} } // Indexed subscripting func indexedSubscripting(b: B, idx: Int, a: A) { b[idx] = a _ = b[idx] as! A } // Keyed subscripting func keyedSubscripting(b: B, idx: A, a: A) { b[a] = a var a2 = b[a] as! A let dict = NSMutableDictionary() dict[NSString()] = a let value = dict[NSString()] dict[nil] = a // expected-error {{nil is not compatible with expected argument type 'NSCopying'}} let q = dict[nil] // expected-error {{nil is not compatible with expected argument type 'NSCopying'}} _ = q } // Typed indexed subscripting func checkHive(hive: Hive, b: Bee) { let b2 = hive.bees[5] as Bee b2.buzz() } // Protocols func testProtocols(b: B, bp: BProto) { var bp2 : BProto = b var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}} bp.method(1, withFloat:2.5) bp.method(1, withDouble:2.5) // expected-error{{incorrect argument label in call (have '_:withDouble:', expected '_:withFloat:')}} {{16-26=withFloat}} bp2 = b.getAsProto() var c1 : Cat1Proto = b var bcat1 = b.getAsProtoWithCat() c1 = bcat1 bcat1 = c1 // expected-error{{cannot assign value of type 'Cat1Proto' to type 'protocol<BProto, Cat1Proto>!'}} } // Methods only defined in a protocol func testProtocolMethods(b: B, p2m: P2.Type) { b.otherMethod(1, withFloat:3.14159) b.p2Method() b.initViaP2(3.14159, second:3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}} // Imported constructor. var b2 = B(viaP2: 3.14159, second:3.14159) p2m.init(viaP2:3.14159, second: 3.14159) } func testId(x: AnyObject) { x.performSelector!("foo:", withObject: x) x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4) x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4) x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4) } class MySubclass : B { // Override a regular method. override func anotherMethodOnB() {} // Override a category method override func anotherCategoryMethod() {} } func getDescription(array: NSArray) { array.description } // Method overriding with unfortunate ordering. func overridingTest(srs: SuperRefsSub) { let rs : RefedSub rs.overridden() } func almostSubscriptableValueMismatch(as1: AlmostSubscriptable, a: A) { as1[a] // expected-error{{type 'AlmostSubscriptable' has no subscript members}} } func almostSubscriptableKeyMismatch(bc: BadCollection, key: NSString) { // FIXME: We end up importing this as read-only due to the mismatch between // getter/setter element types. var _ : AnyObject = bc[key] } func almostSubscriptableKeyMismatchInherited(bc: BadCollectionChild, key: String) { var value : AnyObject = bc[key] // no-warning, inherited from parent bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } func almostSubscriptableKeyMismatchInherited(roc: ReadOnlyCollectionChild, key: String) { var value : AnyObject = roc[key] // no-warning, inherited from parent roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } // Use of 'Class' via dynamic lookup. func classAnyObject(obj: NSObject) { obj.myClass().description!() } // Protocol conformances class Wobbler : NSWobbling { // expected-note{{candidate is not '@objc', but protocol requires it}} {{7-7=@objc }} // expected-error@-1{{type 'Wobbler' does not conform to protocol 'NSWobbling'}} @objc func wobble() { } func returnMyself() -> Self { return self } // expected-note{{candidate is not '@objc', but protocol requires it}} {{3-3=@objc }} } extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}} } @objc class Wobbler2 : NSObject, NSWobbling { // expected-note{{Objective-C method 'init' provided by implicit initializer 'init()' does not match the requirement's selector ('initWithWobble:')}} func wobble() { } func returnMyself() -> Self { return self } } extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}} } func optionalMemberAccess(w: NSWobbling) { w.wobble() w.wibble() // expected-error{{value of optional type '(() -> Void)?' not unwrapped; did you mean to use '!' or '?'?}} {{11-11=!}} var x: AnyObject = w[5] // expected-error{{value of optional type 'AnyObject!?' not unwrapped; did you mean to use '!' or '?'?}} {{26-26=!}} } func protocolInheritance(s: NSString) { var _: NSCoding = s } func ivars(hive: Hive) { var d = hive.bees.description hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}} } class NSObjectable : NSObjectProtocol { @objc var description : String { return "" } @objc func conformsToProtocol(_: Protocol) -> Bool { return false } @objc func isKindOfClass(aClass: AnyClass) -> Bool { return false } } // Properties with custom accessors func customAccessors(hive: Hive, bee: Bee) { markUsed(hive.makingHoney) markUsed(hive.isMakingHoney()) // expected-error{{value of type 'Hive' has no member 'isMakingHoney'}} hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}} hive.`guard`.description // okay hive.`guard`.description! // no-warning hive.`guard` = bee // no-warning } // instancetype/Dynamic Self invocation. func testDynamicSelf(queen: Bee, wobbler: NSWobbling) { var hive = Hive() // Factory method with instancetype result. var hive1 = Hive(queen: queen) hive1 = hive hive = hive1 // Instance method with instancetype result. var hive2 = hive.visit() hive2 = hive hive = hive2 // Instance method on a protocol with instancetype result. var wobbler2 = wobbler.returnMyself() var wobbler: NSWobbling = wobbler2 wobbler2 = wobbler // Instance method on a base class with instancetype result, called on the // class itself. // FIXME: This should be accepted. // FIXME: The error is lousy, too. let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error{{missing argument for parameter #1 in call}} } func testRepeatedProtocolAdoption(w: NSWindow) { w.description } class ProtocolAdopter1 : FooProto { @objc var bar: CInt // no-warning init() { bar = 5 } } class ProtocolAdopter2 : FooProto { @objc var bar: CInt { get { return 42 } set { /* do nothing! */ } } } class ProtocolAdopterBad1 : FooProto { // expected-error{{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}} @objc var bar: Int = 0 // expected-note{{candidate has non-matching type 'Int'}} } class ProtocolAdopterBad2 : FooProto { // expected-error{{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}} let bar: CInt = 0 // expected-note{{candidate is not settable, but protocol requires it}} } class ProtocolAdopterBad3 : FooProto { // expected-error{{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}} var bar: CInt { // expected-note{{candidate is not settable, but protocol requires it}} return 42 } } @objc protocol RefinedFooProtocol : FooProto {} func testPreferClassMethodToCurriedInstanceMethod(obj: NSObject) { // FIXME: We shouldn't need the ": Bool" type annotation here. // <rdar://problem/18006008> let _: Bool = NSObject.isEqual(obj) _ = NSObject.isEqual(obj) as (NSObject!) -> Bool // no-warning } func testPropertyAndMethodCollision(obj: PropertyAndMethodCollision, rev: PropertyAndMethodReverseCollision) { obj.object = nil obj.object(obj, doSomething:"action") rev.object = nil rev.object(rev, doSomething:"action") var value: AnyObject = obj.protoProp() value = obj.protoPropRO() _ = value } func testSubscriptAndPropertyRedeclaration(obj: SubscriptAndProperty) { _ = obj.x obj.x = 5 obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}} obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testSubscriptAndPropertyWithProtocols(obj: SubscriptAndPropertyWithProto) { _ = obj.x obj.x = 5 obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testProtocolMappingSameModule(obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) { markUsed(p.enablePostProcessing) markUsed(obj.enablePostProcessing) _ = obj.backgroundColor } func testProtocolMappingDifferentModules(obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) { markUsed(p.thisIsTheProto) markUsed(obj.thisClassHasAnAwfulName) let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}} _ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}} _ = ObjCParseExtrasToo.ProtoInHelper() _ = ObjCParseExtrasTooHelper.ClassInHelper() _ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}} } func testProtocolClassShadowing(obj: ClassInHelper, p: ProtoInHelper) { let _: ObjCParseExtrasToo.ClassInHelper = obj let _: ObjCParseExtrasToo.ProtoInHelper = p } func testDealloc(obj: NSObject) { // dealloc is subsumed by deinit. // FIXME: Special-case diagnostic in the type checker? obj.dealloc() // expected-error{{value of type 'NSObject' has no member 'dealloc'}} } func testConstantGlobals() { markUsed(MAX) markUsed(SomeImageName) markUsed(SomeNumber.description) MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}} SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}} SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}} } func testWeakVariable() { let _: AnyObject = globalWeakVar } class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}} @objc func getObject() -> AnyObject { return self } } func testNullarySelectorPieces(obj: AnyObject) { obj.foo(1, bar: 2, 3) // no-warning obj.foo(1, 2, bar: 3) // expected-error{{cannot call value of non-function type 'AnyObject?!'}} } func testFactoryMethodAvailability() { _ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}} } func testRepeatedMembers(obj: RepeatedMembers) { obj.repeatedMethod() } // rdar://problem/19726164 class FooDelegateImpl : NSObject, FooDelegate { var _started = false var started: Bool { @objc(isStarted) get { return _started } set { _started = newValue } } } class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto { var foo: AnyObject? // no errors about conformance var bar: AnyObject? // no errors about conformance } func testUnusedResults(ur: UnusedResults) { _ = ur.producesResult() ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}} } func testCStyle() { ExtraSelectors.cStyle(0, 1, 2) // expected-error{{type 'ExtraSelectors' has no member 'cStyle'}} } func testProtocolQualified(obj: CopyableNSObject, cell: CopyableSomeCell, plainObj: NSObject, plainCell: SomeCell) { _ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'NSObject'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = obj as NSObjectProtocol _ = obj as NSCopying _ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'SomeCell'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = cell as NSObject _ = cell as NSObjectProtocol _ = cell as NSCopying // expected-error {{'CopyableSomeCell' (aka 'SomeCell') is not convertible to 'NSCopying'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}} _ = cell as SomeCell _ = plainObj as CopyableNSObject // expected-error {{'NSObject' is not convertible to 'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>'); did you mean to use 'as!' to force downcast?}} {{16-18=as!}} _ = plainCell as CopyableSomeCell // FIXME: This is not really typesafe. } extension Printing { func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } static func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } } // <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated. func testSetInitializers() { let a: [AnyObject] = [NSObject()] let _ = NSCountedSet(array: a) let _ = NSMutableSet(array: a) } func testNSUInteger(obj: NSUIntegerTests, uint: UInt, int: Int) { obj.consumeUnsigned(uint) // okay obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(uint, andAnother: int) // okay do { let x = obj.unsignedProducer() let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.unsignedProducer(uint, fromCount: int) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.normalProducer(int, fromUnsigned: uint) let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} } let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} do { testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = testUnsigned(uint, uint) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } // NSNumber NSNumber(unsignedInteger: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let num = NSNumber(unsignedInteger: uint) let _: String = num.unsignedIntegerValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} }
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0634-getselftypeforcontainer.swift
13
330
// 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 protocol e { protocol c { func g(A") typealias e : a { class func c(") let h>) -> V { } } let c<f = { } func a(c)
apache-2.0
laszlokorte/reform-swift
ReformCore/ReformCore/ProxyTranslator.swift
1
594
// // ProxyTranslator.swift // ReformCore // // Created by Laszlo Korte on 25.09.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath struct ProxyTranslator : Translator { private let formReference : StaticFormReference init(formReference: StaticFormReference) { self.formReference = formReference } func translate<R:Runtime>(_ runtime: R, delta: Vec2d) { guard let form = formReference.getFormFor(runtime) as? Translatable else { return } form.translator.translate(runtime, delta: delta) } }
mit
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Views/PlanList/PlanMealListViewController.swift
1
4756
// // WeeklyFoodListViewController.swift // WeeklyFoodPlan // // Created by vulgur on 2017/1/3. // Copyright © 2017年 MAD. All rights reserved. // import UIKit import RealmSwift class PlanMealListViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! let cellIdentifier = "PlanCell" var plans = [DailyPlan]() override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self loadPlans() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.automaticallyAdjustsScrollViewInsets = false navigationItem.title = "美食计划".localized() collectionView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func loadPlans() { plans = WeeklyPlanManager.shared.nextWeeklyPlan() } @IBAction func barButtonTapped(sender: UIBarButtonItem) { let oldPlans = plans for plan in oldPlans { BaseManager.shared.transaction { plan.reduceIngredients() } } let newPlans = WeeklyPlanManager.shared.fakeWeeklyPlan() plans = newPlans BaseManager.shared.delete(objects: oldPlans) BaseManager.shared.save(objects: plans) collectionView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let backItem = UIBarButtonItem() backItem.title = "" navigationItem.backBarButtonItem = backItem if segue.identifier == "ShowMeals", let button = sender as? UIButton{ let destinationVC = segue.destination as! MealViewController destinationVC.dailyPlan = plans[button.tag] } } } extension PlanMealListViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return plans.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! PlanCell let plan = plans[indexPath.section] cell.plan = plan cell.dateLabel.text = plan.date.dateAndWeekday() cell.section = indexPath.section cell.delegate = self cell.tableView.reloadData() return cell } } extension PlanMealListViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let headerHeight: CGFloat = navigationController!.navigationBar.bounds.height + UIApplication.shared.statusBarFrame.height let footerHeight: CGFloat = tabBarController!.tabBar.bounds.height return CGSize(width: self.view.bounds.width, height: self.view.bounds.height - headerHeight - footerHeight) // return self.view.bounds.size } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets.zero } } extension PlanMealListViewController: PlanCellDelegate { func pickButtonTapped(section: Int) { let plan = plans[section] for meal in plan.meals { BaseManager.shared.transaction { meal.mealFoods.removeAll() let when = Food.When(rawValue: meal.name) for _ in 0..<defaultNumbersOfFoodInAMeal { let mealFood = FoodManager.shared.randomMealFood(of: when!) meal.mealFoods.append(mealFood) } } } collectionView.reloadItems(at: [IndexPath(row: 0, section: section)]) } func editButtonTapped(section: Int) { // nothing } }
mit
Sajjon/Zeus
Pods/SwiftyBeaver/sources/BaseDestination.swift
1
11867
// // BaseDestination.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger (Twitter @skreutzb) on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation // store operating system / platform #if os(iOS) let OS = "iOS" #elseif os(OSX) let OS = "OSX" #elseif os(watchOS) let OS = "watchOS" #elseif os(tvOS) let OS = "tvOS" #elseif os(Linux) let OS = "Linux" #elseif os(FreeBSD) let OS = "FreeBSD" #elseif os(Windows) let OS = "Windows" #elseif os(Android) let OS = "Android" #else let OS = "Unknown" #endif @available(*, deprecated:0.5.5) struct MinLevelFilter { var minLevel = SwiftyBeaver.Level.Verbose var path = "" var function = "" } /// destination which all others inherit from. do not directly use public class BaseDestination: Hashable, Equatable { /// if true additionally logs file, function & line public var detailOutput = true /// adds colored log levels where possible public var colored = true /// colors entire log public var coloredLines = false /// runs in own serial background thread for better performance public var asynchronously = true /// do not log any message which has a lower level than this one public var minLevel = SwiftyBeaver.Level.Verbose { didSet { // Craft a new level filter and add it self.addFilter(filter: Filters.Level.atLeast(level: minLevel)) } } /// standard log format; set to "" to not log date at all public var dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" /// set custom log level words for each level public var levelString = LevelString() /// set custom log level colors for each level public var levelColor = LevelColor() public struct LevelString { public var Verbose = "VERBOSE" public var Debug = "DEBUG" public var Info = "INFO" public var Warning = "WARNING" public var Error = "ERROR" } // For a colored log level word in a logged line // XCode RGB colors public struct LevelColor { public var Verbose = "fg150,178,193;" // silver public var Debug = "fg32,155,124;" // green public var Info = "fg70,204,221;" // blue public var Warning = "fg253,202,78;" // yellow public var Error = "fg243,36,73;" // red } var filters = [FilterType]() let formatter = DateFormatter() var reset = "\u{001b}[;" var escape = "\u{001b}[" // each destination class must have an own hashValue Int lazy public var hashValue: Int = self.defaultHashValue public var defaultHashValue: Int {return 0} // each destination instance must have an own serial queue to ensure serial output // GCD gives it a prioritization between User Initiated and Utility var queue: DispatchQueue? //dispatch_queue_t? public init() { let uuid = NSUUID().uuidString let queueLabel = "swiftybeaver-queue-" + uuid queue = DispatchQueue(label: queueLabel, target: queue) addFilter(filter: Filters.Level.atLeast(level: minLevel)) } /// Add a filter that determines whether or not a particular message will be logged to this destination public func addFilter(filter: FilterType) { // There can only be a maximum of one level filter in the filters collection. // When one is set, remove any others if there are any and then add let isNewLevelFilter = self.getFiltersTargeting(target: Filter.TargetType.LogLevel(minLevel), fromFilters: [filter]).count == 1 if isNewLevelFilter { let levelFilters = self.getFiltersTargeting(target: Filter.TargetType.LogLevel(minLevel), fromFilters: self.filters) levelFilters.forEach { filter in self.removeFilter(filter: filter) } } filters.append(filter) } /// Remove a filter from the list of filters public func removeFilter(filter: FilterType) { let index = filters.index { return ObjectIdentifier($0) == ObjectIdentifier(filter) } guard let filterIndex = index else { return } filters.remove(at: filterIndex) } /// send / store the formatted log message to the destination /// returns the formatted log message for processing by inheriting method /// and for unit tests (nil if error) public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, path: String, function: String, line: Int) -> String? { var dateStr = "" var str = "" let levelStr = formattedLevel(level) let formattedMsg = coloredMessage(msg, forLevel: level) dateStr = formattedDate(dateFormat) str = formattedMessage(dateStr, levelString: levelStr, msg: formattedMsg, thread: thread, path: path, function: function, line: line, detailOutput: detailOutput) return str } /// returns a formatted date string func formattedDate(_ dateFormat: String) -> String { //formatter.timeZone = NSTimeZone(abbreviation: "UTC") formatter.dateFormat = dateFormat let dateStr = formatter.string(from: NSDate() as Date) return dateStr } /// returns the log message entirely colored func coloredMessage(_ msg: String, forLevel level: SwiftyBeaver.Level) -> String { if !(colored && coloredLines) { return msg } let color = colorForLevel(level: level) let coloredMsg = escape + color + msg + reset return coloredMsg } /// returns color string for level func colorForLevel(level: SwiftyBeaver.Level) -> String { var color = "" switch level { case SwiftyBeaver.Level.Debug: color = levelColor.Debug case SwiftyBeaver.Level.Info: color = levelColor.Info case SwiftyBeaver.Level.Warning: color = levelColor.Warning case SwiftyBeaver.Level.Error: color = levelColor.Error default: color = levelColor.Verbose } return color } /// returns an optionally colored level noun (like INFO, etc.) func formattedLevel(_ level: SwiftyBeaver.Level) -> String { // optionally wrap the level string in color let color = colorForLevel(level: level) var levelStr = "" switch level { case SwiftyBeaver.Level.Debug: levelStr = levelString.Debug case SwiftyBeaver.Level.Info: levelStr = levelString.Info case SwiftyBeaver.Level.Warning: levelStr = levelString.Warning case SwiftyBeaver.Level.Error: levelStr = levelString.Error default: // Verbose is default levelStr = levelString.Verbose } if colored { levelStr = escape + color + levelStr + reset } return levelStr } /// returns the formatted log message func formattedMessage(_ dateString: String, levelString: String, msg: String, thread: String, path: String, function: String, line: Int, detailOutput: Bool) -> String { var str = "" if dateString != "" { str += "[\(dateString)] " } if detailOutput { if thread != "main" && thread != "" { str += "|\(thread)| " } // just use the file name of the path and remove suffix //let file = path.components(separatedBy: "/").last!.components(".").first! let pathComponents = path.components(separatedBy: "/") if let lastComponent = pathComponents.last { if let file = lastComponent.components(separatedBy: ".").first { str += "\(file).\(function):\(String(line)) \(levelString): \(msg)" } } } else { str += "\(levelString): \(msg)" } return str } /// Answer whether the destination has any message filters /// returns boolean and is used to decide whether to resolve the message before invoking shouldLevelBeLogged func hasMessageFilters() -> Bool { return !getFiltersTargeting(target: Filter.TargetType.Message(.Equals([], true)), fromFilters: self.filters).isEmpty } /// checks if level is at least minLevel or if a minLevel filter for that path does exist /// returns boolean and can be used to decide if a message should be logged or not func shouldLevelBeLogged(level: SwiftyBeaver.Level, path: String, function: String, message: String? = nil) -> Bool { return passesAllRequiredFilters(level: level, path: path, function: function, message: message) && passesAtLeastOneNonRequiredFilter(level: level, path: path, function: function, message: message) } func getFiltersTargeting(target: Filter.TargetType, fromFilters: [FilterType]) -> [FilterType] { return fromFilters.filter { filter in return filter.getTarget() == target } } func passesAllRequiredFilters(level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Bool { let requiredFilters = self.filters.filter { filter in return filter.isRequired() } return applyFilters(targetFilters: requiredFilters, level: level, path: path, function: function, message: message) == requiredFilters.count } func passesAtLeastOneNonRequiredFilter(level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Bool { let nonRequiredFilters = self.filters.filter { filter in return !filter.isRequired() } return nonRequiredFilters.isEmpty || applyFilters(targetFilters: nonRequiredFilters, level: level, path: path, function: function, message: message) > 0 } func passesLogLevelFilters(level: SwiftyBeaver.Level) -> Bool { let logLevelFilters = getFiltersTargeting(target: Filter.TargetType.LogLevel(level), fromFilters: self.filters) return logLevelFilters.filter { filter in return filter.apply(value: level.rawValue) }.count == logLevelFilters.count } func applyFilters(targetFilters: [FilterType], level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Int { return targetFilters.filter { filter in let passes: Bool switch filter.getTarget() { case .LogLevel(_): passes = filter.apply(value: level.rawValue) case .Path(_): passes = filter.apply(value: path) case .Function(_): passes = filter.apply(value: function) case .Message(_): guard let message = message else { return false } passes = filter.apply(value: message) } return passes }.count } /** Triggered by main flush() method on each destination. Runs in background thread. Use for destinations that buffer log items, implement this function to flush those buffers to their final destination (web server...) */ func flush() { // no implementation in base destination needed } } public func == (lhs: BaseDestination, rhs: BaseDestination) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
apache-2.0
ualch9/onebusaway-iphone
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples-UITests/DemosViewControllerUITests.swift
2
3119
/** Copyright (c) Facebook, Inc. and its affiliates. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest final class DemosViewControllerUITests: UITestCase { func test_whenSelectingTailLoading_thatTailLoadingDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Tail Loading") } func test_whenSelectingSearchAutocomplete_thatSearchAutocompleteDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Search Autocomplete") } func test_whenSelectingMixedData_thatMixedDataDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Mixed Data") } func test_whenSelectingNestedAdapter_thatNestedAdapterDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Nested Adapter") } func test_whenSelectingEmptyView_thatEmptyViewDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Empty View") } func test_whenSelectingSingleSectionController_thatSingleSectionControllerScreenIsPresented() { enterAndAssertScreen(withTitle: "Single Section Controller") } func test_whenSelectingStoryboard_thatStoryboardDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Storyboard") } func test_whenSelectingSingleSectionStoryboard_thatSingleSectionStoryboardDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Single Section Storyboard") } func test_whenSelectingWorkingRange_thatWorkingRangeDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Working Range") } func test_whenSelectingDiffAlgorithm_thatDiffAlgorithmDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Diff Algorithm") } func test_whenSelectingSupplementaryViews_thatSupplementaryViewsDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Supplementary Views") } func test_whenSelectingSelfSizingCells_thatSelfSizingCellsDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Self-sizing cells") } func test_whenSelectingDisplayDelegate_thatDisplayDelegateDetailScreenIsPresented() { enterAndAssertScreen(withTitle: "Display delegate") } private func enterAndAssertScreen(withTitle title: String) { let elem = XCUIApplication().collectionViews.cells.staticTexts[title] if !elem.exists { XCUIApplication().collectionViews.element.swipeUp() } XCTAssertTrue(elem.exists) elem.tap() XCTAssertTrue(XCUIApplication().navigationBars[title].exists) } }
apache-2.0
CPRTeam/CCIP-iOS
OPass/Tabs/MoreTab/MoreTableViewController.swift
1
12580
// // MoreTableViewController.swift // OPass // // Created by 腹黒い茶 on 2019/2/9. // 2019 OPass. // import Foundation import UIKit import SwiftUI import AudioToolbox import AFNetworking import FontAwesome_swift import Nuke let ACKNOWLEDGEMENTS = "Acknowledgements" let INTERNAL_CONFIG = "InternalConfig" class MoreTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var moreTableView: UITableView? var shimmeringLogoView: FBShimmeringView = FBShimmeringView.init(frame: CGRect(x: 0, y: 0, width: 500, height: 50)) var userInfo: ScenarioStatus? var moreItems: NSArray? var switchEventButton: UIBarButtonItem? override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destination = segue.destination guard let cell = sender as? UITableViewCell else { return } let title = cell.textLabel?.text Constants.SendFib("MoreTableView", WithEvents: [ "MoreTitle": title ]) destination.title = title cell.setSelected(false, animated: true) } override func viewDidLoad() { super.viewDidLoad() // set logo on nav title self.shimmeringLogoView.isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(navSingleTap)) tapGesture.numberOfTapsRequired = 1 self.shimmeringLogoView.addGestureRecognizer(tapGesture) self.navigationItem.titleView = self.shimmeringLogoView guard let navController = self.navigationController else { return } let nvBar = navController.navigationBar nvBar.setBackgroundImage(UIImage.init(), for: .default) nvBar.shadowImage = UIImage.init() nvBar.backgroundColor = UIColor.clear nvBar.isTranslucent = false let frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: (self.view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0) + navController.navigationBar.frame.size.height) let headView = UIView.init(frame: frame) headView.setGradientColor(from: Constants.appConfigColor.MoreTitleLeftColor, to: Constants.appConfigColor.MoreTitleRightColor, startPoint: CGPoint(x: -0.4, y: 0.5), toPoint: CGPoint(x: 1, y: 0.5)) let naviBackImg = headView.layer.sublayers?.last?.toImage() nvBar.setBackgroundImage(naviBackImg, for: .default) Constants.SendFib("MoreTableViewController") if self.switchEventButton == nil { let attribute = [ NSAttributedString.Key.font: UIFont.fontAwesome(ofSize: 20, style: .solid) ] self.switchEventButton = UIBarButtonItem.init(title: "", style: .plain, target: self, action: #selector(CallSwitchEventView)) self.switchEventButton?.setTitleTextAttributes(attribute, for: .normal) self.switchEventButton?.title = String.fontAwesomeIcon(code: "fa-sign-out-alt") } self.navigationItem.rightBarButtonItem = self.switchEventButton let emptyButton = UIBarButtonItem.init(title: " ", style: .plain, target: nil, action: nil) self.navigationItem.leftBarButtonItem = emptyButton; } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Constants.LoadDevLogoTo(view: self.shimmeringLogoView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if Constants.haveAccessToken { checkNickName() } let features = OPassAPI.eventInfo?.Features.map { feature -> [Any?] in switch OPassKnownFeatures(rawValue: feature.Feature) { case Optional(.Puzzle): return ["Puzzle", feature] case Optional(.Ticket): return ["Ticket", feature] case Optional(.Telegram): return ["Telegram", feature] case Optional(.WiFiConnect): return ["WiFiConnect", feature] case Optional(.Venue): return ["VenueWeb", feature] case Optional(.Staffs): return ["StaffsWeb", feature] case Optional(.Sponsors): return ["SponsorsWeb", feature] case Optional(.Partners): return ["PartnersWeb", feature] case Optional(.WebView): return ["MoreWeb", feature] default: return ["", nil] } } self.moreItems = ((features ?? [["", nil]]) + [ [ACKNOWLEDGEMENTS, nil] ] + ( Constants.isDevMode ? [[INTERNAL_CONFIG, nil]] : [] )).filter { guard let v = $0[0] else { return false } guard let s = v as? String else { return false } return s.count > 0 } as NSArray } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func CallSwitchEventView() { // clear last event id OPassAPI.lastEventId = "" self.dismiss(animated: true, completion: nil) } @objc func navSingleTap() { //NSLog(@"navSingleTap"); self.handleNavTapTimes() } func checkNickName(max: Int = 10, current: Int = 1, _ milliseconds: Int = 500) { NSLog("Check Nick Name \(current)/\(max)") self.userInfo = OPassAPI.userInfo if (self.userInfo != nil) { self.moreTableView?.reloadSections([0], with: .automatic) } else if (current < max) { let delayMSec: DispatchTimeInterval = .milliseconds(milliseconds) DispatchQueue.main.asyncAfter(deadline: .now() + delayMSec) { self.checkNickName(max: max, current: current + 1, milliseconds) } } } func handleNavTapTimes() { struct tap { static var tapTimes: Int = 0 static var oldTapTime: Date? static var newTapTime: Date? } tap.newTapTime = Date.init() if (tap.oldTapTime == nil) { tap.oldTapTime = tap.newTapTime } if let newTapTime = tap.newTapTime { if let oldTapTime = tap.oldTapTime { if (newTapTime.timeIntervalSince(oldTapTime) <= 0.25) { tap.tapTimes += 1 if (tap.tapTimes >= 10) { NSLog("-- Success tap 10 times --") AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) if !Constants.isDevMode { NSLog("-- Enable DEV_MODE --") Constants.isDevMode = true } else { NSLog("-- Disable DEV_MODE --") Constants.isDevMode = false } Constants.LoadDevLogoTo(view: self.shimmeringLogoView) tap.tapTimes = 1 } } else { NSLog("-- Failed, just tap %2d times --", tap.tapTimes) NSLog("-- Failed to trigger DEV_MODE --") tap.tapTimes = 1 } tap.oldTapTime = tap.newTapTime } } } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let moreTableView = self.moreTableView else { return CGFloat(0) } guard let moreItems = self.moreItems else { return moreTableView.frame.size.height } return moreTableView.frame.size.height / CGFloat(moreItems.count + 1) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let moreItems = self.moreItems else { return 0 } return moreItems.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: NSInteger) -> String? { return (self.userInfo?.UserId.count ?? 0) > 0 ? String(format: NSLocalizedString("Hi", comment: ""), self.userInfo?.UserId ?? "") : nil; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let moreItems = self.moreItems { if let item = moreItems.object(at: indexPath.row) as? NSArray { let feature = item[1] as? EventFeatures if let cellId = item[0] as? String { if let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? MoreCell { cell.Feature = feature cell.backgroundColor = .clear let cellIconId = NSLocalizedString("icon-\(cellId)", comment: ""); // FontAwesome Icon if let classId = cellIconId.split(separator: " ").first { var fontStyle: FontAwesomeStyle { switch String(classId) { case "fas": return FontAwesomeStyle.solid case "fab": return FontAwesomeStyle.brands default: return FontAwesomeStyle.solid } } if let fontName = FontAwesome(rawValue: String(cellIconId.split(separator: " ").last ?? "")) { if let iV = cell.imageView { iV.image = UIImage.fontAwesomeIcon(name: fontName, style: fontStyle, textColor: UIColor.black, size: CGSize(width: 24, height: 24)) } } } // Custome Icon if let customIconUrl = feature?.Icon { ImagePipeline.shared.loadImage( with: customIconUrl, progress: { _, _, _ in print("progress updated") }, completion: { (result: Result<ImageResponse, ImagePipeline.Error>) in print("task completed") cell.imageView?.image = try? result.get().image.scaled(to: CGSize(width: 24, height: 24)) } ) } let cellText = [ACKNOWLEDGEMENTS, INTERNAL_CONFIG].contains(where: { $0 == cellId } ) ? NSLocalizedString(cellId, comment: "") : (feature?.DisplayText[Constants.shortLangUI] ?? "") if ((OPassAPI.userInfo?.Role ?? "").count > 0 && !(feature?.VisibleRoles?.contains(OPassAPI.userInfo?.Role ?? "") ?? true)) { cell.isUserInteractionEnabled = false } cell.textLabel?.text = cellText return cell; } } } } return tableView.dequeueReusableCell(withIdentifier: "", for: indexPath) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) as? MoreCell else { return } switch (cell.Feature?.Feature) { case OPassKnownFeatures.WebView.rawValue: guard let url = cell.Feature?.Url else { break } Constants.OpenInAppSafari(forURL: url) break case OPassKnownFeatures.WiFiConnect.rawValue: guard let wifi = cell.Feature?.WiFi.first else { break } NEHotspot.ConnectWiFi(SSID: wifi.SSID, withPass: wifi.Password) break default: break } tableView.deselectRow(at: indexPath, animated: true) } @IBSegueAction func addInternalConfigView(_ coder: NSCoder) -> UIViewController? { if let hostingController = UIHostingController(coder: coder, rootView: InternalConfigView()) { hostingController.view.backgroundColor = UIColor.clear; return hostingController } return nil } }
gpl-3.0
nRewik/swift-corelibs-foundation
Foundation/NSIndexSet.swift
1
24241
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* Class for managing set of indexes. The set of valid indexes are 0 .. NSNotFound - 1; trying to use indexes outside this range is an error. NSIndexSet uses NSNotFound as a return value in cases where the queried index doesn't exist in the set; for instance, when you ask firstIndex and there are no indexes; or when you ask for indexGreaterThanIndex: on the last index, and so on. The following code snippets can be used to enumerate over the indexes in an NSIndexSet: // Forward var currentIndex = set.firstIndex while currentIndex != NSNotFound { ... currentIndex = set.indexGreaterThanIndex(currentIndex) } // Backward var currentIndex = set.lastIndex while currentIndex != NSNotFound { ... currentIndex = set.indexLessThanIndex(currentIndex) } To enumerate without doing a call per index, you can use the method getIndexes:maxCount:inIndexRange:. */ public class NSIndexSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { // all instance variables are private internal var _ranges = [NSRange]() internal var _count = 0 override public init() { _count = 0 _ranges = [] } public init(indexesInRange range: NSRange) { _count = range.length _ranges = _count == 0 ? [] : [range] } public init(indexSet: NSIndexSet) { _ranges = indexSet._ranges _count = indexSet.count } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public convenience init(index value: Int) { self.init(indexesInRange: NSMakeRange(value, 1)) } public func isEqualToIndexSet(indexSet: NSIndexSet) -> Bool { guard indexSet !== self else { return true } let otherRanges = indexSet._ranges if _ranges.count != otherRanges.count { return false } for (r1, r2) in zip(_ranges, otherRanges) { if r1.length != r2.length || r1.location != r2.location { return false } } return true } public var count: Int { return _count } /* The following six methods will return NSNotFound if there is no index in the set satisfying the query. */ public var firstIndex: Int { return _ranges.first?.location ?? NSNotFound } public var lastIndex: Int { guard _ranges.count > 0 else { return NSNotFound } return NSMaxRange(_ranges.last!) - 1 } internal func _indexAndRangeAdjacentToOrContainingIndex(idx : Int) -> (Int, NSRange)? { let count = _ranges.count guard count > 0 else { return nil } var min = 0 var max = count - 1 while min < max { let rIdx = (min + max) / 2 let range = _ranges[rIdx] if range.location > idx { max = rIdx } else if NSMaxRange(range) - 1 < idx { min = rIdx + 1 } else { return (rIdx, range) } } return (min, _ranges[min]) } internal func _indexOfRangeContainingIndex (idx : Int) -> Int? { if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) { return NSLocationInRange(idx, range) ? rIdx : nil } else { return nil } } internal func _indexOfRangeBeforeOrContainingIndex(idx : Int) -> Int? { if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) { if range.location <= idx { return rIdx } else if rIdx > 0 { return rIdx - 1 } else { return nil } } else { return nil } } internal func _indexOfRangeAfterOrContainingIndex(idx : Int) -> Int? { if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) { if NSMaxRange(range) - 1 >= idx { return rIdx } else if rIdx + 1 < _ranges.count { return rIdx + 1 } else { return nil } } else { return nil } } internal func _indexClosestToIndex(idx: Int, equalAllowed : Bool, following: Bool) -> Int? { guard _count > 0 else { return nil } if following { var result = idx if !equalAllowed { guard idx < NSNotFound else { return nil } result += 1 } if let rangeIndex = _indexOfRangeAfterOrContainingIndex(result) { let range = _ranges[rangeIndex] return NSLocationInRange(result, range) ? result : range.location } } else { var result = idx if !equalAllowed { guard idx > 0 else { return nil } result -= 1 } if let rangeIndex = _indexOfRangeBeforeOrContainingIndex(result) { let range = _ranges[rangeIndex] return NSLocationInRange(result, range) ? result : (NSMaxRange(range) - 1) } } return nil } public func indexGreaterThanIndex(value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: false, following: true) ?? NSNotFound } public func indexLessThanIndex(value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: false, following: false) ?? NSNotFound } public func indexGreaterThanOrEqualToIndex(value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: true, following: true) ?? NSNotFound } public func indexLessThanOrEqualToIndex(value: Int) -> Int { return _indexClosestToIndex(value, equalAllowed: true, following: false) ?? NSNotFound } /* Fills up to bufferSize indexes in the specified range into the buffer and returns the number of indexes actually placed in the buffer; also modifies the optional range passed in by pointer to be "positioned" after the last index filled into the buffer.Example: if the index set contains the indexes 0, 2, 4, ..., 98, 100, for a buffer of size 10 and the range (20, 80) the buffer would contain 20, 22, ..., 38 and the range would be modified to (40, 60). */ public func getIndexes(indexBuffer: UnsafeMutablePointer<Int>, maxCount bufferSize: Int, inIndexRange range: NSRangePointer) -> Int { let minIndex : Int let maxIndex : Int if range != nil { minIndex = range.memory.location maxIndex = NSMaxRange(range.memory) - 1 } else { minIndex = firstIndex maxIndex = lastIndex } guard minIndex <= maxIndex else { return 0 } if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(minIndex) { var rangeIndex = initialRangeIndex let rangeCount = _ranges.count var counter = 0 var idx = minIndex var offset = 0 while rangeIndex < rangeCount && idx <= maxIndex && counter < bufferSize { let currentRange = _ranges[rangeIndex] if currentRange.location <= minIndex { idx = minIndex offset = minIndex - currentRange.location } else { idx = currentRange.location } while idx <= maxIndex && counter < bufferSize && offset < currentRange.length { indexBuffer.advancedBy(counter).memory = idx counter += 1 idx += 1 offset += 1 } if offset >= currentRange.length { rangeIndex += 1 offset = 0 } } if counter > 0 && range != nil { let delta = indexBuffer.advancedBy(counter - 1).memory - minIndex + 1 range.memory.location += delta range.memory.length -= delta } return counter } else { return 0 } } public func countOfIndexesInRange(range: NSRange) -> Int { guard _count > 0 && range.length > 0 else { return 0 } if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location) { var rangeIndex = initialRangeIndex let maxRangeIndex = NSMaxRange(range) - 1 var result = 0 let firstRange = _ranges[rangeIndex] if firstRange.location < range.location { if NSMaxRange(firstRange) - 1 >= maxRangeIndex { return range.length } result = NSMaxRange(firstRange) - range.location rangeIndex += 1 } for curRange in _ranges.suffixFrom(rangeIndex) { if NSMaxRange(curRange) - 1 > maxRangeIndex { if curRange.location <= maxRangeIndex { result += maxRangeIndex + 1 - curRange.location } break } result += curRange.length } return result } else { return 0 } } public func containsIndex(value: Int) -> Bool { return _indexOfRangeContainingIndex(value) != nil } public func containsIndexesInRange(range: NSRange) -> Bool { guard range.length > 0 else { return false } if let rIdx = self._indexOfRangeContainingIndex(range.location) { return NSMaxRange(_ranges[rIdx]) >= NSMaxRange(range) } else { return false } } public func containsIndexes(indexSet: NSIndexSet) -> Bool { guard self !== indexSet else { return true } var result = true enumerateRangesUsingBlock { range, stop in if !self.containsIndexesInRange(range) { result = false stop.memory = true } } return result } public func intersectsIndexesInRange(range: NSRange) -> Bool { guard range.length > 0 else { return false } if let rIdx = _indexOfRangeBeforeOrContainingIndex(range.location) { if NSMaxRange(_ranges[rIdx]) - 1 >= range.location { return true } } if let rIdx = _indexOfRangeAfterOrContainingIndex(range.location) { if NSMaxRange(range) - 1 >= _ranges[rIdx].location { return true } } return false } internal func _enumerateWithOptions<P, R>(opts : NSEnumerationOptions, range: NSRange, paramType: P.Type, returnType: R.Type, block: (P, UnsafeMutablePointer<ObjCBool>) -> R) -> Int? { guard !opts.contains(.Concurrent) else { NSUnimplemented() } guard let startRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location), let endRangeIndex = _indexOfRangeBeforeOrContainingIndex(NSMaxRange(range) - 1) else { return nil } var result : Int? = nil let reverse = opts.contains(.Reverse) let passRanges = paramType == NSRange.self let findIndex = returnType == Bool.self var stop = false let ranges = _ranges[startRangeIndex...endRangeIndex] let rangeSequence = (reverse ? AnySequence(ranges.reverse()) : AnySequence(ranges)) outer: for curRange in rangeSequence { let intersection = NSIntersectionRange(curRange, range) if passRanges { if intersection.length > 0 { block(intersection as! P, &stop) } if stop { break outer } } else if intersection.length > 0 { let maxIndex = NSMaxRange(intersection) - 1 let indexes = reverse ? maxIndex.stride(through: intersection.location, by: -1) : intersection.location.stride(through: maxIndex, by: 1) for idx in indexes { if findIndex { let found : Bool = block(idx as! P, &stop) as! Bool if found { result = idx stop = true } } else { block(idx as! P, &stop) } if stop { break outer } } } // else, continue } return result } public func enumerateIndexesUsingBlock(block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateIndexesWithOptions([], usingBlock: block) } public func enumerateIndexesWithOptions(opts: NSEnumerationOptions, usingBlock block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) { _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Void.self, block: block) } public func enumerateIndexesInRange(range: NSRange, options opts: NSEnumerationOptions, usingBlock block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) { _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self, block: block) } public func indexPassingTest(predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { return indexWithOptions([], passingTest: predicate) } public func indexWithOptions(opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { return _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound } public func indexInRange(range: NSRange, options opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { return _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound } public func indexesPassingTest(predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet { return indexesInRange(NSMakeRange(0, Int.max), options: [], passingTest: predicate) } public func indexesWithOptions(opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet { return indexesInRange(NSMakeRange(0, Int.max), options: opts, passingTest: predicate) } public func indexesInRange(range: NSRange, options opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet { let result = NSMutableIndexSet() _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self) { idx, stop in if predicate(idx, stop) { result.addIndex(idx) } } return result } /* The following three convenience methods allow you to enumerate the indexes in the receiver by ranges of contiguous indexes. The performance of these methods is not guaranteed to be any better than if they were implemented with enumerateIndexesInRange:options:usingBlock:. However, depending on the receiver's implementation, they may perform better than that. If the specified range for enumeration intersects a range of contiguous indexes in the receiver, then the block will be invoked with the intersection of those two ranges. */ public func enumerateRangesUsingBlock(block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateRangesWithOptions([], usingBlock: block) } public func enumerateRangesWithOptions(opts: NSEnumerationOptions, usingBlock block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: NSRange.self, returnType: Void.self, block: block) } public func enumerateRangesInRange(range: NSRange, options opts: NSEnumerationOptions, usingBlock block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { _enumerateWithOptions(opts, range: range, paramType: NSRange.self, returnType: Void.self, block: block) } } extension NSIndexSet : SequenceType { public struct Generator : GeneratorType { internal let _set: NSIndexSet internal var _first: Bool = true internal var _current: Int? internal init(_ set: NSIndexSet) { self._set = set self._current = nil } public mutating func next() -> Int? { if _first { _current = _set.firstIndex _first = false } else if let c = _current { _current = _set.indexGreaterThanIndex(c) } if _current == NSNotFound { _current = nil } return _current } } public func generate() -> Generator { return Generator(self) } } public class NSMutableIndexSet : NSIndexSet { public func addIndexes(indexSet: NSIndexSet) { indexSet.enumerateRangesUsingBlock { range, _ in self.addIndexesInRange(range) } } public func removeIndexes(indexSet: NSIndexSet) { indexSet.enumerateRangesUsingBlock { range, _ in self.removeIndexesInRange(range) } } public func removeAllIndexes() { _ranges = [] _count = 0 } public func addIndex(value: Int) { self.addIndexesInRange(NSMakeRange(value, 1)) } public func removeIndex(value: Int) { self.removeIndexesInRange(NSMakeRange(value, 1)) } internal func _insertRange(range: NSRange, atIndex index: Int) { _ranges.insert(range, atIndex: index) _count += range.length } internal func _replaceRangeAtIndex(index: Int, withRange range: NSRange?) { let oldRange = _ranges[index] if let range = range { _ranges[index] = range _count += range.length - oldRange.length } else { _ranges.removeAtIndex(index) _count -= oldRange.length } } internal func _mergeOverlappingRangesStartingAtIndex(index: Int) { var rangeIndex = index while _ranges.count > 0 && rangeIndex < _ranges.count - 1 { let curRange = _ranges[rangeIndex] let nextRange = _ranges[rangeIndex + 1] let curEnd = NSMaxRange(curRange) let nextEnd = NSMaxRange(nextRange) if curEnd >= nextRange.location { // overlaps if curEnd < nextEnd { self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(nextEnd - curRange.location, curRange.length)) rangeIndex += 1 } self._replaceRangeAtIndex(rangeIndex + 1, withRange: nil) } else { break } } } public func addIndexesInRange(range: NSRange) { guard range.length > 0 else { return } let addEnd = NSMaxRange(range) let startRangeIndex = _indexOfRangeBeforeOrContainingIndex(range.location) ?? 0 var replacedRangeIndex : Int? var rangeIndex = startRangeIndex while rangeIndex < _ranges.count { let curRange = _ranges[rangeIndex] let curEnd = NSMaxRange(curRange) if addEnd < curRange.location { _insertRange(range, atIndex: rangeIndex) // Done. No need to merge return } else if range.location < curRange.location && addEnd >= curRange.location { if addEnd > curEnd { _replaceRangeAtIndex(rangeIndex, withRange: range) } else { _replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(range.location, curEnd - range.location)) } replacedRangeIndex = rangeIndex // Proceed to merging break } else if range.location >= curRange.location && addEnd < curEnd { // Nothing to add return } else if range.location >= curRange.location && range.location <= curEnd && addEnd > curEnd { _replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(addEnd - curRange.location, curRange.location)) replacedRangeIndex = rangeIndex // Proceed to merging break } rangeIndex += 1 } if let r = replacedRangeIndex { _mergeOverlappingRangesStartingAtIndex(r) } else { _insertRange(range, atIndex: _ranges.count) } } public func removeIndexesInRange(range: NSRange) { guard range.length > 0 else { return } guard let startRangeIndex = (range.location > 0) ? _indexOfRangeAfterOrContainingIndex(range.location) : 0 else { return } let removeEnd = NSMaxRange(range) var rangeIndex = startRangeIndex while rangeIndex < _ranges.count { let curRange = _ranges[rangeIndex] let curEnd = NSMaxRange(curRange) if removeEnd < curRange.location { // Nothing to remove return } else if range.location <= curRange.location && removeEnd >= curRange.location { if removeEnd >= curEnd { _replaceRangeAtIndex(rangeIndex, withRange: nil) // Don't increment rangeIndex continue } else { self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(removeEnd, curEnd - removeEnd)) return } } else if range.location > curRange.location && removeEnd < curEnd { let firstPiece = NSMakeRange(curRange.location, range.location - curRange.location) let secondPiece = NSMakeRange(removeEnd, curEnd - removeEnd) _replaceRangeAtIndex(rangeIndex, withRange: secondPiece) _insertRange(firstPiece, atIndex: rangeIndex) } else if range.location > curRange.location && range.location < curEnd && removeEnd >= curEnd { _replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, range.location - curRange.location)) } rangeIndex += 1 } } /* For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta]. */ public func shiftIndexesStartingAtIndex(index: Int, by delta: Int) { NSUnimplemented() } }
apache-2.0
1457792186/JWSwift
SwiftLearn/SwiftDemo/SwiftDemo/Home/JWHomeViewController.swift
1
3897
// // JWHomeViewController.swift // SwiftDemo // // Created by apple on 17/5/4. // Copyright © 2017年 UgoMedia. All rights reserved. // import UIKit class JWHomeViewController: JWBasicViewController,UITableViewDelegate,UITableViewDataSource{ @IBOutlet weak var homeTableView: UITableView! @objc var dataArr = [JWHomeModel](); override func viewDidLoad() { super.viewDidLoad() self.title = "首页"; self.registerTableView(); self.dataArrSet(); } @objc func registerTableView() -> Void { // self.homeTableView.register(JWHomeTableViewCell.self, forCellReuseIdentifier: "JWHomeTableViewCell"); let cellNib = UINib(nibName: "JWHomeTableViewCell", bundle: nil) self.homeTableView.register(cellNib, forCellReuseIdentifier: "JWHomeTableViewCell") } @objc func dataArrSet(){ let nameArr = ["英雄联盟","DOTA"]; let subNameArr = ["各路英雄大逃杀","荣耀背后的嗜血神灵"]; let titleArr = ["英雄联盟","英雄联盟","英雄联盟","英雄联盟"]; let anchorArr = ["水晶卡特","赛事专用直播间","Riot、LCS","主播油条"]; let countArr = ["4535","70000","69000","476000"]; let subTitleArr = ["2J杀人如何利用卡特琳娜顺利爬","LSPL春季赛SNG vs RYL直播中","LCS TSM vs FOX 正在直播","油条:五个隐身英雄套路上分系"]; let imgArr = ["home_logo_video0","home_logo_video1","home_logo_video2","home_logo_video3"]; for index in 0..<2{ let dataDic:NSMutableDictionary = NSMutableDictionary.init(capacity: 0); dataDic.setObject(nameArr[index%2], forKey: "title" as NSCopying); dataDic.setObject("home_logo_type\(index%2)", forKey:"imageName" as NSCopying); dataDic.setObject(subNameArr[index%2], forKey:"subTitle" as NSCopying); let contentArr:NSMutableArray = NSMutableArray.init(capacity: 0); for idx in 0..<titleArr.count { if idx%2 == index { let contentDic:NSMutableDictionary = NSMutableDictionary.init(capacity: 0); contentDic.setObject(titleArr[idx], forKey: "type" as NSCopying); contentDic.setObject(imgArr[idx], forKey: "imageName" as NSCopying); contentDic.setObject(countArr[idx], forKey: "audienceCount" as NSCopying); contentDic.setObject(subTitleArr[idx], forKey: "title" as NSCopying); contentDic.setObject(anchorArr[idx], forKey: "uper" as NSCopying); contentArr.add(contentDic); } } dataDic.setObject(contentArr, forKey:"content" as NSCopying); dataArr.append(JWHomeModel.init(dataDic: dataDic)); } } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ let detailVC = JWHomeDetailViewController(); let detailModel = dataArr[indexPath.row]; detailVC.dataModel = detailModel.content; self.navigationController?.pushViewController(detailVC, animated:true); } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return (80 * mainScreenWidth / 375.0); } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return dataArr.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let homeCell:JWHomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "JWHomeTableViewCell", for: indexPath) as! JWHomeTableViewCell; homeCell.setData(dataModel: dataArr[indexPath.row]); return homeCell; } }
apache-2.0
focuspirit/PxDensity
PxDensity/AppDelegate.swift
1
2144
// // AppDelegate.swift // PxDensity // // Created by focuspirit on 05/01/15. // Copyright (c) 2015 focuspirit. 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
jpedrosa/sua_nc
Sources/csv_table.swift
2
8531
enum CSVTableParserEntry { case Header case HeaderExit case Row case RowExit case Column case ColumnQuoted } // Unicode data. // // The file format is like this: // // * The first row includes the serial number only. It is a sequencial number // starting from 0 that helps to make the rows unique for updating and deleting. // // * The second row is the header row that helps to give a label to each column. // The very first column is already labeled by default with "id". // // * From the third row onwards we find the actual data rows. They all start // with the id column. // // * All rows should end with just the newline character(\n or 10). // // * All rows should include the same number of columns. // // * Data is in general represented in string format only. It simplifies it // a lot and may match the use-case of users when they already have strings to // compare the data with. // // * The column data follows the convention specified on this Wikipedia entry: // https://en.wikipedia.org/wiki/Comma-separated_values // Where columns can start with a double quote which can include within it: // // ** A data comma. E.g. "Hey, ho" // // ** A data newline character. E.g. "So \n it begins." // // ** And even a data double quote if it is escaped with another double // quote. E.g. "Let's "" go" // public struct CSVTable { var _path: String public var serialId = 0 var stream = ByteStream() var entryParser = CSVTableParserEntry.Header var _header = [String]() var columnGroup = CSVTableParserEntry.Header var recordExit = CSVTableParserEntry.HeaderExit var columnValue = "" var _rows = [[String]]() var _row = [String]() var unescapedColumnValue = "" public init(path: String) throws { _path = path try load() } mutating public func load() throws { var f = try File(path: _path) defer { f.close() } stream.bytes = try f.readAllBytes() if stream.eatWhileDigit() { serialId = Int(stream.collectTokenString()!)! if stream.eatOne(10) { // Newline entryParser = .Column _header = [] columnGroup = .Header recordExit = .HeaderExit while !stream.isEol { try next() } // Be nice and check for a last row without a trailing new line // following it. Sometimes when manually editing a file, the last line // could lose its new line. if !_row.isEmpty { try inRowExit() } } else { throw CSVTableError.NewLine } } else { throw CSVTableError.SerialId } } mutating func next() throws { switch entryParser { case .Header: try inHeader() case .HeaderExit: try inHeaderExit() case .Row: try inRow() case .RowExit: try inRowExit() case .Column: try inColumn() case .ColumnQuoted: try inColumnQuoted() } } mutating func inHeader() throws { _header.append(columnValue) entryParser = .Column } mutating func inHeaderExit() throws { if header.isEmpty { throw CSVTableError.Header } entryParser = .Column columnGroup = .Row recordExit = .RowExit _row = [] } mutating func inRow() throws { _row.append(columnValue) entryParser = .Column } mutating func inRowExit() throws { if _row.count != _header.count { throw CSVTableError.Row } entryParser = .Column _rows.append(_row) _row = [] } func matchCommaOrNewLine(c: UInt8) -> Bool { return c == 44 || c == 10 } mutating func inColumn() throws { stream.startIndex = stream.currentIndex if stream.eatDoubleQuote() { unescapedColumnValue = "" entryParser = .ColumnQuoted stream.startIndex = stream.currentIndex } else if stream.eatComma() { columnValue = "" entryParser = columnGroup } else if stream.eatUntil(matchCommaOrNewLine) { columnValue = stream.collectTokenString()! stream.eatComma() entryParser = columnGroup } else if stream.eatOne(10) { entryParser = recordExit } else { throw CSVTableError.Unreachable } } mutating func inColumnQuoted() throws { if stream.skipTo(34) >= 0 { // " if let s = stream.collectTokenString() { unescapedColumnValue += s } stream.eatDoubleQuote() stream.startIndex = stream.currentIndex if !stream.eatDoubleQuote() { // Ends if not an escaped quote sequence: "" if let s = stream.collectTokenString() { unescapedColumnValue += s } columnValue = unescapedColumnValue stream.eatComma() entryParser = columnGroup } } else { throw CSVTableError.Column } } public var path: String { return _path } public var header: [String] { return _header } public var rows: [[String]] { return _rows } // Don't include the id, since it will be automatically generated based on the // next number on the sequence. mutating public func insert(row: [String]) throws -> Int { if row.count + 1 != header.count { throw CSVTableError.Insert } var a = [String]() let sid = serialId a.append("\(sid)") for s in row { a.append(s) } _rows.append(a) serialId += 1 return sid } // Alias for insert. mutating public func append(row: [String]) throws -> Int { return try insert(row) } // This will insert it if it does not exist, and it will keep whatever index // id it was called with. This can help with data migration. The serialId // can be adjusted accordingly afterwards. mutating public func update(index: String, row: [String]) throws { if row.count + 1 != header.count { throw CSVTableError.Update } let n = findIndex(index) if n >= 0 { for i in 0..<row.count { _rows[n][i + 1] = row[i] } } else { var a = [String]() a.append(index) for s in row { a.append(s) } _rows.append(a) } } func findIndex(index: String) -> Int { for i in 0..<_rows.count { if _rows[i][0] == index { return i } } return -1 } // If the record pointed at by index does not exist, simply ignore it. mutating public func delete(index: String) { let n = findIndex(index) if n >= 0 { _rows.removeAtIndex(n) } } mutating public func updateColumn(index: String, columnIndex: Int, value: String) { let n = findIndex(index) if n >= 0 { _rows[n][columnIndex] = value } } mutating public func select(index: String) -> [String]? { let n = findIndex(index) if n >= 0 { return _rows[n] } return nil } public var data: String { var s = "\(serialId)\n" var comma = false for c in _header { if comma { s += "," } s += CSVTable.escape(c) comma = true } s += "\n" if !_rows.isEmpty { for row in _rows { var comma = false for c in row { if comma { s += "," } s += CSVTable.escape(c) comma = true } s += "\n" } s += "\n" } return s } public func save() throws { try IO.write(path, string: data) } // This makes sure the data is escaped for double quote, comma and new line. public static func escape(string: String) -> String { let len = string.utf16.count var i = 0 while i < len { let c = string.utf16.codeUnitAt(i) if c == 34 || c == 44 || c == 10 { // " , newline i += 1 var s = "\"" s += string.utf16.substring(0, endIndex: i) ?? "" if c == 34 { s += "\"" } var si = i while i < len { if string.utf16.codeUnitAt(i) == 34 { s += string.utf16.substring(si, endIndex: i + 1) ?? "" s += "\"" si = i + 1 } i += 1 } s += string.utf16.substring(si, endIndex: i) ?? "" s += "\"" return s } i += 1 } return string } public static func create(path: String, header: [String]) throws -> CSVTable { var s = "0\nid" for c in header { s += "," s += escape(c) } s += "\n" try IO.write(path, string: s) return try CSVTable(path: path) } } enum CSVTableError: ErrorType { case SerialId case NewLine case Header case Row case Column case Insert case Update case Unreachable }
apache-2.0
LinDing/Positano
Positano/Protocols/Shareable.swift
1
246
// // Shareable.swift // Yep // // Created by NIX on 16/8/25. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation import UIKit protocol Shareable { } extension URL: Shareable { } extension UIImage: Shareable { }
mit
milseman/swift
test/stdlib/CharacterTraps.swift
8
917
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out_Debug // RUN: %target-build-swift %s -o %t/a.out_Release -O // // RUN: %target-run %t/a.out_Debug // RUN: %target-run %t/a.out_Release // REQUIRES: executable_test import StdlibUnittest let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release" var CharacterTraps = TestSuite("CharacterTraps" + testSuiteSuffix) CharacterTraps.test("CharacterFromEmptyString") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { var s = "" expectCrashLater() _ = Character(s) } CharacterTraps.test("CharacterFromMoreThanOneGraphemeCluster") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "this trap is only guaranteed to happen in Debug builds")) .code { var s = "ab" expectCrashLater() _ = Character(s) } runAllTests()
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsServices/Email/Badge/EmailVerificationBadgeInteractor.swift
1
660
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import PlatformUIKit import RxRelay import RxSwift final class EmailVerificationBadgeInteractor: DefaultBadgeAssetInteractor { // MARK: - Setup init(service: SettingsServiceAPI) { super.init() service .valueObservable .map(\.isEmailVerified) .map { $0 ? .verified : .unverified } .map { .loaded(next: $0) } // TODO: Error handing .catchAndReturn(.loading) .startWith(.loading) .bindAndCatch(to: stateRelay) .disposed(by: disposeBag) } }
lgpl-3.0
BranchMetrics/ios-branch-deep-linking
Branch-TestBed/Branch-SDK-Tests/BranchEvent.Test.swift
2
5727
// // BranchEvent.Test.swift // Branch-SDK-Tests // // Created by edward on 10/9/17. // Copyright © 2017 Branch, Inc. All rights reserved. // import Foundation class BranchEventTestSwift : BNCTestCase { override func setUp() { Branch.getInstance("key_live_foo") } func testBranchEvent() { // Set up the Branch Universal Object -- let branchUniversalObject = BranchUniversalObject.init() branchUniversalObject.canonicalIdentifier = "item/12345" branchUniversalObject.canonicalUrl = "https://branch.io/deepviews" branchUniversalObject.title = "My Content Title" branchUniversalObject.contentDescription = "my_product_description1" branchUniversalObject.imageUrl = "https://test_img_url" branchUniversalObject.keywords = [ "My_Keyword1", "My_Keyword2" ] branchUniversalObject.creationDate = Date.init(timeIntervalSince1970:1501869445321.0/1000.0) branchUniversalObject.expirationDate = Date.init(timeIntervalSince1970:212123232544.0/1000.0) branchUniversalObject.locallyIndex = true branchUniversalObject.publiclyIndex = false branchUniversalObject.contentMetadata.contentSchema = .commerceProduct branchUniversalObject.contentMetadata.quantity = 2 branchUniversalObject.contentMetadata.price = 23.20 branchUniversalObject.contentMetadata.currency = .USD branchUniversalObject.contentMetadata.sku = "1994320302" branchUniversalObject.contentMetadata.productName = "my_product_name1" branchUniversalObject.contentMetadata.productBrand = "my_prod_Brand1" branchUniversalObject.contentMetadata.productCategory = .babyToddler branchUniversalObject.contentMetadata.productVariant = "3T" branchUniversalObject.contentMetadata.condition = .fair branchUniversalObject.contentMetadata.ratingAverage = 5; branchUniversalObject.contentMetadata.ratingCount = 5; branchUniversalObject.contentMetadata.ratingMax = 7; branchUniversalObject.contentMetadata.rating = 6; branchUniversalObject.contentMetadata.addressStreet = "Street_name1" branchUniversalObject.contentMetadata.addressCity = "city1" branchUniversalObject.contentMetadata.addressRegion = "Region1" branchUniversalObject.contentMetadata.addressCountry = "Country1" branchUniversalObject.contentMetadata.addressPostalCode = "postal_code" branchUniversalObject.contentMetadata.latitude = 12.07 branchUniversalObject.contentMetadata.longitude = -97.5 branchUniversalObject.contentMetadata.imageCaptions = [ "my_img_caption1", "my_img_caption_2" ] branchUniversalObject.contentMetadata.customMetadata = [ "Custom_Content_metadata_key1": "Custom_Content_metadata_val1", "Custom_Content_metadata_key2": "Custom_Content_metadata_val2" ] // Set up the event properties -- let event = BranchEvent.standardEvent(.purchase) event.transactionID = "12344555" event.currency = .USD; event.revenue = 1.5 event.shipping = 10.2 event.tax = 12.3 event.coupon = "test_coupon"; event.affiliation = "test_affiliation"; event.eventDescription = "Event _description"; event.searchQuery = "Query" event.customData = [ "Custom_Event_Property_Key1": "Custom_Event_Property_val1", "Custom_Event_Property_Key2": "Custom_Event_Property_val2" ] var testDictionary = event.dictionary() var dictionary = self.mutableDictionaryFromBundleJSON(withKey: "V2EventProperties") XCTAssert((dictionary?.isEqual(to: testDictionary))!) testDictionary = branchUniversalObject.dictionary() as! [AnyHashable : Any] dictionary = self.mutableDictionaryFromBundleJSON(withKey: "BranchUniversalObjectJSON") dictionary!["$publicly_indexable"] = nil // Remove this value since we don't add false values. XCTAssert((dictionary?.isEqual(to: testDictionary))!) event.contentItems = [ branchUniversalObject ] event.logEvent() } func testExampleSyntaxSwift() { let contentItem = BranchUniversalObject.init() contentItem.canonicalIdentifier = "item/123" contentItem.canonicalUrl = "https://branch.io/item/123" contentItem.contentMetadata.ratingAverage = 5.0; var event = BranchEvent.standardEvent(.spendCredits) event.transactionID = "tx1234" event.eventDescription = "Product Search" event.searchQuery = "user search query terms for product xyz" event.customData["Custom_Event_Property_Key1"] = "Custom_Event_Property_val1" event.contentItems = [ contentItem ] event.logEvent() event = BranchEvent.standardEvent(.viewItem) event.logEvent(); // Quickly log an event: BranchEvent.standardEvent(.viewItem).logEvent() // Quickly log an event with content: let branchUniversalObject = BranchUniversalObject.init() branchUniversalObject.canonicalIdentifier = "item/12345" branchUniversalObject.canonicalUrl = "https://branch.io/deepviews" branchUniversalObject.title = "My Content Title" BranchEvent.standardEvent(.viewItem, withContentItem: branchUniversalObject).logEvent() } }
mit
bridger/NumberPad
NumberPad/ArrowPath.swift
1
1592
// // ArrowPath.swift // NumberPad // // Created by Bridger Maxwell on 7/6/15. // Copyright © 2015 Bridger Maxwell. All rights reserved. // import Foundation import CoreGraphics import DigitRecognizerSDK func createPointingLine(startPoint: CGPoint, endPoint: CGPoint, dash: Bool, arrowHeadPosition: CGFloat?) -> CGPath { let length = (endPoint - startPoint).length() let headWidth: CGFloat = 10 let headLength: CGFloat = 10 // We draw a straight line along going from the origin over to the right var path = CGMutablePath() path.move(to: CGPoint.zero) path.addLine(to: CGPoint(x: length, y: 0)) if dash { let dashPattern: [CGFloat] = [4, 6] if let dashedPath = path.copy(dashingWithPhase: 0, lengths: dashPattern).mutableCopy() { path = dashedPath } } if let arrowHeadPosition = arrowHeadPosition { /* Now add the arrow head * * \ * \ * / * / * */ let arrowStartX = length * arrowHeadPosition path.move(to: CGPoint(x: arrowStartX - headLength, y: headWidth / 2)) // top path.addLine(to: CGPoint(x: arrowStartX, y: 0)) // middle path.addLine(to: CGPoint(x: arrowStartX - headLength, y: -headWidth / 2)) // bottom } // Now transform it so that it starts and ends at the right points let angle = (endPoint - startPoint).angle var transform = CGAffineTransform(translationX: startPoint.x, y: startPoint.y).rotated(by: angle) return path.copy(using: &transform)! }
apache-2.0
calkinssean/TIY-Assignments
Day 11/starWarsApp/DetailViewController.swift
1
2039
// // DetailViewController.swift // starWarsApp // // Created by Sean Calkins on 2/15/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit class DetailViewController: UIViewController { var newCharacter: StarWarsCharacter? //MARK: - Variables @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var profileImageView: UIImageView! //MARK: - View Will Appear override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) print(newCharacter?.description) super.viewDidLoad() self.nameLabel.text = newCharacter?.name self.descriptionLabel.text = newCharacter?.description self.profileImageView.image = UIImage(named: "\(newCharacter!.imageName)") updateColors() } //MARK: - UI update func updateColors() { if newCharacter?.affiliations == "Sith" { self.view.backgroundColor = UIColor.blackColor() nameLabel.font = UIFont(name: "Pure evil 2", size: 45.0) nameLabel.textColor = UIColor.redColor() descriptionLabel.font = UIFont(name: "Pure evil 2", size: 20.0) descriptionLabel.textColor = UIColor.redColor() } else if newCharacter?.affiliations == "Jedi Order" { self.view.backgroundColor = UIColor.whiteColor() nameLabel.font = UIFont(name: "trench", size: 45.0) nameLabel.textColor = UIColor.blackColor() descriptionLabel.font = UIFont(name: "trench", size: 20.0) descriptionLabel.textColor = UIColor.blackColor() } else { self.view.backgroundColor = UIColor.whiteColor() nameLabel.font = UIFont(name: "Papyrus", size: 40.0) nameLabel.textColor = UIColor.blueColor() descriptionLabel.font = UIFont(name: "Papyrus", size: 15.0) descriptionLabel.textColor = UIColor.blueColor() } } }
cc0-1.0
gouyz/GYZBaking
baking/Classes/Category/View/GYZGoodsConmentHeader.swift
1
2629
// // GYZGoodsConmentHeader.swift // baking // 商家评论header // Created by gouyz on 2017/4/17. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZGoodsConmentHeader: UITableViewHeaderFooterView { override init(reuseIdentifier: String?){ super.init(reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ bgView.backgroundColor = kWhiteColor contentView.addSubview(bgView) bgView.addSubview(nameLab) bgView.addSubview(desLab) bgView.addSubview(rightIconView) bgView.addSubview(lineView) rightIconView.isHidden = true bgView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(contentView) make.top.equalTo(kMargin) } nameLab.snp.makeConstraints { (make) in make.top.equalTo(bgView) make.left.equalTo(kMargin) make.bottom.equalTo(lineView.snp.top) make.right.equalTo(desLab.snp.left).offset(-kMargin) } desLab.snp.makeConstraints { (make) in make.right.equalTo(rightIconView.snp.left) make.top.height.equalTo(nameLab) make.width.equalTo(100) } rightIconView.snp.makeConstraints { (make) in make.centerY.equalTo(bgView) make.right.equalTo(-5) make.size.equalTo(CGSize.init(width: 20, height: 20)) } lineView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(bgView) make.height.equalTo(klineWidth) } } fileprivate lazy var bgView: UIView = UIView() /// 店铺名称 lazy var nameLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kBlackFontColor lab.text = "商品评价" return lab }() /// 评论日期 lazy var desLab : UILabel = { let lab = UILabel() lab.font = k13Font lab.textColor = kGaryFontColor // lab.text = "查看全部评价" lab.textAlignment = .right return lab }() /// 右侧箭头图标 fileprivate lazy var rightIconView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_gray")) fileprivate lazy var lineView : UIView = { let line = UIView() line.backgroundColor = kGrayLineColor return line }() }
mit
GrupoGO/PGActionWidget
PGDActionWidgetView.swift
1
14786
// // PGDActionWidgetView.swift // ActionWidget // // Created by Emilio Cubo Ruiz on 13/7/17. // Copyright © 2017 Grupo Go Optimizations, SL. All rights reserved. // import UIKit import CoreLocation struct Action { var cms_url:String var end_date:Date var id:Int var image:String var isDo:Bool var isTodo:Bool var latitude:Double var longitude:Double var metric:String var metric_quantity:Int var platform:String var pledges:Int var review:Int var start_date:Date var text:String var time:Int var title:String var type:String var url:String var categories:[Category] var doUsers:[User] var lists:[List] var poll:[Answer] var todoUsers:[User] } struct Category { var id:Int var image:String var name:String var valor:Int var actions:[Action] var usersWithCategory:[User] } struct User { var address_1:String var address_2:String var alias:String var birdthdate:String var city:String var co2:Int var country:String var dollars:Int var email:String var firstname:String var gender:String var id:Int var image:String var lasname:String var latitude:Double var lives:Int var longitude:Double var nationality:String var official_document:String var phone:String var points:String var postal_code:String var region:String var session:String var time:Int var categories:[Category] var does:[Action] var lists:[List] var messages:[Message] var todoes:[Action] var types:[Type] } struct List { var created:Date var hashid:String var id:Int var isPrivate:Bool var last_update:Date var name:String var actions:[Action] var creator:User } struct Answer { var id:Int var poll_id:Int var poll_title:String var statValue:Int var text:String var action:Action } struct Message { var date:Date var ratting:Int var text:String var sender:User } struct Type { var id:Int var valor:Int var userWithType:User } public class PGDActionWidgetView: UIView { // MARK: Outlets @IBOutlet fileprivate var contentView:UIView? @IBOutlet fileprivate var container:UIView? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var loader: UIActivityIndicatorView! @IBOutlet weak var actionText: UILabel! var downloadPGD:Bool = false var actions: [Action]? { didSet { if let actions = actions { let screenHeight = UIScreen.main.bounds.size.height let height = screenHeight < 408 ? screenHeight - 108 : 300 var originX = 12.0 for action in actions { let actionView = PGDActionView(frame: CGRect(x: originX, y: 0, width: 222.0, height: Double(height))) actionView.action = action actionView.downloadPGD = self.downloadPGD originX += 234 scrollView.addSubview(actionView) } scrollView.layoutIfNeeded(); let width = 234 * actions.count + 12 scrollView.contentSize = CGSize(width: CGFloat(width), height: scrollView.contentSize.height); loader.isHidden = true } } } public override init(frame: CGRect) { super.init(frame: frame) self.commonInit(); } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } public override func layoutSubviews() { super.layoutSubviews() guard let content = contentView else { return } var frameSize = content.bounds let screenHeight = UIScreen.main.bounds.size.height let height = screenHeight < 408 ? screenHeight - 108 : 300 frameSize.size.height = screenHeight < 408 ? screenHeight : 408 content.frame = frameSize for view in scrollView.subviews { if view.isKind(of: PGDActionView.self) { view.frame.size.height = height } } } public func searchActions(coordinates:CLLocationCoordinate2D, locationName:String, keywords:[String]?, numberOfAction:Int?) { actionText.text = "Actions near \(locationName)" let size = numberOfAction != nil ? numberOfAction! : 100 let urlCoordinates = "https://maps.googleapis.com/maps/api/geocode/json?language=en&sensor=false&latlng=\(coordinates.latitude),\(coordinates.longitude)&result_type=administrative_area_level_1&key=AIzaSyBxL5CwUDj15cnfFP0PbEr0k8nq6Po3gEw" let requestCoordinates = NSMutableURLRequest(url: URL(string: urlCoordinates)!) requestCoordinates.httpMethod = "GET" let taskCoordinates = URLSession.shared.dataTask(with: requestCoordinates as URLRequest, completionHandler: { (data, response, error) in if error != nil { print(error!) } else { DispatchQueue.main.async(execute: { do { let json = try JSONSerialization.jsonObject(with: data!) as! [String:Any] if let results = json["results"] as? [Any] { if results.count > 0 { let geometry = (results[0] as! [String:Any])["geometry"] as! [String:Any] let bounds = geometry["bounds"] as! [String:Any] let max_lat = (bounds["northeast"] as! [String:Any])["lat"] as! Double let max_lng = (bounds["northeast"] as! [String:Any])["lng"] as! Double let min_lat = (bounds["southwest"] as! [String:Any])["lat"] as! Double let min_lng = (bounds["southwest"] as! [String:Any])["lng"] as! Double var text2Search = "" if keywords != nil { for i in 0..<keywords!.count { if text2Search == "" { text2Search = keywords![i] } else { text2Search = text2Search + "," + keywords![i] } } } let urlPHP = keywords != nil ? "https://webintra.net/api/Playground/search?keywords=\(text2Search)&size=\(size)&min_lat=\(min_lat)&max_lat=\(max_lat)&min_lng=\(min_lng)&max_lng=\(max_lng)" : "https://webintra.net/api/Playground/search?min_lat=\(min_lat)&max_lat=\(max_lat)&min_lng=\(min_lng)&max_lng=\(max_lng)&size=\(size)" let request = NSMutableURLRequest(url: URL(string: urlPHP.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!) request.httpMethod = "GET" request.addValue("59baef879d68f4af3c97c0269ed46200", forHTTPHeaderField: "Token") request.addValue("b6cccc4e45422e84143cd6a8fa589eb4", forHTTPHeaderField: "Secret") let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in if error != nil { print(error!) } else { DispatchQueue.main.async(execute: { do { let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any] self.parseActions(parsedData: parsedData) } catch let error as NSError { print(error) } }); } }) task.resume() } } } catch let error as NSError { print(error) } }); } }) taskCoordinates.resume() } public func searchActions(keywords:[String]?, numberOfAction:Int?) { actionText.text = "Recommended actions" var text2Search = "" if keywords != nil { for i in 0..<keywords!.count { if text2Search == "" { text2Search = keywords![i] } else { text2Search = text2Search + "," + keywords![i] } } } let size = numberOfAction != nil ? numberOfAction! : 10 let urlPHP = keywords != nil ? "https://webintra.net/api/Playground/search?keywords=\(text2Search)&size=\(size)" : "https://webintra.net/api/Playground/search?list=16758375" let request = NSMutableURLRequest(url: URL(string: urlPHP.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!) request.httpMethod = "GET" request.addValue("59baef879d68f4af3c97c0269ed46200", forHTTPHeaderField: "Token") request.addValue("b6cccc4e45422e84143cd6a8fa589eb4", forHTTPHeaderField: "Secret") let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in if error != nil { print(error!) } else { DispatchQueue.main.async(execute: { do { let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any] self.parseActions(parsedData: parsedData) } catch let error as NSError { print(error) } }); } }) task.resume() } func parseActions(parsedData:[String:Any]) { let info = parsedData["info"] as! [String:Any] if let items = info["items"] as? [[String:Any]] { var parseActions = [Action]() for item in items { var newAction = Action( cms_url: item["cms_url"] as! String, end_date: Date.dateFromString(item["end_date"] as! String, timeZone: false), id: item["id"] as! Int, image: item["image"] as! String, isDo: false, isTodo: false, latitude: item["latitude"] as? Double != nil ? item["latitude"] as! Double : 0.0, longitude: item["longitude"] as? Double != nil ? item["longitude"] as! Double : 0.0, metric: item["metric"] as! String, metric_quantity: item["metric_quantity"] as! Int, platform: item["website"] as! String, pledges: item["plegdes"] as? Int != nil ? item["plegdes"] as! Int : 0, review: item["review"] as? Int != nil ? item["review"] as! Int : 0, start_date: Date.dateFromString(item["start_date"] as! String, timeZone: false), text: item["description"] as! String, time: item["time"] as! Int, title: item["title"] as! String, type: item["type"] as! String, url: item["url"] as! String, categories: [], doUsers: [], lists: [], poll: [], todoUsers: [] ) if newAction.type.lowercased() == "poll" { let poll = item["poll"] as! [String:Any] let pollTitle = poll["title"] as! String newAction.title = pollTitle let pollAnswers = poll["answers"] as! [[String:Any]] var answers = [Answer]() for answer in pollAnswers { let a = Answer( id: answer["id"] as! Int, poll_id: poll["id"] as! Int, poll_title: newAction.title, statValue: 0, text: answer["text"] as! String, action: newAction) answers.append(a) } newAction.poll = answers } parseActions.append(newAction) } self.actions = parseActions } } fileprivate func commonInit() { let bundle = Bundle(for: PGDActionView.self) bundle.loadNibNamed("PGDActionWidgetView", owner: self, options: nil) guard let content = contentView else { return } var frameSize = self.bounds frameSize.size.height = 408 content.frame = frameSize content.autoresizingMask = [.flexibleHeight, .flexibleWidth] container?.layer.cornerRadius = 5 container?.layer.borderWidth = 1 container?.layer.borderColor = UIColor.black.cgColor self.addSubview(content) } } extension Date { static func dateFromString(_ stringDate:String, timeZone:Bool) -> Date { var dateToReturn:Date = Date(); let formatters = [ "dd-MM-yyyy HH:mm", "yyyy-MM-dd" ].map { (format: String) -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = format if timeZone { formatter.timeZone = TimeZone(abbreviation: "UTC"); } return formatter } for formatter in formatters { if let date = formatter.date(from: stringDate) { dateToReturn = date; } } return dateToReturn; } }
mit
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Renderers/ScatterChartRenderer.swift
6
15980
// // ScatterChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class ScatterChartRenderer: LineScatterCandleRadarChartRenderer { open weak var dataProvider: ScatterChartDataProvider? public init(dataProvider: ScatterChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let scatterData = dataProvider?.scatterData else { return } for i in 0 ..< scatterData.dataSetCount { guard let set = scatterData.getDataSetByIndex(i) else { continue } if set.visible { if !(set is IScatterChartDataSet) { fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet") } drawDataSet(context: context, dataSet: set as! IScatterChartDataSet) } } } private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2) open func drawDataSet(context: CGContext, dataSet: IScatterChartDataSet) { guard let dataProvider = dataProvider, let animator = animator else { return } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius let shapeHoleSize = shapeHoleSizeHalf * 2.0 let shapeHoleColor = dataSet.scatterShapeHoleColor let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0 let shapeStrokeSizeHalf = shapeStrokeSize / 2.0 var point = CGPoint() let valueToPixelMatrix = trans.valueToPixelMatrix let shape = dataSet.scatterShape context.saveGState() for j in 0 ..< Int(min(ceil(CGFloat(entryCount) * animator.phaseX), CGFloat(entryCount))) { guard let e = dataSet.entryForIndex(j) else { continue } point.x = CGFloat(e.xIndex) point.y = CGFloat(e.value) * phaseY point = point.applying(valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(point.x)) { break } if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y)) { continue } if (shape == .square) { if shapeHoleSize > 0.0 { context.setStrokeColor(dataSet.colorAt(j).cgColor) context.setLineWidth(shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize context.stroke(rect) if let shapeHoleColor = shapeHoleColor { context.setFillColor(shapeHoleColor.cgColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize context.fill(rect) } } else { context.setFillColor(dataSet.colorAt(j).cgColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize context.fill(rect) } } else if (shape == .circle) { if shapeHoleSize > 0.0 { context.setStrokeColor(dataSet.colorAt(j).cgColor) context.setLineWidth(shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize context.strokeEllipse(in: rect) if let shapeHoleColor = shapeHoleColor { context.setFillColor(shapeHoleColor.cgColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize context.fillEllipse(in: rect) } } else { context.setFillColor(dataSet.colorAt(j).cgColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize context.fillEllipse(in: rect) } } else if (shape == .triangle) { context.setFillColor(dataSet.colorAt(j).cgColor) // create a triangle path context.beginPath() context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf)) context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf)) context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf)) if shapeHoleSize > 0.0 { context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf)) context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) } context.closePath() context.fillPath() if shapeHoleSize > 0.0 && shapeHoleColor != nil { context.setFillColor(shapeHoleColor!.cgColor) // create a triangle path context.beginPath() context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.closePath() context.fillPath() } } else if (shape == .cross) { context.setStrokeColor(dataSet.colorAt(j).cgColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y context.strokeLineSegments(between: _lineSegments) _lineSegments[0].x = point.x _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x _lineSegments[1].y = point.y + shapeHalf context.strokeLineSegments(between: _lineSegments) } else if (shape == .x) { context.setStrokeColor(dataSet.colorAt(j).cgColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y + shapeHalf context.strokeLineSegments(between: _lineSegments) _lineSegments[0].x = point.x + shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x - shapeHalf _lineSegments[1].y = point.y + shapeHalf context.strokeLineSegments(between: _lineSegments) } else if (shape == .custom) { context.setFillColor(dataSet.colorAt(j).cgColor) let customShape = dataSet.customScatterShape if customShape == nil { return } // transform the provided custom path context.saveGState() context.translateBy(x: point.x, y: point.y) context.beginPath() context.addPath(customShape!) context.fillPath() context.restoreGState() } } context.restoreGState() } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let scatterData = dataProvider.scatterData, let animator = animator else { return } // if values are drawn if (scatterData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX))) { guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return } let phaseX = max(0.0, min(1.0, animator.phaseX)) let phaseY = animator.phaseY var pt = CGPoint() for i in 0 ..< scatterData.dataSetCount { let dataSet = dataSets[i] if !dataSet.drawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let lineHeight = valueFont.lineHeight for j in 0 ..< Int(ceil(CGFloat(entryCount) * phaseX)) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the lines don't do shitty things outside bounds if ((!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))) { continue } let text = formatter.string(from: e.value as NSNumber) ChartUtils.drawText( context: context, text: text!, point: CGPoint( x: pt.x, y: pt.y - shapeSize - lineHeight), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } } } open override func drawExtras(context: CGContext) { } private var _highlightPointBuffer = CGPoint() open override func drawHighlighted(context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, let scatterData = dataProvider.scatterData, let animator = animator else { return } let chartXMax = dataProvider.chartXMax context.saveGState() for high in indices { let minDataSetIndex = high.dataSetIndex == -1 ? 0 : high.dataSetIndex let maxDataSetIndex = high.dataSetIndex == -1 ? scatterData.dataSetCount : (high.dataSetIndex + 1) if maxDataSetIndex - minDataSetIndex < 1 { continue } for dataSetIndex in minDataSetIndex..<maxDataSetIndex { guard let set = scatterData.getDataSetByIndex(dataSetIndex) as? IScatterChartDataSet else { continue } if !set.highlightEnabled { continue } context.setStrokeColor(set.highlightColor.cgColor) context.setLineWidth(set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let xIndex = high.xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX) { continue } let yVal = set.yValForXIndex(xIndex) if (yVal.isNaN) { continue } let y = CGFloat(yVal) * animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider.getTransformer(set.axisDependency) trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } } context.restoreGState() } }
mit
uasys/swift
test/SILGen/objc_dealloc.swift
1
5278
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo class X { } func onDestruct() { } @requires_stored_property_inits class SwiftGizmo : Gizmo { var x = X() // CHECK-LABEL: sil hidden [transparent] @_T012objc_dealloc10SwiftGizmoC1xAA1XCvpfi : $@convention(thin) () -> @owned X // CHECK: [[FN:%.*]] = function_ref @_T012objc_dealloc1XCACycfC : $@convention(method) (@thick X.Type) -> @owned X // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick X.Type // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thick X.Type) -> @owned X // CHECK-NEXT: return [[RESULT]] : $X // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $SwiftGizmo): override init() { // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SwiftGizmo }, let, name "self" // CHECK: [[SELF_UNINIT:%.*]] = mark_uninitialized [derivedselfonly] [[SELF_BOX]] : ${ var SwiftGizmo } // CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_UNINIT]] // CHECK-NOT: ref_element_addr // CHECK: [[SELF:%.*]] = load [take] [[SELF_ADDR]] // CHECK-NEXT: [[UPCAST_SELF:%.*]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo // CHECK-NEXT: [[BORROWED_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]] // CHECK-NEXT: [[DOWNCAST_BORROWED_UPCAST_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF]] : $Gizmo to $SwiftGizmo // CHECK-NEXT: super_method [volatile] [[DOWNCAST_BORROWED_UPCAST_SELF]] : $SwiftGizmo // CHECK-NEXT: end_borrow [[BORROWED_UPCAST_SELF]] from [[UPCAST_SELF]] // CHECK: return super.init() } // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> () deinit { // CHECK: bb0([[SELF:%[0-9]+]] : @owned $SwiftGizmo): // Call onDestruct() // CHECK: [[ONDESTRUCT_REF:%[0-9]+]] = function_ref @_T012objc_dealloc10onDestructyyF : $@convention(thin) () -> () // CHECK: [[ONDESTRUCT_RESULT:%[0-9]+]] = apply [[ONDESTRUCT_REF]]() : $@convention(thin) () -> () onDestruct() // Note: don't destroy instance variables // CHECK-NOT: ref_element_addr // Call super -dealloc. // CHECK: [[SUPER_DEALLOC:%[0-9]+]] = super_method [[SELF]] : $SwiftGizmo, #Gizmo.deinit!deallocator.foreign : (Gizmo) -> () -> (), $@convention(objc_method) (Gizmo) -> () // CHECK: [[SUPER:%[0-9]+]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo // CHECK: [[SUPER_DEALLOC_RESULT:%[0-9]+]] = apply [[SUPER_DEALLOC]]([[SUPER]]) : $@convention(objc_method) (Gizmo) -> () // CHECK: end_lifetime [[SUPER]] // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } // Objective-C deallocation deinit thunk (i.e., -dealloc). // CHECK-LABEL: sil hidden [thunk] @_T012objc_dealloc10SwiftGizmoCfDTo : $@convention(objc_method) (SwiftGizmo) -> () // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftGizmo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[GIZMO_DTOR:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[GIZMO_DTOR]]([[SELF_COPY]]) : $@convention(method) (@owned SwiftGizmo) -> () // CHECK: return [[RESULT]] : $() // Objective-C IVar initializer (i.e., -.cxx_construct) // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfeTo : $@convention(objc_method) (@owned SwiftGizmo) -> @owned SwiftGizmo // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $SwiftGizmo): // CHECK-NEXT: debug_value [[SELF_PARAM]] : $SwiftGizmo, let, name "self" // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $SwiftGizmo // CHECK: [[XINIT:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoC1xAA1XCvpfi // CHECK-NEXT: [[XOBJ:%[0-9]+]] = apply [[XINIT]]() : $@convention(thin) () -> @owned X // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $SwiftGizmo, #SwiftGizmo.x // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*X // CHECK-NEXT: assign [[XOBJ]] to [[WRITE]] : $*X // CHECK-NEXT: end_access [[WRITE]] : $*X // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-NEXT: return [[SELF]] : $SwiftGizmo // Objective-C IVar destroyer (i.e., -.cxx_destruct) // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfETo : $@convention(objc_method) (SwiftGizmo) -> () // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftGizmo): // CHECK-NEXT: debug_value [[SELF]] : $SwiftGizmo, let, name "self" // CHECK-NEXT: [[SELF_BORROW:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[SELF_BORROW]] : $SwiftGizmo, #SwiftGizmo.x // CHECK-NEXT: destroy_addr [[X]] : $*X // CHECK-NEXT: end_borrow [[SELF_BORROW]] from [[SELF]] // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() } // CHECK-NOT: sil hidden [thunk] @_T0So11SwiftGizmo2CfETo : $@convention(objc_method) (SwiftGizmo2) -> () class SwiftGizmo2 : Gizmo { }
apache-2.0
alexruperez/ARFacebookShareKitActivity
Example/ARFacebookShareKitActivity/ViewController.swift
1
1746
// // ViewController.swift // ARFacebookShareKitActivity // // Created by alexruperez on 06/01/2016. // Copyright (c) 2016 alexruperez. All rights reserved. // import UIKit import ARFacebookShareKitActivity class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var linkField: UITextField! @IBOutlet weak var shareButton: UIButton! @IBAction func shareAction(sender: AnyObject) { var items = [AnyObject]() if let text = textField.text, text.characters.count > 0 { items.append(text as AnyObject) } if let text = linkField.text, text.characters.count > 0 { if let linkURL = NSURL(string: linkField.text!) { items.append(linkURL) } } let shareViewController = UIActivityViewController(activityItems: items, applicationActivities: [AppInviteActivity(), ShareLinkActivity()]) shareViewController.excludedActivityTypes = [.postToTwitter, .postToWeibo, .message, .mail, .print, .copyToPasteboard, .assignToContact, .saveToCameraRoll, .addToReadingList, .postToFlickr, .postToVimeo, .postToTencentWeibo, .airDrop] if let popoverPresentationController = shareViewController.popoverPresentationController { popoverPresentationController.sourceView = shareButton popoverPresentationController.sourceRect = CGRect(x: shareButton.frame.width/2, y: 0, width: 0, height: 0) } self.present(shareViewController, animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/IRCConnectionDelegate.swift
3
335
// // IRCConnectionDelegate.swift // GamingStreamsTVApp // // Created by Olivier Boucher on 2015-10-18. // Copyright © 2015 Rivus Media Inc. All rights reserved. // import Foundation protocol IRCConnectionDelegate { func IRCConnectionDidConnect() func IRCConnectionDidDisconnect() func IRCConnectionDidNotConnect() }
mit
rsyncOSX/RsyncOSX
RsyncOSX/DecodeConfiguration.swift
1
6201
// // DecodeConfigJSON.swift // RsyncOSX // // Created by Thomas Evensen on 17/10/2020. // Copyright © 2020 Thomas Evensen. All rights reserved. // // Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation struct DecodeConfiguration: Codable { let backupID: String? let dateRun: String? let haltshelltasksonerror: Int? let hiddenID: Int? let localCatalog: String? let offsiteCatalog: String? let offsiteServer: String? let offsiteUsername: String? let parameter1: String? let parameter10: String? let parameter11: String? let parameter12: String? let parameter13: String? let parameter14: String? let parameter2: String? let parameter3: String? let parameter4: String? let parameter5: String? let parameter6: String? let parameter8: String? let parameter9: String? let rsyncdaemon: Int? let sshkeypathandidentityfile: String? let sshport: Int? let task: String? let snapdayoffweek: String? let snaplast: Int? let executepretask: Int? let pretask: String? let executeposttask: Int? let posttask: String? let snapshotnum: Int? enum CodingKeys: String, CodingKey { case backupID case dateRun case haltshelltasksonerror case hiddenID case localCatalog case offsiteCatalog case offsiteServer case offsiteUsername case parameter1 case parameter10 case parameter11 case parameter12 case parameter13 case parameter14 case parameter2 case parameter3 case parameter4 case parameter5 case parameter6 case parameter8 case parameter9 case rsyncdaemon case sshkeypathandidentityfile case sshport case task case snapdayoffweek case snaplast case executepretask case pretask case executeposttask case posttask case snapshotnum } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) backupID = try values.decodeIfPresent(String.self, forKey: .backupID) dateRun = try values.decodeIfPresent(String.self, forKey: .dateRun) haltshelltasksonerror = try values.decodeIfPresent(Int.self, forKey: .haltshelltasksonerror) hiddenID = try values.decodeIfPresent(Int.self, forKey: .hiddenID) localCatalog = try values.decodeIfPresent(String.self, forKey: .localCatalog) offsiteCatalog = try values.decodeIfPresent(String.self, forKey: .offsiteCatalog) offsiteServer = try values.decodeIfPresent(String.self, forKey: .offsiteServer) offsiteUsername = try values.decodeIfPresent(String.self, forKey: .offsiteUsername) parameter1 = try values.decodeIfPresent(String.self, forKey: .parameter1) parameter10 = try values.decodeIfPresent(String.self, forKey: .parameter10) parameter11 = try values.decodeIfPresent(String.self, forKey: .parameter11) parameter12 = try values.decodeIfPresent(String.self, forKey: .parameter12) parameter13 = try values.decodeIfPresent(String.self, forKey: .parameter13) parameter14 = try values.decodeIfPresent(String.self, forKey: .parameter14) parameter2 = try values.decodeIfPresent(String.self, forKey: .parameter2) parameter3 = try values.decodeIfPresent(String.self, forKey: .parameter3) parameter4 = try values.decodeIfPresent(String.self, forKey: .parameter4) parameter5 = try values.decodeIfPresent(String.self, forKey: .parameter5) parameter6 = try values.decodeIfPresent(String.self, forKey: .parameter6) parameter8 = try values.decodeIfPresent(String.self, forKey: .parameter8) parameter9 = try values.decodeIfPresent(String.self, forKey: .parameter9) rsyncdaemon = try values.decodeIfPresent(Int.self, forKey: .rsyncdaemon) sshkeypathandidentityfile = try values.decodeIfPresent(String.self, forKey: .sshkeypathandidentityfile) sshport = try values.decodeIfPresent(Int.self, forKey: .sshport) task = try values.decodeIfPresent(String.self, forKey: .task) snapdayoffweek = try values.decodeIfPresent(String.self, forKey: .snapdayoffweek) snaplast = try values.decodeIfPresent(Int.self, forKey: .snaplast) executepretask = try values.decodeIfPresent(Int.self, forKey: .executepretask) pretask = try values.decodeIfPresent(String.self, forKey: .pretask) executeposttask = try values.decodeIfPresent(Int.self, forKey: .executeposttask) posttask = try values.decodeIfPresent(String.self, forKey: .posttask) snapshotnum = try values.decodeIfPresent(Int.self, forKey: .snapshotnum) } // This init is used in WriteConfigurationJSON init(_ data: Configuration) { backupID = data.backupID dateRun = data.dateRun haltshelltasksonerror = data.haltshelltasksonerror hiddenID = data.hiddenID localCatalog = data.localCatalog offsiteCatalog = data.offsiteCatalog offsiteServer = data.offsiteServer offsiteUsername = data.offsiteUsername parameter1 = data.parameter1 parameter10 = data.parameter10 parameter11 = data.parameter11 parameter12 = data.parameter12 parameter13 = data.parameter13 parameter14 = data.parameter14 parameter2 = data.parameter2 parameter3 = data.parameter3 parameter4 = data.parameter4 parameter5 = data.parameter5 parameter6 = data.parameter6 parameter8 = data.parameter8 parameter9 = data.parameter9 rsyncdaemon = data.rsyncdaemon sshkeypathandidentityfile = data.sshkeypathandidentityfile sshport = data.sshport task = data.task snapdayoffweek = data.snapdayoffweek snaplast = data.snaplast executepretask = data.executepretask pretask = data.pretask executeposttask = data.executeposttask posttask = data.posttask snapshotnum = data.snapshotnum } }
mit
martinverup/g2planner
g2planner/main.swift
1
1389
// // main.swift // g2planner // // Created by Martin Verup on 20/07/2017. // // import Foundation let args = CommandLine.arguments if args.count < 3 { print("Not enough parameters given") exit(0) } let world = Map.createMap() let dijkstra = Dijkstra(world) let source: City let destination: City if let from = City(rawValue: args[1]) { source = from } else { print("City \"\(args[1])\" not recognized") exit(0) } if let to = City(rawValue: args[2]) { destination = to } else { print("City \"\(args[2])\" not recognized") exit(0) } let fastestPath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.fastest) let fastestNoPlanePath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.fastest, exclude: Route.Method.Plane) let cheapestPath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.cheapest) let cheapestNoBusPath = dijkstra.getRoute(from: source, to: destination, searchFor: Dijkstra.Parameter.cheapest, exclude: Route.Method.Bus) print("Routes from \(source.rawValue) to \(destination.rawValue):\n") print("Fastest:") Dijkstra.prettyPrint(fastestPath) print("Cheapest:") Dijkstra.prettyPrint(cheapestPath) print("Cheapest (no bus):") Dijkstra.prettyPrint(cheapestNoBusPath) print("Fastest (no plane):") Dijkstra.prettyPrint(fastestNoPlanePath)
mit
takezou621/SwiftLogging
SwiftLogging/AppDelegate.swift
1
2158
// // AppDelegate.swift // SwiftLogging // // Created by Takeshi Kawai on 2015/05/17. // Copyright (c) 2015年 Takeshi Kawai. 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:. } }
apache-2.0
matrix-org/matrix-ios-kit
MatrixKitTests/UTI/MXKUTITests.swift
1
3119
/* Copyright 2019 The Matrix.org Foundation C.I.C Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import MatrixKit import MobileCoreServices class MXKUTITests: XCTestCase { override func 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. } func testUTIFromMimeType() { guard let uti = MXKUTI(mimeType: "application/pdf") else { XCTFail("uti should not be nil") return } let fileExtension = uti.fileExtension?.lowercased() ?? "" XCTAssertTrue(uti.isFile) XCTAssertEqual(fileExtension, "pdf") } func testUTIFromFileExtension() { let uti = MXKUTI(fileExtension: "pdf") let fileExtension = uti.fileExtension?.lowercased() ?? "" let mimeType = uti.mimeType ?? "" XCTAssertTrue(uti.isFile) XCTAssertEqual(fileExtension, "pdf") XCTAssertEqual(mimeType, "application/pdf") } func testUTIFromLocalFileURLLoadingResourceValues() { let bundle = Bundle(for: type(of: self)) guard let localFileURL = bundle.url(forResource: "Text", withExtension: "txt") else { XCTFail("localFileURL should not be nil") return } guard let uti = MXKUTI(localFileURL: localFileURL) else { XCTFail("uti should not be nil") return } let fileExtension = uti.fileExtension?.lowercased() ?? "" let mimeType = uti.mimeType ?? "" XCTAssertTrue(uti.isFile) XCTAssertEqual(fileExtension, "txt") XCTAssertEqual(mimeType, "text/plain") } func testUTIFromLocalFileURL() { let bundle = Bundle(for: type(of: self)) guard let localFileURL = bundle.url(forResource: "Text", withExtension: "txt") else { XCTFail("localFileURL should not be nil") return } guard let uti = MXKUTI(localFileURL: localFileURL, loadResourceValues: false) else { XCTFail("uti should not be nil") return } let fileExtension = uti.fileExtension?.lowercased() ?? "" let mimeType = uti.mimeType ?? "" XCTAssertTrue(uti.isFile) XCTAssertEqual(fileExtension, "txt") XCTAssertEqual(mimeType, "text/plain") } }
apache-2.0
Ryce/stege-ios
StegeTests/StegeTests.swift
1
888
// // StegeTests.swift // StegeTests // // Created by Hamon Riazy on 25/07/15. // Copyright (c) 2015 ryce. All rights reserved. // import UIKit import XCTest class StegeTests: 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.measureBlock() { // Put the code you want to measure the time of here. } } }
gpl-2.0
ra1028/Former
Former-Demo/Former-Demo/Helpers/String+FormerDemo.swift
1
1014
// // StringExt.swift // Former-Demo // // Created by Ryo Aoyama on 8/10/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit extension String { static func mediumDateShortTime(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.locale = .current dateFormatter.timeStyle = .short dateFormatter.dateStyle = .medium return dateFormatter.string(from: date) } static func mediumDateNoTime(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.locale = .current dateFormatter.timeStyle = .none dateFormatter.dateStyle = .medium return dateFormatter.string(from: date) } static func fullDate(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.locale = .current dateFormatter.timeStyle = .none dateFormatter.dateStyle = .full return dateFormatter.string(from: date) } }
mit
Bygo/BGChatBotMessaging-iOS
BGChatBotMessaging/Classes/BGChatBotMessageData.swift
1
424
// // BGChatBotMessageData.swift // Pods // // Created by Nicholas Garfield on 18/6/16. // // import UIKit import BGMessaging public class BGChatBotMessageData: BGMessageData { public var nextID: String? public init(text: String, direction: BGMessageDirection, date: NSDate, nextID: String?) { super.init(text: text, direction: direction, date: date) self.nextID = nextID } }
mit
IAskWind/IAWExtensionTool
IAWExtensionTool/IAWExtensionTool/Classes/Constant/IAW_Constant.swift
1
3394
// // IAWConstant.swift // CtkApp // // Created by winston on 16/12/9. // Copyright © 2016年 winston. All rights reserved. // import UIKit /// 第一次启动 public let IAW_FirstLaunch = "firstLaunch" /// 是否登录open public let IAW_IsLogin = "isLogin" public let IAW_AccessToken = "accessToken" public let IAW_NavigationH: CGFloat = 64 /// 间距 public let IAW_KMargin: CGFloat = 10.0 /// 圆角 // UITextField 高度 public let IAW_TextFieldH: CGFloat = 55 //左边距 public let IAW_LeftMargin: CGFloat = 10 // 屏幕的宽 public let IAW_ScreenW = UIScreen.main.bounds.size.width // 屏幕的高 public let IAW_ScreenH = UIScreen.main.bounds.size.height public let IAW_Window = UIApplication.shared.keyWindow! ///公用线条 //public var IAW_CommonLine:UIView = { // let line = UIView() // line.alpha = 0.2 // line.backgroundColor = UIColor.gray // return line //}() //公用线条 public func IAW_CommonLine(lineColor:UIColor = UIColor.gray,alpha:CGFloat = 1)-> UIView{ let line = UIView() line.alpha = alpha line.backgroundColor = lineColor return line } //全局NavBar的颜色 public var IAW_GlobalNavBarColor:UIColor { return IAW_GlobalRedColor } /// 背景灰色 public var IAW_GlobalBgColor: UIColor { return UIColor.iaw_Color(240, g: 240, b: 240, a: 1) } /// 红色 public var IAW_GlobalRedColor:UIColor { return UIColor.iaw_Color(245, g: 80, b: 83, a: 1.0) } /// 蓝色 public var IAW_GlobalBlueColor:UIColor { return UIColor.iaw_Color(84, g: 142, b: 252, a: 1.0) } // 颜色值如 #FFFFFF public func IAW_HEXColor(_ hexColor:String,alpha:CGFloat = 1) -> UIColor { var color = UIColor.red var cStr : String = hexColor.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() if cStr.hasPrefix("#") { let index = cStr.index(after: cStr.startIndex) cStr = cStr.substring(from: index) } if cStr.count != 6 { return UIColor.black } let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex, offsetBy: 2) let rStr = cStr.substring(with: rRange) let gRange = cStr.index(cStr.startIndex, offsetBy: 2) ..< cStr.index(cStr.startIndex, offsetBy: 4) let gStr = cStr.substring(with: gRange) let bIndex = cStr.index(cStr.endIndex, offsetBy: -2) let bStr = cStr.substring(from: bIndex) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; Scanner(string: rStr).scanHexInt32(&r) Scanner(string: gStr).scanHexInt32(&g) Scanner(string: bStr).scanHexInt32(&b) color = UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) return color } //px处理 labelMapWidth 标注图用的屏幕宽 pt单位 默认6s为375 public func IAW_PX(px:CGFloat,labelMapWidth:CGFloat = 375)-> CGFloat{ return (IAW_ScreenW/labelMapWidth)*(px/2) } /**view设置点击事件封装方法 例:iaw_SetViewClick(dealView: leftView, target: self, viewClick: #selector(showPsd(_:))) 实现方法:func showPsd(_ sender:UITapGestureRecognizer){} **/ public func iaw_SetViewClick(dealView:UIView,target:Any?,viewClick:Selector){ dealView.isUserInteractionEnabled = true let tapGR = UITapGestureRecognizer(target: target, action: viewClick) tapGR.numberOfTapsRequired = 1 dealView.addGestureRecognizer(tapGR) }
mit
morizotter/KeyboardObserver
KeyboardObserver/KeyboardObserver.swift
1
4224
// // Keyboard.swift // Demo // // Created by MORITANAOKI on 2015/12/14. // Copyright © 2015年 molabo. All rights reserved. // import UIKit public enum KeyboardEventType: CaseIterable { case willShow case didShow case willHide case didHide case willChangeFrame case didChangeFrame public var notificationName: NSNotification.Name { switch self { case .willShow: return UIResponder.keyboardWillShowNotification case .didShow: return UIResponder.keyboardDidShowNotification case .willHide: return UIResponder.keyboardWillHideNotification case .didHide: return UIResponder.keyboardDidHideNotification case .willChangeFrame: return UIResponder.keyboardWillChangeFrameNotification case .didChangeFrame: return UIResponder.keyboardDidChangeFrameNotification } } init?(name: NSNotification.Name) { switch name { case UIResponder.keyboardWillShowNotification: self = .willShow case UIResponder.keyboardDidShowNotification: self = .didShow case UIResponder.keyboardWillHideNotification: self = .willHide case UIResponder.keyboardDidHideNotification: self = .didHide case UIResponder.keyboardWillChangeFrameNotification: self = .willChangeFrame case UIResponder.keyboardDidChangeFrameNotification: self = .didChangeFrame default: return nil } } static func allEventNames() -> [NSNotification.Name] { return allCases.map({ $0.notificationName }) } } public struct KeyboardEvent { public let type: KeyboardEventType public let keyboardFrameBegin: CGRect public let keyboardFrameEnd: CGRect public let curve: UIView.AnimationCurve public let duration: TimeInterval public var isLocal: Bool? public var options: UIView.AnimationOptions { return UIView.AnimationOptions(rawValue: UInt(curve.rawValue << 16)) } init?(notification: Notification) { guard let userInfo = (notification as NSNotification).userInfo else { return nil } guard let type = KeyboardEventType(name: notification.name) else { return nil } guard let begin = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return nil } guard let end = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return nil } guard let curveInt = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue, let curve = UIView.AnimationCurve(rawValue: curveInt) else { return nil } guard let durationDouble = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return nil } self.type = type self.keyboardFrameBegin = begin self.keyboardFrameEnd = end self.curve = curve self.duration = TimeInterval(durationDouble) if #available(iOS 9, *) { guard let isLocalInt = (userInfo[UIResponder.keyboardIsLocalUserInfoKey] as? NSNumber)?.intValue else { return nil } self.isLocal = isLocalInt == 1 } } } public enum KeyboardState { case initial case showing case shown case hiding case hidden case changing } public typealias KeyboardEventClosure = ((_ event: KeyboardEvent) -> Void) open class KeyboardObserver { open var state = KeyboardState.initial open var isEnabled = true fileprivate var eventClosures = [KeyboardEventClosure]() deinit { eventClosures.removeAll() KeyboardEventType.allEventNames().forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) } } public init() { KeyboardEventType.allEventNames().forEach { NotificationCenter.default.addObserver(self, selector: #selector(notified(_:)), name: $0, object: nil) } } open func observe(_ event: @escaping KeyboardEventClosure) { eventClosures.append(event) } } internal extension KeyboardObserver { @objc func notified(_ notification: Notification) { guard let event = KeyboardEvent(notification: notification) else { return } switch event.type { case .willShow: state = .showing case .didShow: state = .shown case .willHide: state = .hiding case .didHide: state = .hidden case .willChangeFrame: state = .changing case .didChangeFrame: state = .shown } if !isEnabled { return } eventClosures.forEach { $0(event) } } }
mit
MChainZhou/DesignPatterns
Mediator/Mediator/ViewController.swift
1
498
// // ViewController.swift // Mediator // // Created by apple on 2017/8/30. // Copyright © 2017年 apple. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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
fabiomassimo/eidolon
KioskTests/Models/SystemTimeTests.swift
2
1440
import Quick import Nimble import Kiosk // Note, stubbed json contains a date in 2422 // If this is an issue ( hello future people! ) then move it along a few centuries. class SystemTimeTests: QuickSpec { override func spec() { describe("in sync") { setupProviderForSuite(Provider.StubbingProvider()) it("returns true") { let time = SystemTime() time.syncSignal().subscribeNext { (_) -> Void in expect(time.inSync()) == true return } } it("returns a date in the future") { let time = SystemTime() time.syncSignal().subscribeNext { (_) -> Void in let currentYear = yearFromDate(NSDate()) let timeYear = yearFromDate(time.date()) expect(timeYear) > currentYear expect(timeYear) == 2422 } } } describe("not in sync") { it("returns false") { let time = SystemTime() expect(time.inSync()) == false } it("returns current time") { let time = SystemTime() let currentYear = yearFromDate(NSDate()) let timeYear = yearFromDate(time.date()) expect(timeYear) == currentYear } } } }
mit
marcelmueller/MyWeight
MyWeightTests/AuthorizationRequestViewControllerTests.swift
1
933
// // AuthorizationRequestViewControllerTests.swift // MyWeight // // Created by Bruno Mazzo on 11/2/16. // Copyright © 2016 Diogo Tridapalli. All rights reserved. // import Quick import Nimble import Nimble_Snapshots @testable import MyWeight class AuthorizationRequestViewControllerTests: QuickSpec { var viewController: AuthorizationRequestViewController! let snapshoService = SnapshotService() override func spec() { describe("AuthorizationRequestViewController Layout") { beforeEach { self.viewController = AuthorizationRequestViewController(with: MassService()) } it("should have the correct portrait layout on all Sizes") { expect(self.viewController.view) == self.snapshoService.snapshot("AuthorizationRequestViewController", sizes: self.snapshoService.iPhonePortraitSizes) } } } }
mit
cdrage/kedge
vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-sample/Sources/main.swift
89
2309
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation func printDocument(document:Openapi_V2_Document, name:String, version:String) -> String { var code = CodePrinter() code.print("READING \(name) (\(version))\n") code.print("Swagger: \(document.swagger)\n") code.print("Host: \(document.host)\n") code.print("BasePath: \(document.basePath)\n") if document.hasInfo { code.print("Info:\n") code.indent() if document.info.title != "" { code.print("Title: \(document.info.title)\n") } if document.info.description_p != "" { code.print("Description: \(document.info.description_p)\n") } if document.info.version != "" { code.print("Version: \(document.info.version)\n") } code.outdent() } code.print("Paths:\n") code.indent() for pair in document.paths.path { let v = pair.value if v.hasGet { code.print("GET \(pair.name)\n") } if v.hasPost { code.print("POST \(pair.name)\n") } } code.outdent() return code.content } func main() throws { var response = Openapi_Plugin_V1_Response() let rawRequest = try Stdin.readall() let request = try Openapi_Plugin_V1_Request(serializedData: rawRequest) let wrapper = request.wrapper let document = try Openapi_V2_Document(serializedData:wrapper.value) let report = printDocument(document:document, name:wrapper.name, version:wrapper.version) if let reportData = report.data(using:.utf8) { var file = Openapi_Plugin_V1_File() file.name = "report.txt" file.data = reportData response.files.append(file) } let serializedResponse = try response.serializedData() Stdout.write(bytes: serializedResponse) } try main()
apache-2.0
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/DeviceInfoMessage.swift
4
6111
// // DeviceInfoMessage.swift // Mixpanel // // Created by Yarden Eitan on 8/26/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import UIKit class DeviceInfoRequest: BaseWebSocketMessage { init() { super.init(type: MessageType.deviceInfoRequest.rawValue) } override func responseCommand(connection: WebSocketWrapper) -> Operation? { let operation = BlockOperation { [weak connection] in guard let connection = connection else { return } var response: DeviceInfoResponse? = nil DispatchQueue.main.sync { let currentDevice = UIDevice.current let infoResponseInput = InfoResponseInput(systemName: currentDevice.systemName, systemVersion: currentDevice.systemVersion, appVersion: Bundle.main.infoDictionary?["CFBundleVersion"] as? String, appRelease: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, deviceName: currentDevice.name, deviceModel: currentDevice.model, libLanguage: "Swift", libVersion: "2.6", // workaround for a/b testing availableFontFamilies: self.availableFontFamilies(), mainBundleIdentifier: Bundle.main.bundleIdentifier, tweaks: self.getTweaks()) response = DeviceInfoResponse(infoResponseInput) } connection.send(message: response) } return operation } func availableFontFamilies() -> [[String: AnyObject]] { var fontFamilies = [[String: AnyObject]]() let systemFonts = [UIFont.systemFont(ofSize: 17), UIFont.boldSystemFont(ofSize: 17), UIFont.italicSystemFont(ofSize: 17)] var foundSystemFamily = false for familyName in UIFont.familyNames { var fontNames = UIFont.fontNames(forFamilyName: familyName) if familyName == systemFonts.first!.familyName { for systemFont in systemFonts { if !fontNames.contains(systemFont.fontName) { fontNames.append(systemFont.fontName) } } foundSystemFamily = true } fontFamilies.append(["family": familyName as AnyObject, "font_names": UIFont.fontNames(forFamilyName: familyName) as AnyObject]) } if !foundSystemFamily { fontFamilies.append(["family": systemFonts.first!.familyName as AnyObject, "font_names": systemFonts.map { $0.fontName } as AnyObject]) } return fontFamilies } func getTweaks() -> [[String: AnyObject]] { var tweaks = [[String: AnyObject]]() guard let allTweaks = MixpanelTweaks.defaultStore.tweakCollections["Mixpanel"]?.allTweaks else { return tweaks } for tweak in allTweaks { let (value, defaultValue, min, max) = MixpanelTweaks.defaultStore.currentViewDataForTweak(tweak).getValueDefaultMinMax() let tweakDict = ["name": tweak.tweakName as AnyObject, "encoding": getEncoding(value) as AnyObject, "value": value as AnyObject, "default": defaultValue as AnyObject, "minimum": min as AnyObject? ?? defaultValue as AnyObject, "maximum": max as AnyObject? ?? defaultValue as AnyObject] as [String : AnyObject] tweaks.append(tweakDict) } return tweaks } func getEncoding(_ value: TweakableType) -> String { if value is Double || value is CGFloat { return "d" } else if value is String { return "@" } else if value is Int { return "i" } else if value is UInt { return "I" } return "" } } struct InfoResponseInput { let systemName: String let systemVersion: String let appVersion: String? let appRelease: String? let deviceName: String let deviceModel: String let libLanguage: String let libVersion: String? let availableFontFamilies: [[String: Any]] let mainBundleIdentifier: String? let tweaks: [[String: Any]] } class DeviceInfoResponse: BaseWebSocketMessage { init(_ infoResponse: InfoResponseInput) { var payload = [String: AnyObject]() payload["system_name"] = infoResponse.systemName as AnyObject payload["system_version"] = infoResponse.systemVersion as AnyObject payload["device_name"] = infoResponse.deviceName as AnyObject payload["device_model"] = infoResponse.deviceModel as AnyObject payload["available_font_families"] = infoResponse.availableFontFamilies as AnyObject payload["tweaks"] = infoResponse.tweaks as AnyObject payload["lib_language"] = infoResponse.libLanguage as AnyObject if let appVersion = infoResponse.appVersion { payload["app_version"] = appVersion as AnyObject } if let appRelease = infoResponse.appRelease { payload["app_release"] = appRelease as AnyObject } if let libVersion = infoResponse.libVersion { payload["lib_version"] = libVersion as AnyObject } if let mainBundleIdentifier = infoResponse.mainBundleIdentifier { payload["main_bundle_identifier"] = mainBundleIdentifier as AnyObject } super.init(type: MessageType.deviceInfoResponse.rawValue, payload: payload) } }
mit
WangWenzhuang/ZKProgressHUD
ZKProgressHUD/ZKProgressHUDMaskStyle.swift
1
323
// // ZKProgressHUDMaskStyle.swift // ZKProgressHUD // // Created by 王文壮 on 2017/4/19. // Copyright © 2017年 WangWenzhuang. All rights reserved. // /// 遮罩样式 public enum ZKProgressHUDMaskStyle { /// 隐藏 case hide /// 显示 case visible } typealias MaskStyle = ZKProgressHUDMaskStyle
mit
howwayla/taipeiAttractions
taipeiAttractions/AppDataService/TAAppDataService.swift
1
1316
// // TAAppDataService.swift // taipeiAttractions // // Created by Hardy on 2016/6/28. // Copyright © 2016年 Hardy. All rights reserved. // import Foundation class TAAppDataService { static let sharedInstance = TAAppDataService() fileprivate init() {} var categories: [String] = [] var attractions: [TAAttraction] = [] { didSet { setupCategories() setupAttractionsByCategory() } } var attractionsByCategory: [String: [TAAttraction]] = [:] //MARK:- Setup methods /** Setup categories from attractions */ fileprivate func setupCategories() { var newCategories: [String] = [] for category in (attractions.map{ $0.category }) { guard let category = category else { continue } if !newCategories.contains(category) { newCategories.append(category) } } self.categories = newCategories } fileprivate func setupAttractionsByCategory() { for category in self.categories { let attractions = self.attractions.filter{ $0.category == category } self.attractionsByCategory[category] = attractions } } }
mit
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/view/widget/MD2TextFieldWidget.swift
1
7127
// // MD2TextFieldWidget.swift // md2-ios-library // // Created by Christoph Rieger on 29.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // import UIKit /// A regular text field widget. class MD2TextFieldWidget: NSObject, MD2SingleWidget, MD2AssistedWidget, UITextFieldDelegate { /// Unique widget identification. let widgetId: MD2WidgetMapping /// The view element value. Using a property observer, external changes trigger a UI control update. var value: MD2Type { didSet { updateElement() } } /// Inner dimensions of the screen occupied by the widget. var dimensions: MD2Dimension? /// Placeholder text for empty text fields. var placeholder: MD2String? /// The native UI control. var widgetElement: UITextField /// Text field caption. var label: MD2String? /// The tooltip text to display for assistance. var tooltip: MD2String? /// The tooltip UI control dimensions. var tooltipDimensions: MD2Dimension? /// Text field type, e.g. single-line, multi-line, ... var type: TextField = TextField.Standard /// Width of the widget as specified by the model (percentage of the availale width). var width: Float? /// The button widget that represents the tooltip control. var infoButton: MD2ButtonWidget /** Default initializer. :param: widgetId Widget identifier */ init(widgetId: MD2WidgetMapping) { self.widgetId = widgetId self.value = MD2String() self.widgetElement = UITextField() self.infoButton = MD2ButtonWidget(widgetId: self.widgetId) } /** Render the view element, i.e. specifying the position and appearance of the widget. :param: view The surrounding view element. :param: controller The responsible view controller. */ func render(view: UIView, controller: UIViewController) { if dimensions == nil { // Element is not specified in layout. Maybe grid with not enough cells?! return } // Set value widgetElement.placeholder = placeholder?.platformValue updateElement() widgetElement.tag = widgetId.rawValue widgetElement.addTarget(self, action: "onUpdate", forControlEvents: (UIControlEvents.EditingDidEnd | UIControlEvents.EditingDidEndOnExit)) // Set styling widgetElement.backgroundColor = UIColor.whiteColor() widgetElement.borderStyle = UITextBorderStyle.RoundedRect widgetElement.font = UIFont(name: MD2ViewConfig.FONT_NAME.rawValue, size: CGFloat(MD2ViewConfig.FONT_SIZE)) // Add to surrounding view widgetElement.delegate = self view.addSubview(widgetElement) // If tooltip info is available show info button if tooltip != nil && tooltip!.isSet() && !tooltip!.equals(MD2String("")) { infoButton.buttonType = UIButtonType.InfoLight infoButton.dimensions = self.tooltipDimensions infoButton.render(view, controller: controller) } } /** Calculate the dimensions of the widget based on the available bounds. The occupied space of the widget is returned. *NOTICE* The occupied space may surpass the bounds (and thus the visible screen), if the height of the element is not sufficient. This is not a problem as the screen will scroll automatically. *NOTICE* The occupied space usually differs from the dimensions property as it refers to the *outer* dimensions in contrast to the dimensions property referring to *inner* dimensions. The difference represents the gutter included in the widget positioning process. :param: bounds The available screen space. :returns: The occupied outer dimensions of the widget. */ func calculateDimensions(bounds: MD2Dimension) -> MD2Dimension { var outerDimensions: MD2Dimension = bounds // If tooltip info is available show info button if tooltip != nil && tooltip!.isSet() && !tooltip!.equals(MD2String("")) { outerDimensions = MD2Dimension( x: bounds.x, y: bounds.y, width: bounds.width, height: MD2ViewConfig.DIMENSION_TEXTFIELD_HEIGHT) var textFieldDimensions = outerDimensions - MD2Dimension( x: Float(0.0), y: Float(0.0), width: Float(MD2ViewConfig.TOOLTIP_WIDTH), height: Float(0.0)) // Add gutter self.dimensions = MD2UIUtil.innerDimensionsWithGutter(textFieldDimensions) widgetElement.frame = MD2UIUtil.dimensionToCGRect(dimensions!) self.tooltipDimensions = MD2Dimension( x: (outerDimensions.x + outerDimensions.width) - Float(MD2ViewConfig.TOOLTIP_WIDTH) - MD2ViewConfig.GUTTER / 2, // center vertically y: textFieldDimensions.y + (textFieldDimensions.height - MD2ViewConfig.TOOLTIP_WIDTH) / 2, width: MD2ViewConfig.TOOLTIP_WIDTH, height: MD2ViewConfig.TOOLTIP_WIDTH) infoButton.widgetElement?.frame = MD2UIUtil.dimensionToCGRect(tooltipDimensions!) return outerDimensions } else { // Normal full-width field outerDimensions = MD2Dimension( x: bounds.x, y: bounds.y, width: bounds.width, height: MD2ViewConfig.DIMENSION_TEXTFIELD_HEIGHT) // Add gutter self.dimensions = MD2UIUtil.innerDimensionsWithGutter(outerDimensions) widgetElement.frame = MD2UIUtil.dimensionToCGRect(dimensions!) return outerDimensions } } /** Enumeration for all possible text field types. *TODO* Currently, only standard text field (single-line) are supported). */ enum TextField { case Standard } func textFieldShouldReturn(textField: UITextField) -> Bool { self.widgetElement.resignFirstResponder() return true } /// Enable the view element. func enable() { self.widgetElement.enabled = true } /// Disable the view element. func disable() { self.widgetElement.enabled = false } /** Target for the value change event. Updates the stored value and passes it to the respective widget wrapper which will process the value, e.g. applying validators and firing further events. */ func onUpdate() { self.value = MD2String(self.widgetElement.text) MD2WidgetRegistry.instance.getWidget(widgetId)?.setValue(self.value) } /** Update the view element after its value was changed externally. */ func updateElement() { self.widgetElement.text = value.toString() } }
apache-2.0
CSD-Public/stonix
src/MacBuild/stonix4mac/stonix4mac/AppDelegate.swift
1
522
// // AppDelegate.swift // stonix4mac // // Created by rsn_local on 11/4/16. // Copyright © 2016 Los Alamos National Laboratory. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
gpl-2.0
kildevaeld/Sockets
Example/Sockets/ViewController.swift
1
2396
// // ViewController.swift // Sockets // // Created by Softshag & Me on 07/29/2015. // Copyright (c) 2015 Softshag & Me. All rights reserved. // import UIKit import Sockets func after(delay: Double, _ fn: () -> Void) { let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { fn() } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var address: [SocketAddressInfo] = [] var s: SocketServer? do { address = try getAddressInfo(nil, port:3000, family: .Inet, type: .Stream, options: SocketAddressInfoOption.Passive) s = try SocketServer(family: address.first!.family, type: .Stream) } catch { } let server = s //let server = Socket.listen(address) server?.acceptQueue = dispatch_queue_create("something", DISPATCH_QUEUE_CONCURRENT) server?.listen(address.first!.address, accept: { (client) -> Void in let bytes = Bytes("Hello client \(client.remoteAddress)") client.send(bytes) let b = client.read() print(CString(bytes:b.block)) client.send("Harry") after(5, { () -> Void in client.send("Somethin good") client.close() }) }) let client = Socket.connect(address) client?.queue = dispatch_queue_create("read", DISPATCH_QUEUE_CONCURRENT) client?.read({ (data, length) -> Void in let str = CString(bytes:data) print("Go from server \(str)") }) client?.send("Rapper") //let data = client?.read() //let str = CString(bytes:data!.block) //let dd = str.description.dataUsingEncoding(NSUTF8StringEncoding) //var bytes = Bytes(void: dd!.bytes, length: dd!.length) //print("Got from server \(str)") //client?.send(bytes) // 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
rugheid/Swift-MathEagle
MathEagle/Permutation/Cycle.swift
1
2968
// // Cycle.swift // MathEagle // // Created by Rugen Heidbuchel on 31/05/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // /** A class representing a cycle in a permutation. */ open class Cycle: ExpressibleByArrayLiteral, CustomStringConvertible, Hashable { // MARK: Inner Structure /** Represents the cycle. Every element will be replaced by the next element. The last element will be replaced by the first. :example: `[0, 1, 2]`: When this is applied to the array `[1, 2, 3]` this gives `[2, 3, 1]`. */ open var cycleRepresentation: [Int] = [] // MARK: Initialisers /** Creates an empty cycle. */ public init() {} /** Creates a cycle with the given cycle representation. */ public init(_ cycleRepresentation: [Int]) { self.cycleRepresentation = cycleRepresentation } /** Creates a cycle with the given cycle representation. */ public convenience required init(arrayLiteral elements: Int...) { self.init(elements) } // MARK: Properties /** Returns a dictionary representation of the cycle. :example: (3 4 7) gives [3: 4, 4: 7, 7: 3] */ open var dictionaryRepresentation: [Int: Int] { get { var dict = [Int: Int]() for (index, element) in self.cycleRepresentation.enumerated() { dict[element] = self.cycleRepresentation[index == self.length-1 ? 0 : index+1] } return dict } } /** Returns the length of the cycle. */ open var length: Int { return self.cycleRepresentation.count } /** Retursn the parity of the cycle. The cycle is even when it's length is odd. */ open var parity: Parity { return self.length % 2 == 0 ? .odd : .even } /** Returns a description of the cycle. :example: (4 3 2) */ open var description: String { let combine = { (a: String, b: Int) in a + (a == "" ? "" : " ") + "\(b)" } return "(" + self.cycleRepresentation.reduce("", combine) + ")" } /** Returns a hash value for the cycle. */ open var hashValue: Int { //FIXME: This is a bad implementation return sum(self.cycleRepresentation) } } // MARK: Equatable /** Returns whether the two given cycles are equal. This means they have the same effect. Note that the cycle representations may vary. */ public func == (left: Cycle, right: Cycle) -> Bool { //TODO: This has to be more efficient return left.dictionaryRepresentation == right.dictionaryRepresentation }
mit
genedelisa/TreeControl
TreeControl/ViewController.swift
1
1586
// // ViewController.swift // TreeControl // // Created by Gene De Lisa on 7/18/15. // Copyright © 2015 Gene De Lisa. All rights reserved. // import Cocoa /// A View Controller that doesn't do much due to binding. /// - Author: Gene class ViewController: NSViewController { @IBOutlet var treeController: NSTreeController! @IBOutlet var outlineView: NSOutlineView! override func viewDidLoad() { super.viewDidLoad() // in case you want to see these. // let treeContentArrayBinding = convertFromOptionalNSBindingInfoKeyDictionary(self.treeController.infoForBinding(NSBindingName(rawValue: "contentArray"))) // let treeSelectionIndexes = convertFromOptionalNSBindingInfoKeyDictionary(self.treeController.infoForBinding(NSBindingName(rawValue: "selectionIndexPaths"))) // let outlineViewContentBinding = convertFromOptionalNSBindingInfoKeyDictionary(self.outlineView.infoForBinding(NSBindingName(rawValue: "content"))) // print(treeContentArrayBinding) // print(treeSelectionIndexes) // print(outlineViewContentBinding) } override var representedObject: Any? { didSet { } } } // Helper function inserted by Swift 4.2 migrator. private func convertFromOptionalNSBindingInfoKeyDictionary(_ input: [NSBindingInfoKey: Any]?) -> [String: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) }
mit
berzerker-io/soothe
SoothingKit/Source/Commands/InterpolateCommand.swift
1
1130
import Foundation import XcodeKit public struct InterpolateCommand { // MARK: - Initialization public init() { } // MARK: - Command public func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) { guard let selection = invocation.buffer.selections.firstObject as? XCSourceTextRange, var line = invocation.buffer.lines[selection.start.line] as? String else { return completionHandler(SelectionError.none) } guard selection.start.line == selection.end.line else { return completionHandler(SelectionError.multi) } line.insert(")", at: line.index(line.startIndex, offsetBy: selection.end.column)) line.insert("(", at: line.index(line.startIndex, offsetBy: selection.start.column)) line.insert(#"\"#, at: line.index(line.startIndex, offsetBy: selection.start.column)) invocation.buffer.lines.replaceObject(at: selection.start.line, with: line) selection.start.column += 2 selection.end.column += 2 completionHandler(nil) } }
unlicense
vmanot/swift-package-manager
Fixtures/Miscellaneous/-DSWIFT_PACKAGE/Foo.swift
3
103
class Foo{ var bar: Int = 0 #if SWIFT_PACKAGE #else var bar: String = "" #endif }
apache-2.0
vmanot/swift-package-manager
Fixtures/Miscellaneous/PackageWithInvalidTargets/Sources/Foo/foo.swift
3
15
struct Foo { }
apache-2.0
nickplee/Aestheticam
Aestheticam/Vendor/RandomKit/Sources/RandomKit/Extensions/Swift/String+RandomKit.swift
2
8919
// // String+RandomKit.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // extension String: Random { /// Generates a random `String`. /// /// - returns: Random value in `UnicodeScalar.randomRange` with length of `10`. public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> String { return random(ofLength: 10, in: UnicodeScalar.randomRange, using: &randomGenerator) } /// Generates a random `String` with a length of `10` inside of the range. /// /// - parameter range: The range in which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<R: RandomGenerator>(in range: Range<UnicodeScalar>, using randomGenerator: inout R) -> String? { return random(ofLength: 10, in: range, using: &randomGenerator) } /// Generates a random `String` of a given length inside of the range. /// /// - parameter length: The length for the generated string. /// - parameter range: The range in which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I, in range: Range<UnicodeScalar>, using randomGenerator: inout R) -> String? where I.Stride: SignedInteger { if range.isEmpty { return nil } var result = UnicodeScalarView() for _ in 0 ..< length { result.append(UnicodeScalar.uncheckedRandom(in: range, using: &randomGenerator)) } return String(result) } /// Generates a random `String` with a length of `10` inside of the closed range. /// /// - parameter closedRange: The range in which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<R: RandomGenerator>(in closedRange: ClosedRange<UnicodeScalar>, using randomGenerator: inout R) -> String { return random(ofLength: 10, in: closedRange, using: &randomGenerator) } /// Generates a random `String` of a given length inside of the closed range. /// /// - parameter length: The length for the generated string. /// - parameter closedRange: The range in which the string will be generated. The default is `UnicodeScalar.randomRange`. /// - parameter randomGenerator: The random generator to use. public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I, in closedRange: ClosedRange<UnicodeScalar> = UnicodeScalar.randomRange, using randomGenerator: inout R) -> String where I.Stride: SignedInteger { var result = UnicodeScalarView() for _ in 0 ..< length { result.append(.random(in: closedRange, using: &randomGenerator)) } return String(result) } #if swift(>=4.0) // No character view for you #else /// Generates a random `String` with a length of `10` from `characters`. /// /// - parameter characters: The characters from which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<R: RandomGenerator>(from characters: CharacterView, using randomGenerator: inout R) -> String? { return random(ofLength: 10, from: characters, using: &randomGenerator) } /// Generates a random `String` of a given length from `characters`. /// /// - parameter length: The length for the generated string. /// - parameter characters: The characters from which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I, from characters: CharacterView, using randomGenerator: inout R) -> String? where I.Stride: SignedInteger { var result = "" for _ in 0 ..< length { let random = self.random(using: &randomGenerator) result.append(random) } return result } #endif /// Generates a random `String` with a length of `10` from `scalars`. /// /// - parameter scalars: The unicode scalars from which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<R: RandomGenerator>(from scalars: UnicodeScalarView, using randomGenerator: inout R) -> String? { return random(ofLength: 10, from: scalars, using: &randomGenerator) } /// Generates a random `String` of a given length from `scalars`. /// /// - parameter length: The length for the generated string. /// - parameter scalars: The unicode scalars from which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I, from scalars: UnicodeScalarView, using randomGenerator: inout R) -> String? where I.Stride: SignedInteger { var result = UnicodeScalarView() for _ in 0 ..< length { guard let random = scalars.random(using: &randomGenerator) else { return nil } result.append(random) } return String(result) } /// Generates a random `String` with a length of `10` from characters in `string`. /// /// - parameter string: The string whose characters from which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<R: RandomGenerator>(from string: String, using randomGenerator: inout R) -> String? { return random(ofLength: 10, from: string, using: &randomGenerator) } /// Generates a random `String` of a given length from characters in `string`. /// /// - parameter length: The length for the generated string. /// - parameter string: The string whose characters from which the string will be generated. /// - parameter randomGenerator: The random generator to use. public static func random<I: ExpressibleByIntegerLiteral & Strideable, R: RandomGenerator>(ofLength length: I, from string: String, using randomGenerator: inout R) -> String? where I.Stride: SignedInteger { return random(ofLength: length, from: string.unicodeScalars, using: &randomGenerator) } } #if swift(>=4.0) extension String: RandomRetrievableInRange {} #else extension String.CharacterView: RandomRetrievableInRange {} #endif extension String.UnicodeScalarView: RandomRetrievableInRange {} extension String.UTF8View: RandomRetrievableInRange {} extension String.UTF16View: RandomRetrievableInRange {} extension String: Shuffleable, UniqueShuffleable { /// Shuffles the elements in `self` and returns the result. public func shuffled<R: RandomGenerator>(using randomGenerator: inout R) -> String { return String(self.shuffled(using: &randomGenerator)) } /// Shuffles the elements in `self` in a unique order and returns the result. public func shuffledUnique<R: RandomGenerator>(using randomGenerator: inout R) -> String { return String(self.shuffledUnique(using: &randomGenerator)) } }
mit
kylecrawshaw/ImagrAdmin
ImagrAdmin/WorkflowSupport/WorkflowComponents/IncludedWorkflowComponent/IncludedWorkflowComponent.swift
1
1281
// // IncludedWorkflowComponent.swift // ImagrManager // // Created by Kyle Crawshaw on 7/15/16. // Copyright © 2016 Kyle Crawshaw. All rights reserved. // import Foundation class IncludedWorkflowComponent: BaseComponent { var includedWorkflow: String? var script: String? init(id: Int!, workflowName: String!, workflowId: Int!) { super.init(id: id, type: "included_workflow", workflowName: workflowName, workflowId: workflowId) super.componentViewController = IncludedWorkflowViewController() } init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) { super.init(id: id, type: "included_workflow", workflowName: workflowName, workflowId: workflowId) super.componentViewController = IncludedWorkflowViewController() self.includedWorkflow = dict.valueForKey("included_workflow") as? String self.script = dict.valueForKey("script") as? String } override func asDict() -> NSDictionary? { var dict: [String: AnyObject] = [ "type": type, ] if includedWorkflow != nil { dict["name"] = includedWorkflow! } if script != nil { dict["script"] = script! } return dict } }
apache-2.0
chrishannah/CHEssentials
CHEssentialsTests/CHEssentialsTests.swift
1
1000
// // CHEssentialsTests.swift // CHEssentialsTests // // Created by Christopher Hannah on 14/07/2017. // Copyright © 2017 Chris Hannah. All rights reserved. // import XCTest @testable import CHEssentials class CHEssentialsTests: 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
mownier/photostream
Photostream/UI/Photo Library/PhotoLibraryDelegate.swift
1
1968
// // PhotoLibraryDelegate.swift // Photostream // // Created by Mounir Ybanez on 11/11/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit extension PhotoLibraryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedIndex = indexPath.row presenter.willShowSelectedPhoto(at: selectedIndex, size: selectedPhotoSize) } } extension PhotoLibraryViewController { var selectedPhotoSize: CGSize { let scale = UIScreen.main.scale return CGSize(width: cropView.bounds.width * scale, height: cropView.bounds.height * scale) } } extension PhotoLibraryViewController { func scrollViewDidScroll(_ view: UIScrollView) { guard let scrollView = scrollHandler.scrollView, scrollView == view, scrollHandler.isScrollable else { return } if !dimView.isHidden { dimView.alpha = min(scrollHandler.percentageOffsetY, 0.5) } switch scrollHandler.direction { case .down: didScrollDown(with: abs(scrollHandler.offsetDelta)) case .up, .none: didScrollUp(with: abs(scrollHandler.offsetDelta), offsetY: view.contentOffset.y) } scrollHandler.update() } func didScrollUp(with delta: CGFloat, offsetY: CGFloat = 0) { guard offsetY < -(48 + 2) else { return } let sum = cropContentViewConstraintTop.constant + delta let newDelta = min(sum, 0) cropContentViewConstraintTop.constant = newDelta } func didScrollDown(with delta: CGFloat) { let diff = cropContentViewConstraintTop.constant - delta let newDelta = max(diff, -(collectionView.contentInset.top - 48)) cropContentViewConstraintTop.constant = newDelta } }
mit
carnivalmobile/carnival-stream-examples
iOS/CarnivalSwiftStreamExamples/CarnivalSwiftStreamExamples/CarnivalLabel.swift
1
519
// // CarnivalLabel.swift // CarnivalSwiftStreamExamples // // Created by Sam Jarman on 14/09/15. // Copyright (c) 2015 Carnival Mobile. All rights reserved. // import UIKit class CarnivalLabel: UILabel { override var bounds: CGRect { didSet { if (self.numberOfLines == 0 && bounds.size.width != self.preferredMaxLayoutWidth) { self.preferredMaxLayoutWidth = self.bounds.size.width self.invalidateIntrinsicContentSize() } } } }
apache-2.0
moongift/NCMBiOSTodo
NCMBiOS_Todo/MasterViewController.swift
1
7118
// // MasterViewController.swift // NCMBiOS_Todo // // Created by naokits on 6/6/15. // import UIKit class MasterViewController: UITableViewController { /// TODOを格納する配列 var objects = [Todo]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.fetchAllTodos() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ------------------------------------------------------------------------ // MARK: - Segues // ------------------------------------------------------------------------ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "editTodo" { if let indexPath = self.tableView.indexPathForSelectedRow() { let todo = self.objects[indexPath.row] if let dvc = segue.destinationViewController as? DetailViewController { dvc.detailItem = todo dvc.updateButton.title = "更新" } } } else if segue.identifier == "addTodo" { (segue.destinationViewController as! DetailViewController).updateButton.title = "追加" } else { // 遷移先が定義されていない } } /// TODO登録/編集画面から戻ってきた時の処理を行います。 /// 今回はUnwind Identifierは必要ないので定義してません。 @IBAction func unwindromTodoEdit(segue:UIStoryboardSegue) { let svc = segue.sourceViewController as! DetailViewController if count(svc.todoTitle.text) < 3 { return } if svc.detailItem == nil { println("TODOオブジェクトが存在しないので、新規とみなします。") self.addTodoWithTitle(svc.todoTitle.text) } else { println("更新処理") svc.detailItem?.title = svc.todoTitle.text svc.detailItem?.saveInBackgroundWithBlock({ (error: NSError!) -> Void in self.tableView.reloadData() }) } } // ------------------------------------------------------------------------ // MARK: - Table View // ------------------------------------------------------------------------ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let todo = objects[indexPath.row] cell.textLabel?.text = todo.title return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let todo = objects[indexPath.row] as NCMBObject let objectID = todo.objectId let query = Todo.query() query.getObjectInBackgroundWithId(objectID, block: { (object: NCMBObject!, fetchError: NSError?) -> Void in if fetchError == nil { // NCMBから非同期で対象オブジェクトを削除します object.deleteInBackgroundWithBlock({ (deleteError: NSError!) -> Void in if (deleteError == nil) { let deletedObject = self.objects.removeAtIndex(indexPath.row) // データソースから削除 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else { println("削除失敗: \(deleteError)") } }) } else { println("オブジェクト取得失敗: \(fetchError)") } }) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } // ------------------------------------------------------------------------ // MARK: Methods for Data Source // ------------------------------------------------------------------------ /// 全てのTODO情報を取得し、プロパティに格納します /// /// :param: None /// :returns: None func fetchAllTodos() { let query = Todo.query() // タイトルにデータが含まれないものは除外(空の文字列は除外されない) query.whereKeyExists("title") // 登録日の降順で取得 query.orderByDescending("createDate") // 取得件数の指定 query.limit = 20 query.findObjectsInBackgroundWithBlock({(NSArray todos, NSError error) in if (error == nil) { println("登録件数: \(todos.count)") for todo in todos { let title = todo.title println("--- \(todo.objectId): \(title)") } self.objects = todos as! [Todo] // NSArray -> Swift Array self.tableView.reloadData() } else { println("Error: \(error)") } }) } /// 新規にTODOを追加します /// /// :param: title TODOのタイトル /// :returns: None func addTodoWithTitle(title: String) { let todo = Todo.object() as! Todo todo.setObject(title, forKey: "title") // 非同期で保存 todo.saveInBackgroundWithBlock { (error: NSError!) -> Void in if(error == nil){ println("新規TODOの保存成功。表示の更新などを行う。") self.insertNewTodoObject(todo) } else { println("新規TODOの保存に失敗しました: \(error)") } } } /// TODOをDataSourceに追加して、表示を更新します /// /// :param: todo TODOオブジェクト /// :returns: None func insertNewTodoObject(todo: Todo!) { self.objects.insert(todo, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) self.tableView.reloadData() } }
mit
johnsextro/cycschedule
cycschedule/ScheduleService.swift
1
3714
import Foundation class ScheduleService { func fetchTeamSchedule(teamId: String, callback: (Array< Game >) -> ()) { var postEndpoint: String = "http://x8-avian-bricolage-r.appspot.com/games/GamesService.games" let url = NSURL(string: postEndpoint) var params = ["team_id": teamId] as Dictionary<String, String> self.makeServiceCall(url!, params: params, callback: callback) } func fetchMultipleTeamSchedules(teamIds: String, callback: (Array< Game >) -> ()) { var postEndpoint: String = "http://x8-avian-bricolage-r.appspot.com/multigames/GamesMultiTeamService.games" let url = NSURL(string: postEndpoint) var params = ["team_ids": teamIds] as Dictionary<String, String> self.makeServiceCall(url!, params: params, callback: callback) } private func makeServiceCall(url: NSURL, params: Dictionary<String, String>, callback: (Array< Game >) -> ()) { var err: NSError? let timeout = 15 var urlRequest = NSMutableURLRequest(URL: url) urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.HTTPMethod = "POST" let queue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest( urlRequest, queue: queue, completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in if data.length > 0 && error == nil{ callback(self.parseJSONIntoArrayofGames(NSString(data: data, encoding: NSASCIIStringEncoding)!)) }else if data.length == 0 && error == nil{ println("Nothing was downloaded") } else if error != nil{ println("Error happened = \(error)") } } ) } private func parseJSONIntoArrayofGames(data:NSString) -> Array< Game >{ var parseError: NSError? var games:Array< Game > = Array < Game >() let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)! let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) if (parseError == nil) { if let schedule_obj = json as? NSDictionary { if let gamesArray = schedule_obj["games"] as? NSArray { for (var i = 0; i < gamesArray.count ; i++ ) { if let game_obj = gamesArray[i] as? NSDictionary { if let gameId = game_obj["game_id"] as? String { var homeTeam: String = (game_obj["home"] as? String)! var awayTeam: String = (game_obj["away"] as? String)! var location: String = (game_obj["location"] as? String)! var score: String = (game_obj["score"] as? String)! var gameDate: String = (game_obj["game_date"] as? String)! var gameTime: String = (game_obj["time"] as? String)! games.append(Game(gameId: gameId, gameDate: gameDate, gameTime: gameTime, opponent: awayTeam, location: location, score: score, home: homeTeam)) } } } } } } return games } }
gpl-2.0
1170197998/SinaWeibo
SFWeiBo/SFWeiBo/Classes/HomeDetail/HomeDetailCommentTableViewCell.swift
1
3936
// // HomeDetailCommentTableViewCell.swift // SFWeiBo // // Created by ShaoFeng on 16/7/12. // Copyright © 2016年 ShaoFeng. All rights reserved. // import UIKit class HomeDetailCommentTableViewCell: UITableViewCell { lazy var contentLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.font = UIFont.systemFontOfSize(15) label.textColor = UIColor.darkTextColor() return label }() var comment: Comments? { didSet { //名字赋值 nameLabel.text = comment?.user?.name //用户头像赋值 if let url = comment?.user?.imageUrl { headerIcon.sd_setImageWithURL(url) } //时间赋值 if let string = comment?.created_at { dateLabel.text = string } //评论内容赋值 if let string = comment?.text { let attributesString = NSMutableAttributedString.init(string: string) let paraghStyle = NSMutableParagraphStyle() paraghStyle.lineSpacing = 3 attributesString.addAttributes([NSParagraphStyleAttributeName : paraghStyle], range: NSMakeRange(0, string.characters.count)) contentLabel.attributedText = attributesString contentLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail contentLabel.contentMode = UIViewContentMode.Top let attributes = [NSFontAttributeName:contentLabel.font,NSParagraphStyleAttributeName:paraghStyle] let text: NSString = NSString(CString: string.cStringUsingEncoding(NSUTF8StringEncoding)!, encoding: NSUTF8StringEncoding)! let size = text.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.width - 60, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size contentLabel.text = attributesString.string contentLabel.frame = CGRectMake(50, 50, size.width, size.height) } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } private func setupUI() { contentView.addSubview(headerIcon) contentView.addSubview(nameLabel) contentView.addSubview(dateLabel) contentView.addSubview(contentLabel) headerIcon.AlignInner(type: AlignType.TopLeft, referView: contentView, size: CGSizeMake(35, 35), offset: CGPointMake(5, 5)) nameLabel.AlignHorizontal(type: AlignType.TopRight, referView: headerIcon, size: CGSizeMake(200, 20), offset: CGPointMake(10, 0)) dateLabel.AlignVertical(type: AlignType.BottomLeft, referView: nameLabel, size: CGSizeMake(150, 15), offset: CGPointMake(0, 5)) // contentLabel.AlignVertical(type: AlignType.BottomLeft, referView: dateLabel, size: CGSizeMake(UIScreen.mainScreen().bounds.width - 50, 20), offset: CGPointMake(0, 5)) } private lazy var headerIcon: UIImageView = { let imageView = UIImageView() imageView.layer.cornerRadius = 18 imageView.layer.masksToBounds = true return imageView }() private lazy var nameLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(15) label.textColor = UIColor.darkTextColor() return label }() private lazy var dateLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(13) label.textColor = UIColor.darkTextColor() return label }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
sharath-cliqz/browser-ios
Client/Frontend/Browser/TabScrollController.swift
2
8945
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } private let ToolbarBaseAnimationDuration: CGFloat = 0.2 class TabScrollingController: NSObject { enum ScrollDirection { case up case down } enum ToolbarState { case collapsed case visible case animating } weak var tab: Tab? { willSet { self.scrollView?.delegate = nil self.scrollView?.removeGestureRecognizer(panGesture) } didSet { self.scrollView?.addGestureRecognizer(panGesture) scrollView?.delegate = self } } weak var header: UIView? weak var footer: UIView? weak var urlBar: URLBarView? weak var snackBars: UIView? var footerBottomConstraint: Constraint? var headerTopConstraint: Constraint? var toolbarsShowing: Bool { return headerTopOffset == 0 } fileprivate var headerTopOffset: CGFloat = 0 { didSet { headerTopConstraint?.update(offset: headerTopOffset) header?.superview?.setNeedsLayout() } } fileprivate var footerBottomOffset: CGFloat = 0 { didSet { footerBottomConstraint?.update(offset: footerBottomOffset) footer?.superview?.setNeedsLayout() } } fileprivate lazy var panGesture: UIPanGestureRecognizer = { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(TabScrollingController.handlePan(_:))) panGesture.maximumNumberOfTouches = 1 panGesture.delegate = self return panGesture }() fileprivate var scrollView: UIScrollView? { return tab?.webView?.scrollView } fileprivate var contentOffset: CGPoint { return scrollView?.contentOffset ?? CGPoint.zero } fileprivate var contentSize: CGSize { return scrollView?.contentSize ?? CGSize.zero } fileprivate var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 } fileprivate var topScrollHeight: CGFloat { return header?.frame.height ?? 0 } fileprivate var bottomScrollHeight: CGFloat { return urlBar?.frame.height ?? 0 } fileprivate var snackBarsFrame: CGRect { return snackBars?.frame ?? CGRect.zero } fileprivate var lastContentOffset: CGFloat = 0 fileprivate var scrollDirection: ScrollDirection = .down fileprivate var toolbarState: ToolbarState = .visible override init() { super.init() } func showToolbars(_ animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) { if toolbarState == .visible { completion?(true) return } toolbarState = .visible let durationRatio = abs(headerTopOffset / topScrollHeight) let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated, duration: actualDuration, headerOffset: 0, footerOffset: 0, alpha: 1, completion: completion) } func hideToolbars(_ animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) { if toolbarState == .collapsed { completion?(true) return } toolbarState = .collapsed let durationRatio = abs((topScrollHeight + headerTopOffset) / topScrollHeight) let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated, duration: actualDuration, headerOffset: -topScrollHeight, footerOffset: bottomScrollHeight, alpha: 0, completion: completion) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentSize" { tab?.webView?.contentSizeChangeDetected() if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing { showToolbars(true, completion: nil) } } } } private extension TabScrollingController { func tabIsLoading() -> Bool { return tab?.loading ?? true } @objc func handlePan(_ gesture: UIPanGestureRecognizer) { if tabIsLoading() { return } if let containerView = scrollView?.superview { let translation = gesture.translation(in: containerView) let delta = lastContentOffset - translation.y if delta > 0 { scrollDirection = .down } else if delta < 0 { scrollDirection = .up } lastContentOffset = translation.y if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() { if toolbarState != .collapsed || contentOffset.y <= 0 { scrollWithDelta(delta) } if headerTopOffset == -topScrollHeight { toolbarState = .collapsed } else if headerTopOffset == 0 { toolbarState = .visible } else { toolbarState = .animating } } if gesture.state == .ended || gesture.state == .cancelled { lastContentOffset = 0 } } } func checkRubberbandingForDelta(_ delta: CGFloat) -> Bool { return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height && scrollViewHeight < contentSize.height) || contentOffset.y < delta) } func scrollWithDelta(_ delta: CGFloat) { if scrollViewHeight >= contentSize.height { return } var updatedOffset = headerTopOffset - delta headerTopOffset = clamp(updatedOffset, min: -topScrollHeight, max: 0) if isHeaderDisplayedForGivenOffset(updatedOffset) { scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta) } updatedOffset = footerBottomOffset + delta footerBottomOffset = clamp(updatedOffset, min: 0, max: bottomScrollHeight) let alpha = 1 - abs(headerTopOffset / topScrollHeight) urlBar?.updateAlphaForSubviews(alpha) } func isHeaderDisplayedForGivenOffset(_ offset: CGFloat) -> Bool { return offset > -topScrollHeight && offset < 0 } func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { if y >= max { return max } else if y <= min { return min } return y } func animateToolbarsWithOffsets(_ animated: Bool, duration: TimeInterval, headerOffset: CGFloat, footerOffset: CGFloat, alpha: CGFloat, completion: ((_ finished: Bool) -> Void)?) { let animation: () -> Void = { self.headerTopOffset = headerOffset self.footerBottomOffset = footerOffset self.urlBar?.updateAlphaForSubviews(alpha) self.header?.superview?.layoutIfNeeded() } if animated { UIView.animate(withDuration: duration, animations: animation, completion: completion) } else { animation() completion?(true) } } func checkScrollHeightIsLargeEnoughForScrolling() -> Bool { return (UIScreen.main.bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height } } extension TabScrollingController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension TabScrollingController: UIScrollViewDelegate { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if tabIsLoading() { return } if (decelerate || (toolbarState == .animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() { if scrollDirection == .up { showToolbars(true) } else if scrollDirection == .down { hideToolbars(true) } } } func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { showToolbars(true) return true } }
mpl-2.0
benlangmuir/swift
test/IRGen/prespecialized-metadata/struct-outmodule-frozen-1argument-1distinct_use-struct-outmodule-frozen-othermodule.swift
16
3343
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule -enable-library-evolution // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s7Generic11OneArgumentVy0C07IntegerVGMN" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // : i8** getelementptr inbounds ( // : %swift.vwtable, // : %swift.vwtable* @" // CHECK-SAME: $s7Generic11OneArgumentVy0C07IntegerVGWV // : ", // : i32 0, // : i32 0 // : ), // CHECK-SAME: [[INT]] 512, // : %swift.type_descriptor* @" // CHECK-SAME: $s7Generic11OneArgumentVMn // : ", // CHECK-SAME: %swift.type* @"$s8Argument7IntegerVN", // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{4|8}}, // CHECK-SAME: i64 1 // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } import Generic import Argument // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[CANONICALIZED_METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @swift_getCanonicalSpecializedMetadata( // CHECK-SAME: [[INT]] 0, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s7Generic11OneArgumentVy0C07IntegerVGMN" to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: %swift.type** @"$s7Generic11OneArgumentVy0C07IntegerVGMJ" // CHECK-SAME: ) // CHECK-NEXT: [[CANONICALIZED_METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[CANONICALIZED_METADATA_RESPONSE]], 0 // CHECK-NEXT: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[CANONICALIZED_METADATA]] // CHECK-SAME: ) // CHECK: } func doit() { consume( OneArgument(Integer(13)) ) } doit()
apache-2.0
robtimp/xswift
exercises/say/Tests/SayTests/SayTests.swift
2
2645
import XCTest @testable import Say class SayTests: XCTestCase { func testZero() { XCTAssertEqual("zero", Say.say(0)) } func testOne() { XCTAssertEqual("one", Say.say(1)) } func testFourteen() { XCTAssertEqual("fourteen", Say.say(14)) } func testTwenty() { XCTAssertEqual("twenty", Say.say(20)) } func testTwentyTwo() { XCTAssertEqual("twenty-two", Say.say(22)) } func testOneHundred() { XCTAssertEqual("one hundred", Say.say(100)) } func testOneHundredTwentyThree() { XCTAssertEqual("one hundred twenty-three", Say.say(123)) } func testOneThousand() { XCTAssertEqual("one thousand", Say.say(1_000)) } func testOneThousandTwoHundredThirtyFour() { XCTAssertEqual("one thousand two hundred thirty-four", Say.say(1_234)) } func testOneMillion() { XCTAssertEqual("one million", Say.say(1_000_000)) } func testOneMillionTwoThousandThreeHundredFortyFive() { XCTAssertEqual("one million two thousand three hundred forty-five", Say.say(1_002_345)) } func testOneBillion() { XCTAssertEqual("one billion", Say.say(1_000_000_000)) } func testABigNumber() { XCTAssertEqual("nine hundred eighty-seven billion six hundred fifty-four million three hundred twenty-one thousand one hundred twenty-three", Say.say(987_654_321_123)) } func testNumbersBelowZeroAreOutOfRange() { XCTAssertNil(Say.say(-1)) } func testNumbersAbove999999999999AreOutOfRange() { XCTAssertNil(Say.say(1_000_000_000_000)) } static var allTests: [(String, (SayTests) -> () throws -> Void)] { return [ ("testZero", testZero), ("testOne", testOne), ("testFourteen", testFourteen), ("testTwenty", testTwenty), ("testTwentyTwo", testTwentyTwo), ("testOneHundred", testOneHundred), ("testOneHundredTwentyThree", testOneHundredTwentyThree), ("testOneThousand", testOneThousand), ("testOneThousandTwoHundredThirtyFour", testOneThousandTwoHundredThirtyFour), ("testOneMillion", testOneMillion), ("testOneMillionTwoThousandThreeHundredFortyFive", testOneMillionTwoThousandThreeHundredFortyFive), ("testOneBillion", testOneBillion), ("testABigNumber", testABigNumber), ("testNumbersBelowZeroAreOutOfRange", testNumbersBelowZeroAreOutOfRange), ("testNumbersAbove999999999999AreOutOfRange", testNumbersAbove999999999999AreOutOfRange), ] } }
mit
atdrendel/Differences
Tests/DifferencesTests/String+Differences.swift
1
5872
import XCTest @testable import Differences class String_Differences: XCTestCase { static var allTests : [(String, (String_Differences) -> () throws -> Void)] { return [ ("testUTF8InsertAtStart", testUTF8InsertAtStart), ("testUTF8InsertAtEnd", testUTF8InsertAtEnd), ("testUTF8InsertChineseAndDeleteAscii", testUTF8InsertChineseAndDeleteAscii), ("testUTF8DeleteChineseAndMoveEmoji", testUTF8DeleteChineseAndMoveEmoji), ("testUTF16InsertAtStart", testUTF16InsertAtStart), ("testUTF16InsertAtEnd", testUTF16InsertAtEnd), ("testUTF16InsertChineseAndDeleteAscii", testUTF16InsertChineseAndDeleteAscii), ("testUTF16DeleteChineseAndMoveEmoji", testUTF16DeleteChineseAndMoveEmoji), ("testComposedCharactersInsertAtStart", testComposedCharactersInsertAtStart), ("testComposedCharactersInsertAtEnd", testComposedCharactersInsertAtEnd), ("testComposedCharactersInsertChineseAndDeleteAscii", testComposedCharactersInsertChineseAndDeleteAscii), ("testComposedCharactersDeleteChineseAndMoveEmoji", testComposedCharactersDeleteChineseAndMoveEmoji), ] } func testUTF8InsertAtStart() { let old = "Test" let new = "ReTest" let expected: Array<Difference> = [.insert(0), .insert(3), .move(0, 2)] _assert(expected: expected, equalsOld: old, diffedWithNew: new) } func testUTF8InsertAtEnd() { let old = "Test" let new = "Tester" let expected: Array<Difference> = [.insert(4), .insert(5)] _assert(expected: expected, equalsOld: old, diffedWithNew: new) } func testUTF8InsertChineseAndDeleteAscii() { let old = "Test" let new = "Te考试t" let expected: Array<Difference> = [ .delete(2), .insert(2), .insert(3), .insert(4), .insert(5), .insert(6), .insert(7) ] _assert(expected: expected, equalsOld: old, diffedWithNew: new) } func testUTF8DeleteChineseAndMoveEmoji() { let old = "👦男孩脸" let new = "男👦脸" let expected: Array<Difference> = [ .delete(7), .delete(8), .delete(9), .move(4, 0), .move(5, 1), .move(6, 2), .move(0, 3), .move(1, 4), .move(2, 5), .move(3, 6), ] _assert(expected: expected, equalsOld: old, diffedWithNew: new) } func testUTF16InsertAtStart() { let old = "Test" let new = "ReTest" let expected: Array<Difference> = [.insert(0), .insert(3), .move(0, 2)] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .utf16) } func testUTF16InsertAtEnd() { let old = "Test" let new = "Tester" let expected: Array<Difference> = [.insert(4), .insert(5)] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .utf16) } func testUTF16InsertChineseAndDeleteAscii() { let old = "Test" let new = "Te考试t" let expected: Array<Difference> = [ .delete(2), .insert(2), .insert(3) ] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .utf16) } func testUTF16DeleteChineseAndMoveEmoji() { let old = "👦男孩脸" let new = "男👦脸" let expected: Array<Difference> = [ .delete(3), .move(2, 0), .move(0, 1), .move(1, 2), ] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .utf16) } func testComposedCharactersInsertAtStart() { let old = "Test" let new = "ReTest" let expected: Array<Difference> = [.insert(0), .insert(3), .move(0, 2)] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .composedCharacters) } func testComposedCharactersInsertAtEnd() { let old = "Test" let new = "Tester" let expected: Array<Difference> = [.insert(4), .insert(5)] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .composedCharacters) } func testComposedCharactersInsertChineseAndDeleteAscii() { let old = "Test" let new = "Te考试t" let expected: Array<Difference> = [ .delete(2), .insert(2), .insert(3) ] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .composedCharacters) } func testComposedCharactersDeleteChineseAndMoveEmoji() { let old = "👦男孩脸" let new = "男👦脸" let expected: Array<Difference> = [ .delete(2), .move(1, 0), .move(0, 1), ] _assert(expected: expected, equalsOld: old, diffedWithNew: new, characterType: .composedCharacters) } // MARK: Helpers private func _assert( expected: Array<Difference>, equalsOld old: String, diffedWithNew new: String, characterType: String.CharacterType = .utf8) { let toNewDiffs = old.differences(to: new, characterType: characterType) let fromOldDiffs = new.differences(from: old, characterType: characterType) XCTAssertEqual(expected.count > 0, toNewDiffs.hasChanges) XCTAssertEqual(expected.count > 0, fromOldDiffs.hasChanges) XCTAssertEqual(expected.count, toNewDiffs.count) XCTAssertEqual(expected.count, fromOldDiffs.count) XCTAssertEqual(Set(expected), Set(toNewDiffs.changes)) XCTAssertEqual(Set(expected), Set(fromOldDiffs.changes)) } }
mit
bastie/swjft
swjft/swjft/lang/Cloneable.swift
1
247
// // Cloneable.swift // swjft // // Created by Sebastian Ritter on 14.12.15. // Copyright © 2015 Sebastian Ritter. All rights reserved. // public protocol swjftCloneable {} extension lang { public typealias Cloneable = swjftCloneable }
isc
rechsteiner/Parchment
Parchment/Enums/PagingMenuItemSource.swift
1
535
import Foundation import UIKit public enum PagingMenuItemSource { case `class`(type: PagingCell.Type) case nib(nib: UINib) } extension PagingMenuItemSource: Equatable { public static func == (lhs: PagingMenuItemSource, rhs: PagingMenuItemSource) -> Bool { switch (lhs, rhs) { case let (.class(lhsType), .class(rhsType)): return lhsType == rhsType case let (.nib(lhsNib), .nib(rhsNib)): return lhsNib === rhsNib default: return false } } }
mit
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Calling/Helper/VoiceChannel+Helper.swift
1
888
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import WireSyncEngine extension VoiceChannel { func toggleMuteState(userSession: ZMUserSession) { let toggled = !muted mute(toggled, userSession: userSession) } }
gpl-3.0
graphcool-examples/react-apollo-auth0-example
quickstart-with-apollo/Instagram/Carthage/Checkouts/apollo-ios/Sources/JSON.swift
1
1990
public typealias JSONValue = Any public typealias JSONObject = [String: JSONValue] public protocol JSONDecodable { init(jsonValue value: JSONValue) throws } public protocol JSONEncodable { var jsonValue: JSONValue { get } } public enum JSONDecodingError: Error, LocalizedError { case missingValue case nullValue case couldNotConvert(value: Any, to: Any.Type) public var errorDescription: String? { switch self { case .missingValue: return "Missing value" case .nullValue: return "Unexpected null value" case .couldNotConvert(let value, let expectedType): return "Could not convert \"\(value)\" to \(expectedType)" } } } extension JSONDecodingError: Matchable { public typealias Base = Error public static func ~=(pattern: JSONDecodingError, value: Error) -> Bool { guard let value = value as? JSONDecodingError else { return false } switch (value, pattern) { case (.missingValue, .missingValue), (.nullValue, .nullValue), (.couldNotConvert, .couldNotConvert): return true default: return false } } } // MARK: Helpers func optional(_ optionalValue: JSONValue?) throws -> JSONValue? { guard let value = optionalValue else { throw JSONDecodingError.missingValue } if value is NSNull { return nil } return value } func required(_ optionalValue: JSONValue?) throws -> JSONValue { guard let value = optionalValue else { throw JSONDecodingError.missingValue } if value is NSNull { throw JSONDecodingError.nullValue } return value } func cast<T>(_ value: JSONValue) throws -> T { guard let castValue = value as? T else { throw JSONDecodingError.couldNotConvert(value: value, to: T.self) } return castValue } func equals(_ lhs: Any, _ rhs: Any) -> Bool { if let lhs = lhs as? Reference, let rhs = rhs as? Reference { return lhs == rhs } let lhs = lhs as AnyObject, rhs = rhs as AnyObject return lhs.isEqual(rhs) }
mit
ericdke/WithOrWithoutEmoji
Sources/WithOrWithoutEmoji.swift
1
4437
import Foundation public extension NSString { fileprivate func _containsAnEmoji() -> Bool { // Original Objective-C code by Gabriel Massana https://github.com/GabrielMassana // Adapted to Swift 3 by Eric Dejonckheere https://github.com/ericdke let hs = self.character(at: 0) // surrogate pair if 0xd800 <= hs && hs <= 0xdbff { if self.length > 1 { let ls = self.character(at: 1) let uc:Int = Int(((hs - 0xd800) * 0x400) + (ls - 0xdc00)) + 0x10000 if 0x1d000 <= uc && uc <= 0x1f9c0 { return true } } } else if self.length > 1 { let ls = self.character(at: 1) if ls == 0x20e3 || ls == 0xfe0f || ls == 0xd83c { return true } } else { // non surrogate if (0x2100 <= hs && hs <= 0x27ff) || (0x2b05 <= hs && hs <= 0x2b07) || (0x2934 <= hs && hs <= 0x2935) || (0x3297 <= hs && hs <= 0x3299) { return true } else if hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50 { return true } } return false } } public extension String { public var condensedWhitespace: String { #if os(OSX) let components = self.components(separatedBy: .whitespacesAndNewlines) #else let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines()) #endif return components.filter { !$0.isEmpty }.joined(separator: " ") } public var emojiRanges: [NSRange] { var ranges = [NSRange]() let s = NSString(string:self) s.enumerateSubstrings(in: NSRange(location: 0, length: s.length), options: .byComposedCharacterSequences) { (substring, substringRange, _, _) in if let substring = substring { if NSString(string: substring)._containsAnEmoji() { ranges.append(substringRange) } } } return ranges } public var containsEmoji: Bool { var isEmoji = false let s = NSString(string:self) s.enumerateSubstrings(in: NSRange(location: 0, length: s.length), options: .byComposedCharacterSequences) { (substring, substringRange, _, stop) in if let substring = substring { if NSString(string:substring)._containsAnEmoji() { isEmoji = true // Stops the enumeration by setting the unsafe pointer to ObjcBool memory value, false by default in the closure parameters, to true. stop[0] = true } } } return isEmoji } public var emojisWithoutLetters: [String] { let s = NSString(string:self) return self.emojiRanges.map { s.substring(with: $0) } } public var lettersWithoutEmojis: [String] { #if os(OSX) var charSet = CharacterSet() charSet.insert(charactersIn: self.emojisWithoutLetters.joined(separator: "")) #else let charSet = NSCharacterSet(charactersIn: self.emojisWithoutLetters.joined(separator: "")) #endif let wo = self.components(separatedBy: charSet).joined(separator: "") return wo.characters.map { String($0) }.filter { $0 != "" } } public var condensedLettersWithoutEmojis: [String] { return self.lettersWithoutEmojis.filter { !$0.isEmpty && $0 != " " } } public var withoutEmojis: String { return self.lettersWithoutEmojis.joined(separator: "") } public var condensedStringWithoutEmojis: String { return self.lettersWithoutEmojis.joined(separator: "").condensedWhitespace } public var onlyEmojis: String { return self.emojisWithoutLetters.joined(separator: "") } public var emojiCount: Int { return self.emojisWithoutLetters.count } }
mit
erlandranvinge/swift-mini-json
legacy/Json-2.0.swift
1
1243
import Foundation class JsonGenerator: AnyGenerator<Json> { init(data:AnyObject?) { items = data as? [AnyObject] length = items?.count ?? 0 } private let items:[AnyObject]? private let length:Int private var current = 0 override func next() -> Json? { return current < length ? Json(data: items?[current++]) : .None } } class Json: SequenceType { let data:AnyObject? init(data:AnyObject?) { if (data is NSData) { self.data = try? NSJSONSerialization.JSONObjectWithData( data as! NSData, options: .AllowFragments) } else { self.data = data } } func string() -> String { return data as? String ?? "" } func int() -> Int { return data as? Int ?? 0 } func float() -> Float { return data as? Float ?? 0.0 } func double() -> Double { return data as? Double ?? 0.0 } func bool() -> Bool { return data as? Bool ?? false } subscript(name:String) -> Json { let hash = data as? NSDictionary return Json(data: hash?.valueForKey(name)) } func generate() -> AnyGenerator<Json> { return JsonGenerator(data: data) } }
mit
litoarias/SwiftTemplate
TemplateSwift3/Utils/Extensions/UITableViewCell.swift
1
236
// // UITableViewCell.swift // TemplateSwift3 // // Created by Hipolito Arias on 13/07/2017. // Copyright © 2017 Hipolito Arias. All rights reserved. // import Foundation import UIKit extension UITableViewCell: ReusableView { }
mit
RiotKit/RiotKit
RiotKit/RiotKit/Model/Champions/Champion.swift
1
1093
// // Champion.swift // RiotKit // // Created by Grant Douglas on 16/03/2016. // Copyright © 2016 Reconditorium Ltd. All rights reserved. // import Foundation /// `Champion` struct, containing all of the relevant status data public struct Champion { /// The `Champion` identifier public let id: Int; /// The `Champion` name public let name: String; /// Whether or not the `Champion` is active or disabled public let active: Bool; /// Whether or not the `Champion` can be used as a bot public let botEnabled: Bool; /// Whether or not the `Champion` is playable in CoOp vs AI public let botMMEnabled: Bool; /// Whether or not the `Champion` is in the free rotation `Champion` pool public let freeEnabled: Bool; /// Whether or not the `Champion` is available in ranked matches. public let rankedEnabled: Bool; /// The `Champion` avatar/icon. Var because we set this after. /// Optional because it has to be nil initially public var icon: UIImage?; /// THe champion data public var championData: ChampionData?; }
mit
inacioferrarini/York
Example/Tests/York/Extensions/StringExtensionsTests.swift
1
2227
// 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 XCTest import York class StringExtensionsTests: XCTestCase { // MARK: - Tests func test_isNumber_onlyNumber_mustReturnTrue() { let string = "40" XCTAssertTrue(string.isNumber()) } func test_isNumber_stringWithSpace_mustReturnFalse() { let string = "40 " XCTAssertFalse(string.isNumber()) } func test_isNumber_stringWithChar_mustReturnFalse() { let string = "40x" XCTAssertFalse(string.isNumber()) } func test_replaceStrings_mustNotCrash() { let baseString = "111.111.111-11" let replacedString = baseString.replaceStrings(pairing: ["." : "x", "-" : "y"]) let compareString = "111x111x111y11" XCTAssertEqual(replacedString, compareString) } func test_removeStrings_mustNotCrash() { let baseString = "111.111.111-11" let replacedString = baseString.removeStrings([".", "-"]) let compareString = "11111111111" XCTAssertEqual(replacedString, compareString) } }
mit
jeevanRao7/Swift_Playgrounds
Swift Playgrounds/Challenges/LinkedIn Placements 2017/Consecutive 1's in Binary Numbers/Consecutive 1's in Binary Numbers .playground/Contents.swift
1
520
/* Consecutive 1's in Binary Numbers */ import Foundation let n = Int(readLine()!)! let strN = String(n , radix:2); var maxCount = 0; var tempCount = 0; //Loop each characters for i in strN.characters.indices { if (strN[i] == "1") { //Increment count of '1' tempCount = tempCount + 1; } else{ //Reset count tempCount = 0; } //Track max count of '1's if (tempCount > maxCount) { maxCount = tempCount; } } print(maxCount);
mit
devgabrielcoman/nosce
Example/Nosce/ViewController.swift
1
521
// // ViewController.swift // Nosce // // Created by Gabriel Coman on 03/01/2016. // Copyright (c) 2016 Gabriel Coman. All rights reserved. // import UIKit import Nosce class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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. } }
gpl-3.0
thiagotmb/BEPiD-Challenges-2016
2016-02-12-WatchBordoes/WatchBordoes/WatchBordoes WatchKit Extension/CatchphraseTableRowController.swift
2
285
// // CatchphraseTableRowController.swift // WatchBordoes // // Created by Thiago-Bernardes on 2/12/16. // Copyright © 2016 TMB. All rights reserved. // import WatchKit class CatchphraseTableRowController: NSObject { @IBOutlet var saveCatchphraseLabel: WKInterfaceLabel! }
mit
anagac3/living-together-server
Sources/App/Controllers/HouseholdController.swift
1
4667
// // HouseholdController.swift // LivingTogetherServer // // Created by Andres Aguilar on 8/5/17. // // import Vapor import HTTP final class HouseholdController { /// it should return an index of all available posts func index(_ req: Request) throws -> ResponseRepresentable { return try Household.all().makeJSON() } /// When consumers call 'POST' on '/posts' with valid JSON /// create and save the post func create(_ req: Request) throws -> ResponseRepresentable { var household : Household var unique: Bool //Keep generating a new household until we get a unique code name repeat { household = try req.household() let queryResult = try Household.makeQuery().filter(Household.codeNameKey, .equals, household.codeName) unique = (try queryResult.count() == 0) ? true: false } while(!unique) try household.save() return household } /// When the consumer calls 'GET' on a specific resource, ie: /// '/posts/13rd88' we should show that specific post func show(_ req: Request) throws -> ResponseRepresentable { guard let householdId = req.data[Household.idKey]?.int else { throw Abort.badRequest } guard let household = try Household.find(householdId) else { throw Abort.notFound } return household } /// When the consumer calls 'DELETE' on a specific resource, ie: /// 'posts/l2jd9' we should remove that resource from the database func delete(_ req: Request) throws -> ResponseRepresentable { guard let householdId = req.data[Household.idKey]?.int else { throw Abort.badRequest } guard let household = try Household.find(householdId) else { throw Abort.notFound } try household.delete() return Response(status: .ok) } /// When the consumer calls 'DELETE' on the entire table, ie: /// '/posts' we should remove the entire table func clear(_ req: Request) throws -> ResponseRepresentable { try CompleteHistory.makeQuery().delete() try BoardMessage.makeQuery().delete() try ToDo.makeQuery().delete() try Bill.makeQuery().delete() try Resident.makeQuery().delete() try Household.makeQuery().delete() return Response(status: .ok) } /// When the user calls 'PATCH' on a specific resourcex, we should /// update that resource to the new values. func update(_ req: Request) throws -> ResponseRepresentable { // See `extension Post: Updateable` guard let householdId = req.data[Household.idKey]?.int else { throw Abort.badRequest } guard let household = try Household.find(householdId) else { throw Abort.notFound } try household.update(for: req) // Save an return the updated post. try household.save() return household } func joinHousehold(_ req: Request) throws -> ResponseRepresentable { guard let houseCodeName = req.data[Household.codeNameKey]?.string, let houseCode = req.data[Household.codeKey]?.int else { throw Abort.badRequest } guard let household = try Household.makeQuery().filter(Household.codeNameKey, .equals, houseCodeName).filter(Household.codeKey, .equals, houseCode).first() else { throw Abort.unauthorized } return household } func addRoutes(routeBuilder: RouteBuilder) { let householdBuilder = routeBuilder.grouped("household") householdBuilder.post("create", handler: create) householdBuilder.post("show", handler: show) householdBuilder.post("delete", handler: delete) householdBuilder.post("update", handler: update) householdBuilder.post("joinHousehold", handler: joinHousehold) //To keep out of production householdBuilder.get(handler: index) householdBuilder.post("deleteAll", handler: clear) } } extension Request { /// Create a post from the JSON body /// return BadRequest error if invalid /// or no JSON func household() throws -> Household { guard let name = data[Household.nameKey]?.string else { throw Abort.badRequest } return Household.init(name: name) } } /// Since PostController doesn't require anything to /// be initialized we can conform it to EmptyInitializable. /// /// This will allow it to be passed by type. extension HouseholdController: EmptyInitializable { }
mit
ZhangMingNan/MNMeiTuan
15-MeiTuan/15-MeiTuan/View/EmptyPromptView.swift
1
1729
// // EmptyPromptView.swift // 15-MeiTuan // // Created by 张明楠 on 15/8/25. // Copyright (c) 2015年 张明楠. All rights reserved. // import UIKit class EmptyPromptView: UIView { var imageView:UIImageView? var textLabel:UILabel? /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ class func emptyPromptView()->EmptyPromptView{ var view = EmptyPromptView() return view } override init(frame: CGRect) { super.init(frame: frame) var emptyInfoView = UIImageView(image: UIImage(named: "icon_deal_empty")!) self.imageView = emptyInfoView self.textLabel = UILabel() self.textLabel?.text = "暂无此类团购" self.textLabel?.textAlignment = NSTextAlignment.Center self.textLabel?.frame.size = CGSizeMake(screenWidth, 20) self.textLabel?.textColor = detailLabelColor self.addSubview(self.imageView!) self.addSubview(self.textLabel!) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.frame = self.superview!.bounds println(self.superview?.center) self.imageView?.frame.size = CGSizeMake(self.imageView!.image!.size.width * 0.5, self.imageView!.image!.size.height * 0.5) self.imageView?.center = CGPointMake(screenWidth * 0.5, screenWidth * 0.5 - 44) self.textLabel?.frame.origin = CGPointMake(0, CGRectGetMaxY(self.imageView!.frame)) } }
apache-2.0
rudkx/swift
SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift
1
2037
//===--- PassRegistration.swift - Register optimzation passes -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL import OptimizerBridging #if canImport(ExperimentalRegex) import ExperimentalRegex #endif @_cdecl("initializeSwiftModules") public func initializeSwiftModules() { registerSILClasses() registerSwiftPasses() #if canImport(ExperimentalRegex) registerRegexParser() #endif } private func registerPass( _ pass: FunctionPass, _ runFn: @escaping (@convention(c) (BridgedFunctionPassCtxt) -> ())) { pass.name.withBridgedStringRef { nameStr in SILPassManager_registerFunctionPass(nameStr, runFn) } } private func registerPass<InstType: Instruction>( _ pass: InstructionPass<InstType>, _ runFn: @escaping (@convention(c) (BridgedInstructionPassCtxt) -> ())) { pass.name.withBridgedStringRef { nameStr in SILCombine_registerInstructionPass(nameStr, runFn) } } private func registerSwiftPasses() { registerPass(silPrinterPass, { silPrinterPass.run($0) }) registerPass(mergeCondFailsPass, { mergeCondFailsPass.run($0) }) registerPass(simplifyBeginCOWMutationPass, { simplifyBeginCOWMutationPass.run($0) }) registerPass(simplifyGlobalValuePass, { simplifyGlobalValuePass.run($0) }) registerPass(simplifyStrongRetainPass, { simplifyStrongRetainPass.run($0) }) registerPass(simplifyStrongReleasePass, { simplifyStrongReleasePass.run($0) }) registerPass(assumeSingleThreadedPass, { assumeSingleThreadedPass.run($0) }) registerPass(runUnitTests, { runUnitTests.run($0) }) registerPass(releaseDevirtualizerPass, { releaseDevirtualizerPass.run($0) }) }
apache-2.0
ChinaHackers/Alipay
Alipay/Alipay/Classes/Home/Controller/Search/View/HotSearchCollectionViewCell.swift
1
3395
// // HotSearchCollectionViewCell.swift // SimpleSugars // // Created by 苑伟 on 2016/10/19. // Copyright © 2016年 苑伟. All rights reserved. // import UIKit import SnapKit // MARK: - 热门搜索cell class HotSearchCollectionViewCell: UICollectionViewCell { // MARK: - 懒加载 /// 排行榜数字 lazy var RankLabel: UILabel = { let rankLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 25, height: 30)) rankLabel.textAlignment = .center rankLabel.textColor = UIColor.white return rankLabel }() /// 热门搜索中 按钮 lazy var hotButton: UIButton = { let hotButton = UIButton(type: .custom) // 设置按钮 边框\背景颜色 //hotButton.backgroundColor = UIColor(red:0.07, green:0.14, blue:0.19, alpha:1.00) hotButton.backgroundColor = UIColor.groupTableViewBackground // hotButton.layer.borderColor = UIColor.white.cgColor // 边框宽度 // hotButton.layer.borderWidth = 0.5 // 设置按钮圆角 hotButton.layer.cornerRadius = 5 hotButton.layer.masksToBounds = true // 开启按钮交互 hotButton.isUserInteractionEnabled = true // 设置文字颜色\字体大小\对齐方式 hotButton.setTitleColor(UIColor.black, for: .normal) hotButton.titleLabel?.font = UIFont.systemFont(ofSize: 15) // 按钮文字对齐方式 hotButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left // 居左显示很难看,太靠边了。设置UIButton的文字边距 hotButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 0) return hotButton }() /// 删除按钮 lazy var deleteButton: UIButton = { let deleteButton = UIButton(type: .custom) deleteButton.setImage(UIImage(named:"delete"), for: .normal) deleteButton.isUserInteractionEnabled = true return deleteButton }() /// 容器视图 private lazy var containerView:UIView = { let containerView = UIView() containerView.backgroundColor = UIColor.clear containerView.isUserInteractionEnabled = true return containerView }() // MARK: - 构造函数 private override init(frame: CGRect) { super.init(frame: frame) // MARK: -添加控件 //contentView: 自定义添加子视图的单元格的内容视图 contentView.addSubview(containerView) containerView.frame = contentView.bounds // 添加按钮到容器里 containerView.addSubview(hotButton) containerView.addSubview(deleteButton) hotButton.addSubview(RankLabel) hotButton.frame = contentView.bounds // 默认隐藏删除按钮 deleteButton.isHidden = true //布局删除按钮 deleteButton.snp.makeConstraints { (make) in make.width.height.equalTo(15) make.top.equalTo(hotButton.snp.top).offset(-5) make.right.equalTo(hotButton.snp.right).offset(5) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Money/Shared/Decimal/Decimal.swift
1
6021
// // Decimal.swift // Money // // The MIT License (MIT) // // Copyright (c) 2015 Daniel Thorpe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation //import ValueCoding /** # Decimal A value type which implements `DecimalNumberType` using `NSDecimalNumber` internally. It is generic over the decimal number behavior type, which defines the rounding and scale rules for base 10 decimal arithmetic. */ public struct _Decimal<Behavior: DecimalNumberBehaviorType>: DecimalNumberType, Comparable { public typealias Magnitude = Double public typealias DecimalNumberBehavior = Behavior public var magnitude: Magnitude public static func -=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) { lhs = lhs.subtract(rhs) } public static func +=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) { lhs = lhs.add(rhs) } public static func *=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) { lhs = lhs.multiply(by: rhs) } public static func *(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> _Decimal<Behavior> { return lhs.multiply(by: rhs) } public static func +=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> _Decimal<Behavior> { return lhs.add(rhs) } public static func -=(lhs: inout _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> _Decimal<Behavior> { return lhs.subtract(rhs) } public static prefix func +(lhs: _Decimal<Behavior>) -> _Decimal<Behavior> { return lhs } public static prefix func -(lhs: _Decimal<Behavior>) -> _Decimal<Behavior> { return lhs.multiply(by: -1) } public static func ==(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool { return lhs.storage == rhs.storage } /// Returns a Boolean value indicating whether the value of the first /// argument is less than or equal to that of the second argument. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func <=(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool { return lhs.storage <= lhs.storage } /// Returns a Boolean value indicating whether the value of the first /// argument is greater than or equal to that of the second argument. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func >=(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool { return lhs.storage >= lhs.storage } /// Returns a Boolean value indicating whether the value of the first /// argument is greater than that of the second argument. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func >(lhs: _Decimal<Behavior>, rhs: _Decimal<Behavior>) -> Bool { return lhs.storage > lhs.storage } /// Access the underlying decimal storage. /// - returns: the `NSDecimalNumber` public let storage: NSDecimalNumber public init?<T>(exactly source: T) where T : BinaryInteger { self.storage = NSDecimalNumber(integerLiteral: Int(source)) self.magnitude = Double(source.magnitude as? String ?? "0.0")!//NSDecimalNumber(string: source.magnitude as? String) } /** Initialize a new value using the underlying decimal storage. - parameter storage: a `NSDecimalNumber` defaults to zero. */ public init(storage: NSDecimalNumber = NSDecimalNumber.zero) { self.storage = storage self.magnitude = storage.doubleValue } } // MARK: - Equality public func ==<B>(lhs: _Decimal<B>, rhs: _Decimal<B>) -> Bool { return lhs.storage == rhs.storage } // MARK: - Comparable public func <<B>(lhs: _Decimal<B>, rhs: _Decimal<B>) -> Bool { return lhs.storage < rhs.storage } /// `Decimal` with plain decimal number behavior public typealias PlainDecimal = _Decimal<DecimalNumberBehavior.Plain> /// `BankersDecimal` with banking decimal number behavior public typealias BankersDecimal = _Decimal<DecimalNumberBehavior.Bankers> // MARK: - Value Coding extension _Decimal: ValueCoding { public typealias Coder = _DecimalCoder<Behavior> } /** Coding class to support `_Decimal` `ValueCoding` conformance. */ public final class _DecimalCoder<Behavior: DecimalNumberBehaviorType>: NSObject, NSCoding, CodedValue, CodingProtocol{ public let value: _Decimal<Behavior> public required init(_ v: _Decimal<Behavior>) { value = v } public init?(coder aDecoder: NSCoder) { let storage = aDecoder.decodeObject(forKey: "storage") as! NSDecimalNumber value = _Decimal<Behavior>(storage: storage) } public func encode(with aCoder: NSCoder) { aCoder.encode(value.storage, forKey: "storage") } }
mit
csrose/DesignPattern
Factory/Factory/BMW320.swift
1
265
// // BMW320.swift // Factory // // Created by 杨晓冬 on 31/8/2017. // Copyright © 2017 YangXiaodong. All rights reserved. // import Foundation public class BMW320: ProductProtocol { public func Construct() { print("Construct BMW320") } }
mit
WillowChat/Squeak
Squeak-Core/Sources/Network/ResourceDescriptor.swift
1
255
import Foundation protocol ResourceDescriptor { associatedtype NetworkResponseType: Equatable associatedtype SuccessResponseType: Equatable var route: URLRequest { get } var parse: (NetworkResponseType) -> SuccessResponseType? { get } }
isc
jawwad/swift-algorithm-club
Splay Tree/SplayTree.playground/Contents.swift
1
635
//: Playground - Splay Tree Implementation // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift 4!") #endif let splayTree = SplayTree(value: 1) splayTree.insert(value: 2) splayTree.insert(value: 10) splayTree.insert(value: 6) splayTree.remove(value: 10) splayTree.remove(value: 6) splayTree.insert(value: 55) splayTree.insert(value: 559) splayTree.remove(value: 2) splayTree.remove(value: 1) splayTree.remove(value: 55) splayTree.remove(value: 559) splayTree.insert(value: 1843000) splayTree.insert(value: 1238) splayTree.insert(value: -1) splayTree.insert(value: 87) splayTree.minimum() splayTree.maximum()
mit
salemoh/GoldenQuraniOS
GoldenQuranSwift/Pods/GRDB.swift/GRDB/QueryInterface/Support/SQLFunctions.swift
2
6810
// MARK: - Custom Functions extension DatabaseFunction { /// Returns an SQL expression that applies the function. /// /// See https://github.com/groue/GRDB.swift/#sql-functions public func apply(_ arguments: SQLExpressible...) -> SQLExpression { return SQLExpressionFunction(SQLFunctionName(name), arguments: arguments.map { $0.sqlExpression }) } } // MARK: - ABS(...) extension SQLFunctionName { /// The `ABS` function name public static let abs = SQLFunctionName("ABS") } /// Returns an expression that evaluates the `ABS` SQL function. /// /// // ABS(amount) /// abs(Column("amount")) public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionFunction(.abs, arguments: value) } // MARK: - AVG(...) extension SQLFunctionName { /// The `AVG` function name public static let avg = SQLFunctionName("AVG") } /// Returns an expression that evaluates the `AVG` SQL function. /// /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionFunction(.avg, arguments: value) } // MARK: - COUNT(...) /// Returns an expression that evaluates the `COUNT` SQL function. /// /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { return SQLExpressionCount(counted) } // MARK: - COUNT(DISTINCT ...) /// Returns an expression that evaluates the `COUNT(DISTINCT)` SQL function. /// /// // COUNT(DISTINCT email) /// count(distinct: Column("email")) public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionCountDistinct(value.sqlExpression) } // MARK: - IFNULL(...) extension SQLFunctionName { /// The `IFNULL` function name public static let ifNull = SQLFunctionName("IFNULL") } /// Returns an expression that evaluates the `IFNULL` SQL function. /// /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { return SQLExpressionFunction(.ifNull, arguments: lhs, rhs) } // MARK: - LENGTH(...) extension SQLFunctionName { /// The `LENGTH` function name public static let length = SQLFunctionName("LENGTH") } /// Returns an expression that evaluates the `LENGTH` SQL function. /// /// // LENGTH(name) /// length(Column("name")) public func length(_ value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionFunction(.length, arguments: value) } // MARK: - MAX(...) extension SQLFunctionName { /// The `MAX` function name public static let max = SQLFunctionName("MAX") } /// Returns an expression that evaluates the `MAX` SQL function. /// /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionFunction(.max, arguments: value) } // MARK: - MIN(...) extension SQLFunctionName { /// The `MIN` function name public static let min = SQLFunctionName("MIN") } /// Returns an expression that evaluates the `MIN` SQL function. /// /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionFunction(.min, arguments: value) } // MARK: - SUM(...) extension SQLFunctionName { /// The `SUM` function name public static let sum = SQLFunctionName("SUM") } /// Returns an expression that evaluates the `SUM` SQL function. /// /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { return SQLExpressionFunction(.sum, arguments: value) } // MARK: - Swift String functions extension SQLSpecificExpressible { /// Returns an SQL expression that applies the Swift's built-in /// capitalized String property. It is NULL for non-String arguments. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn.capitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] public var capitalized: SQLExpression { return DatabaseFunction.capitalize.apply(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in /// lowercased String property. It is NULL for non-String arguments. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn.lowercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] public var lowercased: SQLExpression { return DatabaseFunction.lowercase.apply(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in /// uppercased String property. It is NULL for non-String arguments. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn.uppercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] public var uppercased: SQLExpression { return DatabaseFunction.uppercase.apply(sqlExpression) } } extension SQLSpecificExpressible { /// Returns an SQL expression that applies the Swift's built-in /// localizedCapitalized String property. It is NULL for non-String arguments. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) public var localizedCapitalized: SQLExpression { return DatabaseFunction.localizedCapitalize.apply(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in /// localizedLowercased String property. It is NULL for non-String arguments. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) public var localizedLowercased: SQLExpression { return DatabaseFunction.localizedLowercase.apply(sqlExpression) } /// Returns an SQL expression that applies the Swift's built-in /// localizedUppercased String property. It is NULL for non-String arguments. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) public var localizedUppercased: SQLExpression { return DatabaseFunction.localizedUppercase.apply(sqlExpression) } }
mit
kimlanbui/CircularRevealTransition
CircularRevealTransition/Classes/CircularRevealTransitionDelegate.swift
1
999
// // CircularRevealTransitionDelegate.swift // Pods // // Created by Kim Lan Bui on 11/02/17. // // import UIKit open class CircularRevealTransitionDelegate : NSObject { let sourceFrame : CGRect let duration : TimeInterval public init(frame: CGRect, duration: TimeInterval = 0.3) { self.sourceFrame = frame self.duration = duration } } extension CircularRevealTransitionDelegate : UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CircularRevealTransition(frame: sourceFrame, duration: duration, expanding: true) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CircularRevealTransition(frame: sourceFrame, duration: duration, expanding: false) } }
mit
bradkratky/BradColorPicker
Example/BradColorPicker/ViewController.swift
1
1172
// // ViewController.swift // BradColorPicker // // Created by brad on 07/08/2016. // Copyright (c) 2016 brad. All rights reserved. // import UIKit import BradColorPicker class ViewController: UIViewController, BradColorPickerDelegate { @IBOutlet weak var colorDisplay: UIView! override func viewDidLoad() { super.viewDidLoad() // 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. } @IBAction func btnLaunchPressed(_ sender: AnyObject) { let picker:BradColorPicker = BradColorPicker(delegate: self); // init with white //let picker:BradColorPicker = BradColorPicker(delegate: self, r:0.5, g:0, b:0.5, a:1); //let picker:BradColorPicker = BradColorPicker(delegate: self, color: UIColor.greenColor()); self.present(picker, animated: true, completion: {}); } // MARK: BradColorPickerDelegate func bradColorPicked(_ color: UIColor) { colorDisplay.backgroundColor = color; } }
mit
idapgroup/IDPDesign
IDPDesign/UIKit/Generated/Lens+UITextViewGenerated.swift
1
5695
// Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import UIKit public func delegate<Object: UITextView>() -> Lens<Object, UITextViewDelegate?> { return Lens( get: { $0.delegate }, setter: { $0.delegate = $1 } ) } public func text<Object: UITextView>() -> Lens<Object, String?> { return Lens( get: { $0.text }, setter: { $0.text = $1 } ) } public func font<Object: UITextView>() -> Lens<Object, UIFont?> { return Lens( get: { $0.font }, setter: { $0.font = $1 } ) } public func textColor<Object: UITextView>() -> Lens<Object, UIColor?> { return Lens( get: { $0.textColor }, setter: { $0.textColor = $1 } ) } public func textAlignment<Object: UITextView>() -> Lens<Object, NSTextAlignment> { return Lens( get: { $0.textAlignment }, setter: { $0.textAlignment = $1 } ) } public func selectedRange<Object: UITextView>() -> Lens<Object, NSRange> { return Lens( get: { $0.selectedRange }, setter: { $0.selectedRange = $1 } ) } public func isEditable<Object: UITextView>() -> Lens<Object, Bool> { return Lens( get: { $0.isEditable }, setter: { $0.isEditable = $1 } ) } public func isSelectable<Object: UITextView>() -> Lens<Object, Bool> { return Lens( get: { $0.isSelectable }, setter: { $0.isSelectable = $1 } ) } public func dataDetectorTypes<Object: UITextView>() -> Lens<Object, UIDataDetectorTypes> { return Lens( get: { $0.dataDetectorTypes }, setter: { $0.dataDetectorTypes = $1 } ) } public func allowsEditingTextAttributes<Object: UITextView>() -> Lens<Object, Bool> { return Lens( get: { $0.allowsEditingTextAttributes }, setter: { $0.allowsEditingTextAttributes = $1 } ) } public func attributedText<Object: UITextView>() -> Lens<Object, NSAttributedString?> { return Lens( get: { $0.attributedText }, setter: { $0.attributedText = $1 } ) } public func typingAttributes<Object: UITextView>() -> Lens<Object, [NSAttributedString.Key : Any]> { return Lens( get: { $0.typingAttributes }, setter: { $0.typingAttributes = $1 } ) } public func inputView<Object: UITextView>() -> Lens<Object, UIView?> { return Lens( get: { $0.inputView }, setter: { $0.inputView = $1 } ) } public func inputAccessoryView<Object: UITextView>() -> Lens<Object, UIView?> { return Lens( get: { $0.inputAccessoryView }, setter: { $0.inputAccessoryView = $1 } ) } public func clearsOnInsertion<Object: UITextView>() -> Lens<Object, Bool> { return Lens( get: { $0.clearsOnInsertion }, setter: { $0.clearsOnInsertion = $1 } ) } public func textContainer<Object: UITextView>() -> Lens<Object, NSTextContainer> { return Lens { $0.textContainer } } public func textContainerInset<Object: UITextView>() -> Lens<Object, UIEdgeInsets> { return Lens( get: { $0.textContainerInset }, setter: { $0.textContainerInset = $1 } ) } public func layoutManager<Object: UITextView>() -> Lens<Object, NSLayoutManager> { return Lens { $0.layoutManager } } public func textStorage<Object: UITextView>() -> Lens<Object, NSTextStorage> { return Lens { $0.textStorage } } public func linkTextAttributes<Object: UITextView>() -> Lens<Object, [NSAttributedString.Key : Any]?> { return Lens( get: { $0.linkTextAttributes }, setter: { $0.linkTextAttributes = $1 } ) } public func autocorrectionType<Object: UITextView>() -> Lens<Object, UITextAutocorrectionType> { return Lens( get: { $0.autocorrectionType }, setter: { $0.autocorrectionType = $1 } ) } public func spellCheckingType<Object: UITextView>() -> Lens<Object, UITextSpellCheckingType> { return Lens( get: { $0.spellCheckingType }, setter: { $0.spellCheckingType = $1 } ) } @available(iOS 11.0, *) public func smartQuotesType<Object: UITextView>() -> Lens<Object, UITextSmartQuotesType> { return Lens( get: { $0.smartQuotesType }, setter: { $0.smartQuotesType = $1 } ) } @available(iOS 11.0, *) public func smartDashesType<Object: UITextView>() -> Lens<Object, UITextSmartDashesType> { return Lens( get: { $0.smartDashesType }, setter: { $0.smartDashesType = $1 } ) } @available(iOS 11.0, *) public func smartInsertDeleteType<Object: UITextView>() -> Lens<Object, UITextSmartInsertDeleteType> { return Lens( get: { $0.smartInsertDeleteType }, setter: { $0.smartInsertDeleteType = $1 } ) } public func keyboardType<Object: UITextView>() -> Lens<Object, UIKeyboardType> { return Lens( get: { $0.keyboardType }, setter: { $0.keyboardType = $1 } ) } public func keyboardAppearance<Object: UITextView>() -> Lens<Object, UIKeyboardAppearance> { return Lens( get: { $0.keyboardAppearance }, setter: { $0.keyboardAppearance = $1 } ) } public func returnKeyType<Object: UITextView>() -> Lens<Object, UIReturnKeyType> { return Lens( get: { $0.returnKeyType }, setter: { $0.returnKeyType = $1 } ) } public func enablesReturnKeyAutomatically<Object: UITextView>() -> Lens<Object, Bool> { return Lens( get: { $0.enablesReturnKeyAutomatically }, setter: { $0.enablesReturnKeyAutomatically = $1 } ) } public func isSecureTextEntry<Object: UITextView>() -> Lens<Object, Bool> { return Lens( get: { $0.isSecureTextEntry }, setter: { $0.isSecureTextEntry = $1 } ) }
bsd-3-clause
vasarhelyia/Smogler
Smogler/AppDelegate.swift
1
1720
// // AppDelegate.swift // Smogler // // Created by Vasarhelyi Agnes on 2017. 02. 19.. // Copyright © 2017. vasarhelyia. All rights reserved. // import UIKit import WatchConnectivity @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate { var window: UIWindow? private let session: WCSession? = WCSession.isSupported() ? WCSession.default : nil func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { session?.delegate = self session?.activate() UIApplication.shared.setMinimumBackgroundFetchInterval(60 * 30) return true } func applicationDidBecomeActive(_ application: UIApplication) { APIService.sharedInstance.fetchAQI() } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { APIService.sharedInstance.fetchAQI() // TODO: completionHandler(.newData)? } // WCSessionDelegate func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } func sessionDidBecomeInactive(_ session: WCSession) { } func sessionDidDeactivate(_ session: WCSession) { session.activate() } func sendAQI(aqi: AQIInfo) { if !((session?.isPaired)! && (session?.isWatchAppInstalled)! && (session?.isReachable)!) { return } session?.sendMessage(["aqi": aqi.aqiLevel.value, "city": aqi.city], replyHandler: { dict in print("dict sent to Watch: \(dict)") }, errorHandler: { err in print("error sending message to Watch: \(err.localizedDescription)") }) } }
mit
emilstahl/swift
test/SILPasses/spec_recursion.swift
11
676
// RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s // Make sure we are not looping forever. extension Array { mutating func new_method(predicate: (Element, Element) -> Bool, left : Int, right : Int) { new_method(predicate, left: left, right: right); } } var x1 = [1] x1.new_method(<, left: 0, right: 1) struct Test<T> { init() {} func recursive(x x : T) { return recursive(x: x) } } // Make sure that the specialized function calls itself. //CHECK: sil shared @_TTSg5Si___TFV14spec_recursion4Test9recursive //CHECK: function_ref @_TTSg5Si___TFV14spec_recursion4Test9recursive //CHECK: return var x2 = Test<Int>() x2.recursive(x: 3)
apache-2.0
ben-ng/swift
benchmark/single-source/Integrate.swift
1
1923
//===--- Integrate.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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // A micro-benchmark for recursive divide and conquer problems. // The program performs integration via Gaussian Quadrature class Integrate { static let epsilon = 1.0e-9 let fun: (Double) -> Double init (f: @escaping (Double) -> Double) { fun = f } private func recEval(_ l: Double, fl: Double, r: Double, fr: Double, a: Double) -> Double { let h = (r - l) / 2 let hh = h / 2 let c = l + h let fc = fun(c) let al = (fl + fc) * hh let ar = (fr + fc) * hh let alr = al + ar let error = abs(alr-a) if (error < Integrate.epsilon) { return alr } else { let a1 = recEval(c, fl:fc, r:r, fr:fr, a:ar) let a2 = recEval(l, fl:fl, r:c, fr:fc, a:al) return a1 + a2 } } @inline(never) func computeArea(_ left: Double, right: Double) -> Double { return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0) } } @inline(never) public func run_Integrate(_ N: Int) { let obj = Integrate(f: { x in (x*x + 1.0) * x}) let left = 0.0 let right = 10.0 let ref_result = 2550.0 let bound = 0.0001 var result = 0.0 for _ in 1...N { result = obj.computeArea(left, right:right) if abs(result - ref_result) > bound { break } } CheckResults(abs(result - ref_result) < bound, "Incorrect results in Integrate: abs(\(result) - \(ref_result)) > \(bound)") }
apache-2.0
rockbruno/swiftshield
Sources/SwiftShieldCore/Log/Logger.swift
1
1289
import Foundation public protocol LoggerProtocol { func log(_ message: String, verbose: Bool, sourceKit: Bool) func fatalError(forMessage message: String) -> NSError } extension LoggerProtocol { func log(_ message: String) { log(message, verbose: false, sourceKit: false) } func log(_ message: String, verbose: Bool) { log(message, verbose: verbose, sourceKit: false) } func log(_ message: String, sourceKit: Bool) { log(message, verbose: false, sourceKit: sourceKit) } } public struct Logger: LoggerProtocol { let verbose: Bool let printSourceKit: Bool public init( verbose: Bool = false, printSourceKit: Bool = false ) { self.verbose = verbose self.printSourceKit = printSourceKit } public func fatalError(forMessage message: String) -> NSError { NSError( domain: "com.rockbruno.swiftshield", code: 0, userInfo: [NSLocalizedDescriptionKey: message] ) } public func log(_ message: String, verbose: Bool, sourceKit: Bool) { if sourceKit && !printSourceKit { return } guard verbose == false || self.verbose else { return } print(message) } }
gpl-3.0
kimseongrim/KimSampleCode
UITableView/UITableViewTests/UITableViewTests.swift
1
905
// // UITableViewTests.swift // UITableViewTests // // Created by 金成林 on 15/1/30. // Copyright (c) 2015年 Kim. All rights reserved. // import UIKit import XCTest class UITableViewTests: 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.measureBlock() { // Put the code you want to measure the time of here. } } }
gpl-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/01433-swift-constraints-solution-simplifytype.swift
1
588
// 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 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 var b = c(a: 1]] typealias h: b = i(Any)) -> String { class c { } } protocol c : d { typealias b { class A where g.B.B : (t: T -> String { } func g<3)):Any, Any) -> (g<3) } typealias d = g(
apache-2.0
bluezald/DesignPatterns
DesignPatterns/DesignPatterns/PrivateClassDataPattern.swift
1
1005
// // PrivateClassDataPattern.swift // DesignPatterns // // Created by Vincent Bacalso on 07/10/2016. // Copyright © 2016 bluezald. All rights reserved. // import UIKit /** Intent: Control write access to class attributes Separate data from methods that use it Encapsulate class data initialization Providing new type of final - final after constructor */ // Reduce exposure of attributes by limiting their visibility class PrivateClassDataPattern: NSObject { } class PrivateClassDataPatternCircle { private var radius: Double private var color: UIColor private var origin: CGPoint init(radius: Double, color: UIColor, origin: CGPoint) { self.radius = radius self.color = color self.origin = origin } public var circumference: Double { get { return 2 * Double.pi * self.radius } } public var diameter: Double { get { return 2 * self.radius } } }
mit
jkschoen/PitchPerfect
Pitch Perfect/AppDelegate.swift
1
2151
// // AppDelegate.swift // Pitch Perfect // // Created by Jacob Schoen on 3/11/15. // Copyright (c) 2015 Jacob Schoen. 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
iOS-mamu/SS
P/Library/Eureka/Source/Rows/ButtonRowWithPresent.swift
1
3863
// Rows.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2015 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 open class _ButtonRowWithPresent<T: Equatable, VCType: TypedRowControllerType>: Row<T, ButtonCellOf<T>>, PresenterRowType where VCType: UIViewController, VCType.RowValue == T { open var presentationMode: PresentationMode<VCType>? open var onPresentCallback : ((FormViewController, VCType)->())? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil cellStyle = .default } open override func customUpdateCell() { super.customUpdateCell() let leftAligmnment = presentationMode != nil cell.textLabel?.textAlignment = leftAligmnment ? .left : .center cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator cell.editingAccessoryType = cell.accessoryType if (!leftAligmnment){ var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0) } else{ cell.textLabel?.textColor = nil } } open override func customDidSelect() { super.customDidSelect() if let presentationMode = presentationMode, !isDisabled { if let controller = presentationMode.createController(){ controller.row = self onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!) } else{ presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!) } } } open override func prepareForSegue(_ segue: UIStoryboardSegue) { super.prepareForSegue(segue) guard let rowVC = segue.destination as? VCType else { return } if let callback = self.presentationMode?.completionHandler{ rowVC.completionCallback = callback } rowVC.row = self onPresentCallback?(cell.formViewController()!, rowVC) } } //MARK: Rows /// A generic row with a button that presents a view controller when tapped public final class ButtonRowWithPresent<T: Equatable, VCType: TypedRowControllerType> : _ButtonRowWithPresent<T, VCType>, RowType where VCType: UIViewController, VCType.RowValue == T { public required init(tag: String?) { super.init(tag: tag) } }
mit
Latyntsev/bumper
bumper/Parametres.swift
1
1883
// // Parametres.swift // bumper // // Created by Aleksandr Latyntsev on 1/12/16. // Copyright © 2016 Aleksandr Latyntsev. All rights reserved. // import Foundation class Parametres { var imagesFolderPath: String? var text = "" var fontName = "Menlo Regular" var help = false var showVersion = false private func parseArgument() { var setParametersValueHandler: ((value: String) -> Void)? let arguments = Process.arguments for argument in arguments[1..<arguments.count] { if setParametersValueHandler == nil { switch argument.lowercaseString { case "-path": setParametersValueHandler = {(value) -> Void in self.imagesFolderPath = value } case "-text": setParametersValueHandler = {(value) -> Void in self.text = value.stringByReplacingOccurrencesOfString("\\n", withString: "\n") } case "-fontName": setParametersValueHandler = {(value) -> Void in self.fontName = value } case "-help", "--h": self.help = true case "-version", "--v": self.showVersion = true default: break } } else { if (setParametersValueHandler != nil) { setParametersValueHandler!(value: argument) setParametersValueHandler = nil } } } } init() { self.parseArgument() } }
mit
mrdepth/Neocom
Neocom/Neocom/Fitting/Actions/DamagePatternsCustom.swift
2
4278
// // DamagePatternsCustom.swift // Neocom // // Created by Artem Shimanski on 3/19/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp import Expressible import CoreData struct DamagePatternsCustom: View { var onSelect: (DGMDamageVector) -> Void @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \DamagePattern.name, ascending: true)]) private var damagePatterns: FetchedResults<DamagePattern> var body: some View { Section(header: Text("CUSTOM")) { ForEach(damagePatterns, id: \.objectID) { row in CustomDamagePatternCell(damagePattern: row, onSelect: self.onSelect) }.onDelete { (indices) in indices.map{self.damagePatterns[$0]}.forEach {$0.managedObjectContext?.delete($0)} } NewDamagePatternButton() } } } struct CustomDamagePatternCell: View { var damagePattern: DamagePattern var onSelect: (DGMDamageVector) -> Void @Environment(\.editMode) private var editMode @Environment(\.self) private var environment @State private var selectedDamagePattern: DamagePattern? @EnvironmentObject private var sharedState: SharedState private func action() { if editMode?.wrappedValue == .active { self.selectedDamagePattern = damagePattern } else { self.onSelect(damagePattern.damageVector) } } var body: some View { Button(action: action) { VStack(alignment: .leading, spacing: 4) { if damagePattern.name?.isEmpty == false { Text(damagePattern.name!) } else { Text("Unnamed").italic() } DamageVectorView(damage: damagePattern.damageVector) }.contentShape(Rectangle()) }.buttonStyle(PlainButtonStyle()) .sheet(item: $selectedDamagePattern) { pattern in NavigationView { DamagePatternEditor(damagePattern: pattern) { self.selectedDamagePattern = nil } } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } } struct NewDamagePatternButton: View { @State private var selectedDamagePattern: DamagePattern? @Environment(\.self) private var environment @Environment(\.managedObjectContext) private var managedObjectContext @EnvironmentObject private var sharedState: SharedState var body: some View { Button(action: { self.selectedDamagePattern = DamagePattern(entity: NSEntityDescription.entity(forEntityName: "DamagePattern", in: self.managedObjectContext)!, insertInto: nil) self.selectedDamagePattern?.damageVector = .omni }) { Text("Add New Pattern").frame(maxWidth: .infinity, alignment: .center) .frame(height: 30) .contentShape(Rectangle()) } .buttonStyle(BorderlessButtonStyle()) .sheet(item: $selectedDamagePattern) { pattern in NavigationView { DamagePatternEditor(damagePattern: pattern) { self.selectedDamagePattern = nil } } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } } #if DEBUG struct DamagePatternsCustom_Previews: PreviewProvider { static var previews: some View { if (try? Storage.testStorage.persistentContainer.viewContext.from(DamagePattern.self).count()) == 0 { let pattern = DamagePattern(context: Storage.testStorage.persistentContainer.viewContext) pattern.name = "Pattern1" pattern.em = 2 pattern.thermal = 1 } return NavigationView { List { DamagePatternsCustom { _ in} }.listStyle(GroupedListStyle()) .navigationBarItems(trailing: EditButton()) } .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
adrfer/swift
validation-test/compiler_crashers_fixed/25581-swift-protocoltype-canonicalizeprotocols.swift
13
245
// 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 {struct S{func a{{class case,
apache-2.0
iDevelopper/PBRevealViewController
ExampleWithSwiftLibrary/ExampleWithSwiftLibrary/SettingsViewController.swift
1
8634
// // SettingsViewController.swift // ExampleWithSwiftLibrary // // Created by Patrick BODET on 19/08/2017. // Copyright © 2017 iDevelopper. All rights reserved. // import UIKit import PBRevealViewController class SettingsViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var leftButton: UIBarButtonItem! @IBOutlet weak var rightButton: UIBarButtonItem! @IBOutlet weak var leftBlurSegmentedControl: UISegmentedControl! @IBOutlet weak var rightBlurSegmentedControl: UISegmentedControl! @IBOutlet weak var leftPresentOnTopSwitch: UISwitch! @IBOutlet weak var rightPresentOnTopSwitch: UISwitch! @IBOutlet weak var leftHierarchicallySwitch: UISwitch! @IBOutlet weak var rightHierarchicallySwitch: UISwitch! @IBOutlet weak var leftRevealWidthField: UITextField! @IBOutlet weak var rightRevealWidthField: UITextField! @IBOutlet weak var leftOverdrawField: UITextField! @IBOutlet weak var rightOverdrawField: UITextField! @IBOutlet weak var leftDisplacementField: UITextField! @IBOutlet weak var rightDisplacementField: UITextField! @IBOutlet weak var leftPanBoderWidthField: UITextField! @IBOutlet weak var rightPanBoderWidthField: UITextField! @IBOutlet weak var toolBar: UIToolbar! var currentTextField: UITextField? var isMainUserInteraction: Bool = true let styles:[PBRevealBlurEffectStyle] = [.none, .extraLight, .light, .dark] override func viewDidLoad() { super.viewDidLoad() leftButton.target = self.revealViewController() leftButton.action = #selector(PBRevealViewController.revealLeftView) rightButton.target = self.revealViewController() rightButton.action = #selector(PBRevealViewController.revealRightView) leftBlurSegmentedControl.selectedSegmentIndex = (revealViewController()?.leftViewBlurEffectStyle.rawValue)! + 1 rightBlurSegmentedControl.selectedSegmentIndex = (revealViewController()?.rightViewBlurEffectStyle.rawValue)! + 1 leftPresentOnTopSwitch.isOn = (revealViewController()?.isLeftPresentViewOnTop)! rightPresentOnTopSwitch.isOn = (revealViewController()?.isRightPresentViewOnTop)! leftHierarchicallySwitch.isOn = (revealViewController()?.isLeftPresentViewHierarchically)! rightHierarchicallySwitch.isOn = (revealViewController()?.isRightPresentViewHierarchically)! Bundle.main.loadNibNamed("KeyboardTool", owner: self, options: nil) leftRevealWidthField.inputAccessoryView = toolBar leftRevealWidthField.text = "\(Int((revealViewController()?.leftViewRevealWidth)!))" rightRevealWidthField.inputAccessoryView = toolBar rightRevealWidthField.text = "\(Int((revealViewController()?.rightViewRevealWidth)!))" leftOverdrawField.inputAccessoryView = toolBar leftOverdrawField.text = "\(Int((revealViewController()?.leftViewRevealOverdraw)!))" rightOverdrawField.inputAccessoryView = toolBar rightOverdrawField.text = "\(Int((revealViewController()?.rightViewRevealOverdraw)!))" leftDisplacementField.inputAccessoryView = toolBar leftDisplacementField.text = "\(Int((revealViewController()?.leftViewRevealDisplacement)!))" rightDisplacementField.inputAccessoryView = toolBar rightDisplacementField.text = "\(Int((revealViewController()?.rightViewRevealDisplacement)!))" leftPanBoderWidthField.inputAccessoryView = toolBar leftPanBoderWidthField.text = "\(Int((revealViewController()?.panFromLeftBorderWidth)!))" rightPanBoderWidthField.inputAccessoryView = toolBar rightPanBoderWidthField.text = "\(Int((revealViewController()?.panFromRightBorderWidth)!))" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func blurValueChanged(_ sender: UISegmentedControl) { switch sender.tag { case 100: // Left revealViewController()?.leftViewBlurEffectStyle = styles[sender.selectedSegmentIndex] let nc = revealViewController()?.leftViewController as! UINavigationController let controller = nc.topViewController as! MenuTableViewController if sender.selectedSegmentIndex == 0 { controller.tableView.backgroundColor = UIColor.white } controller.tableView.reloadData() case 200: // Right revealViewController()?.rightViewBlurEffectStyle = styles[sender.selectedSegmentIndex] let nc = revealViewController()?.rightViewController as! UINavigationController let controller = nc.topViewController as! MenuTableViewController if sender.selectedSegmentIndex == 0 { controller.tableView.backgroundColor = UIColor.white } controller.tableView.reloadData() default: break } } @IBAction func onTopValueChanged(_ sender: UISwitch) { switch sender.tag { case 100: // Left revealViewController()?.isLeftPresentViewOnTop = sender.isOn if !sender.isOn { revealViewController()?.isLeftPresentViewHierarchically = false leftHierarchicallySwitch.isOn = false } case 200: // Right revealViewController()?.isRightPresentViewOnTop = sender.isOn if !sender.isOn { revealViewController()?.isRightPresentViewHierarchically = false rightHierarchicallySwitch.isOn = false } default: break } } @IBAction func hierarchicallyValueChanged(_ sender: UISwitch) { switch sender.tag { case 100: // Left revealViewController()?.isLeftPresentViewHierarchically = sender.isOn if sender.isOn { revealViewController()?.isLeftPresentViewOnTop = true leftPresentOnTopSwitch.isOn = true } case 200: // Right revealViewController()?.isRightPresentViewHierarchically = sender.isOn if sender.isOn { revealViewController()?.isRightPresentViewOnTop = true rightPresentOnTopSwitch.isOn = true } default: break } } @IBAction func mainUserInteractionValueChanged(_ sender: UISwitch) { isMainUserInteraction = sender.isOn } func textFieldDidBeginEditing(_ textField: UITextField) { currentTextField = textField let contentOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height) scrollView.setContentOffset(contentOffset, animated: true) } @IBAction func clear(_ sender: UIBarButtonItem) { currentTextField?.text = nil } @IBAction func done(_ sender: UIBarButtonItem) { if currentTextField == leftRevealWidthField { revealViewController()?.leftViewRevealWidth = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == rightRevealWidthField { revealViewController()?.rightViewRevealWidth = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == leftOverdrawField { revealViewController()?.leftViewRevealOverdraw = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == rightOverdrawField { revealViewController()?.rightViewRevealOverdraw = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == leftDisplacementField { revealViewController()?.leftViewRevealDisplacement = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == rightDisplacementField { revealViewController()?.rightViewRevealDisplacement = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == leftPanBoderWidthField { revealViewController()?.panFromLeftBorderWidth = CGFloat(Float(currentTextField!.text!)!) } if currentTextField == rightPanBoderWidthField { revealViewController()?.panFromRightBorderWidth = CGFloat(Float(currentTextField!.text!)!) } currentTextField?.resignFirstResponder() let contentOffset = CGPoint(x: 0, y: -scrollView.contentInset.top) scrollView.setContentOffset(contentOffset, animated: true) } }
mit