repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
skedgo/tripkit-ios
Sources/TripKitUI/views/results/TKUIProgressCell.swift
1
1005
// // TKUIProgressCell.swift // TripKitUI-iOS // // Created by Kuan Lun Huang on 12/12/19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import UIKit import TripKit public class TKUIProgressCell: UITableViewCell { @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var titleLabel: UILabel! public static let nib = UINib(nibName: "TKUIProgressCell", bundle: Bundle(for: TKUIProgressCell.self)) public static let reuseIdentifier: String = "TKUIProgressCell" override public func awakeFromNib() { super.awakeFromNib() contentView.backgroundColor = .tkBackground spinner.style = .medium spinner.color = .tkLabelPrimary spinner.startAnimating() titleLabel.font = TKStyleManager.customFont(forTextStyle: .body) titleLabel.textColor = .tkLabelPrimary titleLabel.text = Loc.LoadingDotDotDot } public override func prepareForReuse() { super.prepareForReuse() spinner.startAnimating() } }
apache-2.0
5373d3740ebf3b5d566d9b00ba6b5931
23.487805
104
0.721116
4.563636
false
false
false
false
arvedviehweger/swift
test/SILGen/expressions.swift
1
19628
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t - // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s -I%t -disable-access-control | %FileCheck %s import Swift import FooBar struct SillyString : _ExpressibleByBuiltinStringLiteral, ExpressibleByStringLiteral { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {} init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { } init(stringLiteral value: SillyString) { } } struct SillyUTF16String : _ExpressibleByBuiltinUTF16StringLiteral, ExpressibleByStringLiteral { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { } init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { } init(stringLiteral value: SillyUTF16String) { } } struct SillyConstUTF16String : _ExpressibleByBuiltinConstUTF16StringLiteral, ExpressibleByStringLiteral { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { } init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinConstStringLiteral start: Builtin.RawPointer) { } init( _builtinConstUTF16StringLiteral start: Builtin.RawPointer) { } init(stringLiteral value: SillyUTF16String) { } } func literals() { var a = 1 var b = 1.25 var d = "foö" var e:SillyString = "foo" var f:SillyConstUTF16String = "foobar" var non_ascii:SillyConstUTF16String = "foobarö" } // CHECK-LABEL: sil hidden @_T011expressions8literalsyyF // CHECK: integer_literal $Builtin.Int2048, 1 // CHECK: float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF4000000000000|0x3FFFA000000000000000}} // CHECK: string_literal utf16 "foö" // CHECK: string_literal utf8 "foo" // CHECK: [[CONST_STRING_LIT:%.*]] = const_string_literal utf8 "foobar" // CHECK: [[METATYPE:%.*]] = metatype $@thin SillyConstUTF16String.Type // CHECK: [[FUN:%.*]] = function_ref @_T011expressions21SillyConstUTF16StringVACBp08_builtincE7Literal_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String // CHECK: apply [[FUN]]([[CONST_STRING_LIT]], [[METATYPE]]) : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String // CHECK: [[CONST_UTF16STRING_LIT:%.*]] = const_string_literal utf16 "foobarö" // CHECK: [[FUN:%.*]] = function_ref @_T011expressions21SillyConstUTF16StringVACBp08_builtincdE7Literal_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String // CHECK: apply [[FUN]]([[CONST_UTF16STRING_LIT]], {{.*}}) : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String func bar(_ x: Int) {} func bar(_ x: Int, _ y: Int) {} func call_one() { bar(42); } // CHECK-LABEL: sil hidden @_T011expressions8call_oneyyF // CHECK: [[BAR:%[0-9]+]] = function_ref @_T011expressions3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int) -> () // CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42 // CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}}) // CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]]) func call_two() { bar(42, 219) } // CHECK-LABEL: sil hidden @_T011expressions8call_twoyyF // CHECK: [[BAR:%[0-9]+]] = function_ref @_T011expressions3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int, Int) -> () // CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42 // CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}}) // CHECK: [[TWONINETEEN:%[0-9]+]] = integer_literal {{.*}} 219 // CHECK: [[TWONINETEEN_CONVERTED:%[0-9]+]] = apply {{.*}}([[TWONINETEEN]], {{.*}}) // CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]], [[TWONINETEEN_CONVERTED]]) func tuples() { bar((4, 5).1) var T1 : (a: Int16, b: Int) = (b : 42, a : 777) } // CHECK-LABEL: sil hidden @_T011expressions6tuplesyyF class C { var chi:Int init() { chi = 219 } init(x:Int) { chi = x } } // CHECK-LABEL: sil hidden @_T011expressions7classesyyF func classes() { // CHECK: function_ref @_T011expressions1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C var a = C() // CHECK: function_ref @_T011expressions1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thick C.Type) -> @owned C var b = C(x: 0) } struct S { var x:Int init() { x = 219 } init(x: Int) { self.x = x } } // CHECK-LABEL: sil hidden @_T011expressions7structsyyF func structs() { // CHECK: function_ref @_T011expressions1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S var a = S() // CHECK: function_ref @_T011expressions1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thin S.Type) -> S var b = S(x: 0) } func inoutcallee(_ x: inout Int) {} func address_of_expr() { var x: Int = 4 inoutcallee(&x) } func identity<T>(_ x: T) -> T {} struct SomeStruct { mutating func a() {} } // CHECK-LABEL: sil hidden @_T011expressions5callsyyF // CHECK: [[METHOD:%[0-9]+]] = function_ref @_T011expressions10SomeStructV1a{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout SomeStruct) -> () // CHECK: apply [[METHOD]]({{.*}}) func calls() { var a : SomeStruct a.a() } // CHECK-LABEL: sil hidden @_T011expressions11module_path{{[_0-9a-zA-Z]*}}F func module_path() -> Int { return FooBar.x // CHECK: [[x_GET:%[0-9]+]] = function_ref @_T06FooBar1xSifau // CHECK-NEXT: apply [[x_GET]]() } func default_args(_ x: Int, y: Int = 219, z: Int = 20721) {} // CHECK-LABEL: sil hidden @_T011expressions19call_default_args_1{{[_0-9a-zA-Z]*}}F func call_default_args_1(_ x: Int) { default_args(x) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}F // CHECK: [[YFUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}A0_ // CHECK: [[Y:%[0-9]+]] = apply [[YFUNC]]() // CHECK: [[ZFUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}A1_ // CHECK: [[Z:%[0-9]+]] = apply [[ZFUNC]]() // CHECK: apply [[FUNC]]({{.*}}, [[Y]], [[Z]]) } // CHECK-LABEL: sil hidden @_T011expressions19call_default_args_2{{[_0-9a-zA-Z]*}}F func call_default_args_2(_ x: Int, z: Int) { default_args(x, z:z) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}F // CHECK: [[DEFFN:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}A0_ // CHECK-NEXT: [[C219:%[0-9]+]] = apply [[DEFFN]]() // CHECK: apply [[FUNC]]({{.*}}, [[C219]], {{.*}}) } struct Generic<T> { var mono_member:Int var typevar_member:T // CHECK-LABEL: sil hidden @_T011expressions7GenericV13type_variable{{[_0-9a-zA-Z]*}}F mutating func type_variable() -> T.Type { return T.self // CHECK: [[METATYPE:%[0-9]+]] = metatype $@thick T.Type // CHECK: return [[METATYPE]] } // CHECK-LABEL: sil hidden @_T011expressions7GenericV19copy_typevar_member{{[_0-9a-zA-Z]*}}F mutating func copy_typevar_member(_ x: Generic<T>) { typevar_member = x.typevar_member } // CHECK-LABEL: sil hidden @_T011expressions7GenericV12class_method{{[_0-9a-zA-Z]*}}FZ static func class_method() {} } // CHECK-LABEL: sil hidden @_T011expressions18generic_member_ref{{[_0-9a-zA-Z]*}}F func generic_member_ref<T>(_ x: Generic<T>) -> Int { // CHECK: bb0([[XADDR:%[0-9]+]] : $*Generic<T>): return x.mono_member // CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member // CHECK: load [trivial] [[MEMBER_ADDR]] } // CHECK-LABEL: sil hidden @_T011expressions24bound_generic_member_ref{{[_0-9a-zA-Z]*}}F func bound_generic_member_ref(_ x: Generic<UnicodeScalar>) -> Int { var x = x // CHECK: bb0([[XADDR:%[0-9]+]] : $Generic<UnicodeScalar>): return x.mono_member // CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member // CHECK: load [trivial] [[MEMBER_ADDR]] } // CHECK-LABEL: sil hidden @_T011expressions6coerce{{[_0-9a-zA-Z]*}}F func coerce(_ x: Int32) -> Int64 { return 0 } class B { } class D : B { } // CHECK-LABEL: sil hidden @_T011expressions8downcast{{[_0-9a-zA-Z]*}}F func downcast(_ x: B) -> D { return x as! D // CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $D } // CHECK-LABEL: sil hidden @_T011expressions6upcast{{[_0-9a-zA-Z]*}}F func upcast(_ x: D) -> B { return x // CHECK: upcast %{{[0-9]+}} : ${{.*}} to $B } // CHECK-LABEL: sil hidden @_T011expressions14generic_upcast{{[_0-9a-zA-Z]*}}F func generic_upcast<T : B>(_ x: T) -> B { return x // CHECK: upcast %{{.*}} to $B // CHECK: return } // CHECK-LABEL: sil hidden @_T011expressions16generic_downcast{{[_0-9a-zA-Z]*}}F func generic_downcast<T : B>(_ x: T, y: B) -> T { return y as! T // CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $T // CHECK: return } // TODO: generic_downcast // CHECK-LABEL: sil hidden @_T011expressions15metatype_upcast{{[_0-9a-zA-Z]*}}F func metatype_upcast() -> B.Type { return D.self // CHECK: metatype $@thick D // CHECK-NEXT: upcast } // CHECK-LABEL: sil hidden @_T011expressions19interpolated_string{{[_0-9a-zA-Z]*}}F func interpolated_string(_ x: Int, y: String) -> String { return "The \(x) Million Dollar \(y)" } protocol Runcible { associatedtype U var free:Int { get } var associated:U { get } func free_method() -> Int mutating func associated_method() -> U.Type static func static_method() } protocol Mincible { var free:Int { get } func free_method() -> Int static func static_method() } protocol Bendable { } protocol Wibbleable { } // CHECK-LABEL: sil hidden @_T011expressions20archetype_member_ref{{[_0-9a-zA-Z]*}}F func archetype_member_ref<T : Runcible>(_ x: T) { var x = x x.free_method() // CHECK: witness_method $T, #Runcible.free_method!1 // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[X:%.*]] // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr [[READ]] to [initialization] [[TEMP]] // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: apply // CHECK-NEXT: destroy_addr [[TEMP]] var u = x.associated_method() // CHECK: witness_method $T, #Runcible.associated_method!1 // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] // CHECK-NEXT: apply T.static_method() // CHECK: witness_method $T, #Runcible.static_method!1 // CHECK-NEXT: metatype $@thick T.Type // CHECK-NEXT: apply } // CHECK-LABEL: sil hidden @_T011expressions22existential_member_ref{{[_0-9a-zA-Z]*}}F func existential_member_ref(_ x: Mincible) { x.free_method() // CHECK: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply } /*TODO archetype and existential properties and subscripts func archetype_property_ref<T : Runcible>(_ x: T) -> (Int, T.U) { x.free = x.free_method() x.associated = x.associated_method() return (x.free, x.associated) } func existential_property_ref<T : Runcible>(_ x: T) -> Int { x.free = x.free_method() return x.free } also archetype/existential subscripts */ struct Spoon : Runcible, Mincible { typealias U = Float var free: Int { return 4 } var associated: Float { return 12 } func free_method() -> Int {} func associated_method() -> Float.Type {} static func static_method() {} } struct Hat<T> : Runcible { typealias U = [T] var free: Int { return 1 } var associated: U { get {} } func free_method() -> Int {} // CHECK-LABEL: sil hidden @_T011expressions3HatV17associated_method{{[_0-9a-zA-Z]*}}F mutating func associated_method() -> U.Type { return U.self // CHECK: [[META:%[0-9]+]] = metatype $@thin Array<T>.Type // CHECK: return [[META]] } static func static_method() {} } // CHECK-LABEL: sil hidden @_T011expressions7erasure{{[_0-9a-zA-Z]*}}F func erasure(_ x: Spoon) -> Mincible { return x // CHECK: init_existential_addr // CHECK: return } // CHECK-LABEL: sil hidden @_T011expressions19declref_to_metatypeAA5SpoonVmyF func declref_to_metatype() -> Spoon.Type { return Spoon.self // CHECK: metatype $@thin Spoon.Type } // CHECK-LABEL: sil hidden @_T011expressions27declref_to_generic_metatype{{[_0-9a-zA-Z]*}}F func declref_to_generic_metatype() -> Generic<UnicodeScalar>.Type { // FIXME parsing of T<U> in expression context typealias GenericChar = Generic<UnicodeScalar> return GenericChar.self // CHECK: metatype $@thin Generic<UnicodeScalar>.Type } func int(_ x: Int) {} func float(_ x: Float) {} func tuple() -> (Int, Float) { return (1, 1.0) } // CHECK-LABEL: sil hidden @_T011expressions13tuple_element{{[_0-9a-zA-Z]*}}F func tuple_element(_ x: (Int, Float)) { var x = x // CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Float) } // CHECK: [[PB:%.*]] = project_box [[XADDR]] int(x.0) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: tuple_element_addr [[READ]] : {{.*}}, 0 // CHECK: apply float(x.1) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: tuple_element_addr [[READ]] : {{.*}}, 1 // CHECK: apply int(tuple().0) // CHECK: [[ZERO:%.*]] = tuple_extract {{%.*}} : {{.*}}, 0 // CHECK: apply {{.*}}([[ZERO]]) float(tuple().1) // CHECK: [[ONE:%.*]] = tuple_extract {{%.*}} : {{.*}}, 1 // CHECK: apply {{.*}}([[ONE]]) } // CHECK-LABEL: sil hidden @_T011expressions10containers{{[_0-9a-zA-Z]*}}F func containers() -> ([Int], Dictionary<String, Int>) { return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3]) } // CHECK-LABEL: sil hidden @_T011expressions7if_expr{{[_0-9a-zA-Z]*}}F func if_expr(_ a: Bool, b: Bool, x: Int, y: Int, z: Int) -> Int { var a = a var b = b var x = x var y = y var z = z // CHECK: bb0({{.*}}): // CHECK: [[AB:%[0-9]+]] = alloc_box ${ var Bool } // CHECK: [[PBA:%.*]] = project_box [[AB]] // CHECK: [[BB:%[0-9]+]] = alloc_box ${ var Bool } // CHECK: [[PBB:%.*]] = project_box [[BB]] // CHECK: [[XB:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBX:%.*]] = project_box [[XB]] // CHECK: [[YB:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBY:%.*]] = project_box [[YB]] // CHECK: [[ZB:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBZ:%.*]] = project_box [[ZB]] return a ? x : b ? y : z // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBA]] // CHECK: [[A:%[0-9]+]] = load [trivial] [[READ]] // CHECK: [[ACOND:%[0-9]+]] = apply {{.*}}([[A]]) // CHECK: cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]] // CHECK: [[IF_A]]: // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]] // CHECK: [[XVAL:%[0-9]+]] = load [trivial] [[READ]] // CHECK: br [[CONT_A:bb[0-9]+]]([[XVAL]] : $Int) // CHECK: [[ELSE_A]]: // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBB]] // CHECK: [[B:%[0-9]+]] = load [trivial] [[READ]] // CHECK: [[BCOND:%[0-9]+]] = apply {{.*}}([[B]]) // CHECK: cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]] // CHECK: [[IF_B]]: // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBY]] // CHECK: [[YVAL:%[0-9]+]] = load [trivial] [[READ]] // CHECK: br [[CONT_B:bb[0-9]+]]([[YVAL]] : $Int) // CHECK: [[ELSE_B]]: // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBZ]] // CHECK: [[ZVAL:%[0-9]+]] = load [trivial] [[READ]] // CHECK: br [[CONT_B:bb[0-9]+]]([[ZVAL]] : $Int) // CHECK: [[CONT_B]]([[B_RES:%[0-9]+]] : $Int): // CHECK: br [[CONT_A:bb[0-9]+]]([[B_RES]] : $Int) // CHECK: [[CONT_A]]([[A_RES:%[0-9]+]] : $Int): // CHECK: return [[A_RES]] } // Test that magic identifiers expand properly. We test #column here because // it isn't affected as this testcase slides up and down the file over time. func magic_identifier_expansion(_ a: Int = #column) { // CHECK-LABEL: sil hidden @{{.*}}magic_identifier_expansion // This should expand to the column number of the first _. var tmp = #column // CHECK: integer_literal $Builtin.Int2048, 13 // This should expand to the column number of the (, not to the column number // of #column in the default argument list of this function. // rdar://14315674 magic_identifier_expansion() // CHECK: integer_literal $Builtin.Int2048, 29 } func print_string() { // CHECK-LABEL: print_string var str = "\u{08}\u{09}\thello\r\n\0wörld\u{1e}\u{7f}" // CHECK: string_literal utf16 "\u{08}\t\thello\r\n\0wörld\u{1E}\u{7F}" } // Test that we can silgen superclass calls that go farther than the immediate // superclass. class Super1 { func funge() {} } class Super2 : Super1 {} class Super3 : Super2 { override func funge() { super.funge() } } // <rdar://problem/16880240> SILGen crash assigning to _ func testDiscardLValue() { var a = 42 _ = a } func dynamicTypePlusZero(_ a : Super1) -> Super1.Type { return type(of: a) } // CHECK-LABEL: dynamicTypePlusZero // CHECK: bb0([[ARG:%.*]] : $Super1): // CHECK-NOT: copy_value // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NOT: copy_value // CHECK: value_metatype $@thick Super1.Type, [[BORROWED_ARG]] : $Super1 // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] struct NonTrivialStruct { var c : Super1 } func dontEmitIgnoredLoadExpr(_ a : NonTrivialStruct) -> NonTrivialStruct.Type { return type(of: a) } // CHECK-LABEL: dontEmitIgnoredLoadExpr // CHECK: bb0(%0 : $NonTrivialStruct): // CHECK-NEXT: debug_value // CHECK-NEXT: begin_borrow // CHECK-NEXT: end_borrow // CHECK-NEXT: %4 = metatype $@thin NonTrivialStruct.Type // CHECK-NEXT: destroy_value %0 // CHECK-NEXT: return %4 : $@thin NonTrivialStruct.Type // <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding // CHECK-LABEL: sil hidden @_T011expressions21implodeRecursiveTupleySi_Sit_SitSgF // CHECK: bb0(%0 : $Optional<((Int, Int), Int)>): func implodeRecursiveTuple(_ expr: ((Int, Int), Int)?) { // CHECK: bb2([[WHOLE:%.*]] : $((Int, Int), Int)): // CHECK-NEXT: [[X:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 0 // CHECK-NEXT: [[X0:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 0 // CHECK-NEXT: [[X1:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 1 // CHECK-NEXT: [[Y:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 1 // CHECK-NEXT: [[X:%[0-9]+]] = tuple ([[X0]] : $Int, [[X1]] : $Int) // CHECK-NEXT: debug_value [[X]] : $(Int, Int), let, name "x" // CHECK-NEXT: debug_value [[Y]] : $Int, let, name "y" let (x, y) = expr! } func test20087517() { class Color { static func greenColor() -> Color { return Color() } } let x: (Color?, Int) = (.greenColor(), 1) } func test20596042() { enum E { case thing1 case thing2 } func f() -> (E?, Int)? { return (.thing1, 1) } } func test21886435() { () = () }
apache-2.0
40e63be4ad0142a5abd89b053e4c0dbf
30.445513
211
0.620477
3.137512
false
false
false
false
lotpb/iosSQLswift
mySQLswift/AppDelegate.swift
1
10466
// // AppDelegate.swift // mySQLswift // // Created by Peter Balsamo on 12/8/15. // Copyright © 2015 Peter Balsamo. All rights reserved. // import UIKit import Parse import Firebase import FBSDKCoreKit import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var backgroundSessionCompletionHandler: (() -> Void)? var window: UIWindow? var defaults = NSUserDefaults.standardUserDefaults() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // MARK: - Register Settings defaults.registerDefaults([ "soundKey": false, "parsedataKey": true, "autolockKey": false, "fontKey": "System", "fontsizeKey": "20pt", "nameColorKey": "Blue", "usernameKey": "Peter Balsamo", "passwordKey": "3911", "websiteKey": "http://lotpb.github.io/UnitedWebPage/index.html", "eventtitleKey": "Appt", "areacodeKey": "516", "versionKey": "1.0", "emailtitleKey": "TheLight Support", "emailmessageKey": "<h3>Programming in Swift</h3>" ]) // MARK: - Firebase FIRApp.configure() // MARK: - Parse if (defaults.boolForKey("parsedataKey")) { Parse.setApplicationId("lMUWcnNfBE2HcaGb2zhgfcTgDLKifbyi6dgmEK3M", clientKey: "UVyAQYRpcfZdkCa5Jzoza5fTIPdELFChJ7TVbSeX") PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions) } // MARK: - prevent Autolock if (defaults.boolForKey("autolockKey")) { UIApplication.sharedApplication().idleTimerDisabled = true } // MARK: - RegisterUserNotification let mySettings = UIUserNotificationSettings(forTypes:[.Badge, .Sound, .Alert], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(mySettings) application.applicationIconBadgeNumber = 0 // MARK: - Background Fetch UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) // MARK: - ApplicationIconBadgeNumber let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification! if (notification != nil) { notification.applicationIconBadgeNumber = 0 } // MARK: - Register login if (!(defaults.boolForKey("registerKey")) || defaults.boolForKey("loginKey")) { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController : UIViewController = storyboard.instantiateViewControllerWithIdentifier("loginViewController") as UIViewController self.window?.rootViewController = initialViewController self.window?.makeKeyAndVisible() } // MARK: - SplitViewController /* // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self */ // MARK: - Facebook Sign-in FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) customizeAppearance() return true } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { application.applicationIconBadgeNumber = 0 } // MARK: - Google/Facebook @available(iOS 9.0, *) func application(application: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { return self.application(application, openURL: url, sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] as! String?, annotation: [:]) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if GIDSignIn.sharedInstance().handleURL(url, sourceApplication: sourceApplication,annotation: annotation) { return true } return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } // MARK: - Background Fetch func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { print("########### Received Background Fetch ###########") let localNotification: UILocalNotification = UILocalNotification() localNotification.alertAction = "Background transfer service download!" localNotification.alertBody = "Background transfer service: Download complete!" localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 UIApplication.sharedApplication().presentLocalNotificationNow(localNotification) completionHandler(UIBackgroundFetchResult.NewData) } // MARK: - Music Controller func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { backgroundSessionCompletionHandler = completionHandler } // MARK: 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. } // MARK: - Facebook 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. FBSDKAppEvents.activateApp() } // MARK: func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { /* guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? SnapshotController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } */ return false } // MARK - App Theme Customization private func customizeAppearance() { //UIApplication.sharedApplication().networkActivityIndicatorVisible = true //Activity Status Bar UIApplication.sharedApplication().statusBarStyle = .LightContent UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] UINavigationBar.appearance().barTintColor = UIColor.blackColor() UINavigationBar.appearance().tintColor = UIColor.grayColor() UINavigationBar.appearance().translucent = false UITabBar.appearance().barTintColor = UIColor.blackColor() UITabBar.appearance().tintColor = UIColor.whiteColor() UITabBar.appearance().translucent = false UIToolbar.appearance().barTintColor = UIColor(white:0.45, alpha:1.0) UIToolbar.appearance().tintColor = UIColor.whiteColor() UISearchBar.appearance().barTintColor = UIColor.blackColor() UISearchBar.appearance().tintColor = UIColor.whiteColor() UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = UIColor.grayColor() } } // MARK: CLLocationManagerDelegate - Beacons extension AppDelegate: CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { if let _ = region as? CLBeaconRegion { let notification = UILocalNotification() notification.alertBody = "Are you forgetting something?" notification.soundName = "Default" UIApplication.sharedApplication().presentLocalNotificationNow(notification) } } }
gpl-2.0
4def4e3ebe9ae78d4c68e57c22394ab9
41.889344
285
0.68495
6.20332
false
false
false
false
PumpMagic/ostrich
gameboy/gameboy/Source/CPUs/Intel8080Like.swift
1
76015
// // 8080Like.swift // ostrichframework // // Created by Ryan Conway on 4/6/16. // Copyright © 2016 Ryan Conway. All rights reserved. // import Foundation struct Intel8080InstructionContext { var lastInstructionWasDI: Bool var lastInstructionWasEI: Bool } enum FlipFlop { case enabled case disabled } /// Everything in common between the Z80 and the LR35902. protocol Intel8080Like { var A: Register8 { get } var B: Register8 { get } var C: Register8 { get } var D: Register8 { get } var E: Register8 { get } var F: Register8 { get } var H: Register8 { get } var L: Register8 { get } var I: Register8 { get } var R: Register8 { get } var AF: Register16Computed { get } var BC: Register16Computed { get } var DE: Register16Computed { get } var HL: Register16Computed { get } var SP: Register16 { get } var PC: Register16 { get } var ZF: Flag { get } var NF: Flag { get } var HF: Flag { get } var CF: Flag { get } var IFF1: FlipFlop { get } var IFF2: FlipFlop { get } var bus: DataBus { get } func push(_ val: UInt16) func pop() -> UInt16 } extension Intel8080Like { /// Push a two-byte value onto the stack. /// Adjusts the stack pointer accordingly. func push(_ val: UInt16) { let oldAddr = self.SP.read() let newAddr = oldAddr - 2 self.SP.write(newAddr) self.bus.write16(val, to: newAddr) } func pop() -> UInt16 { let addr = self.SP.read() let val = self.bus.read16(addr) self.SP.write(addr + 2) return val } func fetchInstructionCommon() -> Instruction? { let firstByte = bus.read(PC.read()) var instruction: Z80Instruction? = nil var instructionLength: UInt16 = 1 switch firstByte { case 0x00: // NOP instruction = NOP() instructionLength = 1 case 0x01: // LD BC, nn let val = bus.read16(PC.read()+1) instruction = LD(dest: self.BC, src: Immediate16(val: val)) instructionLength = 3 case 0x02: // LD (BC), A instruction = LD(dest: self.BC.asPointerOn(self.bus), src: self.A) instructionLength = 1 case 0x03: // INC BC instruction = INC16(operand: self.BC) instructionLength = 1 case 0x04: // INC B instruction = INC8(operand: self.B) instructionLength = 1 case 0x05: // DEC B instruction = DEC8(operand: self.B) instructionLength = 1 case 0x06: // LD B, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.B, src: Immediate8(val: val)) instructionLength = 2 case 0x07: // RLCA instruction = RLCA() instructionLength = 1 case 0x09: // ADD HL, BC instruction = ADD16(op1: self.HL, op2: self.BC) instructionLength = 1 case 0x0A: // LD A, (BC) instruction = LD(dest: self.A, src: self.BC.asPointerOn(bus)) instructionLength = 1 case 0x0B: // DEC BC instruction = DEC16(operand: self.BC) instructionLength = 1 case 0x0C: // INC C instruction = INC8(operand: self.C) instructionLength = 1 case 0x0D: // DEC C instruction = DEC8(operand: self.C) instructionLength = 1 case 0x0E: // LD C, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.C, src: Immediate8(val: val)) instructionLength = 2 case 0x0F: // RRCA instruction = RRCA() instructionLength = 1 case 0x11: // LD DE, nn let val = bus.read16(PC.read()+1) instruction = LD(dest: self.DE, src: Immediate16(val: val)) instructionLength = 3 case 0x12: // LD (DE), A instruction = LD(dest: self.DE.asPointerOn(self.bus), src: self.A) instructionLength = 1 case 0x13: // INC DE instruction = INC16(operand: self.DE) instructionLength = 1 case 0x14: // INC D instruction = INC8(operand: self.D) instructionLength = 1 case 0x15: // DEC D instruction = DEC8(operand: self.D) instructionLength = 1 case 0x16: // LD D, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.D, src: Immediate8(val: val)) instructionLength = 2 case 0x17: // RLA instruction = RLA() instructionLength = 1 case 0x18: // JR n let displacement = Int8(bitPattern: bus.read(PC.read()+1)) instruction = JR(condition: nil, displacementMinusTwo: displacement) instructionLength = 2 case 0x19: // ADD HL, DE instruction = ADD16(op1: self.HL, op2: self.DE) instructionLength = 1 case 0x1A: // LD A, (DE) instruction = LD(dest: self.A, src: self.DE.asPointerOn(bus)) instructionLength = 1 case 0x1B: // DEC DE instruction = DEC16(operand: self.DE) instructionLength = 1 case 0x1C: // INC E instruction = INC8(operand: self.E) instructionLength = 1 case 0x1D: // DEC E instruction = DEC8(operand: self.E) instructionLength = 1 case 0x1E: // LD E, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.E, src: Immediate8(val: val)) instructionLength = 2 case 0x1F: // RRCA instruction = RRCA() instructionLength = 1 case 0x20: // JR NZ n let displacement = Int8(bitPattern: bus.read(PC.read()+1)) instruction = JR(condition: Condition(flag: self.ZF, target: false), displacementMinusTwo: displacement) instructionLength = 2 case 0x21: // LD HL, nn let val = bus.read16(PC.read()+1) instruction = LD(dest: self.HL, src: Immediate16(val: val)) instructionLength = 3 case 0x23: // INC HL instruction = INC16(operand: self.HL) instructionLength = 1 case 0x24: // INC H instruction = INC8(operand: self.H) instructionLength = 1 case 0x25: // DEC H instruction = DEC8(operand: self.H) instructionLength = 1 case 0x26: // LD H, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.H, src: Immediate8(val: val)) instructionLength = 2 case 0x28: // JR Z n let displacement = Int8(bitPattern: bus.read(PC.read()+1)) instruction = JR(condition: Condition(flag: self.ZF, target: true), displacementMinusTwo: displacement) instructionLength = 2 case 0x29: // ADD HL, HL instruction = ADD16(op1: self.HL, op2: self.HL) instructionLength = 1 case 0x2B: // DEC HL instruction = DEC16(operand: self.HL) instructionLength = 1 case 0x2C: // INC L instruction = INC8(operand: self.L) instructionLength = 1 case 0x2D: // DEC L instruction = DEC8(operand: self.L) instructionLength = 1 case 0x2E: // LD L, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.L, src: Immediate8(val: val)) instructionLength = 2 case 0x2F: // CPL instruction = CPL() instructionLength = 1 case 0x30: // JR NC n let displacement = Int8(bus.read(PC.read()+1)) instruction = JR(condition: Condition(flag: self.CF, target: false), displacementMinusTwo: displacement) instructionLength = 2 case 0x31: // LD SP, nn let val = bus.read16(PC.read()+1) instruction = LD(dest: self.SP, src: Immediate16(val: val)) instructionLength = 3 case 0x33: // INC SP instruction = INC16(operand: self.SP) instructionLength = 1 case 0x34: // INC (HL) instruction = INC8(operand: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x35: // DEC (HL) instruction = DEC8(operand: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x36: // LD (HL), n let val = bus.read(PC.read()+1) instruction = LD(dest: self.HL.asPointerOn(bus), src: Immediate8(val: val)) instructionLength = 2 case 0x37: // SCF instruction = SCF() instructionLength = 1 case 0x38: // JR C n let displacement = Int8(bitPattern: bus.read(PC.read()+1)) instruction = JR(condition: Condition(flag: self.CF, target: true), displacementMinusTwo: displacement) instructionLength = 2 case 0x39: // ADD HL, SP instruction = ADD16(op1: self.HL, op2: self.SP) instructionLength = 1 case 0x3B: // DEC SP instruction = DEC16(operand: self.SP) instructionLength = 1 case 0x3C: // INC A instruction = INC8(operand: self.A) instructionLength = 1 case 0x3D: // DEC A instruction = DEC8(operand: self.A) instructionLength = 1 case 0x3E: // LD A, n let val = bus.read(PC.read()+1) instruction = LD(dest: self.A, src: Immediate8(val: val)) instructionLength = 2 case 0x3F: // CCF instruction = CCF() instructionLength = 1 case 0x40: // LD B, B instruction = LD(dest: self.B, src: self.B) instructionLength = 1 case 0x41: // LD B, C instruction = LD(dest: self.B, src: self.C) instructionLength = 1 case 0x42: // LD B, D instruction = LD(dest: self.B, src: self.D) instructionLength = 1 case 0x43: // LD B, E instruction = LD(dest: self.B, src: self.E) instructionLength = 1 case 0x44: // LD B, H instruction = LD(dest: self.B, src: self.H) instructionLength = 1 case 0x45: // LD B, L instruction = LD(dest: self.B, src: self.L) instructionLength = 1 case 0x46: // LD B, (HL) instruction = LD(dest: self.B, src: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x47: // LD B, A instruction = LD(dest: self.B, src: self.A) instructionLength = 1 case 0x48: // LD C, B instruction = LD(dest: self.C, src: self.B) instructionLength = 1 case 0x49: // LD C, C instruction = LD(dest: self.C, src: self.C) instructionLength = 1 case 0x4A: // LD C, D instruction = LD(dest: self.C, src: self.D) instructionLength = 1 case 0x4B: // LD C, E instruction = LD(dest: self.C, src: self.E) instructionLength = 1 case 0x4C: // LD C, H instruction = LD(dest: self.C, src: self.H) instructionLength = 1 case 0x4D: // LD C, L instruction = LD(dest: self.C, src: self.L) instructionLength = 1 case 0x4E: // LD C, (HL) instruction = LD(dest: self.C, src: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x4F: // LD C, A instruction = LD(dest: self.C, src: self.A) instructionLength = 1 case 0x50: // LD D, B instruction = LD(dest: self.D, src: self.B) instructionLength = 1 case 0x51: // LD D, C instruction = LD(dest: self.D, src: self.C) instructionLength = 1 case 0x52: // LD D, D instruction = LD(dest: self.D, src: self.D) instructionLength = 1 case 0x53: // LD D, E instruction = LD(dest: self.D, src: self.E) instructionLength = 1 case 0x54: // LD D, H instruction = LD(dest: self.D, src: self.H) instructionLength = 1 case 0x55: // LD D, L instruction = LD(dest: self.D, src: self.L) instructionLength = 1 case 0x56: // LD D, (HL) instruction = LD(dest: self.D, src: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x57: // LD D, A instruction = LD(dest: self.D, src: self.A) instructionLength = 1 case 0x58: // LD E, B instruction = LD(dest: self.E, src: self.B) instructionLength = 1 case 0x59: // LD E, C instruction = LD(dest: self.E, src: self.C) instructionLength = 1 case 0x5A: // LD E, D instruction = LD(dest: self.E, src: self.D) instructionLength = 1 case 0x5B: // LD E, E instruction = LD(dest: self.E, src: self.E) instructionLength = 1 case 0x5C: // LD E, H instruction = LD(dest: self.E, src: self.H) instructionLength = 1 case 0x5D: // LD E, L instruction = LD(dest: self.E, src: self.L) instructionLength = 1 case 0x5E: // LD E, (HL) instruction = LD(dest: self.E, src: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x5F: // LD E, A instruction = LD(dest: self.E, src: self.A) instructionLength = 1 case 0x60: // LD H, B instruction = LD(dest: self.H, src: self.B) instructionLength = 1 case 0x61: // LD H, C instruction = LD(dest: self.H, src: self.C) instructionLength = 1 case 0x62: // LD H, D instruction = LD(dest: self.H, src: self.D) instructionLength = 1 case 0x63: // LD H, E instruction = LD(dest: self.H, src: self.E) instructionLength = 1 case 0x64: // LD H, H instruction = LD(dest: self.H, src: self.H) instructionLength = 1 case 0x65: // LD H, L instruction = LD(dest: self.H, src: self.L) instructionLength = 1 case 0x66: // LD H, (HL) instruction = LD(dest: self.H, src: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0x67: // LD H, A instruction = LD(dest: self.H, src: self.A) instructionLength = 1 case 0x68: // LD L, B instruction = LD(dest: self.L, src: self.B) instructionLength = 1 case 0x69: // LD L, C instruction = LD(dest: self.L, src: self.C) instructionLength = 1 case 0x6A: // LD L, D instruction = LD(dest: self.L, src: self.D) instructionLength = 1 case 0x6B: // LD L, E instruction = LD(dest: self.L, src: self.E) instructionLength = 1 case 0x6C: // LD L, H instruction = LD(dest: self.L, src: self.H) instructionLength = 1 case 0x6D: // LD L, L instruction = LD(dest: self.L, src: self.L) instructionLength = 1 case 0x6E: // LD L, (HL) instruction = LD(dest: self.L, src: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x6F: // LD L, A instruction = LD(dest: self.L, src: self.A) instructionLength = 1 case 0x70: // LD (HL), B instruction = LD(dest: self.HL.asPointerOn(self.bus), src: self.B) instructionLength = 1 case 0x71: // LD (HL), C instruction = LD(dest: self.HL.asPointerOn(self.bus), src: self.C) instructionLength = 1 case 0x72: // LD (HL), D instruction = LD(dest: self.HL.asPointerOn(self.bus), src: self.D) instructionLength = 1 case 0x73: // LD (HL), E instruction = LD(dest: self.HL.asPointerOn(self.bus), src: self.E) instructionLength = 1 case 0x74: // LD (HL), H instruction = LD(dest: self.HL.asPointerOn(self.bus), src: self.H) instructionLength = 1 case 0x75: // LD (HL), L instruction = LD(dest: self.HL.asPointerOn(self.bus), src: self.L) instructionLength = 1 case 0x77: // LD (HL), A instruction = LD(dest: self.HL.asPointerOn(bus), src: self.A) instructionLength = 1 case 0x78: // LD A, B instruction = LD(dest: self.A, src: self.B) instructionLength = 1 case 0x79: // LD A, C instruction = LD(dest: self.A, src: self.C) instructionLength = 1 case 0x7A: // LD A, D instruction = LD(dest: self.A, src: self.D) instructionLength = 1 case 0x7B: // LD A, E instruction = LD(dest: self.A, src: self.E) instructionLength = 1 case 0x7C: // LD A, H instruction = LD(dest: self.A, src: self.H) instructionLength = 1 case 0x7D: // LD A, L instruction = LD(dest: self.A, src: self.L) instructionLength = 1 case 0x7E: // LD A, (HL) instruction = LD(dest: self.A, src: self.HL.asPointerOn(bus)) instructionLength = 1 case 0x7F: // LD A, A instruction = LD(dest: self.A, src: self.A) instructionLength = 1 case 0x80: // ADD A, B instruction = ADD8(op1: self.A, op2: self.B) instructionLength = 1 case 0x81: // ADD A, C instruction = ADD8(op1: self.A, op2: self.C) instructionLength = 1 case 0x82: // ADD A, D instruction = ADD8(op1: self.A, op2: self.D) instructionLength = 1 case 0x83: // ADD A, E instruction = ADD8(op1: self.A, op2: self.E) instructionLength = 1 case 0x84: // ADD A, H instruction = ADD8(op1: self.A, op2: self.H) instructionLength = 1 case 0x85: // ADD A, L instruction = ADD8(op1: self.A, op2: self.L) instructionLength = 1 case 0x86: // ADD A, (HL) instruction = ADD8(op1: self.A, op2: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0x87: // ADD A, A instruction = ADD8(op1: self.A, op2: self.A) instructionLength = 1 case 0x88: // ADC A, B instruction = ADC8(op1: self.A, op2: self.B) instructionLength = 1 case 0x89: // ADC A, C instruction = ADC8(op1: self.A, op2: self.C) instructionLength = 1 case 0x8A: // ADC A, D instruction = ADC8(op1: self.A, op2: self.D) instructionLength = 1 case 0x8B: // ADC A, E instruction = ADC8(op1: self.A, op2: self.E) instructionLength = 1 case 0x8C: // ADC A, H instruction = ADC8(op1: self.A, op2: self.H) instructionLength = 1 case 0x8D: // ADC A, L instruction = ADC8(op1: self.A, op2: self.L) instructionLength = 1 case 0x8E: // ADC A, (HL) instruction = ADC8(op1: self.A, op2: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0x8F: // ADC A, A instruction = ADC8(op1: self.A, op2: self.A) instructionLength = 1 case 0x90: // SUB B instruction = SUB(op: self.B) instructionLength = 1 case 0x91: // SUB C instruction = SUB(op: self.C) instructionLength = 1 case 0x92: // SUB D instruction = SUB(op: self.D) instructionLength = 1 case 0x93: // SUB E instruction = SUB(op: self.E) instructionLength = 1 case 0x94: // SUB H instruction = SUB(op: self.H) instructionLength = 1 case 0x95: // SUB L instruction = SUB(op: self.L) instructionLength = 1 case 0x96: // SUB (HL) instruction = SUB(op: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0x97: // SUB A instruction = SUB(op: self.A) instructionLength = 1 case 0x98: // SBC B instruction = SBC(op: self.B) instructionLength = 1 case 0x99: // SBC C instruction = SBC(op: self.C) instructionLength = 1 case 0x9A: // SBC D instruction = SBC(op: self.D) instructionLength = 1 case 0x9B: // SBC E instruction = SBC(op: self.E) instructionLength = 1 case 0x9C: // SBC H instruction = SBC(op: self.H) instructionLength = 1 case 0x9D: // SBC L instruction = SBC(op: self.L) instructionLength = 1 case 0x9E: // SBC (HL) instruction = SBC(op: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0x9F: // SBC A instruction = SBC(op: self.A) instructionLength = 1 case 0xA0: // AND B instruction = AND(op: self.B) instructionLength = 1 case 0xA1: // AND C instruction = AND(op: self.C) instructionLength = 1 case 0xA2: // AND D instruction = AND(op: self.D) instructionLength = 1 case 0xA3: // AND E instruction = AND(op: self.E) instructionLength = 1 case 0xA4: // AND H instruction = AND(op: self.H) instructionLength = 1 case 0xA5: // AND L instruction = AND(op: self.L) instructionLength = 1 case 0xA6: // AND (HL) instruction = AND(op: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0xA7: // AND A instruction = AND(op: self.A) instructionLength = 1 case 0xA8: // XOR B instruction = XOR(op: self.B) instructionLength = 1 case 0xA9: // XOR C instruction = XOR(op: self.C) instructionLength = 1 case 0xAA: // XOR D instruction = XOR(op: self.D) instructionLength = 1 case 0xAB: // XOR E instruction = XOR(op: self.E) instructionLength = 1 case 0xAC: // XOR H instruction = XOR(op: self.H) instructionLength = 1 case 0xAD: // XOR L instruction = XOR(op: self.L) instructionLength = 1 case 0xAE: // XOR (HL) instruction = XOR(op: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0xAF: // XOR A instruction = XOR(op: self.A) instructionLength = 1 case 0xB0: // OR B instruction = OR(op: self.B) instructionLength = 1 case 0xB1: // OR C instruction = OR(op: self.C) instructionLength = 1 case 0xB2: // OR D instruction = OR(op: self.D) instructionLength = 1 case 0xB3: // OR E instruction = OR(op: self.E) instructionLength = 1 case 0xB4: // OR H instruction = OR(op: self.H) instructionLength = 1 case 0xB5: // OR L instruction = OR(op: self.L) instructionLength = 1 case 0xB6: // OR (HL) instruction = OR(op: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0xB7: // OR A instruction = OR(op: self.A) instructionLength = 1 case 0xB8: // CP B instruction = CP(op: self.B) instructionLength = 1 case 0xB9: // CP C instruction = CP(op: self.C) instructionLength = 1 case 0xBA: // CP D instruction = CP(op: self.D) instructionLength = 1 case 0xBB: // CP E instruction = CP(op: self.E) instructionLength = 1 case 0xBC: // CP H instruction = CP(op: self.H) instructionLength = 1 case 0xBD: // CP L instruction = CP(op: self.L) instructionLength = 1 case 0xBE: // CP (HL) instruction = CP(op: self.HL.asPointerOn(self.bus)) instructionLength = 1 case 0xBF: // CP A instruction = CP(op: self.A) instructionLength = 1 case 0xC0: // RET nz instruction = RET(condition: Condition(flag: self.ZF, target: false)) instructionLength = 1 case 0xC1: // POP BC instruction = POP(operand: self.BC) instructionLength = 1 case 0xC2: // JP nz, nn let addr = bus.read16(PC.read()+1) instruction = JP(condition: Condition(flag: self.ZF, target: false), dest: Immediate16(val: addr)) instructionLength = 3 case 0xC3: // JP nn let addr = bus.read16(PC.read()+1) instruction = JP(condition: nil, dest: Immediate16(val: addr)) instructionLength = 3 case 0xC4: // CALL NZ, nn let addr = bus.read16(PC.read()+1) instruction = CALL(condition: Condition(flag: self.ZF, target: false), dest: Immediate16(val: addr)) instructionLength = 3 case 0xC5: // PUSH BC instruction = PUSH(operand: self.BC) instructionLength = 1 case 0xC6: // ADD A, n let val = bus.read(PC.read()+1) instruction = ADD8(op1: self.A, op2: Immediate8(val: val)) instructionLength = 2 case 0xC8: // RET z instruction = RET(condition: Condition(flag: self.ZF, target: true)) instructionLength = 1 case 0xC9: // RET instruction = RET(condition: nil) instructionLength = 1 case 0xCA: // JP z, nn let addr = bus.read16(PC.read()+1) instruction = JP(condition: Condition(flag: self.ZF, target: true), dest: Immediate16(val: addr)) instructionLength = 3 case 0xCC: // CALL Z, nn let addr = bus.read16(PC.read()+1) instruction = CALL(condition: Condition(flag: self.ZF, target: true), dest: Immediate16(val: addr)) instructionLength = 3 case 0xCD: // CALL nn let addr = bus.read16(PC.read()+1) instruction = CALL(condition: nil, dest: Immediate16(val: addr)) instructionLength = 3 case 0xCE: // ADC A, n let val = bus.read(PC.read()+1) instruction = ADC8(op1: self.A, op2: Immediate8(val: val)) instructionLength = 2 case 0xD0: // RET nc instruction = RET(condition: Condition(flag: self.CF, target: false)) instructionLength = 1 case 0xD1: // POP DE instruction = POP(operand: self.DE) instructionLength = 1 case 0xD2: // JP nc, nn let addr = bus.read16(PC.read()+1) instruction = JP(condition: Condition(flag: self.CF, target: false), dest: Immediate16(val: addr)) instructionLength = 3 case 0xD4: // CALL NC, nn let addr = bus.read16(PC.read()+1) instruction = CALL(condition: Condition(flag: self.CF, target: false), dest: Immediate16(val: addr)) instructionLength = 3 case 0xD5: // PUSH DE instruction = PUSH(operand: self.DE) instructionLength = 1 case 0xD6: // SUB n let val = bus.read(PC.read()+1) instruction = SUB(op: Immediate8(val: val)) instructionLength = 2 case 0xD8: // RET c instruction = RET(condition: Condition(flag: self.CF, target: true)) instructionLength = 1 case 0xDA: // JP c, nn let addr = bus.read16(PC.read()+1) instruction = JP(condition: Condition(flag: self.CF, target: true), dest: Immediate16(val: addr)) instructionLength = 3 case 0xDC: // CALL C, nn let addr = bus.read16(PC.read()+1) instruction = CALL(condition: Condition(flag: self.CF, target: true), dest: Immediate16(val: addr)) instructionLength = 3 //@todo: Figure out how to create patch RST vectors as described in GBS spec /* case 0xDF: // RST 0x18 instruction = RST(restartAddress: 0x18) instructionLength = 1 */ case 0xE1: // POP HL instruction = POP(operand: self.HL) instructionLength = 1 case 0xE5: // PUSH HL instruction = PUSH(operand: self.HL) instructionLength = 1 case 0xE6: // AND n let val = bus.read(PC.read()+1) instruction = AND(op: Immediate8(val: val)) instructionLength = 2 case 0xE9: // JP (HL) instruction = JP(condition: nil, dest: self.HL) instructionLength = 1 case 0xEF: // XOR n let val = bus.read(PC.read()+1) instruction = XOR(op: Immediate8(val: val)) instructionLength = 2 case 0xF1: // POP AF instruction = POP(operand: self.AF) instructionLength = 1 case 0xF3: // DI instruction = DI() instructionLength = 1 case 0xF5: // PUSH AF instruction = PUSH(operand: self.AF) instructionLength = 1 case 0xF6: // OR n let val = bus.read(PC.read()+1) instruction = OR(op: Immediate8(val: val)) instructionLength = 2 case 0xFB: // EI instruction = EI() instructionLength = 1 case 0xFE: // CP n let subtrahend = bus.read(PC.read()+1) instruction = CP(op: Immediate8(val: subtrahend)) instructionLength = 2 case 0xCB: // bit instructions let secondByte = bus.read(PC.read()+1) switch secondByte { case 0x00: // RLC B instruction = RLC(op: self.B) instructionLength = 2 case 0x01: // RLC C instruction = RLC(op: self.C) instructionLength = 2 case 0x02: // RLC D instruction = RLC(op: self.D) instructionLength = 2 case 0x03: // RLC E instruction = RLC(op: self.E) instructionLength = 2 case 0x04: // RLC H instruction = RLC(op: self.H) instructionLength = 2 case 0x05: // RLC L instruction = RLC(op: self.L) instructionLength = 2 case 0x06: // RLC (HL) instruction = RLC(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x07: // RLC A instruction = RLC(op: self.A) instructionLength = 2 case 0x08: // RRC B instruction = RRC(op: self.B) instructionLength = 2 case 0x09: // RRC C instruction = RRC(op: self.C) instructionLength = 2 case 0x0A: // RRC D instruction = RRC(op: self.D) instructionLength = 2 case 0x0B: // RRC E instruction = RRC(op: self.E) instructionLength = 2 case 0x0C: // RRC H instruction = RRC(op: self.H) instructionLength = 2 case 0x0D: // RRC L instruction = RRC(op: self.L) instructionLength = 2 case 0x0E: // RRC (HL) instruction = RRC(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x0F: // RRC A instruction = RRC(op: self.A) instructionLength = 2 case 0x10: // RL B instruction = RL(op: self.B) instructionLength = 2 case 0x11: // RL C instruction = RL(op: self.C) instructionLength = 2 case 0x12: // RL D instruction = RL(op: self.D) instructionLength = 2 case 0x13: // RL E instruction = RL(op: self.E) instructionLength = 2 case 0x14: // RL H instruction = RL(op: self.H) instructionLength = 2 case 0x15: // RL L instruction = RL(op: self.L) instructionLength = 2 case 0x16: // RL (HL) instruction = RL(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x17: // RL A instruction = RL(op: self.A) instructionLength = 2 case 0x18: // RR B instruction = RR(op: self.B) instructionLength = 2 case 0x19: // RR C instruction = RR(op: self.C) instructionLength = 2 case 0x1A: // RR D instruction = RR(op: self.D) instructionLength = 2 case 0x1B: // RR E instruction = RR(op: self.E) instructionLength = 2 case 0x1C: // RR H instruction = RR(op: self.H) instructionLength = 2 case 0x1D: // RR L instruction = RR(op: self.L) instructionLength = 2 case 0x1E: // RR (HL) instruction = RR(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x1F: // RR A instruction = RR(op: self.A) instructionLength = 2 case 0x20: // SLA B instruction = SLA(op: self.B) instructionLength = 2 case 0x21: // SLA C instruction = SLA(op: self.C) instructionLength = 2 case 0x22: // SLA D instruction = SLA(op: self.D) instructionLength = 2 case 0x23: // SLA E instruction = SLA(op: self.E) instructionLength = 2 case 0x24: // SLA H instruction = SLA(op: self.H) instructionLength = 2 case 0x25: // SLA L instruction = SLA(op: self.L) instructionLength = 2 case 0x26: // SLA (HL) instruction = SLA(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x27: // SLA A instruction = SLA(op: self.A) instructionLength = 2 case 0x28: // SRA B instruction = SRA(op: self.B) instructionLength = 2 case 0x29: // SRA C instruction = SRA(op: self.C) instructionLength = 2 case 0x2A: // SRA D instruction = SRA(op: self.D) instructionLength = 2 case 0x2B: // SRA E instruction = SRA(op: self.E) instructionLength = 2 case 0x2C: // SRA H instruction = SRA(op: self.H) instructionLength = 2 case 0x2D: // SRA L instruction = SRA(op: self.L) instructionLength = 2 case 0x2E: // SRA (HL) instruction = SRA(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x2F: // SRA A instruction = SRA(op: self.A) instructionLength = 2 case 0x38: // SRL B instruction = SRL(op: self.B) instructionLength = 2 case 0x39: // SRL C instruction = SRL(op: self.C) instructionLength = 2 case 0x3A: // SRL D instruction = SRL(op: self.D) instructionLength = 2 case 0x3B: // SRL E instruction = SRL(op: self.E) instructionLength = 2 case 0x3C: // SRL H instruction = SRL(op: self.H) instructionLength = 2 case 0x3D: // SRL L instruction = SRL(op: self.L) instructionLength = 2 case 0x3E: // SRL (HL) instruction = SRL(op: self.HL.asPointerOn(self.bus)) instructionLength = 2 case 0x3F: // SRL A instruction = SRL(op: self.A) instructionLength = 2 case 0x40: // BIT 0, B instruction = BIT(op: self.B, bit: 0) instructionLength = 2 case 0x41: // BIT 0, C instruction = BIT(op: self.C, bit: 0) instructionLength = 2 case 0x42: // BIT 0, D instruction = BIT(op: self.D, bit: 0) instructionLength = 2 case 0x43: // BIT 0, E instruction = BIT(op: self.E, bit: 0) instructionLength = 2 case 0x44: // BIT 0, H instruction = BIT(op: self.H, bit: 0) instructionLength = 2 case 0x45: // BIT 0, L instruction = BIT(op: self.L, bit: 0) instructionLength = 2 case 0x46: // BIT 0, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 0) instructionLength = 2 case 0x47: // BIT 0, A instruction = BIT(op: self.A, bit: 0) instructionLength = 2 case 0x48: // BIT 1, B instruction = BIT(op: self.B, bit: 1) instructionLength = 2 case 0x49: // BIT 1, C instruction = BIT(op: self.C, bit: 1) instructionLength = 2 case 0x4A: // BIT 1, D instruction = BIT(op: self.D, bit: 1) instructionLength = 2 case 0x4B: // BIT 1, E instruction = BIT(op: self.E, bit: 1) instructionLength = 2 case 0x4C: // BIT 1, H instruction = BIT(op: self.H, bit: 1) instructionLength = 2 case 0x4D: // BIT 1, L instruction = BIT(op: self.L, bit: 1) instructionLength = 2 case 0x4E: // BIT 1, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 1) instructionLength = 2 case 0x4F: // BIT 1, A instruction = BIT(op: self.A, bit: 1) instructionLength = 2 case 0x50: // BIT 2, B instruction = BIT(op: self.B, bit: 2) instructionLength = 2 case 0x51: // BIT 2, C instruction = BIT(op: self.C, bit: 2) instructionLength = 2 case 0x52: // BIT 2, D instruction = BIT(op: self.D, bit: 2) instructionLength = 2 case 0x53: // BIT 2, E instruction = BIT(op: self.E, bit: 2) instructionLength = 2 case 0x54: // BIT 2, H instruction = BIT(op: self.H, bit: 2) instructionLength = 2 case 0x55: // BIT 2, L instruction = BIT(op: self.L, bit: 2) instructionLength = 2 case 0x56: // BIT 2, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 2) instructionLength = 2 case 0x57: // BIT 2, A instruction = BIT(op: self.A, bit: 2) instructionLength = 2 case 0x58: // BIT 3, B instruction = BIT(op: self.B, bit: 3) instructionLength = 2 case 0x59: // BIT 3, C instruction = BIT(op: self.C, bit: 3) instructionLength = 2 case 0x5A: // BIT 3, D instruction = BIT(op: self.D, bit: 3) instructionLength = 2 case 0x5B: // BIT 3, E instruction = BIT(op: self.E, bit: 3) instructionLength = 2 case 0x5C: // BIT 3, H instruction = BIT(op: self.H, bit: 3) instructionLength = 2 case 0x5D: // BIT 3, L instruction = BIT(op: self.L, bit: 3) instructionLength = 2 case 0x5E: // BIT 3, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 3) instructionLength = 2 case 0x5F: // BIT 3, A instruction = BIT(op: self.A, bit: 3) instructionLength = 2 case 0x60: // BIT 4, B instruction = BIT(op: self.B, bit: 4) instructionLength = 2 case 0x61: // BIT 4, C instruction = BIT(op: self.C, bit: 4) instructionLength = 2 case 0x62: // BIT 4, D instruction = BIT(op: self.D, bit: 4) instructionLength = 2 case 0x63: // BIT 4, E instruction = BIT(op: self.E, bit: 4) instructionLength = 2 case 0x64: // BIT 4, H instruction = BIT(op: self.H, bit: 4) instructionLength = 2 case 0x65: // BIT 4, L instruction = BIT(op: self.L, bit: 4) instructionLength = 2 case 0x66: // BIT 4, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 4) instructionLength = 2 case 0x67: // BIT 4, A instruction = BIT(op: self.A, bit: 4) instructionLength = 2 case 0x68: // BIT 5, B instruction = BIT(op: self.B, bit: 5) instructionLength = 2 case 0x69: // BIT 5, C instruction = BIT(op: self.C, bit: 5) instructionLength = 2 case 0x6A: // BIT 5, D instruction = BIT(op: self.D, bit: 5) instructionLength = 2 case 0x6B: // BIT 5, E instruction = BIT(op: self.E, bit: 5) instructionLength = 2 case 0x6C: // BIT 5, H instruction = BIT(op: self.H, bit: 5) instructionLength = 2 case 0x6D: // BIT 5, L instruction = BIT(op: self.L, bit: 5) instructionLength = 2 case 0x6E: // BIT 5, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 5) instructionLength = 2 case 0x6F: // BIT 5, A instruction = BIT(op: self.A, bit: 5) instructionLength = 2 case 0x70: // BIT 6, B instruction = BIT(op: self.B, bit: 6) instructionLength = 2 case 0x71: // BIT 6, C instruction = BIT(op: self.C, bit: 6) instructionLength = 2 case 0x72: // BIT 6, D instruction = BIT(op: self.D, bit: 6) instructionLength = 2 case 0x73: // BIT 6, E instruction = BIT(op: self.E, bit: 6) instructionLength = 2 case 0x74: // BIT 6, H instruction = BIT(op: self.H, bit: 6) instructionLength = 2 case 0x75: // BIT 6, L instruction = BIT(op: self.L, bit: 6) instructionLength = 2 case 0x76: // BIT 6, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 6) instructionLength = 2 case 0x77: // BIT 6, A instruction = BIT(op: self.A, bit: 6) instructionLength = 2 case 0x78: // BIT 7, B instruction = BIT(op: self.B, bit: 7) instructionLength = 2 case 0x79: // BIT 7, C instruction = BIT(op: self.C, bit: 7) instructionLength = 2 case 0x7A: // BIT 7, D instruction = BIT(op: self.D, bit: 7) instructionLength = 2 case 0x7B: // BIT 7, E instruction = BIT(op: self.E, bit: 7) instructionLength = 2 case 0x7C: // BIT 7, H instruction = BIT(op: self.H, bit: 7) instructionLength = 2 case 0x7D: // BIT 7, L instruction = BIT(op: self.L, bit: 7) instructionLength = 2 case 0x7E: // BIT 7, (HL) instruction = BIT(op: self.HL.asPointerOn(self.bus), bit: 7) instructionLength = 2 case 0x7F: // BIT 7, A instruction = BIT(op: self.A, bit: 7) instructionLength = 2 case 0x80: // RES 0, B instruction = RES(op: self.B, bit: 0) instructionLength = 2 case 0x81: // RES 0, C instruction = RES(op: self.C, bit: 0) instructionLength = 2 case 0x82: // RES 0, D instruction = RES(op: self.D, bit: 0) instructionLength = 2 case 0x83: // RES 0, E instruction = RES(op: self.E, bit: 0) instructionLength = 2 case 0x84: // RES 0, H instruction = RES(op: self.H, bit: 0) instructionLength = 2 case 0x85: // RES 0, L instruction = RES(op: self.L, bit: 0) instructionLength = 2 case 0x86: // RES 0, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 0) instructionLength = 2 case 0x87: // RES 0, A instruction = RES(op: self.A, bit: 0) instructionLength = 2 case 0x88: // RES 1, B instruction = RES(op: self.B, bit: 1) instructionLength = 2 case 0x89: // RES 1, C instruction = RES(op: self.C, bit: 1) instructionLength = 2 case 0x8A: // RES 1, D instruction = RES(op: self.D, bit: 1) instructionLength = 2 case 0x8B: // RES 1, E instruction = RES(op: self.E, bit: 1) instructionLength = 2 case 0x8C: // RES 1, H instruction = RES(op: self.H, bit: 1) instructionLength = 2 case 0x8D: // RES 1, L instruction = RES(op: self.L, bit: 1) instructionLength = 2 case 0x8E: // RES 1, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 1) instructionLength = 2 case 0x8F: // RES 1, A instruction = RES(op: self.A, bit: 1) instructionLength = 2 case 0x90: // RES 2, B instruction = RES(op: self.B, bit: 2) instructionLength = 2 case 0x91: // RES 2, C instruction = RES(op: self.C, bit: 2) instructionLength = 2 case 0x92: // RES 2, D instruction = RES(op: self.D, bit: 2) instructionLength = 2 case 0x93: // RES 2, E instruction = RES(op: self.E, bit: 2) instructionLength = 2 case 0x94: // RES 2, H instruction = RES(op: self.H, bit: 2) instructionLength = 2 case 0x95: // RES 2, L instruction = RES(op: self.L, bit: 2) instructionLength = 2 case 0x96: // RES 2, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 2) instructionLength = 2 case 0x97: // RES 2, A instruction = RES(op: self.A, bit: 2) instructionLength = 2 case 0x98: // RES 3, B instruction = RES(op: self.B, bit: 3) instructionLength = 2 case 0x99: // RES 3, C instruction = RES(op: self.C, bit: 3) instructionLength = 2 case 0x9A: // RES 3, D instruction = RES(op: self.D, bit: 3) instructionLength = 2 case 0x9B: // RES 3, E instruction = RES(op: self.E, bit: 3) instructionLength = 2 case 0x9C: // RES 3, H instruction = RES(op: self.H, bit: 3) instructionLength = 2 case 0x9D: // RES 3, L instruction = RES(op: self.L, bit: 3) instructionLength = 2 case 0x9E: // RES 3, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 3) instructionLength = 2 case 0x9F: // RES 3, A instruction = RES(op: self.A, bit: 3) instructionLength = 2 case 0xA0: // RES 4, B instruction = RES(op: self.B, bit: 4) instructionLength = 2 case 0xA1: // RES 4, C instruction = RES(op: self.C, bit: 4) instructionLength = 2 case 0xA2: // RES 4, D instruction = RES(op: self.D, bit: 4) instructionLength = 2 case 0xA3: // RES 4, E instruction = RES(op: self.E, bit: 4) instructionLength = 2 case 0xA4: // RES 4, H instruction = RES(op: self.H, bit: 4) instructionLength = 2 case 0xA5: // RES 4, L instruction = RES(op: self.L, bit: 4) instructionLength = 2 case 0xA6: // RES 4, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 4) instructionLength = 2 case 0xA7: // RES 4, A instruction = RES(op: self.A, bit: 4) instructionLength = 2 case 0xA8: // RES 5, B instruction = RES(op: self.B, bit: 5) instructionLength = 2 case 0xA9: // RES 5, C instruction = RES(op: self.C, bit: 5) instructionLength = 2 case 0xAA: // RES 5, D instruction = RES(op: self.D, bit: 5) instructionLength = 2 case 0xAB: // RES 5, E instruction = RES(op: self.E, bit: 5) instructionLength = 2 case 0xAC: // RES 5, H instruction = RES(op: self.H, bit: 5) instructionLength = 2 case 0xAD: // RES 5, L instruction = RES(op: self.L, bit: 5) instructionLength = 2 case 0xAE: // RES 5, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 5) instructionLength = 2 case 0xAF: // RES 5, A instruction = RES(op: self.A, bit: 5) instructionLength = 2 case 0xB0: // RES 6, B instruction = RES(op: self.B, bit: 6) instructionLength = 2 case 0xB1: // RES 6, C instruction = RES(op: self.C, bit: 6) instructionLength = 2 case 0xB2: // RES 6, D instruction = RES(op: self.D, bit: 6) instructionLength = 2 case 0xB3: // RES 6, E instruction = RES(op: self.E, bit: 6) instructionLength = 2 case 0xB4: // RES 6, H instruction = RES(op: self.H, bit: 6) instructionLength = 2 case 0xB5: // RES 6, L instruction = RES(op: self.L, bit: 6) instructionLength = 2 case 0xB6: // RES 6, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 6) instructionLength = 2 case 0xB7: // RES 6, A instruction = RES(op: self.A, bit: 6) instructionLength = 2 case 0xB8: // RES 7, B instruction = RES(op: self.B, bit: 7) instructionLength = 2 case 0xB9: // RES 7, C instruction = RES(op: self.C, bit: 7) instructionLength = 2 case 0xBA: // RES 7, D instruction = RES(op: self.D, bit: 7) instructionLength = 2 case 0xBB: // RES 7, E instruction = RES(op: self.E, bit: 7) instructionLength = 2 case 0xBC: // RES 7, H instruction = RES(op: self.H, bit: 7) instructionLength = 2 case 0xBD: // RES 7, L instruction = RES(op: self.L, bit: 7) instructionLength = 2 case 0xBE: // RES 7, (HL) instruction = RES(op: self.HL.asPointerOn(self.bus), bit: 7) instructionLength = 2 case 0xBF: // RES 7, A instruction = RES(op: self.A, bit: 7) instructionLength = 2 case 0xC0: // SET 0, B instruction = SET(op: self.B, bit: 0) instructionLength = 2 case 0xC1: // SET 0, C instruction = SET(op: self.C, bit: 0) instructionLength = 2 case 0xC2: // SET 0, D instruction = SET(op: self.D, bit: 0) instructionLength = 2 case 0xC3: // SET 0, E instruction = SET(op: self.E, bit: 0) instructionLength = 2 case 0xC4: // SET 0, H instruction = SET(op: self.H, bit: 0) instructionLength = 2 case 0xC5: // SET 0, L instruction = SET(op: self.L, bit: 0) instructionLength = 2 case 0xC6: // SET 0, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 0) instructionLength = 2 case 0xC7: // SET 0, A instruction = SET(op: self.A, bit: 0) instructionLength = 2 case 0xC8: // SET 1, B instruction = SET(op: self.B, bit: 1) instructionLength = 2 case 0xC9: // SET 1, C instruction = SET(op: self.C, bit: 1) instructionLength = 2 case 0xCA: // SET 1, D instruction = SET(op: self.D, bit: 1) instructionLength = 2 case 0xCB: // SET 1, E instruction = SET(op: self.E, bit: 1) instructionLength = 2 case 0xCC: // SET 1, H instruction = SET(op: self.H, bit: 1) instructionLength = 2 case 0xCD: // SET 1, L instruction = SET(op: self.L, bit: 1) instructionLength = 2 case 0xCE: // SET 1, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 1) instructionLength = 2 case 0xCF: // SET 1, A instruction = SET(op: self.A, bit: 1) instructionLength = 2 case 0xD0: // SET 2, B instruction = SET(op: self.B, bit: 2) instructionLength = 2 case 0xD1: // SET 2, C instruction = SET(op: self.C, bit: 2) instructionLength = 2 case 0xD2: // SET 2, D instruction = SET(op: self.D, bit: 2) instructionLength = 2 case 0xD3: // SET 2, E instruction = SET(op: self.E, bit: 2) instructionLength = 2 case 0xD4: // SET 2, H instruction = SET(op: self.H, bit: 2) instructionLength = 2 case 0xD5: // SET 2, L instruction = SET(op: self.L, bit: 2) instructionLength = 2 case 0xD6: // SET 2, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 2) instructionLength = 2 case 0xD7: // SET 2, A instruction = SET(op: self.A, bit: 2) instructionLength = 2 case 0xD8: // SET 3, B instruction = SET(op: self.B, bit: 3) instructionLength = 2 case 0xD9: // SET 3, C instruction = SET(op: self.C, bit: 3) instructionLength = 2 case 0xDA: // SET 3, D instruction = SET(op: self.D, bit: 3) instructionLength = 2 case 0xDB: // SET 3, E instruction = SET(op: self.E, bit: 3) instructionLength = 2 case 0xDC: // SET 3, H instruction = SET(op: self.H, bit: 3) instructionLength = 2 case 0xDD: // SET 3, L instruction = SET(op: self.L, bit: 3) instructionLength = 2 case 0xDE: // SET 3, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 3) instructionLength = 2 case 0xDF: // SET 3, A instruction = SET(op: self.A, bit: 3) instructionLength = 2 case 0xE0: // SET 4, B instruction = SET(op: self.B, bit: 4) instructionLength = 2 case 0xE1: // SET 4, C instruction = SET(op: self.C, bit: 4) instructionLength = 2 case 0xE2: // SET 4, D instruction = SET(op: self.D, bit: 4) instructionLength = 2 case 0xE3: // SET 4, E instruction = SET(op: self.E, bit: 4) instructionLength = 2 case 0xE4: // SET 4, H instruction = SET(op: self.H, bit: 4) instructionLength = 2 case 0xE5: // SET 4, L instruction = SET(op: self.L, bit: 4) instructionLength = 2 case 0xE6: // SET 4, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 4) instructionLength = 2 case 0xE7: // SET 4, A instruction = SET(op: self.A, bit: 4) instructionLength = 2 case 0xE8: // SET 5, B instruction = SET(op: self.B, bit: 5) instructionLength = 2 case 0xE9: // SET 5, C instruction = SET(op: self.C, bit: 5) instructionLength = 2 case 0xEA: // SET 5, D instruction = SET(op: self.D, bit: 5) instructionLength = 2 case 0xEB: // SET 5, E instruction = SET(op: self.E, bit: 5) instructionLength = 2 case 0xEC: // SET 5, H instruction = SET(op: self.H, bit: 5) instructionLength = 2 case 0xED: // SET 5, L instruction = SET(op: self.L, bit: 5) instructionLength = 2 case 0xEE: // SET 5, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 5) instructionLength = 2 case 0xEF: // SET 5, A instruction = SET(op: self.A, bit: 5) instructionLength = 2 case 0xF0: // SET 6, B instruction = SET(op: self.B, bit: 6) instructionLength = 2 case 0xF1: // SET 6, C instruction = SET(op: self.C, bit: 6) instructionLength = 2 case 0xF2: // SET 6, D instruction = SET(op: self.D, bit: 6) instructionLength = 2 case 0xF3: // SET 6, E instruction = SET(op: self.E, bit: 6) instructionLength = 2 case 0xF4: // SET 6, H instruction = SET(op: self.H, bit: 6) instructionLength = 2 case 0xF5: // SET 6, L instruction = SET(op: self.L, bit: 6) instructionLength = 2 case 0xF6: // SET 6, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 6) instructionLength = 2 case 0xF7: // SET 6, A instruction = SET(op: self.A, bit: 6) instructionLength = 2 case 0xF8: // SET 7, B instruction = SET(op: self.B, bit: 7) instructionLength = 2 case 0xF9: // SET 7, C instruction = SET(op: self.C, bit: 7) instructionLength = 2 case 0xFA: // SET 7, D instruction = SET(op: self.D, bit: 7) instructionLength = 2 case 0xFB: // SET 7, E instruction = SET(op: self.E, bit: 7) instructionLength = 2 case 0xFC: // SET 7, H instruction = SET(op: self.H, bit: 7) instructionLength = 2 case 0xFD: // SET 7, L instruction = SET(op: self.L, bit: 7) instructionLength = 2 case 0xFE: // SET 7, (HL) instruction = SET(op: self.HL.asPointerOn(self.bus), bit: 7) instructionLength = 2 case 0xFF: // SET 7, A instruction = SET(op: self.A, bit: 7) instructionLength = 2 default: break } default: break } if let instruction = instruction { // print("C \(PC.read().hexString): ", terminator: "") // for i in 0..<instructionLength { // print("\(bus.read(PC.read()+i).hexString) ", terminator: "") // } // print("\n\t\(instruction)\n") //@todo make PC-incrementing common self.PC.write(self.PC.read() + instructionLength) } return instruction } }
mit
94dbf0b670ff95c28b98c563a8fbbac0
29.97555
116
0.400505
4.640093
false
false
false
false
Piwigo/Piwigo-Mobile
piwigoKit/Network/PwgSession.swift
1
14887
// // PwgSession.swift // piwigoKit // // Created by Eddy Lelièvre-Berna on 08/06/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Foundation public class PwgSession: NSObject { // Singleton public static var shared = PwgSession() // Create single instance public lazy var dataSession: URLSession = { let config = URLSessionConfiguration.default // Additional headers that are added to all tasks config.httpAdditionalHeaders = ["Content-Type" : "application/x-www-form-urlencoded", "Accept" : "application/json", "Accept-Charset" : "utf-8"] /// Network service type for data that the user is actively waiting for. config.networkServiceType = .responsiveData /// Indicates that the request is allowed to use the built-in cellular radios to satisfy the request. config.allowsCellularAccess = true /// How long a task should wait for additional data to arrive before giving up (30 seconds) config.timeoutIntervalForRequest = 30 /// How long a task should be allowed to be retried or transferred (10 minutes). config.timeoutIntervalForResource = 600 /// Determines the maximum number of simultaneous connections made to the host by tasks (4 by default) config.httpMaximumConnectionsPerHost = 4 /// Requests should contain cookies from the cookie store. config.httpShouldSetCookies = true /// Accept all cookies. config.httpCookieAcceptPolicy = .always /// Allows a seamless handover from Wi-Fi to cellular if #available(iOS 11.0, *) { config.multipathServiceType = .handover } /// Create the main session and set its description let session = URLSession(configuration: config, delegate: self, delegateQueue: nil) session.sessionDescription = "Main Session" return session }() // MARK: - Session Methods public func postRequest<T: Decodable>(withMethod method: String, paramDict: [String: Any], jsonObjectClientExpectsToReceive: T.Type, countOfBytesClientExpectsToReceive:Int64, success: @escaping (Data) -> Void, failure: @escaping (NSError) -> Void) { // Create POST request let urlStr = "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)" let url = URL(string: urlStr + "/ws.php?\(method)") var request = URLRequest(url: url!) request.httpMethod = "POST" request.networkServiceType = .responsiveData // Combine percent encoded parameters var encPairs = [String]() for (key, value) in paramDict { if let valStr = value as? String, valStr.isEmpty == false { let encKey = key.addingPercentEncoding(withAllowedCharacters: .pwgURLQueryAllowed) ?? key // Piwigo 2.10.2 supports the 3-byte UTF-8, not the standard UTF-8 (4 bytes) let utf8mb3Str = NetworkUtilities.utf8mb3String(from: valStr) let encVal = utf8mb3Str.addingPercentEncoding(withAllowedCharacters: .pwgURLQueryAllowed) ?? utf8mb3Str encPairs.append(String(format: "%@=%@", encKey, encVal)) continue } else if let val = value as? NSNumber { let encKey = key.addingPercentEncoding(withAllowedCharacters: .pwgURLQueryAllowed) ?? key let encVal = val.stringValue encPairs.append(String(format: "%@=%@", encKey, encVal)) continue } else { let encKey = key.addingPercentEncoding(withAllowedCharacters: .pwgURLQueryAllowed) ?? key encPairs.append(encKey) } } let encParams = encPairs.joined(separator: "&") let httpBody = encParams.data(using: .utf8, allowLossyConversion: true) request.httpBody = httpBody // Launch the HTTP(S) request let task = dataSession.dataTask(with: request) { data, response, error in // Transaction completed? guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { // Transaction error guard let error = error else { // No communication error returned, // so Piwigo returned an error to be handled by the caller. guard var jsonData = data, jsonData.isEmpty == false else { // Empty JSON data guard let httpResponse = response as? HTTPURLResponse else { // Nothing to report failure(JsonError.emptyJSONobject as NSError) return } // Return error code let error = PwgSession.shared.localizedError(for: httpResponse.statusCode) failure(error as NSError) return } // Data returned, is this a valid JSON object? guard jsonData.isPiwigoResponseValid(for: jsonObjectClientExpectsToReceive.self) else { // Invalid JSON data #if DEBUG let dataStr = String(decoding: jsonData, as: UTF8.self) print(" > JSON: \(dataStr)") #endif guard let httpResponse = response as? HTTPURLResponse else { // Nothing to report failure(JsonError.invalidJSONobject as NSError) return } // Return error code let errorMessage = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode) let error = PwgSession.shared.localizedError(for: httpResponse.statusCode, errorMessage: errorMessage) failure(error as NSError) return } // The caller will decode the returned data success(jsonData) return } // Return transaction error failure(error as NSError) return } // No error, check that the JSON object is not empty guard var jsonData = data, jsonData.isEmpty == false else { // Empty JSON data failure(JsonError.emptyJSONobject as NSError) return } // Return Piwigo error if no error and no data returned. guard jsonData.isPiwigoResponseValid(for: jsonObjectClientExpectsToReceive.self) else { failure(JsonError.invalidJSONobject as NSError) return } // Check returned data /// - The following 2 lines are used to determine the count of returned bytes. /// - This value can then be used to provide the expected count of returned bytes. /// - The last 2 lines display the content of the returned data for debugging. #if DEBUG let countsOfByte = httpResponse.allHeaderFields.count * MemoryLayout<Dictionary<String, Any>>.stride + jsonData.count * MemoryLayout<Data>.stride let dataStr = String(decoding: jsonData, as: UTF8.self) print(" > JSON — \(countsOfByte) bytes received:\r \(dataStr)") #endif // The caller will decode the returned data success(jsonData) } // Inform iOS so that it can optimize the scheduling of the task if #available(iOS 11.0, *) { // Tell the system how many bytes are expected to be exchanged task.countOfBytesClientExpectsToSend = Int64((httpBody ?? Data()).count + (request.allHTTPHeaderFields ?? [:]).count) task.countOfBytesClientExpectsToReceive = countOfBytesClientExpectsToReceive } // Sets the task description from the method if let pos = method.lastIndex(of: "=") { task.taskDescription = String(method[pos...].dropFirst()) } else { task.taskDescription = method.components(separatedBy: "=").last } // Execute the task task.resume() } } // MARK: - Session Delegate extension PwgSession: URLSessionDelegate { public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { print(" > The data session has been invalidated") } public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print(" > Session-level authentication request from the remote server \(NetworkVars.domain())") // Get protection space for current domain let protectionSpace = challenge.protectionSpace guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust else { completionHandler(.rejectProtectionSpace, nil) return } // Initialise SSL certificate approval flag NetworkVars.didRejectCertificate = false // Get state of the server SSL transaction state guard let serverTrust = protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } // Check validity of certificate if KeychainUtilities.isSSLtransactionValid(inState: serverTrust, for: NetworkVars.domain()) { let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) return } // If there is no certificate, reject server (should rarely happen) if SecTrustGetCertificateCount(serverTrust) == 0 { completionHandler(.performDefaultHandling, nil) } // Retrieve the certificate of the server guard let certificate = SecTrustGetCertificateAtIndex(serverTrust, CFIndex(0)) else { completionHandler(.performDefaultHandling, nil) return } // Check if the certificate is trusted by user (i.e. is in the Keychain) // Case where the certificate is e.g. self-signed if KeychainUtilities.isCertKnownForSSLtransaction(certificate, for: NetworkVars.domain()) { let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) return } // No certificate or different non-trusted certificate found in Keychain // Did the user approve this certificate? if NetworkVars.didApproveCertificate { // Delete certificate in Keychain (updating the certificate data is not sufficient) KeychainUtilities.deleteCertificate(for: NetworkVars.domain()) // Store server certificate in Keychain with same label "Piwigo:<host>" KeychainUtilities.storeCertificate(certificate, for: NetworkVars.domain()) // Will reject a connection if the certificate is changed during a session // but it will still be possible to logout. NetworkVars.didApproveCertificate = false // Accept connection let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) return } // Will ask the user whether we should trust this server. NetworkVars.certificateInformation = KeychainUtilities.getCertificateInfo(certificate, for: NetworkVars.domain()) NetworkVars.didRejectCertificate = true // Reject the request completionHandler(.performDefaultHandling, nil) } } // MARK: - Session Task Delegate extension PwgSession: URLSessionDataDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print(" > Task-level authentication request from the remote server") // Check authentication method let authMethod = challenge.protectionSpace.authenticationMethod guard [NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest].contains(authMethod) else { completionHandler(.performDefaultHandling, nil) return } // Initialise HTTP authentication flag NetworkVars.didFailHTTPauthentication = false // Get HTTP basic authentification credentials let service = NetworkVars.serverProtocol + NetworkVars.serverPath var account = NetworkVars.httpUsername var password = KeychainUtilities.password(forService: service, account: account) // Without HTTP credentials available, tries Piwigo credentials if account.isEmpty || password.isEmpty { // Retrieve Piwigo credentials account = NetworkVars.username password = KeychainUtilities.password(forService: NetworkVars.serverPath, account: account) // Adopt Piwigo credentials as HTTP basic authentification credentials NetworkVars.httpUsername = account KeychainUtilities.setPassword(password, forService: service, account: account) } // Supply requested credentials if not provided yet if (challenge.previousFailureCount == 0) { // Try HTTP credentials… let credential = URLCredential(user: account, password: password, persistence: .forSession) completionHandler(.useCredential, credential) return } // HTTP credentials refused... delete them in Keychain KeychainUtilities.deletePassword(forService: service, account: account) // Remember failed HTTP authentication NetworkVars.didFailHTTPauthentication = true completionHandler(.performDefaultHandling, nil) } }
mit
7b2bde9b5fe8ecc88580ce5b2d49a6c4
43.822289
215
0.598817
5.884144
false
false
false
false
frtlupsvn/Vietnam-To-Go
VietNamToGo/ViewControllers/MakeTrip/ZCCMakeTripStepOneViewController.swift
1
9523
// // ZCCMakeTripStepOneViewController.swift // Fuot // // Created by Zoom Nguyen on 1/1/16. // Copyright © 2016 Zoom Nguyen. All rights reserved. // import UIKit import EZSwiftExtensions import THCalendarDatePicker class ZCCMakeTripStepOneViewController: ZCCViewController,ZCCCititesViewControllerDelegate,THDatePickerDelegate { enum calendarType { case Arrival case Depart } var calendarPickerType:calendarType? @IBOutlet weak var tableView: UITableView! @IBOutlet weak var btnContinue: ZCCButton! @IBOutlet weak var imgBackground: UIImageView! var curDate : NSDate? = NSDate() lazy var formatter: NSDateFormatter = { var tmpFormatter = NSDateFormatter() tmpFormatter.dateFormat = "dd/MM/yyyy" return tmpFormatter }() lazy var datePicker : THDatePickerViewController = { let picker = THDatePickerViewController.datePicker() picker.delegate = self picker.date = self.curDate picker.setAllowClearDate(false) picker.setClearAsToday(false) picker.setAutoCloseOnSelectDate(true) picker.setAllowSelectionOfSelectedDate(true) picker.setDisableYearSwitch(true) //picker.setDisableFutureSelection(false) picker.setDaysInHistorySelection(1) picker.setDaysInFutureSelection(0) picker.setDateTimeZoneWithName("UTC") picker.autoCloseCancelDelay = 5.0 picker.rounded = true picker.dateTitle = "Calendar" picker.selectedBackgroundColor = colorYellow picker.currentDateColor = colorYellow picker.currentDateColorSelected = UIColor.whiteColor() return picker }() /* Data */ var cityPicked:City? var dateArrival:NSDate? var dateDepart:NSDate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. /* Tableview layout */ self.tableView.registerNib(UINib(nibName: "ZCCPickCityTableViewCell", bundle: nil), forCellReuseIdentifier: "ZCCPickCityTableViewCell") self.tableView.registerNib(UINib(nibName: "ZCCMoneySliderTableViewCell", bundle: nil), forCellReuseIdentifier: "ZCCMoneySliderTableViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnContinueTapped(sender: AnyObject) { } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: THDatePickerDelegate func datePickerDonePressed(datePicker: THDatePickerViewController!) { curDate = datePicker.date dismissSemiModalView() } func datePickerCancelPressed(datePicker: THDatePickerViewController!) { dismissSemiModalView() } func datePicker(datePicker: THDatePickerViewController!, selectedDate: NSDate!) { print("Date selected: ", formatter.stringFromDate(selectedDate)) if (self.calendarPickerType == .Arrival){ dateArrival = selectedDate }else{ dateDepart = selectedDate } // if (self.dateDepart < self.dateArrival){ // self.showDialog("Error",message:"Please a depart date after arrival date") // return // } self.tableView.reloadData() } func convertCfTypeToString(cfValue: Unmanaged<NSString>!) -> String?{ /* Coded by Vandad Nahavandipoor */ let value = Unmanaged<CFStringRef>.fromOpaque( cfValue.toOpaque()).takeUnretainedValue() as CFStringRef if CFGetTypeID(value) == CFStringGetTypeID(){ return value as String } else { return nil } } // MARK: TableViewDelegate func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ if (indexPath.section == 3){ let cellMoney = tableView.dequeueReusableCellWithIdentifier("ZCCMoneySliderTableViewCell", forIndexPath: indexPath) as! ZCCMoneySliderTableViewCell cellMoney.selectionStyle = .None cellMoney.lblPickLocation.text = "Chọn số tiền" cellMoney.setIcon(UIImage(named: "[email protected]")!) return cellMoney }else{ let cell : ZCCPickCityTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("ZCCPickCityTableViewCell", forIndexPath: indexPath) as! ZCCPickCityTableViewCell cell.selectionStyle = .None switch (indexPath.section) { case 0: cell.lblPickLocation.text = "Chọn nơi đến" cell.lblValueLocationPicked.text = self.cityPicked?.name cell.setIcon(UIImage(named: "[email protected]")!) break case 1: cell.lblPickLocation.text = "Chọn ngày đi" if let dateArrival = self.dateArrival{ cell.lblValueLocationPicked.text = formatter.stringFromDate(dateArrival) } cell.setIcon(UIImage(named: "[email protected]")!) break case 2: cell.lblPickLocation.text = "Chọn ngày về" if let dateDepart = self.dateDepart{ cell.lblValueLocationPicked.text = formatter.stringFromDate(dateDepart) } cell.setIcon(UIImage(named: "[email protected]")!) break default: break } return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch (indexPath.section) { case 0: /* Pick City */ let citiesVC = self.storyboard?.instantiateViewControllerWithIdentifier("ZCCCititesViewController") as! ZCCCititesViewController citiesVC.citiesType = .Picker citiesVC.delegate = self self.navigationController?.pushViewController(citiesVC, animated: true) break case 1: self.calendarPickerType = .Arrival datePicker.date = self.curDate presentSemiViewController(datePicker, withOptions: [ convertCfTypeToString(KNSemiModalOptionKeys.shadowOpacity) as String! : 0.1 as Float, convertCfTypeToString(KNSemiModalOptionKeys.animationDuration) as String! : 0.5 as Float, convertCfTypeToString(KNSemiModalOptionKeys.pushParentBack) as String! : false as Bool ]) break case 2: /* Pick Date */ self.calendarPickerType = .Depart datePicker.date = self.curDate presentSemiViewController(datePicker, withOptions: [ convertCfTypeToString(KNSemiModalOptionKeys.shadowOpacity) as String! : 0.1 as Float, convertCfTypeToString(KNSemiModalOptionKeys.animationDuration) as String! : 0.5 as Float, convertCfTypeToString(KNSemiModalOptionKeys.pushParentBack) as String! : false as Bool ]) break case 3: /* Pick Budget */ break default: break } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{ return ZCCPickCityTableViewCell.heightOfCell() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 4 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0{ return 0 } return 0; // space b/w cells } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 10; // space b/w cells } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView() header.backgroundColor = UIColor.clearColor() return header } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footer = UIView() footer.backgroundColor = UIColor.clearColor() return footer } // MARK: Cities Delegate func pickCity(city:City){ self.cityPicked = city if let imageUrl = city.cityImage{ let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType!, imageURL: NSURL!) -> Void in } let url = NSURL(string: imageUrl) self.imgBackground.sd_setImageWithURL(url,placeholderImage: UIImage(named: "[email protected]") ,completed: block) } self.tableView.reloadData() } }
mit
8077f9907629d3e5835f0661df599362
34.059041
180
0.622777
5.10532
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/IncrementalCompilation/Bitcode/BitstreamReader.swift
1
11614
//===--------------- BitstreamReader.swift - LLVM Bitstream Reader -------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 struct TSCBasic.ByteString private extension Bits.Cursor { enum BitcodeError: Swift.Error { case vbrOverflow } mutating func readVBR(_ width: Int) throws -> UInt64 { precondition(width > 1) let testBit = UInt64(1 << (width &- 1)) let mask = testBit &- 1 var result: UInt64 = 0 var offset: UInt64 = 0 var next: UInt64 repeat { next = try self.read(width) result |= (next & mask) << offset offset += UInt64(width &- 1) if offset > 64 { throw BitcodeError.vbrOverflow } } while next & testBit != 0 return result } } internal struct BitstreamReader { enum Error: Swift.Error { case invalidAbbrev case nestedBlockInBlockInfo case missingSETBID case invalidBlockInfoRecord(recordID: UInt64) case abbrevWidthTooSmall(width: Int) case noSuchAbbrev(blockID: UInt64, abbrevID: Int) case missingEndBlock(blockID: UInt64) } var cursor: Bits.Cursor var blockInfo: [UInt64: BlockInfo] = [:] var globalAbbrevs: [UInt64: [Bitstream.Abbreviation]] = [:] init(buffer: ByteString) { self.cursor = Bits.Cursor(buffer: buffer) } mutating func readSignature() throws -> Bitcode.Signature { precondition(self.cursor.isAtStart) let bits = try UInt32(self.cursor.read(MemoryLayout<UInt32>.size * 8)) return Bitcode.Signature(value: bits) } mutating func readAbbrevOp() throws -> Bitstream.Abbreviation.Operand { let isLiteralFlag = try cursor.read(1) if isLiteralFlag == 1 { return .literal(try cursor.readVBR(8)) } switch try cursor.read(3) { case 0: throw Error.invalidAbbrev case 1: return .fixed(bitWidth: UInt8(try cursor.readVBR(5))) case 2: return .vbr(chunkBitWidth: UInt8(try cursor.readVBR(5))) case 3: return .array(try readAbbrevOp()) case 4: return .char6 case 5: return .blob case 6, 7: throw Error.invalidAbbrev default: fatalError() } } mutating func readAbbrev(numOps: Int) throws -> Bitstream.Abbreviation { guard numOps > 0 else { throw Error.invalidAbbrev } var operands: [Bitstream.Abbreviation.Operand] = [] operands.reserveCapacity(numOps) for i in 0..<numOps { operands.append(try readAbbrevOp()) if case .array = operands.last! { guard i == numOps - 2 else { throw Error.invalidAbbrev } break } else if case .blob = operands.last! { guard i == numOps - 1 else { throw Error.invalidAbbrev } } } return Bitstream.Abbreviation(operands) } mutating func readSingleAbbreviatedRecordOperand(_ operand: Bitstream.Abbreviation.Operand) throws -> UInt64 { switch operand { case .char6: let value = try cursor.read(6) switch value { case 0...25: return value + UInt64(("a" as UnicodeScalar).value) case 26...51: return value + UInt64(("A" as UnicodeScalar).value) - 26 case 52...61: return value + UInt64(("0" as UnicodeScalar).value) - 52 case 62: return UInt64(("." as UnicodeScalar).value) case 63: return UInt64(("_" as UnicodeScalar).value) default: fatalError() } case .literal(let value): return value case .fixed(let width): return try cursor.read(Int(width)) case .vbr(let width): return try cursor.readVBR(Int(width)) case .array, .blob: fatalError() } } /// Computes a non-owning view of a `BitcodeElement.Record` that is valid for /// the lifetime of the call to `body`. /// /// - Warning: If this function throws, the `body` block will not be called. mutating func withAbbreviatedRecord( _ abbrev: Bitstream.Abbreviation, body: (BitcodeElement.Record) throws -> Void ) throws { let code = try readSingleAbbreviatedRecordOperand(abbrev.operands.first!) let lastOperand = abbrev.operands.last! let lastRegularOperandIndex: Int = abbrev.operands.endIndex - (lastOperand.isPayload ? 1 : 0) // Safety: `lastRegularOperandIndex` is always at least 1. An abbreviation // is required by the format to contain at least one operand. If that last // operand is a payload (and thus we subtracted one from the total number of // operands above), then that must mean it is either a trailing array // or trailing blob. Both of these are preceded by their length field. let fields = UnsafeMutableBufferPointer<UInt64>.allocate(capacity: lastRegularOperandIndex - 1) defer { fields.deallocate() } for (idx, op) in abbrev.operands[1..<lastRegularOperandIndex].enumerated() { fields[idx] = try readSingleAbbreviatedRecordOperand(op) } let payload: BitcodeElement.Record.Payload if !lastOperand.isPayload { payload = .none } else { switch lastOperand { case .array(let element): let length = try cursor.readVBR(6) if case .char6 = element { // FIXME: Once the minimum deployment target bumps to macOS 11, use // the more ergonomic stdlib API everywhere. if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { payload = try .char6String(String(unsafeUninitializedCapacity: Int(length)) { buffer in for i in 0..<Int(length) { buffer[i] = try UInt8(readSingleAbbreviatedRecordOperand(element)) } return Int(length) }) } else { let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: Int(length)) defer { buffer.deallocate() } for i in 0..<Int(length) { buffer[i] = try UInt8(readSingleAbbreviatedRecordOperand(element)) } payload = .char6String(String(decoding: buffer, as: UTF8.self)) } } else { var elements = [UInt64]() for _ in 0..<length { elements.append(try readSingleAbbreviatedRecordOperand(element)) } payload = .array(elements) } case .blob: let length = Int(try cursor.readVBR(6)) try cursor.advance(toBitAlignment: 32) payload = .blob(try cursor.read(bytes: length)) try cursor.advance(toBitAlignment: 32) default: fatalError() } } return try body(.init(id: code, fields: UnsafeBufferPointer(fields), payload: payload)) } mutating func readBlockInfoBlock(abbrevWidth: Int) throws { var currentBlockID: UInt64? while true { switch try cursor.read(abbrevWidth) { case Bitstream.AbbreviationID.endBlock.rawValue: try cursor.advance(toBitAlignment: 32) // FIXME: check expected length return case Bitstream.AbbreviationID.enterSubblock.rawValue: throw Error.nestedBlockInBlockInfo case Bitstream.AbbreviationID.defineAbbreviation.rawValue: guard let blockID = currentBlockID else { throw Error.missingSETBID } let numOps = Int(try cursor.readVBR(5)) if globalAbbrevs[blockID] == nil { globalAbbrevs[blockID] = [] } globalAbbrevs[blockID]!.append(try readAbbrev(numOps: numOps)) case Bitstream.AbbreviationID.unabbreviatedRecord.rawValue: let code = try cursor.readVBR(6) let numOps = try cursor.readVBR(6) var operands = [UInt64]() for _ in 0..<numOps { operands.append(try cursor.readVBR(6)) } switch code { case UInt64(Bitstream.BlockInfoCode.setBID.rawValue): guard operands.count == 1 else { throw Error.invalidBlockInfoRecord(recordID: code) } currentBlockID = operands.first case UInt64(Bitstream.BlockInfoCode.blockName.rawValue): guard let blockID = currentBlockID else { throw Error.missingSETBID } if blockInfo[blockID] == nil { blockInfo[blockID] = BlockInfo() } blockInfo[blockID]!.name = String(bytes: operands.map { UInt8($0) }, encoding: .utf8) ?? "<invalid>" case UInt64(Bitstream.BlockInfoCode.setRecordName.rawValue): guard let blockID = currentBlockID else { throw Error.missingSETBID } if blockInfo[blockID] == nil { blockInfo[blockID] = BlockInfo() } guard let recordID = operands.first else { throw Error.invalidBlockInfoRecord(recordID: code) } blockInfo[blockID]!.recordNames[recordID] = String(bytes: operands.dropFirst().map { UInt8($0) }, encoding: .utf8) ?? "<invalid>" default: throw Error.invalidBlockInfoRecord(recordID: code) } case let abbrevID: throw Error.noSuchAbbrev(blockID: 0, abbrevID: Int(abbrevID)) } } } mutating func readBlock<Visitor: BitstreamVisitor>(id: UInt64, abbrevWidth: Int, abbrevInfo: [Bitstream.Abbreviation], visitor: inout Visitor) throws { var abbrevInfo = abbrevInfo while !cursor.isAtEnd { switch try cursor.read(abbrevWidth) { case Bitstream.AbbreviationID.endBlock.rawValue: try cursor.advance(toBitAlignment: 32) // FIXME: check expected length try visitor.didExitBlock() return case Bitstream.AbbreviationID.enterSubblock.rawValue: let blockID = try cursor.readVBR(8) let newAbbrevWidth = Int(try cursor.readVBR(4)) try cursor.advance(toBitAlignment: 32) let blockLength = try cursor.read(32) * 4 switch blockID { case 0: try readBlockInfoBlock(abbrevWidth: newAbbrevWidth) case 1...7: // Metadata blocks we don't understand yet fallthrough default: guard try visitor.shouldEnterBlock(id: blockID) else { try cursor.skip(bytes: Int(blockLength)) break } try readBlock( id: blockID, abbrevWidth: newAbbrevWidth, abbrevInfo: globalAbbrevs[blockID] ?? [], visitor: &visitor) } case Bitstream.AbbreviationID.defineAbbreviation.rawValue: let numOps = Int(try cursor.readVBR(5)) abbrevInfo.append(try readAbbrev(numOps: numOps)) case Bitstream.AbbreviationID.unabbreviatedRecord.rawValue: let code = try cursor.readVBR(6) let numOps = try cursor.readVBR(6) let operands = UnsafeMutableBufferPointer<UInt64>.allocate(capacity: Int(numOps)) defer { operands.deallocate() } for i in 0..<Int(numOps) { operands[i] = try cursor.readVBR(6) } try visitor.visit(record: .init(id: code, fields: UnsafeBufferPointer(operands), payload: .none)) case let abbrevID: guard Int(abbrevID) - 4 < abbrevInfo.count else { throw Error.noSuchAbbrev(blockID: id, abbrevID: Int(abbrevID)) } try withAbbreviatedRecord(abbrevInfo[Int(abbrevID) - 4]) { record in try visitor.visit(record: record) } } } guard id == Self.fakeTopLevelBlockID else { throw Error.missingEndBlock(blockID: id) } } static let fakeTopLevelBlockID: UInt64 = ~0 }
apache-2.0
79620d23a750436b2e21427161342aea
34.408537
153
0.63699
4.128688
false
false
false
false
jonasman/AsyncStarterKit
AsyncStarterKit/ViewController.swift
1
695
// // ViewController.swift // AsyncStarterKit // // Created by Joao Nunes on 01/06/16. // Copyright © 2016 Joao Nunes. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! var service = PostsService() override func viewDidLoad() { super.viewDidLoad() } @IBAction func get(sender: AnyObject) { service.getAllPosts().then { (posts) -> Void in self.textView.text = posts.first?.body } } @IBAction func post(sender: AnyObject) { let post = Post() post.title = "test" service.createPost(post).then { post -> Void in self.textView.text = "Posted: \(post.title)" } } }
mit
8f6f0fdf548b2f1dbf901cc8d354185e
14.422222
53
0.652738
3.304762
false
false
false
false
frankcjw/CJWUtilsS
CJWUtilsS/QPLib/Utils/QPMemberUtils.swift
1
2784
// // QPMemberUtils.swift // QHProject // // Created by quickplain on 15/12/24. // Copyright © 2015年 quickplain. All rights reserved. // import UIKit private let KEY_LOGIN = "LOGIN" private let KEY_ACCOUNT = "ACCOUNT" private let KEY_PASSWORD = "PASSWORD" private let KEY_YES = "YES" private let KEY_NO = "NO" class QPMemberUtils: NSObject { var memberInfo = NSDictionary() { didSet { if let imToken = memberInfo["imToken"] as? String { self.imToken = imToken } } } var loginFlag = false class func login(){ QPMemberUtils.sharedInstance.loginFlag = true } var imToken = "" class func logout(){ // QPHttpUtils.sharedInstance.logout({ (resp) -> Void in // // // }) { () -> Void in // // // } } // class func isLogin() -> Bool{ // if let str = QPKeyChainUtils.stringForKey(KEY_LOGIN) { // if str == KEY_YES { // return true // } // } // return false // } class func clearUserInfo(){ QPKeyChainUtils.removeKey(KEY_PASSWORD) QPKeyChainUtils.removeKey(KEY_ACCOUNT) } class func isLoginInfoExist(){ if QPKeyChainUtils.stringForKey(KEY_ACCOUNT) != nil && QPKeyChainUtils.stringForKey(KEY_PASSWORD) != nil { } } class func saveInfo(account:String,password:String){ QPKeyChainUtils.setString(account, forKey: KEY_ACCOUNT) QPKeyChainUtils.setString(password, forKey: KEY_PASSWORD) QPMemberUtils.login() } class func account() -> String? { return QPKeyChainUtils.stringForKey(KEY_ACCOUNT) } class func password() -> String? { return QPKeyChainUtils.stringForKey(KEY_PASSWORD) } class var sharedInstance : QPMemberUtils { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : QPMemberUtils? = nil } dispatch_once(&Static.onceToken) { Static.instance = QPMemberUtils() } return Static.instance! } var memberId : Int { if let id = memberInfo["id"] as? Int { return id } return -1 } var name : String { if let value = memberInfo["name"] as? String { return value } return "" } var thumbnail : String { let tmp = logo.stringByReplacingOccurrencesOfString(".png", withString: "_s.png") return tmp } var logo : String { if let value = memberInfo["logo"] as? String { return value } return "" } }
mit
842cf4d8b3255b3a1f0dc9c9ad06545a
24.054054
114
0.544049
4.318323
false
false
false
false
Calvin-Huang/CHProgressSuit
CHProgressSuit/ViewController.swift
1
1006
// // ViewController.swift // CHProgressSuit // // Created by Calvin on 6/26/16. // Copyright © 2016 CapsLock. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var circularProgress: CircularProgress! override func viewDidLoad() { super.viewDidLoad() circularProgress.animateCompletion = { (progress) in print("Progress: \(progress)") } } //MARK: - IBActions @IBAction func resetButtonClicked(_: AnyObject) { circularProgress.reset() } @IBAction func add2ButtonClicked(_: AnyObject) { circularProgress.progress += 0.02 } @IBAction func add20ButtonClicked(_: AnyObject) { circularProgress.progress += 0.2 } @IBAction func reduce2ButtonClicked(_: AnyObject) { circularProgress.progress -= 0.02 } @IBAction func reduce20ButtonClicked(_: AnyObject) { circularProgress.progress -= 0.2 } }
mit
83e56f3bec0944887b94b33e183a8549
22.372093
60
0.624876
4.631336
false
false
false
false
happylance/MacKey
MacKeyUnit/Domain/ReducibleState.swift
1
1281
// // Reducible.swift // MacKey // // Created by Liu Liang on 5/12/18. // Copyright © 2018 Liu Liang. All rights reserved. // import RxSwift import RxCocoa protocol ReducibleState { associatedtype InputAction associatedtype OutputAction func reduce(_ inputAction:InputAction) -> (Self?, OutputAction?) } extension ReducibleState { func getStateAndActions(inputActions: PublishRelay<InputAction>, disposeBag: DisposeBag) -> (BehaviorRelay<Self>, PublishRelay<OutputAction>) { let state = BehaviorRelay(value: self) let outputActions = PublishRelay<OutputAction>() inputActions.scan((self, nil, nil)) { (arg0, action: InputAction) -> (Self, Self?, OutputAction?) in let (previousState, _, _) = arg0 let (newState, outputAction) = previousState.reduce(action) return (newState ?? previousState, newState, outputAction) } .subscribe(onNext: { if let newState = $0.1 { state.accept(newState) } if let action = $0.2 { outputActions.accept(action) } }) .disposed(by: disposeBag) return (state, outputActions) } }
mit
b4219c187a5ebf49d77a3c650cbf6701
30.219512
147
0.589844
4.491228
false
false
false
false
cliffpanos/True-Pass-iOS
iOSApp/CheckIn/View and Design/CPTextFieldManager.swift
2
4206
// // CPTextFieldManager.swift // True Pass // // Created by Cliff Panos on 6/28/17. // Copyright © 2017 Clifford Panos. All rights reserved. // import UIKit class CPTextFieldManager: NSObject, UITextFieldDelegate { var textFields: [UITextField] unowned var viewController: UIViewController var unselectedTextColor: UIColor? var selectedTextColor: UIColor? var finalReturnAction: (() -> Void)? internal var tapToDismiss: Bool = false { //Internal because it does not yet work didSet { if (tapToDismiss) { print("Added Tap Gesture Recognizer") viewController.view.addGestureRecognizer(tapGestureRecognizer) } else { print("Removed Tap Gesture Recognizer") viewController.view.removeGestureRecognizer(tapGestureRecognizer) } } } var selectedTextField: UITextField? var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) init?(textFields: [UITextField], in viewController: UIViewController) { //Once initialized, the CPTextFieldManager instance should be retained as a property in the UIViewController class that holds the UITextFields. if textFields.count == 0 { return nil } self.textFields = textFields self.viewController = viewController } func setupTextFields(withAccessory accessoryViewStyle: CPTextFieldManagerAccessoryViewStyle = .none) { individualSetup: for textField in textFields { textField.delegate = self textField.returnKeyType = .next if accessoryViewStyle == .none { continue individualSetup } if UIDevice.current.userInterfaceIdiom == .pad && textField.inputView == nil { continue individualSetup } let numberToolbar: UIToolbar = UIToolbar() numberToolbar.barStyle = UIBarStyle.default let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil) let done = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let textInputAccessories = [flexibleSpace, done] numberToolbar.items = textInputAccessories numberToolbar.sizeToFit() textField.inputAccessoryView = numberToolbar } //End for loop for setting up each individual textField's inputAccessoryView and delegate } func setFinalReturn(keyType: UIReturnKeyType, action: (() -> Void)? = nil) { textFields.last!.returnKeyType = keyType self.finalReturnAction = action } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == textFields.last { finalReturnAction?() dismissKeyboard() return true } guard let currentIndex = textFields.index(of: textField) else { return true } let nextTextField = textFields[currentIndex + 1] nextTextField.becomeFirstResponder() //let indexPath = IndexPath(row: 0, section: 2) //tableView.scrollToRow(at: indexPath, at: .middle, animated: true) return true } func textFieldDidBeginEditing(_ textField: UITextField) { selectedTextField = textField textField.textColor = selectedTextColor ?? textField.textColor } func textFieldDidEndEditing(_ textField: UITextField) { textField.textColor = unselectedTextColor ?? textField.textColor } func goToFirst() { textFields.first!.becomeFirstResponder() } func goToLast() { textFields.last!.becomeFirstResponder() } @objc func dismissKeyboard() { self.viewController.view.endEditing(true) } } enum CPTextFieldManagerAccessoryViewStyle: Int { case none case done case upDownArrows case doneAndArrows }
apache-2.0
ecfa60687cc7443eca33c0ac9a09e3a3
32.64
151
0.635434
5.864714
false
false
false
false
nodes-ios/nstack-translations-generator
LocalizationsGenerator/Classes/Parser/Parser.swift
1
2741
// // Parser.swift // nstack-localizations-generator // // Created by Dominik Hádl on 14/02/16. // Copyright © 2016 Nodes. All rights reserved. // import Foundation struct ParserOutput { var JSON: [String: AnyObject] var mainKeys: [String] var language: [String: AnyObject] var isFlat: Bool } struct Parser { static func parseResponseData(_ data: Data) throws -> ParserOutput { let object = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let dictionary = object as? [String: AnyObject] else { throw NSError(domain: Constants.ErrorDomain.tGenerator.rawValue, code: ErrorCode.parserError.rawValue, userInfo: [NSLocalizedDescriptionKey : "The data isn't in the correct format. Localizations JSON file should have a dictionary as its root object."]) } var content: [String: AnyObject]? = dictionary content = content?["data"] as? [String : AnyObject] ?? content if let t = content?["Translation"] as? [String : AnyObject] { content = t } else if let t = content?["translations"] as? [String : AnyObject] { content = t } guard let langsDictionary = content, let first = langsDictionary.first else { throw NSError(domain: Constants.ErrorDomain.tGenerator.rawValue, code: ErrorCode.parserError.rawValue, userInfo: [NSLocalizedDescriptionKey : "Parsed JSON didn't contain localization data."]) } // Check if key is either "en" or "en-UK" let isPossibleLanguageKey = first.key.count == 2 || (first.key.count == 5 && first.key.contains("-")) let testKey = first.key[first.key.startIndex..<first.key.index(first.key.startIndex, offsetBy: 2)] // substring 0..2 let isWrappedInLanguages = isPossibleLanguageKey && Locale.isoLanguageCodes.contains(String(testKey)) var language: [String: AnyObject] if isWrappedInLanguages, let val = first.value as? [String: AnyObject] { // the nested lang is value language = val } else { // the root obj is the translations language = langsDictionary } // Fix for default if let object = language["default"] { language.removeValue(forKey: "default") language["defaultSection"] = object } return ParserOutput(JSON: dictionary, mainKeys: language.map({ return $0.0 }).sorted(by: {$0 < $1}), language: language, isFlat: language is [String: String]) } }
mit
238add0ec82a062dd5ecde860acf83c6
40.5
155
0.610442
4.698113
false
false
false
false
micolous/metrodroid
native/metrodroid/metrodroid/LicenseViewController.swift
1
1760
// // LicenseViewController.swift // // Copyright 2019 Google // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // import UIKit import metrolib class LicenseViewController: UIViewController { @IBOutlet weak var licenseTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() var licenseText = "" licenseText += readLicenseTextFromAsset("Metrodroid-NOTICE") licenseText += readLicenseTextFromAsset("Logos-NOTICE") licenseText += readLicenseTextFromAsset("NOTICE.AOSP") licenseText += readLicenseTextFromAsset("NOTICE.noto-emoji") licenseText += readLicenseTextFromAsset("NOTICE.protobuf") for factory in CardInfoRegistry.init().allFactories { guard let notice = factory.notice else { continue } licenseText += notice licenseText += "\n\n" } licenseTextView.text = licenseText } func readLicenseTextFromAsset(_ res: String) -> String { return (Utils.loadResourceFileString(resource: res) ?? "error loading \(res)") + "\n\n" } }
gpl-3.0
d3c58cb6428ea9d77426f6a75ff75d99
32.846154
95
0.669886
4.501279
false
false
false
false
think-dev/MadridBUS
MadridBUS/Source/Data/BusLineSchedule.swift
1
2244
import Foundation import ObjectMapper class BusLineBasicSchedule: Mappable { var line: String = "" var headerStartTime: Date = Date() var headerEndTime: Date = Date() var terminusStartTime: Date = Date() var terminusEndTime: Date = Date() var dayType: BusDayType = .undefined init() {} required init?(map: Map) {} func mapping(map: Map) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy h:mm:ss" line <- map["line"] headerStartTime <- (map["timeFirstA"], DateFormatterTransform(dateFormatter: dateFormatter)) headerEndTime <- (map["timeEndA"], DateFormatterTransform(dateFormatter: dateFormatter)) terminusStartTime <- (map["timeFirstB"], DateFormatterTransform(dateFormatter: dateFormatter)) terminusEndTime <- (map["timeEndB"], DateFormatterTransform(dateFormatter: dateFormatter)) dayType <- (map["typeDay"], EnumTransform<BusDayType>()) } } final class BusLineSchedule: Mappable { var holidaySchedule: BusLineBasicSchedule? var labourSchedule: BusLineBasicSchedule? var saturdaySchedule: BusLineBasicSchedule? var fridaySchedule: BusLineBasicSchedule? init(using json: String) { let schedules: [BusLineBasicSchedule] = Mapper<BusLineBasicSchedule>().mapArray(JSONString: json)! for aSchedule in schedules { switch aSchedule.dayType { case .holiday: holidaySchedule = aSchedule case .labour: labourSchedule = aSchedule case .saturday: saturdaySchedule = aSchedule case .friday: fridaySchedule = aSchedule case .undefined: break } } } required init?(map: Map) {} func mapping(map: Map) { var schedules: [BusLineBasicSchedule] = [] schedules <- map for aSchedule in schedules { switch aSchedule.dayType { case .holiday: holidaySchedule = aSchedule case .labour: labourSchedule = aSchedule case .saturday: saturdaySchedule = aSchedule case .friday: fridaySchedule = aSchedule case .undefined: break } } } }
mit
b5971863d194de889a0148b5c9b48e7c
34.0625
106
0.638146
4.794872
false
false
false
false
inforeqd512/StickyTableHeader
NonScrollingTableHeader/NonScrollingTableHeader/HeaderViewScrollDown.swift
1
5877
// // HeaderViewReduceHeightAtScrollUpDelegate.swift // NonScrollingTableHeader // // Created by Info Reqd on 2/4/17. // Copyright © 2017 Info Reqd. All rights reserved. // import UIKit /// SRP : handles the logic to continuously increase the height of the headerView as the tableview scrolls downwards. This is till the height reaches preferred max class HeaderViewExpandHeightAtScrollDownDelegate: NSObject { let kvoKeyPathForContentOffset = "contentOffset" let headerView : HeaderView unowned let scrollView : UIScrollView init(headerView: HeaderView, scrollView: UIScrollView) { self.headerView = headerView self.scrollView = scrollView super.init() self.scrollView.addObserver(self, forKeyPath: kvoKeyPathForContentOffset, options: [.old, .new], context: nil) } deinit { self.scrollView.removeObserver(self, forKeyPath: kvoKeyPathForContentOffset) } /// Provides continuous change in the height of the header as derived from the continuous change in the content offset of the associated scrollView /// /// - Parameters: /// - keyPath: "contentOffset" /// - object: the scrollView. But has to be cast as KVO returns Any? /// - change: the old and new values of the keypath /// - context: nil for now. Will put in if we need it override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let tableView = object as? UITableView { let newContentOffset = change?[.newKey] as! CGPoint let oldContentOffset = change?[.oldKey] as! CGPoint //compute offset as vector which indicates the scroll direction let offset = newContentOffset.y - oldContentOffset.y self.headerView.heightConstraint.constant = increasedHeight(of: self.headerView, by: offset, contentInset: tableView.contentInset, newContentOffset: newContentOffset, oldContentOffset: oldContentOffset) self.headerView.headerViewBottomEqualInnerHeaderBottom.constant = overstretchedValue(of: self.headerView, by: offset, newContentOffset: newContentOffset, oldContentOffset: oldContentOffset) } } /// decides if the scroll down is so that the real height of the headerView should increase upto preferred max /// scrollview has scrolled south of (0,0) contentOffset, which will always be the case even after the collapse, the content offset of the scrollview is zero at the collapsed header height /// /// - newContentOffset: newContentOffset new value as returned by KVO /// - Returns: true if height should decrease func shouldIncreaseRealHeaderHeight(newContentOffset : CGPoint) -> Bool { if newContentOffset.y < 0 { //if scrolling downwards from content offset (0,0) return true //then actual height of the header view will increase }else{ return false } } /// informs if the user is scrolling down /// /// - Parameters: /// - newContentOffset: newContentOffset new value as returned by KVO /// - oldContentOffset: oldContentOffset old value that was , by KVO /// - Returns: true if scrolling down func isScrollingDown(newContentOffset:CGPoint, oldContentOffset:CGPoint) -> Bool { let offset = newContentOffset.y - oldContentOffset.y if offset < 0 { return true }else{ return false } } func increasedHeight(of headerView: HeaderView, by offset: CGFloat, contentInset: UIEdgeInsets, newContentOffset : CGPoint, oldContentOffset : CGPoint) -> CGFloat { if shouldIncreaseRealHeaderHeight(newContentOffset: newContentOffset) { if isScrollingDown(newContentOffset: newContentOffset, oldContentOffset: oldContentOffset) { let finalHeight = finalHeaderHeight(deltaContentOffset: CGPoint(x: 0.0, y: offset), contentInset: contentInset, headerHeight: headerView.heightConstraint.constant, preferredMinimumHeight: headerView.preferredMinimumHeight, preferredMaximumHeight: headerView.preferredMaximumHeight) return finalHeight } } return headerView.heightConstraint.constant } func overstretchedValue(of headerView: HeaderView, by offset: CGFloat, newContentOffset : CGPoint, oldContentOffset : CGPoint) -> CGFloat { if needsOverstretching(for: headerView, preferredMaxHeight: headerView.preferredMaximumHeight) { if isScrollingDown(newContentOffset: newContentOffset, oldContentOffset: oldContentOffset) { return increasedConstantForOverstretchInHeaderViewBottomEqualInnerHeaderBottomConstraint(headerView: headerView, deltaOffsetOfDownwardScroll: offset) } } return headerView.headerViewBottomEqualInnerHeaderBottom.constant } func needsOverstretching(for headerView: HeaderView, preferredMaxHeight: CGFloat) -> Bool { if headerView.heightConstraint.constant >= preferredMaxHeight { return true }else{ return false } } func increasedConstantForOverstretchInHeaderViewBottomEqualInnerHeaderBottomConstraint(headerView: HeaderView, deltaOffsetOfDownwardScroll: CGFloat) -> CGFloat { let overstretchVector = headerView.headerViewBottomEqualInnerHeaderBottom.constant let newOverstretchVector = overstretchVector + deltaOffsetOfDownwardScroll return newOverstretchVector } }
mit
b3cda80771cd7f86e23e9d76bbb1d13a
47.561983
214
0.678182
5.569668
false
false
false
false
okerivy/AlgorithmLeetCode
AlgorithmLeetCode/AlgorithmLeetCode/M_34_SearchforARange.swift
1
4808
// // M_34_SearchforARange.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/9. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/search-for-a-range import Foundation // MARK: - 题目名称: 34. Search for a Range /* MARK: - 所属类别: 标签: Binary Search, Array 相关题目: (E) First Bad Version */ /* MARK: - 题目英文: Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. */ /* MARK: - 题目翻译: 给定一个按升序排列的整数数组,查找给定目标值的起始和结束位置。 您的算法的时间复杂性必须是O(log n)。 如果在数组中找不到目标,返回 [-1, -1]。 例如, 给定[5, 7, 7, 8, 8, 10]和目标值8, 返回[3, 4]。 */ /* MARK: - 解题思路: 这题要求在一个排好序可能有重复元素的数组里面找到包含某个值的区间范围。 要求使用O(log n)的时间,所以我们采用两次二分查找。 首先二分找到第一个该值出现的位置,譬如m,然后在[m, n)区间内第二次二分找到最后一个该值出现的位置。代码如下: */ /* MARK: - 复杂度分析: 时间复杂度:O(lgn) 空间复杂度:O(1) */ // MARK: - 代码: private class Solution { func searchRange(_ nums: [Int], _ target: Int) -> [Int] { // 标定起始位置 和终点位置 var low = 0 var high = nums.count - 1 // 返回的range var result = [Int](repeating: -1, count: 2) //第一次二分找第一个位置 // 如果 low 小于high的时候进行循环 // 注意这里不能用 low <= high 可能会死循环 while low < high { // 中间指针 // 因为 mid = (low + high) / 2 是小处取整 所以mid 有很大可能 = row let mid = (low + high) / 2 // 如果这个数小于targe low 就指向 中点的下一个位置 // 需要注意: low = mid + 1 是因为mid 这个位置小于 目标, 所以可以+1 // 如果 low = mid 可能会死循环 if nums[mid] < target { low = mid + 1 } else { // 这里是high = mid 而不 high = mid - 1 // 因为 来到这里,可能是 nums[mid] = target high = mid // 如果相等 high 是向前逐步逼近的 } // 进行二分查找第一个元素的时候 // 1, mid = (low + high) / 2 // 2, 需要 让 mid < target 进行比较 // 3, 然后 让 low = mid + 1 // 4, else 让 high = mid } if low < nums.count && nums[low] == target { result[0] = low } else { return result // [-1, -1] } // 从第一个位置开始进行第二次二分,找最后一个位置 // 重新标定起始位置 low = low high = nums.count - 1 while low < high { // 因为 mid = (low + high + 1) / 2 是小处取整 // 所以 + 1 的意思是向大的取整 let mid = (low + high + 1) / 2 // 注意这里是 nums[mid] > target 和第一个查找不一样 if nums[mid] > target { high = mid - 1 } else { // 如果相等 low 是向后逐步逼近的 low = mid } // 进行二分查找最后一个元素的时候 // 1, mid = (low + high + 1) / 2 // 2, 需要 让 mid > target 进行比较 // 3, 然后 让 high = mid - 1 // 4, else 让 low = mid } result[1] = high return result } } // MARK: - 测试代码: func searchforARange() { let nums1 = [5, 7, 7, 8, 8, 8] // [1,3,5,6] print(Solution().searchRange(nums1, 7)) // [1, 2] print(Solution().searchRange(nums1, 8)) // [3, 5] print(Solution().searchRange(nums1, 5)) // [0, 0] print(Solution().searchRange(nums1, 10)) // [6, 6] print(Solution().searchRange(nums1, 11)) // [-1, -1] print(Solution().searchRange([1], 1)) // [0, 0] print(Solution().searchRange([1], 9)) // [-1, -1] print(Solution().searchRange([1, 1], 1)) // [0, 1] print(Solution().searchRange([1, 1], 9)) // [-1, -1] }
mit
a86047777414352e7a657045c9ae7bde
22.03012
117
0.476066
3.08058
false
false
false
false
tranhieutt/Dollar.swift
Dollar/Dollar/Dollar.swift
7
52715
// // ___ ___ __ ___ ________ _________ // _|\ \__|\ \ |\ \|\ \|\ _____\\___ ___\ // |\ ____\ \ \ \ \ \ \ \ \ \__/\|___ \ \_| // \ \ \___|\ \ \ __\ \ \ \ \ \ __\ \ \ \ // \ \_____ \ \ \|\__\_\ \ \ \ \ \_| \ \ \ // \|____|\ \ \____________\ \__\ \__\ \ \__\ // ____\_\ \|____________|\|__|\|__| \|__| // |\___ __\ // \|___|\__\_| // \|__| // // Dollar.swift // $ - A functional tool-belt for Swift Language // // Created by Ankur Patel on 6/3/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation public class $ { /// ___ ___ _______ ___ ________ _______ ________ /// |\ \|\ \|\ ___ \ |\ \ |\ __ \|\ ___ \ |\ __ \ /// \ \ \\\ \ \ __/|\ \ \ \ \ \|\ \ \ __/|\ \ \|\ \ /// \ \ __ \ \ \_|/_\ \ \ \ \ ____\ \ \_|/_\ \ _ _\ /// \ \ \ \ \ \ \_|\ \ \ \____\ \ \___|\ \ \_|\ \ \ \\ \| /// \ \__\ \__\ \_______\ \_______\ \__\ \ \_______\ \__\\ _\ /// \|__|\|__|\|_______|\|_______|\|__| \|_______|\|__|\|__| /// /// Creates a function that executes passed function only after being called n times. /// /// :param n Number of times after which to call function. /// :param function Function to be called that takes params. /// :return Function that can be called n times after which the callback function is called. public class func after<T, E>(n: Int, function: (T...) -> E) -> ((T...) -> E?) { var counter = n return { (params: T...) -> E? in typealias Function = [T] -> E if --counter <= 0 { let f = unsafeBitCast(function, Function.self) return f(params) } return .None } } /// Creates a function that executes passed function only after being called n times. /// /// :param n Number of times after which to call function. /// :param function Function to be called that does not take any params. /// :return Function that can be called n times after which the callback function is called. public class func after<T>(n: Int, function: () -> T) -> (() -> T?) { let f = self.after(n) { (params: Any?...) -> T in return function() } return { f() } } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// :param array The array to source from /// :param indexes Get elements from these indexes /// :return New array with elements from the indexes specified. public class func at<T>(array: [T], indexes: Int...) -> [T] { return self.at(array, indexes: indexes) } /// Creates an array of elements from the specified indexes, or keys, of the collection. /// Indexes may be specified as individual arguments or as arrays of indexes. /// /// :param array The array to source from /// :param indexes Get elements from these indexes /// :return New array with elements from the indexes specified. public class func at<T>(array: [T], indexes: [Int]) -> [T] { var result: [T] = [] for index in indexes { result.append(array[index]) } return result } /// Creates a function that, when called, invokes func with the binding of arguments provided. /// /// :param function Function to be bound. /// :param parameters Parameters to be passed into the function when being invoked. /// :return A new function that when called will invoked the passed function with the parameters specified. public class func bind<T, E>(function: (T...) -> E, _ parameters: T...) -> (() -> E) { return { () -> E in typealias Function = [T] -> E let f = unsafeBitCast(function, Function.self) return f(parameters) } } /// Creates an array of elements split into groups the length of size. /// If array can’t be split evenly, the final chunk will be the remaining elements. /// /// :param array to chunk /// :param size size of each chunk /// :return array elements chunked public class func chunk<T>(array: [T], size: Int = 1) -> [[T]] { var result = [[T]]() var chunk = -1 for (index, elem) in enumerate(array) { if index % size == 0 { result.append([T]()) chunk += 1 } result[chunk].append(elem) } return result } /// Creates an array with all nil values removed. /// /// :param array Array to be compacted. /// :return A new array that doesnt have any nil values. public class func compact<T>(array: [T?]) -> [T] { var result: [T] = [] for elem in array { if let val = elem { result.append(val) } } return result } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// :param functions - list of functions /// :return A function that can be called with variadic parameters of values public class func compose<T>(functions: ((T...) -> [T])...) -> ((T...) -> [T]) { typealias Function = [T] -> [T] return { var result = $0 for fun in functions { let f = unsafeBitCast(fun, Function.self) result = f(result) } return result } } /// Compose two or more functions passing result of the first function /// into the next function until all the functions have been evaluated /// /// :param functions - list of functions /// :return A function that can be called with array of values public class func compose<T>(functions: ([T] -> [T])...) -> ([T] -> [T]) { return { var result = $0 for fun in functions { result = fun(result) } return result } } /// Checks if a given value is present in the array. /// /// :param array The array to check against. /// :param value The value to check. /// :return Whether value is in the array. public class func contains<T : Equatable>(array: [T], value: T) -> Bool { return Swift.contains(array, value) } /// Create a copy of an array /// /// :param array The array to copy /// :return New copy of array public class func copy<T>(array: [T]) -> [T] { var newArr : [T] = [] for elem in array { newArr.append(elem) } return newArr } /// Cycles through the array indefinetly passing each element into the callback function /// /// :param array to cycle through /// :param callback function to call with the element public class func cycle<T, U>(array: [T], callback: (T) -> (U)) { while true { for elem in array { callback(elem) } } } /// Cycles through the array n times passing each element into the callback function /// /// :param array to cycle through /// :param times Number of times to cycle through the array /// :param callback function to call with the element public class func cycle<T, U>(array: [T], _ times: Int, callback: (T) -> (U)) { var i = 0 while i++ < times { for elem in array { callback(elem) } } } /// Creates an array excluding all values of the provided arrays. /// /// :param arrays The arrays to difference between. /// :return The difference between the first array and all the remaining arrays from the arrays params. public class func difference<T : Hashable>(arrays: [T]...) -> [T] { var result : [T] = [] var map : [T: Int] = [T: Int]() let firstArr : [T] = self.first(arrays)! let restArr : [[T]] = self.rest(arrays) as [[T]] for elem in firstArr { if let val = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } for arr in restArr { for elem in arr { map.removeValueForKey(elem) } } for (key, count) in map { for _ in 0..<count { result.append(key) } } return result } /// Call the callback passing each element in the array /// /// :param array The array to iterate over /// :param callback function that gets called with each item in the array /// :return The array passed public class func each<T>(array: [T], callback: (T) -> ()) -> [T] { for elem in array { callback(elem) } return array } /// Call the callback passing index of the element and each element in the array /// /// :param array The array to iterate over /// :param callback function that gets called with each item in the array with its index /// :return The array passed public class func each<T>(array: [T], callback: (Int, T) -> ()) -> [T] { for (index, elem : T) in enumerate(array) { callback(index, elem) } return array } /// Checks if two optionals containing Equatable types are equal. /// /// :param value The first optional to check. /// :param other The second optional to check. /// :return: true if the optionals contain two equal values, or both are nil; false otherwise. public class func equal<T: Equatable>(value: T?, _ other: T?) -> Bool { switch (value, other) { case (.None, .None): return true case (.None, .Some(_)): return false case (.Some(_), .None): return false case (.Some(let unwrappedValue), .Some(let otherUnwrappedValue)): return unwrappedValue == otherUnwrappedValue } } /// Checks if the given callback returns true value for all items in the array. /// /// :param array The array to check. /// :param callback Check whether element value is true or false. /// :return First element from the array. public class func every<T>(array: [T], callback: (T) -> Bool) -> Bool { for elem in array { if !callback(elem) { return false } } return true } /// Get element from an array at the given index which can be negative /// to find elements from the end of the array /// /// :param array The array to fetch from /// :param index Can be positive or negative to find from end of the array /// :param orElse Default value to use if index is out of bounds /// :return Element fetched from the array or the default value passed in orElse public class func fetch<T>(array: [T], _ index: Int, orElse: T? = .None) -> T! { if index < 0 && -index < array.count { return array[array.count + index] } else if index < array.count { return array[index] } else { return orElse } } /// Fills elements of array with value from start up to, but not including, end. /// /// :param array to fill /// :param elem the element to replace /// :return array elements chunked public class func fill<T>(inout array: [T], withElem elem: T, startIndex: Int = 0, endIndex: Int? = .None) -> [T] { let endIndex = endIndex ?? array.count for (index, _) in enumerate(array) { if index > endIndex { break } if index >= startIndex && index <= endIndex { array[index] = elem } } return array } /// Iterates over elements of an array and returning the first element /// that the callback returns true for. /// /// :param array The array to search for the element in. /// :param callback The callback function to tell whether element is found. /// :return Optional containing either found element or nil. public class func find<T>(array: [T], callback: (T) -> Bool) -> T? { for elem in array { let result = callback(elem) if result { return elem } } return .None } /// This method is like find except that it returns the index of the first element /// that passes the callback check. /// /// :param array The array to search for the element in. /// :param callback Function used to figure out whether element is the same. /// :return First element's index from the array found using the callback. public class func findIndex<T>(array: [T], callback: (T) -> Bool) -> Int? { for (index, elem : T) in enumerate(array) { if callback(elem) { return index } } return .None } /// This method is like findIndex except that it iterates over elements of the array /// from right to left. /// /// :param array The array to search for the element in. /// :param callback Function used to figure out whether element is the same. /// :return Last element's index from the array found using the callback. public class func findLastIndex<T>(array: [T], callback: (T) -> Bool) -> Int? { let count = array.count for (index, _) in enumerate(array) { let reverseIndex = count - (index + 1) let elem : T = array[reverseIndex] if callback(elem) { return reverseIndex } } return .None } /// Gets the first element in the array. /// /// :param array The array to wrap. /// :return First element from the array. public class func first<T>(array: [T]) -> T? { if array.isEmpty { return .None } else { return array[0] } } /// Gets the second element in the array. /// /// :param array The array to wrap. /// :return Second element from the array. public class func second<T>(array: [T]) -> T? { if array.count < 2 { return .None } else { return array[1] } } /// Gets the third element in the array. /// /// :param array The array to wrap. /// :return Third element from the array. public class func third<T>(array: [T]) -> T? { if array.count < 3 { return .None } else { return array[2] } } /// Flattens a nested array of any depth. /// /// :param array The array to flatten. /// :return Flattened array. public class func flatten<T>(array: [T]) -> [T] { var resultArr: [T] = [] for elem : T in array { if let val = elem as? [T] { resultArr += self.flatten(val) } else { resultArr.append(elem) } } return resultArr } /// Maps a function that converts elements to a list and then concatenates them. /// /// :param array The array to map. /// :return The array with the transformed values concatenated together. public class func flatMap<T, U>(array: [T], f: (T) -> ([U])) -> [U] { return array.map(f).reduce([], combine: +) } /// Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional. /// /// :param array The array to map. /// :return The array with the transformed values concatenated together. public class func flatMap<T, U>(value: T?, f: (T) -> (U?)) -> U? { if let unwrapped = value.map(f) { return unwrapped } else { return .None } } /// Returns size of the array /// /// :param array The array to size. /// :return size of the array public class func size<T>(array: [T]) -> Int { return array.count } /// Randomly shuffles the elements of an array. /// /// :param array The array to shuffle. /// :return Shuffled array public class func shuffle<T>(array: [T]) -> [T] { var newArr = self.copy(array) // Implementation of Fisher-Yates shuffle // http://en.wikipedia.org/wiki/Fisher-Yates_Shuffle for index in 0..<array.count { var randIndex = self.random(index) // We use in-out parameters to swap the internals of the array Swift.swap(&newArr[index], &newArr[randIndex]) } return newArr } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. /// /// :param array The array to source from. /// :return Dictionary that contains the key generated from the element passed in the function. public class func frequencies<T>(array: [T]) -> [T: Int] { return self.frequencies(array) { $0 } } /// This method returns a dictionary of values in an array mapping to the /// total number of occurrences in the array. If passed a function it returns /// a frequency table of the results of the given function on the arrays elements. /// /// :param array The array to source from. /// :param function The function to get value of the key for each element to group by. /// :return Dictionary that contains the key generated from the element passed in the function. public class func frequencies<T, U: Equatable>(array: [T], function: (T) -> U) -> [U: Int] { var result = [U: Int]() for elem in array { let key = function(elem) if let freq = result[key] { result[key] = freq + 1 } else { result[key] = 1 } } return result } /// The identity function. Returns the argument it is given. /// /// :param arg Value to return /// :return Argument that was passed public class func id<T>(arg: T) -> T { return arg } /// Gets the index at which the first occurrence of value is found. /// /// :param array The array to source from. /// :param value Value whose index needs to be found. /// :return Index of the element otherwise returns nil if not found. public class func indexOf<T: Equatable>(array: [T], value: T) -> Int? { return self.findIndex(array) { $0 == value } } /// Gets all but the last element or last n elements of an array. /// /// :param array The array to source from. /// :param numElements The number of elements to ignore in the end. /// :return Array of initial values. public class func initial<T>(array: [T], numElements: Int = 1) -> [T] { var result: [T] = [] if (array.count > numElements && numElements >= 0) { for index in 0..<(array.count - numElements) { result.append(array[index]) } } return result } /// Creates an array of unique values present in all provided arrays. /// /// :param arrays The arrays to perform an intersection on. /// :return Intersection of all arrays passed. public class func intersection<T : Hashable>(arrays: [T]...) -> [T] { var map : [T: Int] = [T: Int]() for arr in arrays { for elem in arr { if let val : Int = map[elem] { map[elem] = val + 1 } else { map[elem] = 1 } } } var result : [T] = [] let count = arrays.count for (key, value) in map { if value == count { result.append(key) } } return result } /// Joins the elements in the array to create a concatenated element of the same type. /// /// :param array The array to join the elements of. /// :param separator The separator to join the elements with. /// :return Joined element from the array of elements. public class func join<T: ExtensibleCollectionType>(array: [T], separator: T) -> T { return Swift.join(separator, array) } /// Creates an array of keys given a dictionary. /// /// :param dictionary The dictionary to source from. /// :return Array of keys from dictionary. public class func keys<T, U>(dictionary: [T: U]) -> [T] { var result : [T] = [] for key in dictionary.keys { result.append(key) } return result } /// Gets the last element from the array. /// /// :param array The array to source from. /// :return Last element from the array. public class func last<T>(array: [T]) -> T? { if array.isEmpty { return .None } else { return array[array.count - 1] } } /// Gets the index at which the last occurrence of value is found. /// /// param: array:: The array to source from. /// :param value The value whose last index needs to be found. /// :return Last index of element if found otherwise returns nil. public class func lastIndexOf<T: Equatable>(array: [T], value: T) -> Int? { return self.findLastIndex(array) { $0 == value } } /// Maps each element to new value based on the map function passed /// /// :param collection The collection to source from /// :param transform The mapping function /// :return Array of elements mapped using the map function public class func map<T : CollectionType, E>(collection: T, transform: (T.Generator.Element) -> E) -> [E] { return Swift.map(collection, transform) } /// Maps each element to new value based on the map function passed /// /// :param sequence The sequence to source from /// :param transform The mapping function /// :return Array of elements mapped using the map function public class func map<T : SequenceType, E>(sequence: T, transform: (T.Generator.Element) -> E) -> [E] { return Swift.map(sequence, transform) } /// Retrieves the maximum value in an array. /// /// :param array The array to source from. /// :return Maximum element in array. public class func max<T : Comparable>(array: [T]) -> T? { if var maxVal = array.first { for elem in array { if maxVal < elem { maxVal = elem } } return maxVal } return .None } /// Get memoized function to improve performance /// /// :param function The function to memoize. /// :return Memoized function public class func memoize<T: Hashable, U>(function: ((T -> U), T) -> U) -> (T -> U) { var cache = [T: U]() var funcRef: (T -> U)! funcRef = { (param : T) -> U in if let cacheVal = cache[param] { return cacheVal } else { cache[param] = function(funcRef, param) return cache[param]! } } return funcRef } /// Merge dictionaries together, later dictionaries overiding earlier values of keys. /// /// :param dictionaries The dictionaries to source from. /// :return Merged dictionary with all of its keys and values. public class func merge<T, U>(dictionaries: [T: U]...) -> [T: U] { var result = [T: U]() for dict in dictionaries { for (key, value) in dict { result[key] = value } } return result } /// Merge arrays together in the supplied order. /// /// :param arrays The arrays to source from. /// :return Array with all values merged, including duplicates. public class func merge<T>(arrays: [T]...) -> [T] { var result = [T]() for arr in arrays { result += arr } return result } /// Retrieves the minimum value in an array. /// /// :param array The array to source from. /// :return Minimum value from array. public class func min<T : Comparable>(array: [T]) -> T? { if var minVal = array.first { for elem in array { if minVal > elem { minVal = elem } } return minVal } return .None } /// A no-operation function. /// /// :return nil. public class func noop() -> () { } /// Gets the number of seconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC). /// /// :return number of seconds as double public class func now() -> NSTimeInterval { return NSDate().timeIntervalSince1970 } /// Creates a shallow clone of a dictionary excluding the specified keys. /// /// :param dictionary The dictionary to source from. /// :param keys The keys to omit from returning dictionary. /// :return Dictionary with the keys specified omitted. public class func omit<T, U>(dictionary: [T: U], keys: T...) -> [T: U] { var result : [T: U] = [T: U]() for (key, value) in dictionary { if !self.contains(keys, value: key) { result[key] = value } } return result } /// Get a wrapper function that executes the passed function only once /// /// :param function That takes variadic arguments and return nil or some value /// :return Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time public class func once<T, U>(function: (T...) -> U) -> (T...) -> U { var result: U? var onceFunc = { (params: T...) -> U in typealias Function = [T] -> U if let returnVal = result { return returnVal } else { var f = unsafeBitCast(function, Function.self) result = f(params) return result! } } return onceFunc } /// Get a wrapper function that executes the passed function only once /// /// :param function That takes variadic arguments and return nil or some value /// :return Wrapper function that executes the passed function only once /// Consecutive calls will return the value returned when calling the function first time public class func once<U>(function: () -> U) -> () -> U { var result: U? var onceFunc = { () -> U in if let returnVal = result { return returnVal } else { result = function() return result! } } return onceFunc } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return First element from the array. public class func partial<T, E> (function: (T...) -> E, _ parameters: T...) -> ((T...) -> E) { return { (params: T...) -> E in typealias Function = [T] -> E let f = unsafeBitCast(function, Function.self) return f(parameters + params) } } /// Produces an array of arrays, each containing n elements, each offset by step. /// If the final partition is not n elements long it is dropped. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partition<T>(array: [T], var n: Int, var step: Int? = .None) -> [[T]] { var result = [[T]]() if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > array.count { return [[]] } for i in self.range(from: 0, through: array.count - n, incrementBy: step!) { result.append(Array(array[i..<(i+n)] as ArraySlice<T>)) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :param pad An array of elements to pad the last partition if it is not long enough to /// contain n elements. If nil is passed or there are not enough pad elements /// the last partition may less than n elements long. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partition<T>(var array: [T], var n: Int, var step: Int? = .None, pad: [T]?) -> [[T]] { var result : [[T]] = [] if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + n if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) if end != i+n { break } } if let padding = pad { let remain = array.count % n let end = padding.count > remain ? remain : padding.count result[result.count - 1] += Array(padding[0..<end] as ArraySlice<T>) } return result } /// Produces an array of arrays, each containing n elements, each offset by step. /// /// :param array The array to partition. /// :param n The number of elements in each partition. /// :param step The number of elements to progress between each partition. Set to n if not supplied. /// :return Array partitioned into n element arrays, starting step elements apart. public class func partitionAll<T>(array: [T], var n: Int, var step: Int? = .None) -> [[T]] { var result = [[T]]() if step == .None { step = n } // If no step is supplied move n each step. if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in self.range(from: 0, to: array.count, incrementBy: step!) { var end = i + n if end > array.count { end = array.count } result.append(Array(array[i..<end] as ArraySlice<T>)) } return result } /// Applies function to each element in array, splitting it each time function returns a new value. /// /// :param array The array to partition. /// :param function Function which takes an element and produces an equatable result. /// :return Array partitioned in order, splitting via results of function. public class func partitionBy<T, U: Equatable>(array: [T], function: (T) -> U) -> [[T]] { var result = [[T]]() var lastValue: U? = .None for item in array { let value = function(item) if let lastValue = lastValue where value == lastValue { result[result.count-1].append(item) } else { result.append([item]) lastValue = value } } return result } /// Creates a shallow clone of a dictionary composed of the specified keys. /// /// :param dictionary The dictionary to source from. /// :param keys The keys to pick values from. /// :return Dictionary with the key and values picked from the keys specified. public class func pick<T, U>(dictionary: [T: U], keys: T...) -> [T: U] { var result : [T: U] = [T: U]() for key in keys { result[key] = dictionary[key] } return result } /// Retrieves the value of a specified property from all elements in the array. /// /// :param array The array to source from. /// :param value The property on object to pull out value from. /// :return Array of values from array of objects with property of value. public class func pluck<T, E>(array: [[T: E]], value: T) -> [E] { var result : [E] = [] for obj in array { if let val = obj[value] { result.append(val) } } return result } /// Removes all provided values from the given array. /// /// :param array The array to source from. /// :return Array with values pulled out. public class func pull<T : Equatable>(array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Removes all provided values from the given array. /// /// :param array The array to source from. /// :param values The values to remove. /// :return Array with values pulled out. public class func pull<T : Equatable>(array: [T], values: [T]) -> [T] { return array.filter { !self.contains(values, value: $0) } } /// Removes all provided values from the given array at the given indices /// /// :param array The array to source from. /// :param values The indices to remove from. /// :return Array with values pulled out. public class func pullAt<T : Equatable>(array: [T], indices: Int...) -> [T] { var elemToRemove = [T]() for index in indices { elemToRemove.append(array[index]) } return $.pull(array, values: elemToRemove) } public class func random(upperBound: Int) -> Int { return Int(arc4random_uniform(UInt32(upperBound))) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param endVal End value of range. /// :return Array of elements based on the sequence starting from 0 to endVal and incremented by 1. public class func range<T : Strideable where T : IntegerLiteralConvertible>(endVal: T) -> [T] { return self.range(from: 0, to: endVal) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range /// :param to End value of range /// :return Array of elements based on the sequence that is incremented by 1 public class func range<T : Strideable where T.Stride : IntegerLiteralConvertible>(from startVal: T, to endVal: T) -> [T] { return self.range(from: startVal, to: endVal, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range. /// :param to End value of range. /// :param incrementBy Increment sequence by. /// :return Array of elements based on the sequence. public class func range<T : Strideable>(from startVal: T, to endVal: T, incrementBy: T.Stride) -> [T] { var range = Swift.stride(from: startVal, to: endVal, by: incrementBy) return self.sequence(range) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range /// :param through End value of range /// :return Array of elements based on the sequence that is incremented by 1 public class func range<T : Strideable where T.Stride : IntegerLiteralConvertible>(from startVal: T, through endVal: T) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: 1) } /// Creates an array of numbers (positive and/or negative) progressing from start up to but not including end. /// /// :param from Start value of range. /// :param through End value of range. /// :param incrementBy Increment sequence by. /// :return Array of elements based on the sequence. public class func range<T : Strideable>(from startVal: T, through endVal: T, incrementBy: T.Stride) -> [T] { return self.range(from: startVal, to: endVal + 1, incrementBy: incrementBy) } /// Reduce function that will resolve to one value after performing combine function on all elements /// /// :param array The array to source from. /// :param initial Initial value to seed the reduce function with /// :param combine Function that will combine the passed value with element in the array /// :return The result of reducing all of the elements in the array into one value public class func reduce<U, T>(array: [T], initial: U, combine: (U, T) -> U) -> U { return array.reduce(initial, combine: combine) } /// Creates an array of an arbitrary sequence. Especially useful with builtin ranges. /// /// :param seq The sequence to generate from. /// :return Array of elements generated from the sequence. public class func sequence<S : SequenceType>(seq: S) -> [S.Generator.Element] { return Array<S.Generator.Element>(seq) } /// Removes all elements from an array that the callback returns true. /// /// :param array The array to wrap. /// :param callback Remove elements for which callback returns true. /// :return Array with elements filtered out. public class func remove<T>(array: [T], callback: (T) -> Bool) -> [T] { return array.filter { !callback($0) } } /// Removes an element from an array. /// /// :param array The array to source from. /// :param element Element that is to be removed /// :return Array with element removed. public class func remove<T: Equatable>(array: [T], value: T) -> [T] { return self.remove(array, callback: {$0 == value}) } /// The opposite of initial this method gets all but the first element or first n elements of an array. /// /// :param array The array to source from. /// :param numElements The number of elements to exclude from the beginning. /// :return The rest of the elements. public class func rest<T>(array: [T], numElements: Int = 1) -> [T] { var result : [T] = [] if (numElements < array.count && numElements >= 0) { for index in numElements..<array.count { result.append(array[index]) } } return result } /// Returns a sample from the array. /// /// :param array The array to sample from. /// :return Random element from array. public class func sample<T>(array: [T]) -> T { return array[self.random(array.count)] } /// Slices the array based on the start and end position. If an end position is not specified it will slice till the end of the array. /// /// :param array The array to slice. /// :param start Start index. /// :param end End index. /// :return First element from the array. public class func slice<T>(array: [T], start: Int, end: Int = 0) -> [T] { var uend = end; if (uend == 0) { uend = array.count; } if end > array.count || start > array.count || uend < start { return []; } else { return Array(array[start..<uend]); } } /// Gives the smallest index at which a value should be inserted into a given the array is sorted. /// /// :param array The array to source from. /// :param value Find sorted index of this value. /// :return Index of where the elemnt should be inserted. public class func sortedIndex<T : Comparable>(array: [T], value: T) -> Int { for (index, elem) in enumerate(array) { if elem > value { return index } } return array.count } /// Invokes interceptor with the object and then returns object. /// /// :param object Object to tap into. /// :param function Callback function to invoke. /// :return Returns the object back. public class func tap<T>(object: T, function: (T) -> ()) -> T { function(object) return object } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time. /// :return Values returned from callback function. public class func times<T>(n: Int, function: () -> T) -> [T] { return self.times(n) { (index: Int) -> T in return function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time. public class func times(n: Int, function: () -> ()) { self.times(n) { (index: Int) -> () in function() } } /// Call a function n times and also passes the index. If a value is returned /// in the function then the times method will return an array of those values. /// /// :param n Number of times to call function. /// :param function The function to be called every time that takes index. /// :return Values returned from callback function. public class func times<T>(n: Int, function: (Int) -> T) -> [T] { var result : [T] = [] for index in (0..<n) { result.append(function(index)) } return result } /// Creates an array of unique values, in order, of the provided arrays. /// /// :param arrays The arrays to perform union on. /// :return Resulting array after union. public class func union<T : Hashable>(arrays: [T]...) -> [T] { var result : [T] = [] for arr in arrays { result += arr } return self.uniq(result) } /// Creates a duplicate-value-free version of an array. /// /// :param array The array to source from. /// :return An array with unique values. public class func uniq<T : Hashable>(array: [T]) -> [T] { var result: [T] = [] var map: [T: Bool] = [T: Bool]() for elem in array { if map[elem] == .None { result.append(elem) } map[elem] = true } return result } /// Create a duplicate-value-free version of an array based on the condition. /// Uses the last value generated by the condition function /// /// :param array The array to source from. /// :param condition Called per iteration /// :return An array with unique values. public class func uniq<T: Hashable, U: Hashable>(array: [T], by condition: (T) -> U) -> [T] { var result: [T] = [] var map : [U: Bool] = [U: Bool]() for elem in array { let val = condition(elem) if map[val] == .None { result.append(elem) } map[val] = true } return result } /// Creates an array of values of a given dictionary. /// /// :param dictionary The dictionary to source from. /// :return An array of values from the dictionary. public class func values<T, U>(dictionary: [T: U]) -> [U] { var result : [U] = [] for value in dictionary.values { result.append(value) } return result } /// Creates an array excluding all provided values. /// /// :param array The array to source from. /// :param values Values to exclude. /// :return Array excluding provided values. public class func without<T : Equatable>(array: [T], values: T...) -> [T] { return self.pull(array, values: values) } /// Creates an array that is the symmetric difference of the provided arrays. /// /// :param arrays The arrays to perform xor on in order. /// :return Resulting array after performing xor. public class func xor<T : Hashable>(arrays: [T]...) -> [T] { var map : [T: Bool] = [T: Bool]() for arr in arrays { for elem in arr { map[elem] = !(map[elem] ?? false) } } var result : [T] = [] for (key, value) in map { if value { result.append(key) } } return result } /// Creates an array of grouped elements, the first of which contains the first elements /// of the given arrays. /// /// :param arrays The arrays to be grouped. /// :return An array of grouped elements. public class func zip<T>(arrays: [T]...) -> [[T]] { var result: [[T]] = [] for _ in self.first(arrays)! as [T] { result.append([] as [T]) } for (index, array) in enumerate(arrays) { for (elemIndex, elem : T) in enumerate(array) { result[elemIndex].append(elem) } } return result } /// Creates an object composed from arrays of keys and values. /// /// :param keys The array of keys. /// :param values The array of values. /// :return Dictionary based on the keys and values passed in order. public class func zipObject<T, E>(keys: [T], values: [E]) -> [T: E] { var result = [T: E]() for (index, key) in enumerate(keys) { result[key] = values[index] } return result } /// Returns the collection wrapped in the chain object /// /// :param collection of elements /// :return Chain object public class func chain<T>(collection: [T]) -> Chain<T> { return Chain(collection) } } // ________ ___ ___ ________ ___ ________ // |\ ____\|\ \|\ \|\ __ \|\ \|\ ___ \ // \ \ \___|\ \ \\\ \ \ \|\ \ \ \ \ \\ \ \ // \ \ \ \ \ __ \ \ __ \ \ \ \ \\ \ \ // \ \ \____\ \ \ \ \ \ \ \ \ \ \ \ \\ \ \ // \ \_______\ \__\ \__\ \__\ \__\ \__\ \__\\ \__\ // \|_______|\|__|\|__|\|__|\|__|\|__|\|__| \|__| // public class Chain<C> { private var result: Wrapper<[C]> private var funcQueue: [Wrapper<[C]> -> Wrapper<[C]>] = [] public var value: [C] { get { var result: Wrapper<[C]> = self.result for function in self.funcQueue { result = function(result) } return result.value } } /// Initializer of the wrapper object for chaining. /// /// :param array The array to wrap. public init(_ collection: [C]) { self.result = Wrapper(collection) } /// Get the first object in the wrapper object. /// /// :return First element from the array. public func first() -> C? { return $.first(self.value) } /// Get the second object in the wrapper object. /// /// :return Second element from the array. public func second() -> C? { return $.first(self.value) } /// Get the third object in the wrapper object. /// /// :return Third element from the array. public func third() -> C? { return $.first(self.value) } /// Flattens nested array. /// /// :return The wrapper object. public func flatten() -> Chain { return self.queue { return Wrapper($.flatten($0.value)) } } /// Keeps all the elements except last one. /// /// :return The wrapper object. public func initial() -> Chain { return self.initial(1) } /// Keeps all the elements except last n elements. /// /// :param numElements Number of items to remove from the end of the array. /// :return The wrapper object. public func initial(numElements: Int) -> Chain { return self.queue { return Wrapper($.initial($0.value, numElements: numElements)) } } /// Maps elements to new elements. /// /// :param function Function to map. /// :return The wrapper object. public func map(function: C -> C) -> Chain { return self.queue { var result: [C] = [] for elem: C in $0.value { result.append(function(elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func map(function: (Int, C) -> C) -> Chain { return self.queue { var result: [C] = [] for (index, elem) in enumerate($0.value) { result.append(function(index, elem)) } return Wrapper(result) } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func each(function: (C) -> ()) -> Chain { return self.queue { for elem in $0.value { function(elem) } return $0 } } /// Get the first object in the wrapper object. /// /// :param array The array to wrap. /// :return The wrapper object. public func each(function: (Int, C) -> ()) -> Chain { return self.queue { for (index, elem) in enumerate($0.value) { function(index, elem) } return $0 } } /// Filter elements based on the function passed. /// /// :param function Function to tell whether to keep an element or remove. /// :return The wrapper object. public func filter(function: (C) -> Bool) -> Chain { return self.queue { return Wrapper(($0.value).filter(function)) } } /// Returns if all elements in array are true based on the passed function. /// /// :param function Function to tell whether element value is true or false. /// :return Whether all elements are true according to func function. public func all(function: (C) -> Bool) -> Bool { return $.every(self.value, callback: function) } /// Returns if any element in array is true based on the passed function. /// /// :param function Function to tell whether element value is true or false. /// :return Whether any one element is true according to func function in the array. public func any(function: (C) -> Bool) -> Bool { var resultArr = self.value for elem in resultArr { if function(elem) { return true } } return false } /// Returns size of the array /// /// :return The wrapper object. public func size() -> Int { return self.value.count } /// Slice the array into smaller size based on start and end value. /// /// :param start Start index to start slicing from. /// :param end End index to stop slicing to and not including element at that index. /// :return The wrapper object. public func slice(start: Int, end: Int = 0) -> Chain { return self.queue { return Wrapper($.slice($0.value, start: start, end: end)) } } private func queue(function: Wrapper<[C]> -> Wrapper<[C]>) -> Chain { funcQueue.append(function) return self } } private struct Wrapper<V> { let value: V init(_ value: V) { self.value = value } }
mit
e6778183cdd3dfa4ea353609da6b5b8a
35.708217
138
0.551572
4.265841
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/YPImagePicker/Source/Pages/Gallery/YPAlbumVC.swift
1
3204
// // YPAlbumVC.swift // YPImagePicker // // Created by Sacha Durand Saint Omer on 20/07/2017. // Copyright © 2017 Yummypets. All rights reserved. // import UIKit import Stevia import Photos class YPAlbumVC: UIViewController { override var prefersStatusBarHidden: Bool { return YPConfig.hidesStatusBar } var didSelectAlbum: ((YPAlbum) -> Void)? var albums = [YPAlbum]() let albumsManager: YPAlbumsManager let v = YPAlbumView() override func loadView() { view = v } required init(albumsManager: YPAlbumsManager) { self.albumsManager = albumsManager super.init(nibName: nil, bundle: nil) title = YPConfig.wordings.albumsTitle } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: YPConfig.wordings.cancel, style: .plain, target: self, action: #selector(close)) navigationItem.leftBarButtonItem?.tintColor = YPConfig.colors.tintColor setUpTableView() fetchAlbumsInBackground() } func fetchAlbumsInBackground() { v.spinner.startAnimating() DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.albums = self?.albumsManager.fetchAlbums() ?? [] DispatchQueue.main.async { self?.v.spinner.stopAnimating() self?.v.tableView.isHidden = false self?.v.tableView.reloadData() } } } @objc func close() { dismiss(animated: true, completion: nil) } func setUpTableView() { v.tableView.isHidden = true v.tableView.dataSource = self v.tableView.delegate = self v.tableView.rowHeight = UITableView.automaticDimension v.tableView.estimatedRowHeight = 80 v.tableView.separatorStyle = .none v.tableView.register(YPAlbumCell.self, forCellReuseIdentifier: "AlbumCell") } } extension YPAlbumVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let album = albums[indexPath.row] if let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumCell", for: indexPath) as? YPAlbumCell { cell.thumbnail.backgroundColor = .ypSystemGray cell.thumbnail.image = album.thumbnail cell.title.text = album.title cell.numberOfItems.text = "\(album.numberOfItems)" return cell } return UITableViewCell() } } extension YPAlbumVC: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { didSelectAlbum?(albums[indexPath.row]) } }
mit
673673b2dc37b4c45d83c3e700b1288f
31.353535
114
0.610677
5.028257
false
false
false
false
jingchc/Mr-Ride-iOS
Mr-Ride-iOS/HistoryViewController.swift
1
9572
// // HistoryViewController.swift // Mr-Ride-iOS // // Created by 莊晶涵 on 2016/6/15. // Copyright © 2016年 AppWorks School Jing. All rights reserved. // import UIKit import CoreData import Charts class HistoryViewController: UIViewController { static var ride: Ride? = nil static var historyPage: String? = nil let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext lazy var fetchedResultsController: NSFetchedResultsController = { [unowned self] in let rideFetchRequest = NSFetchRequest(entityName: "Ride") let sortDescriptor = NSSortDescriptor(key:"date", ascending: false) rideFetchRequest.sortDescriptors = [sortDescriptor] let frc = NSFetchedResultsController( fetchRequest: rideFetchRequest, managedObjectContext: self.moc, sectionNameKeyPath: "dateForSection", cacheName: nil) frc.delegate = self return frc }() @IBOutlet weak var historyTableView: UITableView! @IBOutlet weak var backgroundImage: UIImageView! @IBOutlet weak var chartView: LineChartView! override func viewDidLoad() { super.viewDidLoad() setUp() fetchData() // checkCoreDate() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) historyTableView.reloadData() getChartViewContent() } } extension HistoryViewController { private func setUp() { // backbround self.view.backgroundColor = UIColor.mrLightblueColor() let backgroundGradientlayer = CAGradientLayer() backgroundGradientlayer.frame.size = backgroundImage.frame.size backgroundGradientlayer.colors = [UIColor.mrLightblueColor().CGColor, UIColor.pineGreen50Color().CGColor] backgroundImage.layer.addSublayer(backgroundGradientlayer) // table view historyTableView.opaque = false historyTableView.backgroundColor = UIColor.clearColor() historyTableView.showsVerticalScrollIndicator = false // navigation transparent self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.translucent = true //navigation title self.navigationItem.title = "History" // icon - right button - menu let templateMenuIcon = UIImage(named: "icon-menu")?.imageWithRenderingMode(.AlwaysTemplate) self.navigationItem.leftBarButtonItem?.tintColor = UIColor.mrWhiteColor() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: templateMenuIcon, style: .Plain, target: nil, action: nil) // side bar if self.revealViewController() != nil { self.navigationItem.leftBarButtonItem?.target = self.revealViewController() self.navigationItem.leftBarButtonItem?.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } // chart View chartView.backgroundColor = UIColor.clearColor() chartView.userInteractionEnabled = false chartView.drawGridBackgroundEnabled = false chartView.dragEnabled = false chartView.drawMarkers = false chartView.descriptionText = "" chartView.legend.enabled = false chartView.rightAxis.enabled = false chartView.leftAxis.enabled = false chartView.xAxis.drawLabelsEnabled = false chartView.xAxis.drawAxisLineEnabled = false chartView.xAxis.drawGridLinesEnabled = false } } // core data & table view extension HistoryViewController: UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate { private func fetchData() { do { try fetchedResultsController.performFetch() } catch { fatalError("fetch core data error") } } // MARK: - TableView Data Source func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let currentSection = sections[section] return currentSection.numberOfObjects } return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! HistoryTableViewCell let ride = fetchedResultsController.objectAtIndexPath(indexPath) as! Ride // cell.layoutMargins = UIEdgeInsetsMake(0, 0, 10, 0) // cell.separatorInset = UIEdgeInsetsMake(0, 0, 10, 0) let calendar = NSCalendar.currentCalendar() let components = calendar.component(.Day, fromDate: ride.date!) cell.date.text = String(components) cell.distance.text = RideInfoHelper.shared.getDistanceFormatkm(Double(ride.distance!)) cell.time.text = RideInfoHelper.shared.getTimeFormatForHistoryPage(ride.time!) //set up cell.date.font = UIFont(name: "RobotoMono-Light", size: 24) cell.th.font = UIFont(name: "RobotoMono-Light", size: 12) cell.distance.font = UIFont(name: "RobotoMono-Light", size: 24) cell.km.font = UIFont(name: "RobotoMono-Light", size: 24) cell.time.font = UIFont(name: "RobotoMono-Light", size: 24) return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let sections = fetchedResultsController.sections { let currentSection = sections[section] return currentSection.name } return nil } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let ridedata = fetchedResultsController.objectAtIndexPath(indexPath) as! Ride HistoryViewController.ride = ridedata HistoryViewController.historyPage = "HistoryPage" let statisticPage = self.storyboard?.instantiateViewControllerWithIdentifier("StatictisViewController") as! StatictisViewController self.navigationController?.pushViewController(statisticPage, animated: true) } // func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // todo: cunstom header view(cell) // } private func checkCoreDate() { let request = NSFetchRequest(entityName: "Ride") do { let results = try moc.executeFetchRequest(request) as! [Ride] for result in results { print("=============") print(result.id) print(result.time) print(result.averageSpeed) print(result.date) print(result.distance) print(result.calorie) print(result.route) print("=============") } } catch { fatalError("fail to fetch core data") } } } // chart view extension HistoryViewController { private func getChartViewContent() { // get core data let rideInfos = RideInfoModel().fetchDataFromCoreData() // date and distance array var dates: [String] = [] var distances: [Double] = [] for rideinfo in rideInfos { let date = RideInfoHelper.shared.getDateFormat(rideinfo.Date) let distance = rideinfo.Distance dates.append(date) distances.append(distance) } setChartViewContent(dates, values: distances) } private func setChartViewContent(dataPoints:[String], values:[Double]) { var dataEntries: [ChartDataEntry] = [] for i in 0..<dataPoints.count { let dataEntry = ChartDataEntry(value: values[i], xIndex: i) dataEntries.append(dataEntry) } let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "") // line attributes lineChartDataSet.drawFilledEnabled = true lineChartDataSet.drawCirclesEnabled = false lineChartDataSet.drawValuesEnabled = false lineChartDataSet.mode = .CubicBezier lineChartDataSet.lineWidth = 0.0 // chart fill attribute let gradientColors = [UIColor.mrLightblueColor().CGColor, UIColor.waterBlueColor().CGColor] let colorLocations:[CGFloat] = [0.0, 0.19] let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradientColors, colorLocations) lineChartDataSet.fill = ChartFill.fillWithLinearGradient(gradient!, angle: 90.0) let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet) chartView.data = lineChartData } }
apache-2.0
21559cc019a8ed78e41e828e5712ae82
33.648551
139
0.637561
5.556653
false
false
false
false
amnuaym/TiAppBuilder
Day5/RateMyStudentDB/RateMyStudentDB/AppDelegate.swift
1
4599
// // AppDelegate.swift // RateMyStudentDB // // Created by Amnuay M on 9/11/17. // Copyright © 2017 Amnuay M. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "RateMyStudentDB") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
b13cb64246fc3bedff54b359075a3cb4
48.44086
285
0.686168
5.835025
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
Example/Pods/KDEAudioPlayer/AudioPlayer/AudioPlayer/item/AudioItem.swift
1
7596
// // AudioItem.swift // AudioPlayer // // Created by Kevin DELANNOY on 12/03/16. // Copyright © 2016 Kevin Delannoy. All rights reserved. // import AVFoundation #if os(iOS) || os(tvOS) import UIKit import MediaPlayer public typealias Image = UIImage #else import Cocoa public typealias Image = NSImage #endif // MARK: - AudioQuality /// `AudioQuality` differentiates qualities for audio. /// /// - low: The lowest quality. /// - medium: The quality between highest and lowest. /// - high: The highest quality. public enum AudioQuality: Int { case low = 0 case medium = 1 case high = 2 } // MARK: - AudioItemURL /// `AudioItemURL` contains information about an Item URL such as its quality. public struct AudioItemURL { /// The quality of the stream. public let quality: AudioQuality /// The url of the stream. public let url: URL /// Initializes an AudioItemURL. /// /// - Parameters: /// - quality: The quality of the stream. /// - url: The url of the stream. public init?(quality: AudioQuality, url: URL?) { guard let url = url else { return nil } self.quality = quality self.url = url } } // MARK: - AudioItem /// An `AudioItem` instance contains every piece of information needed for an `AudioPlayer` to play. /// /// URLs can be remote or local. open class AudioItem: NSObject { /// Returns the available qualities. public let soundURLs: [AudioQuality: URL] // MARK: Initialization /// Initializes an AudioItem. Fails if every urls are nil. /// /// - Parameters: /// - highQualitySoundURL: The URL for the high quality sound. /// - mediumQualitySoundURL: The URL for the medium quality sound. /// - lowQualitySoundURL: The URL for the low quality sound. public convenience init?(highQualitySoundURL: URL? = nil, mediumQualitySoundURL: URL? = nil, lowQualitySoundURL: URL? = nil) { var URLs = [AudioQuality: URL]() if let highURL = highQualitySoundURL { URLs[.high] = highURL } if let mediumURL = mediumQualitySoundURL { URLs[.medium] = mediumURL } if let lowURL = lowQualitySoundURL { URLs[.low] = lowURL } self.init(soundURLs: URLs) } /// Initializes an `AudioItem`. /// /// - Parameter soundURLs: The URLs of the sound associated with its quality wrapped in a `Dictionary`. public init?(soundURLs: [AudioQuality: URL]) { self.soundURLs = soundURLs super.init() if soundURLs.isEmpty { return nil } } // MARK: Quality selection /// Returns the highest quality URL found or nil if no URLs are available open var highestQualityURL: AudioItemURL { //swiftlint:disable force_unwrapping return (AudioItemURL(quality: .high, url: soundURLs[.high]) ?? AudioItemURL(quality: .medium, url: soundURLs[.medium]) ?? AudioItemURL(quality: .low, url: soundURLs[.low]))! } /// Returns the medium quality URL found or nil if no URLs are available open var mediumQualityURL: AudioItemURL { //swiftlint:disable force_unwrapping return (AudioItemURL(quality: .medium, url: soundURLs[.medium]) ?? AudioItemURL(quality: .low, url: soundURLs[.low]) ?? AudioItemURL(quality: .high, url: soundURLs[.high]))! } /// Returns the lowest quality URL found or nil if no URLs are available open var lowestQualityURL: AudioItemURL { //swiftlint:disable force_unwrapping return (AudioItemURL(quality: .low, url: soundURLs[.low]) ?? AudioItemURL(quality: .medium, url: soundURLs[.medium]) ?? AudioItemURL(quality: .high, url: soundURLs[.high]))! } /// Returns an URL that best fits a given quality. /// /// - Parameter quality: The quality for the requested URL. /// - Returns: The URL that best fits the given quality. func url(for quality: AudioQuality) -> AudioItemURL { switch quality { case .high: return highestQualityURL case .medium: return mediumQualityURL default: return lowestQualityURL } } // MARK: Additional properties /// The artist of the item. /// /// This can change over time which is why the property is dynamic. It enables KVO on the property. open dynamic var artist: String? /// The title of the item. /// /// This can change over time which is why the property is dynamic. It enables KVO on the property. open dynamic var title: String? /// The album of the item. /// /// This can change over time which is why the property is dynamic. It enables KVO on the property. open dynamic var album: String? ///The track count of the item's album. /// /// This can change over time which is why the property is dynamic. It enables KVO on the property. open dynamic var trackCount: NSNumber? /// The track number of the item in its album. /// /// This can change over time which is why the property is dynamic. It enables KVO on the property. open dynamic var trackNumber: NSNumber? /// The artwork image of the item. open var artworkImage: Image? { get { #if os(OSX) return artwork #else return artwork?.image(at: imageSize ?? CGSize(width: 512, height: 512)) #endif } set { #if os(OSX) artwork = newValue #else imageSize = newValue?.size artwork = newValue.map { image in if #available(iOS 10.0, tvOS 10.0, *) { return MPMediaItemArtwork(boundsSize: image.size) { _ in image } } return MPMediaItemArtwork(image: image) } #endif } } /// The artwork image of the item. /// /// This can change over time which is why the property is dynamic. It enables KVO on the property. #if os(OSX) open dynamic var artwork: Image? #else open dynamic var artwork: MPMediaItemArtwork? /// The image size. private var imageSize: CGSize? #endif // MARK: Metadata /// Parses the metadata coming from the stream/file specified in the URL's. The default behavior is to set values /// for every property that is nil. Customization is available through subclassing. /// /// - Parameter items: The metadata items. open func parseMetadata(_ items: [AVMetadataItem]) { items.forEach { if let commonKey = $0.commonKey { switch commonKey { case AVMetadataCommonKeyTitle where title == nil: title = $0.value as? String case AVMetadataCommonKeyArtist where artist == nil: artist = $0.value as? String case AVMetadataCommonKeyAlbumName where album == nil: album = $0.value as? String case AVMetadataID3MetadataKeyTrackNumber where trackNumber == nil: trackNumber = $0.value as? NSNumber case AVMetadataCommonKeyArtwork where artwork == nil: artworkImage = ($0.value as? Data).flatMap { Image(data: $0) } default: break } } } } }
apache-2.0
e24ed1ee918cdac2fbc929ac2258242b
31.737069
117
0.599342
4.60303
false
false
false
false
CaryZheng/VaporDemo
Sources/App/Controllers/UserController.swift
1
2104
// // UserController.swift // App // // Created by CaryZheng on 2018/4/11. // import Vapor import FluentMySQL class UserController: RouteCollection { func boot(router: Router) throws { let routes = router.grouped("users") routes.get(use: getAllUsers) routes.get(Int.parameter, use: getSpecifiedUser) routes.get("pagelist", use: getUserPageList) routes.post(use: createUser) } // Fetch all users func getAllUsers(_ req: Request) throws -> Future<[User]> { return User.query(on: req).all() } // Fetch specified user func getSpecifiedUser(_ req: Request) throws -> Future<String> { let userId = try req.parameters.next(Int.self) return try User.query(on: req).filter(\.id == userId).first().map(to: String.self) { user in if user != nil { return ResponseWrapper(protocolCode: .success, obj: user).makeResponse() } return ResponseWrapper<DefaultResponseObj>(protocolCode: .failAccountNoExisted).makeResponse() } } // Fetch users by page func getUserPageList(_ req: Request) throws -> Future<[User]> { let pageSize = try? req.query.get(Int.self, at: "pageSize") let startPage = try? req.query.get(Int.self, at: "startPage") if let pageSize = pageSize, let startPage = startPage { let startIndex = startPage * pageSize let endIndex = startIndex + pageSize let queryRange: Range = startIndex..<endIndex return User.query(on: req).range(queryRange).all() } throw MyException.requestParamError } // Create new user func createUser(_ req: Request) throws -> Future<String> { let result = try req.content.decode(User.self).map(to: String.self) { user in try user.validate() _ = user.save(on: req) return ResponseWrapper(protocolCode: .success, obj: user).makeResponse() } return result } }
mit
60b20c759dd80a66ea719157e28ac8c2
30.878788
106
0.591255
4.329218
false
false
false
false
johntmcintosh/BarricadeKit
DevelopmentApp/Pods/Sourcery/bin/Sourcery.app/Contents/Resources/SwiftTemplateRuntime/Struct.swift
1
1651
// // Struct.swift // Sourcery // // Created by Krzysztof Zablocki on 13/09/2016. // Copyright © 2016 Pixle. All rights reserved. // import Foundation // sourcery: skipDescription /// Describes Swift struct public final class Struct: Type { /// Returns "struct" public override var kind: String { return "struct" } override init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: [String: Attribute] = [:], annotations: [String: NSObject] = [:], isGeneric: Bool = false) { super.init( name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, annotations: annotations, isGeneric: isGeneric ) } // sourcery:inline:Struct.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) } // sourcery:end }
mit
8ba1486c085813a7a4074b41560af921
28.464286
59
0.523636
5.124224
false
false
false
false
kaunteya/Linex
XcodeKit/TextRange.swift
1
1170
// // TextRange.swift // Linex // // Created by Kaunteya Suryawanshi on 19/05/18. // Copyright © 2018 Kaunteya Suryawanshi. All rights reserved. // import Foundation import XcodeKit typealias TextRange = XCSourceTextRange extension TextRange { enum Selection { case none(line: Int, column: Int) case words, lines } var selectedLines: IndexSet { switch selection { case .none, .words: return IndexSet(integer: start.line) //Complete line selection is counted multiline case .lines: return IndexSet(integersIn: start.line...(end.column == 0 ? end.line - 1 : end.line)) } } var selection: Selection { if start == end { return .none(line: start.line, column: start.column) } else if start.line == end.line { return .words } return .lines } var isSelectionEmpty: Bool { if case Selection.none(_, _) = selection { return true } return false } func updateSelection(range: TextRange) { self.start = range.start self.end = range.end } }
mit
e056d42b486f914d345d4941161af3ce
21.480769
97
0.581694
4.073171
false
false
false
false
juheon0615/HandongSwift2
HandongAppSwift/ProfessorModel.swift
3
554
// // ProfessorModel.swift // HandongAppSwift // // Created by ghost on 2015. 7. 23.. // Copyright (c) 2015년 GHOST. All rights reserved. // import Foundation class Professor{ var name: String var major: String var phone: String var email: String var office: String init (name: String, major: String, phone: String, email: String, office: String?){ self.name = name self.major = major self.phone = phone self.email = email self.office = (office != nil ? office!:"") } }
mit
be7a37eeef856051a01127a5a7f5c838
20.269231
86
0.601449
3.780822
false
false
false
false
na4lapy/Na4LapyAPI
Sources/Na4LapyCore/PaymentController.swift
1
3152
// // File.swift // Na4lapyAPI // // Created by Marek Kaluzny on 19.03.2017. // // import CryptoSwift import Kitura import SwiftyJSON import Foundation import LoggerAPI public class PaymentController { public let router = Router() private let shelterBackend: ShelterBackend private let merchant_id = "marek.kaluzny" //this should be retrieved from shelterDB private let salt = "la4cle6c" //this should be retrieved from shelterDB public init(shelterBackend: ShelterBackend) { self.shelterBackend = shelterBackend setup() } // // MARK: konfiguracja routerów // private func setup() { router.get("/form/shelter/:id", handler: onFormForShelter) router.get("/form/shelter/:id/finish", handler: onFinish) router.post("/hash", handler: onHash) } private func onFormForShelter(request: RouterRequest, response: RouterResponse, next: () -> Void) { do { if let id = request.parameters["id"], let shelterId = Int(id), let shelter: Shelter = try shelterBackend.getShelter(byId: shelterId) { try response.render("Payments/PaymentForm", context: ["merchant_id": merchant_id, "back_url": request.originalURL + "/finish", "shelterName": shelter.name]) } else { try! response.status(.internalServerError).send("Error: " + "Unable to get shelter details").end() } } catch (let error) { try! response.status(.internalServerError).send("Error: " + error.localizedDescription).end() } } private func onFinish(request: RouterRequest, response: RouterResponse, next: () -> Void) { do { try response.render("Payments/PaymentFinishForm", context: [:]) } catch (let error) { try! response.status(.internalServerError).send("Error: " + error.localizedDescription).end() } } private func onHash(request: RouterRequest, response: RouterResponse, next: () -> Void) { guard let parsedBody = request.body else { next() return } switch(parsedBody) { case .json(let json): let amount: String = json["amount"].stringValue let currency: String = json["currency"].stringValue let description: String = json["description"].stringValue let transaction_type: String = json["transaction_type"].stringValue let hash = self.calculateHash(salt: self.salt, description: description, amount: amount, currency: currency, transaction_type: transaction_type) try? response.status(.OK).send(json: JSON(["hash" : hash])).end() default: break } next() } private func calculateHash(salt: String, description: String, amount: String, currency: String, transaction_type: String) -> String { let pas: String = "\(self.salt)|\(description)|\(amount)|\(currency)|\(transaction_type)" let data = Data(Array(pas.utf8)) return data.sha1().toHexString() } }
apache-2.0
3f7d6eecd2836d5b8c70c8d04471ece1
36.511905
172
0.613139
4.438028
false
false
false
false
naokuro/sticker
Carthage/Checkouts/RapidFire/RapidFire/RapidFire.Util.swift
1
1959
// // RapidFire.Util.swift // RapidFire // // Created by keygx on 2016/11/19. // Copyright © 2016年 keygx. All rights reserved. // import Foundation extension RapidFire { public class Util { // Convert JSON to Dictionary public static func toDictionary(from data: Data?) -> [String: Any] { var dic = [String: Any]() if let jsonData = data { do { dic = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String: Any] } catch { print("Converting Failed.") } } return dic } // Convert JSON to Array public static func toArray(from data: Data?) -> [[String: Any]] { var arr = [[String: Any]]() if let jsonData = data { do { arr = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [[String: Any]] } catch { print("Converting Failed.") } } return arr } // Convert JSON to String public static func toString(from data: Data?) -> String { if let stringData = data { if let string = String(data: stringData, encoding: String.Encoding.utf8) { return string } } return "" } // Convert to JSON public static func toJSON(from object: Any) -> Data { var json = Data() do { json = try JSONSerialization.data(withJSONObject: object, options: .prettyPrinted) } catch { print("JSON Generation failed.") } return json } } }
mit
84be490829d1d309ffb786d650b75c38
27.347826
120
0.45501
5.433333
false
false
false
false
li1024316925/Swift-TimeMovie
Swift-TimeMovie/Swift-TimeMovie/CriticismCell.swift
1
1594
// // CriticismCell.swift // SwiftTimeMovie // // Created by DahaiZhang on 16/10/25. // Copyright © 2016年 LLQ. All rights reserved. // import UIKit class CriticismCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var movieImage: UIImageView! @IBOutlet weak var comment: UILabel! @IBOutlet weak var rating: UILabel! @IBOutlet weak var movieName: UILabel! @IBOutlet weak var userName: UILabel! @IBOutlet weak var userImage: UIImageView! //赋值完成后调用 var model:CriticismModel?{ didSet{ let movieImageUrl = model?.relatedObj?["image"] as! String movieImage.sd_setImage(with: URL(string: movieImageUrl)) comment.text = model?.summary title.text = model?.title userImage.sd_setImage(with: URL(string: (model?.userImage)!)) userName.text = "\((model?.nickname)!)-评" movieName.text = model?.relatedObj?["title"] as? String //评分 let aStr = NSMutableAttributedString(string: (model?.rating)!) aStr.setAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 15)], range: NSRange(location: 2, length: 1)) rating.attributedText = aStr } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
159036f147a39eacfed860346ab13a0a
29.803922
123
0.621897
4.450425
false
false
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/00144-swift-parser-consumetoken.swift
1
1227
// 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 f e) func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { class func i() } class d: f{ class func i {} class A<T : A> { } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? { for (mx : T?) in xs { func a(b:T -> T) -> T { var b: ((T, T -> T) -> T)! return b } struct A<T> { let a: [(T, () -> ())] = [] } func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } }
apache-2.0
8a1ed1fe7faf0d25afea6ed669039a70
18.790323
87
0.481663
2.655844
false
false
false
false
rodrigok/wwdc-2016-shcolarship
Rodrigo Nascimento/UIButtonRounded.swift
1
685
// // UIButtonView.swift // Rodrigo Nascimento // // Created by Rodrigo Nascimento on 23/04/16. // Copyright (c) 2016 Rodrigo Nascimento. All rights reserved. // import UIKit @IBDesignable class UIButtonRounded: UIButton { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius clipsToBounds = true } } @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } }
mit
afe2971dcfb52c0f0f2f35713570f813
21.129032
68
0.60438
4.691781
false
false
false
false
contentful/gallery-app-ios
Code/ImageDetailsViewController.swift
1
6928
// // ImageDetailsViewController.swift // Gallery // // Created by Boris Bügling on 03/03/15. // Copyright (c) 2015 Contentful GmbH. All rights reserved. // import UIKit import markymark let metaInformationHeight: CGFloat = 100.0 class ImageDetailsViewController: UIViewController, UIScrollViewDelegate { let imageView = UIImageView(frame: .zero) let metaInformationView = UITextView(frame: .zero) weak var pageViewController: UIPageViewController? let scrollView = UIScrollView(frame: .zero) init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { computeFrames() } func computeFrames() { // FIXME: switch UIDevice.current.orientation { case .portrait, .portraitUpsideDown: // TODO: leave room for metaInformationHeight scrollView.frame.size.height = view.frame.size.height - metaInformationHeight metaInformationView.frame.size.height = metaInformationHeight default: scrollView.frame.size.height = view.frame.size.height metaInformationView.frame.origin.y = view.frame.maxY } metaInformationView.frame.size.height = metaInformationHeight metaInformationView.frame.origin.y = scrollView.frame.maxY } func defaultZoom() { guard let image = imageView.image else { return } let xZoom = image.size.width / scrollView.frame.size.width let yZoom = image.size.height / scrollView.frame.size.height scrollView.zoomScale = max(xZoom, yZoom) scrollViewDidZoom(scrollView) } func statusBarStyleForBackgroundColor(color: UIColor?) -> UIBarStyle { guard let componentColors = color?.cgColor.components else { return .black } var darknessScore = componentColors[0] * 255 * 299 darknessScore += componentColors[1] * 255 * 587 darknessScore += componentColors[2] * 255 * 114 darknessScore /= 1000.0 return (darknessScore >= 125.0) ? .default : .black } func updateImage(image: UIImage?) { guard image != nil else { view.backgroundColor = .white imageView.backgroundColor = .white return } defaultZoom() DispatchQueue.global(qos: DispatchQoS.default.qosClass).async { let size = CGSize(width: 100.0, height: 100.0) UIGraphicsBeginImageContextWithOptions(size, true, 0.0) self.imageView.image?.draw(in: CGRect(origin: .zero, size: size)) DispatchQueue.main.async { self.updateNavigationBar(force: false) } } } func updateNavigationBar(force: Bool) { if let viewController = pageViewController, let firstVC = viewController.viewControllers?.first { if !force && firstVC !== self { return } if let navBar = viewController.navigationController?.navigationBar { navBar.barStyle = statusBarStyleForBackgroundColor(color: view.backgroundColor) navBar.barTintColor = view.backgroundColor } } } // TODO: Move. static func attributedMarkdownText(text: String, font: UIFont) -> NSAttributedString { let markyMark = MarkyMark() { $0.setFlavor(ContentfulFlavor()) } let markdownItems = markyMark.parseMarkDown(text) let styling = DefaultStyling() let config = MarkDownToAttributedStringConverterConfiguration(styling: styling) // Configure markymark to leverage the Contentful images API when encountering inline SVGs. let converter = MarkDownConverter(configuration: config) let attributedText = converter.convert(markdownItems) let range = NSRange(location: 0, length: attributedText.length) attributedText.addAttributes([.font: font], range: range) return attributedText } func updateText(_ text: String) { metaInformationView.attributedText = ImageDetailsViewController.attributedMarkdownText(text: text, font: UIFont.systemFont(ofSize: 14.0, weight: .regular)) metaInformationView.textColor = .white } override func viewDidLoad() { super.viewDidLoad() for view in [metaInformationView, imageView, scrollView] { view.autoresizingMask = .flexibleWidth view.frame.size.width = self.view.frame.size.width } metaInformationView.backgroundColor = .clear metaInformationView.isEditable = false metaInformationView.textContainerInset = UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0) imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFit scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.delegate = self scrollView.maximumZoomScale = 2.0 scrollView.addSubview(imageView) let recognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapped)) recognizer.numberOfTapsRequired = 2 scrollView.addGestureRecognizer(recognizer) view.addSubview(metaInformationView) view.addSubview(scrollView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) computeFrames() defaultZoom() updateNavigationBar(force: true) } // MARK: Actions @objc func doubleTapped() { UIView.animate(withDuration: 0.1) { self.defaultZoom() } } // MARK: UIScrollViewDelegate func scrollViewDidZoom(_ scrollView: UIScrollView) { let innerFrame = imageView.frame let scrollerBounds = scrollView.bounds if (innerFrame.size.width < scrollerBounds.size.width) || (innerFrame.size.height < scrollerBounds.size.height) { scrollView.contentOffset = CGPoint(x: imageView.center.x - (scrollerBounds.size.width / 2), y: imageView.center.y - (scrollerBounds.size.height / 2)) } var insets = UIEdgeInsets.zero if (scrollerBounds.size.width > innerFrame.size.width) { insets.left = (scrollerBounds.size.width - innerFrame.size.width) / 2 insets.right = -insets.left } if (scrollerBounds.size.height > innerFrame.size.height) { insets.top = (scrollerBounds.size.height - innerFrame.size.height) / 2 insets.bottom = -insets.top } scrollView.contentInset = insets } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } }
mit
a438b4a5e28274603ffefb9d858f4049
33.292079
163
0.65685
4.840671
false
false
false
false
jisudong/study
MyPlayground.playground/Pages/内存管理.xcplaygroundpage/Contents.swift
1
2514
//: [Previous](@previous) import UIKit //// Copy-on-Write //struct BezierPath { // private var _path = UIBezierPath() // var pathForReading: UIBezierPath { // return _path // } // var pathForWriting: UIBezierPath { // mutating get { // // isKnownUniquelyReferenced(&<#T##object: T##T#>)是swift方法,只能传swift引用类型对象 // if !isKnownUniquelyReferenced(&_path) { // _path = _path.copy() as! UIBezierPath // print("拷贝") // return _path // } // // print("未拷贝") // return _path // } // } //} //var bezierA = BezierPath() //bezierA.pathForWriting //var bezierB = bezierA //bezierB.pathForWriting.lineWidth = 10 //bezierA.pathForReading.lineWidth //bezierB.pathForReading.lineWidth class Box<T> { var rawValue: T init(rawValue: T) { self.rawValue = rawValue } } struct BezierPath { private var _boxOfPath = Box(rawValue: UIBezierPath()) var boxForReading: Box<UIBezierPath> { return _boxOfPath } var boxForWriting: Box<UIBezierPath> { mutating get { if !isKnownUniquelyReferenced(&_boxOfPath) { _boxOfPath = Box(rawValue: _boxOfPath.rawValue.copy() as! UIBezierPath) print("拷贝") return _boxOfPath } print("未拷贝") return _boxOfPath } } } MemoryLayout<BezierPath>.size var bezierA = BezierPath() MemoryLayout.size(ofValue: bezierA) bezierA.boxForWriting.rawValue.lineWidth = 3 var bezierB = bezierA bezierB.boxForWriting.rawValue.lineWidth = 5 bezierA.boxForWriting.rawValue.lineWidth = 10 bezierA.boxForReading.rawValue.lineWidth bezierB.boxForReading.rawValue.lineWidth // 对象中定义的方法本身以及方法的参数都不会保存在该对象的实例中, // 当闭包作为方法的参数的时候,即便闭包中会持有self,也不会引起循环引用 // 动态派发:在运行时程序会根据被调用的方法的名字去内存中的方法表中查表,找到方法的实现并执行 // 静态派发:在运行时调用方法不需要查表,直接跳到方法的代码中执行 // 内联:指在编译器把每一处方法的调用替换成直接执行方法的内部代码 // 静态派发为内联提供了支持,支持内联的方法要求方法本身必须是静态派发的 // Swift中值类型的方法是默认执行内联的
mit
f50d41c5bbce7144c88363dc570f238a
24.696203
87
0.637438
3.464164
false
false
false
false
MakiZz/30DaysToLearnSwift3.0
project 14 - emoji老虎机/project 14 - emoji老虎机/ViewController.swift
1
3993
// // ViewController.swift // project 14 - emoji老虎机 // // Created by mk on 17/3/20. // Copyright © 2017年 maki. All rights reserved. // import UIKit class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource { @IBOutlet weak var emojiPickerView: UIPickerView! @IBOutlet weak var goBtn: UIButton! @IBAction func goAction(_ sender: AnyObject) { emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 0, animated: true) emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 1, animated: true) emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 2, animated: true) if dataArray1[emojiPickerView.selectedRow(inComponent: 0)] == dataArray2[emojiPickerView.selectedRow(inComponent: 1)] && dataArray2[emojiPickerView.selectedRow(inComponent: 1)] == dataArray3[emojiPickerView.selectedRow(inComponent: 2)]{ resultLabel.text = "Bingo!" }else { resultLabel.text = "💔" } UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.1, initialSpringVelocity: 5, options: .curveLinear, animations: { self.goBtn.bounds.size.width = self.bounds.size.width + 20 }) { (compelete) in UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.goBtn.bounds = self.bounds }, completion: nil) } } @IBOutlet weak var resultLabel: UILabel! var imageArray = [String]() var dataArray1 = [Int]() var dataArray2 = [Int]() var dataArray3 = [Int]() var bounds: CGRect = CGRect.zero override func viewDidLoad() { super.viewDidLoad() bounds = goBtn.bounds imageArray = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"] for _ in 0..<100 { dataArray1.append((Int)(arc4random()%10)) dataArray2.append((Int)(arc4random()%10)) dataArray3.append((Int)(arc4random()%10)) } resultLabel.text = "" emojiPickerView.delegate = self emojiPickerView.dataSource = self goBtn.layer.cornerRadius = 5 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) goBtn.alpha = 0 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseOut, animations: { self.goBtn.alpha = 1 }, completion: nil) } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 100 } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 100.0 } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 100.0 } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let pickerLabel = UILabel() if component == 0 { pickerLabel.text = imageArray[(Int)(dataArray1[row])] }else if component == 1{ pickerLabel.text = imageArray[(Int)(dataArray2[row])] }else { pickerLabel.text = imageArray[(Int)(dataArray3[row])] } pickerLabel.font = UIFont.init(name: "Apple Color Emoji", size: 80) pickerLabel.textAlignment = NSTextAlignment.center return pickerLabel } }
mit
f3a04db931ace50b23a642cf9fa1b822
29.160305
244
0.578335
4.703571
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Laundry/Networking/LaundryAPIService.swift
1
3645
// // LaundryAPIService.swift // LaundryTester // // Created by Josh Doman on 2017/10/24. // Copyright © 2017 Penn Labs. All rights reserved. // import Foundation import SwiftyJSON class LaundryAPIService: Requestable { static let instance = LaundryAPIService() fileprivate let laundryUrl = "https://pennmobile.org/api/laundry/rooms" fileprivate let idsUrl = "https://pennmobile.org/api/laundry/halls/ids" fileprivate let statusURL = "https://pennmobile.org/api/laundry/status" public var idToRooms: [Int: LaundryRoom]? // Prepare the service func prepare(_ completion: @escaping () -> Void) { if Storage.fileExists(LaundryRoom.directory, in: .caches) { self.idToRooms = Storage.retrieve(LaundryRoom.directory, from: .caches, as: Dictionary<Int, LaundryRoom>.self) completion() } else { loadIds { (_) in DispatchQueue.main.async { completion() } } } } func clearDirectory() { Storage.remove(LaundryRoom.directory, from: .caches) } func loadIds(_ callback: @escaping (_ success: Bool) -> Void) { fetchIds { (dictionary) in self.idToRooms = dictionary if let dict = dictionary { Storage.store(dict, to: .caches, as: LaundryRoom.directory) } callback(dictionary != nil) } } private func fetchIds(callback: @escaping ([Int: LaundryRoom]?) -> Void) { getRequestData(url: idsUrl) { (data, _, _) in if let data = data, let rooms = try? JSONDecoder().decode([LaundryRoom].self, from: data) { callback(Dictionary(uniqueKeysWithValues: rooms.map { ($0.id, $0) })) } else { callback(nil) } } } } // MARK: - Fetch API extension LaundryAPIService { func fetchLaundryData(for ids: [Int], _ callback: @escaping (_ rooms: [LaundryRoom]?) -> Void) { let ids: String = ids.map { String($0) }.joined(separator: ",") let url = "\(laundryUrl)/\(ids)" getRequest(url: url) { (dict, _, _) in var rooms: [LaundryRoom]? if let dict = dict { let json = JSON(dict) let jsonArray = json["rooms"].arrayValue rooms = [LaundryRoom]() for json in jsonArray { let room = LaundryRoom(json: json) rooms?.append(room) } } callback(rooms) } } func fetchLaundryData(for rooms: [LaundryRoom], _ callback: @escaping (_ rooms: [LaundryRoom]?) -> Void) { let ids: [Int] = rooms.map { $0.id } fetchLaundryData(for: ids, callback) } } // MARK: - Laundry Status API extension LaundryAPIService { func checkIfWorking(_ callback: @escaping (_ isWorking: Bool?) -> Void) { getRequest(url: statusURL) { (dict, _, _) in if let dict = dict { let json = JSON(dict) let isWorking = json["is_working"].bool callback(isWorking) } else { callback(nil) } } } } // MARK: - Room ID Parsing extension Dictionary where Key == Int, Value == LaundryRoom { init(json: JSON) throws { guard let jsonArray = json["halls"].array else { throw NetworkingError.jsonError } self.init() for json in jsonArray { let id = json["id"].intValue let room = LaundryRoom(json: json) self[id] = room } } }
mit
8730b851b2f17ab44cf8a17786543ba6
30.964912
122
0.548847
4.140909
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Group layers/LayersTableViewController.swift
1
7483
// Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class LayersTableViewController: UITableViewController, GroupLayersCellDelegate, GroupLayersSectionViewDelegate { var layers = [AGSGroupLayer]() var tableViewContentSizeObservation: NSKeyValueObservation? override func viewDidLoad() { super.viewDidLoad() self.tableView.register(GroupLayersSectionView.nib, forHeaderFooterViewReuseIdentifier: GroupLayersSectionView.reuseIdentifier) } // Adjust the size of the table view according to its contents. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableViewContentSizeObservation = tableView.observe(\.contentSize) { [unowned self] (tableView, _) in self.preferredContentSize = CGSize(width: self.preferredContentSize.width, height: tableView.contentSize.height) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tableViewContentSizeObservation = nil } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return layers.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let groupLayer = layers[section] return groupLayer.layers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Get the group and child layer. let groupLayer = layers[indexPath.section] guard let childLayers = groupLayer.layers as? [AGSLayer] else { fatalError("Unknown child layers error") } let childLayer = childLayers[indexPath.row] switch groupLayer.visibilityMode { case .independent: let cell = tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as! GroupLayersCell // Set label. cell.layerNameLabel.text = formattedValue(of: childLayer.name) // Set state of the cell and switch. cell.isUserInteractionEnabled = groupLayer.isVisible cell.layerVisibilitySwitch.isOn = childLayer.isVisible cell.layerVisibilitySwitch.isEnabled = groupLayer.isVisible // To update the visibility of operational layers on switch toggle. cell.delegate = self return cell case .exclusive: let cell = tableView.dequeueReusableCell(withIdentifier: "exclusiveCell", for: indexPath) // Set label. cell.textLabel?.text = formattedValue(of: childLayer.name) // Enable or disable the cell accordingly. cell.isUserInteractionEnabled = groupLayer.isVisible cell.textLabel?.isEnabled = groupLayer.isVisible // Adjust the tint if the cell is enabled. cell.tintColor = view.tintColor if groupLayer.isVisible { cell.tintAdjustmentMode = .automatic } else { cell.tintAdjustmentMode = .dimmed } // Indicate which layer is visible. if childLayer.isVisible { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell default: fatalError("Unknown cell type") } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: GroupLayersSectionView.reuseIdentifier) as? GroupLayersSectionView else { return nil } let layer = layers[section] // Set label. headerView.layerNameLabel.text = formattedValue(of: layer.name) // Set the switch to on or off. headerView.layerVisibilitySwitch?.isOn = layer.isVisible // To update the visibility of operational layers on switch toggle. headerView.delegate = self return headerView } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let groupLayer = layers[indexPath.section] let childLayers = groupLayer.layers as! [AGSLayer] var indexPathsToReload = [indexPath] if let indexOfPreviouslyVisibleLayer = childLayers.firstIndex(where: { $0.isVisible }) { indexPathsToReload.append(IndexPath(row: indexOfPreviouslyVisibleLayer, section: indexPath.section)) } childLayers[indexPath.row].isVisible = true tableViewContentSizeObservation = nil tableView.reloadRows(at: indexPathsToReload, with: .automatic) } // MARK: - GroupLayersCellDelegate func didToggleSwitch(_ cell: GroupLayersCell, isOn: Bool) { guard let indexPath = tableView.indexPath(for: cell) else { return } let groupLayer = layers[indexPath.section] if let childLayers = groupLayer.layers as? [AGSLayer] { childLayers[indexPath.row].isVisible = isOn } } // MARK: - GroupLayersSectionViewDelegate func didToggleSwitch(_ sectionView: GroupLayersSectionView, isOn: Bool) { guard let section = tableView.section(forHeaderView: sectionView) else { return } layers[section].isVisible = isOn tableViewContentSizeObservation = nil tableView.reloadSections([section], with: .automatic) } // MARK: - Helper methods /// Modifies name of the layer. /// /// - Parameter name: Original name of the layer. /// - Returns: A modified name or the original name of the layer. func formattedValue(of name: String) -> String { switch name { case "DevA_Trees": return "Trees" case "DevA_Pathways": return "Pathways" case "DevA_BuildingShells": return "Buildings A" case "DevB_BuildingShells": return "Buildings B" case "DevelopmentProjectArea": return "Project Area" default: return name } } } class GroupLayersCell: UITableViewCell { @IBOutlet var layerNameLabel: UILabel! @IBOutlet var layerVisibilitySwitch: UISwitch! weak var delegate: GroupLayersCellDelegate? @IBAction func switchDidChange(_ sender: UISwitch) { delegate?.didToggleSwitch(self, isOn: sender.isOn) } } protocol GroupLayersCellDelegate: AnyObject { func didToggleSwitch(_ cell: GroupLayersCell, isOn: Bool) } extension UITableView { func section(forHeaderView headerView: UITableViewHeaderFooterView) -> Int? { return (0..<numberOfSections).first { self.headerView(forSection: $0) == headerView } } }
apache-2.0
884fab460b531d4aef495a723da6d5b7
38.592593
175
0.659228
5.18932
false
false
false
false
AccessLite/BYT-Golden
BYT/Views/FoaasView.swift
1
6980
// // FoaasView.swift // BYT // // Created by Louis Tur on 1/23/17. // Copyright © 2017 AccessLite. All rights reserved. // import UIKit protocol FoaasViewDelegate: class { func didTapActionButton() func didTapSettingsButton() } class FoaasView: UIView { internal var delegate: FoaasViewDelegate? var subtitleLabelConstraint = NSLayoutConstraint() // MARK: - Setup override init(frame: CGRect) { super.init(frame: frame) self.setupViewHierarchy() self.configureConstraints() } internal func setupViewHierarchy() { self.addSubview(resizingView) self.addSubview(addButton) self.addSubview(settingsMenuButton) resizingView.addSubview(self.mainTextLabel) resizingView.addSubview(self.subtitleTextLabel) resizingView.accessibilityIdentifier = "resizingView" addButton.accessibilityIdentifier = "addButton" settingsMenuButton.accessibilityIdentifier = "settingsMenuButton" mainTextLabel.accessibilityIdentifier = "mainTextLabel" subtitleTextLabel.accessibilityIdentifier = "subtitleTextLabel" self.backgroundColor = .purple self.settingsMenuButton.addTarget(self, action: #selector(didTapSettingsButton), for: .touchUpInside) self.addButton.addTarget(self, action: #selector(didTapButton(sender:)), for: .touchDown) } internal func configureConstraints() { stripAutoResizingMasks(self, resizingView, mainTextLabel, subtitleTextLabel , addButton, settingsMenuButton) let resizingViewConstraints = [ resizingView.leadingAnchor.constraint(equalTo: self.leadingAnchor), resizingView.trailingAnchor.constraint(equalTo: self.trailingAnchor), resizingView.topAnchor.constraint(equalTo: self.topAnchor), resizingView.bottomAnchor.constraint(equalTo: addButton.topAnchor, constant: -48.0) ] //self.subtitleLabelConstraint = subtitleTextLabel.leadingAnchor.constraint(equalTo: resizingView.leadingAnchor, constant: 225.0) self.subtitleLabelConstraint = subtitleTextLabel.leadingAnchor.constraint(greaterThanOrEqualTo: resizingView.leadingAnchor, constant: 16.0) let labelConstraints = [ mainTextLabel.leadingAnchor.constraint(equalTo: resizingView.leadingAnchor, constant: 16.0), mainTextLabel.topAnchor.constraint(equalTo: resizingView.topAnchor, constant: 16.0), mainTextLabel.trailingAnchor.constraint(equalTo: resizingView.trailingAnchor, constant: -16.0), mainTextLabel.heightAnchor.constraint(equalTo: resizingView.heightAnchor, multiplier: 0.7), subtitleLabelConstraint, //subtitleTextLabel.leadingAnchor.constraint(equalTo: resizingView.leadingAnchor, constant: 16.0), subtitleTextLabel.trailingAnchor.constraint(equalTo: resizingView.trailingAnchor, constant: -16.0), subtitleTextLabel.topAnchor.constraint(equalTo: self.mainTextLabel.bottomAnchor, constant: 16.0), subtitleTextLabel.bottomAnchor.constraint(equalTo: resizingView.bottomAnchor, constant: -16.0), ] let buttonConstraints = [ addButton.widthAnchor.constraint(equalToConstant: 54.0), addButton.heightAnchor.constraint(equalToConstant: 54.0), addButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -48.0), addButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -48.0), settingsMenuButton.centerXAnchor.constraint(equalTo: self.centerXAnchor), settingsMenuButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -20), ] let _ = [resizingViewConstraints, labelConstraints, buttonConstraints].map{ $0.map{ $0.isActive = true } } } override func layoutSubviews() { // TOOD: adjust sizing self.configureConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Actions internal func didTapButton(sender: UIButton) { let newTransform = CGAffineTransform(scaleX: 1.1, y: 1.1) let originalTransform = sender.imageView!.transform UIView.animate(withDuration: 0.1, animations: { sender.layer.transform = CATransform3DMakeAffineTransform(newTransform) }, completion: { (complete) in sender.layer.transform = CATransform3DMakeAffineTransform(originalTransform) self.delegate?.didTapActionButton() }) } internal func didTapSettingsButton() { self.delegate?.didTapSettingsButton() } // MARK: - Lazy Inits internal lazy var resizingView: UIView = { let view: UIView = UIView() view.backgroundColor = .clear return view }() // TODO: fix this label to properly expand/shrink internal lazy var mainTextLabel: UILabel = { let label = UILabel() label.text = " " //updating font and color according to PM notes label.font = UIFont.Roboto.light(size: 56.0) label.textColor = UIColor.white label.alpha = 1.0 label.textAlignment = .left label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.25 label.numberOfLines = 0 return label }() internal lazy var subtitleTextLabel: UILabel = { let label = UILabel() label.text = " " //updating font and color according to PM notes label.font = UIFont.Roboto.regular(size: 34.0) label.textColor = UIColor.white label.alpha = 0.70 //PM spec has subtitle text aligned to the left label.textAlignment = .left label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.25 label.numberOfLines = 0 return label }() internal lazy var addButton: UIButton = { let button: UIButton = UIButton(type: .custom) button.setImage(UIImage(named: "plus_symbol")!, for: .normal) button.backgroundColor = ColorManager.shared.currentColorScheme.accent button.layer.cornerRadius = 26 button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOpacity = 0.8 button.layer.shadowOffset = CGSize(width: 0, height: 5) button.layer.shadowRadius = 8 return button }() internal lazy var settingsMenuButton: UIButton = { let button = UIButton() let origImage = UIImage(named: "disclosure_up") let tintedImage = origImage?.withRenderingMode(.alwaysTemplate) button.setImage(tintedImage, for: .normal) button.tintColor = ColorManager.shared.currentColorScheme.accent return button }() }
mit
83b15a74cf99472e6966c78c7d926aad
37.558011
147
0.665855
5.075636
false
false
false
false
lattejed/Swift-ToDo
Swift-ToDo/UIAlertView+ActionClosure.swift
1
1425
// // UIAlertView+ActionClosure.swift // Swift-ToDo // // Created by Matthew Smith on 10/20/14. // Copyright (c) 2014 Matthew Smith. All rights reserved. // import Foundation import UIKit class AlertViewHelper { typealias ActionSheetFinished = (alertView: UIAlertView) -> () var finished: ActionSheetFinished init(finished: ActionSheetFinished) { self.finished = finished } } private let _helperClassKey = malloc(4) extension UIAlertView: UIAlertViewDelegate { private var helperObject: AlertViewHelper? { get { let r : AnyObject! = objc_getAssociatedObject(self, _helperClassKey) return r as? AlertViewHelper } set { objc_setAssociatedObject(self, _helperClassKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)); } } convenience init(title: String, message: String, cancelButtonTitle: String?, firstButtonTitle: String, finished:(alertView: UIAlertView) -> ()) { self.init(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: firstButtonTitle) self.delegate = self self.helperObject = AlertViewHelper(finished: finished) } public func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == 1 { self.helperObject?.finished(alertView: self) } } }
mit
9185225c5b7205c00997cb049122e7f2
30.688889
149
0.68
4.70297
false
false
false
false
grpc/grpc-swift
Sources/GRPC/GRPCClientStateMachine.swift
1
30179
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Logging import NIOCore import NIOHPACK import NIOHTTP1 import SwiftProtobuf enum ReceiveResponseHeadError: Error, Equatable { /// The 'content-type' header was missing or the value is not supported by this implementation. case invalidContentType(String?) /// The HTTP response status from the server was not 200 OK. case invalidHTTPStatus(String?) /// The encoding used by the server is not supported. case unsupportedMessageEncoding(String) /// An invalid state was encountered. This is a serious implementation error. case invalidState } enum ReceiveEndOfResponseStreamError: Error, Equatable { /// The 'content-type' header was missing or the value is not supported by this implementation. case invalidContentType(String?) /// The HTTP response status from the server was not 200 OK. case invalidHTTPStatus(String?) /// The HTTP response status from the server was not 200 OK but the "grpc-status" header contained /// a valid value. case invalidHTTPStatusWithGRPCStatus(GRPCStatus) /// An invalid state was encountered. This is a serious implementation error. case invalidState } enum SendRequestHeadersError: Error { /// An invalid state was encountered. This is a serious implementation error. case invalidState } enum SendEndOfRequestStreamError: Error { /// The request stream has already been closed. This may happen if the RPC was cancelled, timed /// out, the server terminated the RPC, or the user explicitly closed the stream multiple times. case alreadyClosed /// An invalid state was encountered. This is a serious implementation error. case invalidState } /// A state machine for a single gRPC call from the perspective of a client. /// /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md struct GRPCClientStateMachine { /// The combined state of the request (client) and response (server) streams for an RPC call. /// /// The following states are not possible: /// - `.clientIdleServerActive`: The client must initiate the call before the server moves /// from the idle state. /// - `.clientIdleServerClosed`: The client must initiate the call before the server moves from /// the idle state. /// - `.clientActiveServerClosed`: The client may not stream if the server is closed. /// /// Note: when a peer (client or server) state is "active" it means that messages _may_ be sent or /// received. That is, the headers for the stream have been processed by the state machine and /// end-of-stream has not yet been processed. A stream may expect any number of messages (i.e. up /// to one for a unary call and many for a streaming call). enum State { /// Initial state. Neither request stream nor response stream have been initiated. Holds the /// pending write state for the request stream and arity for the response stream, respectively. /// /// Valid transitions: /// - `clientActiveServerIdle`: if the client initiates the RPC, /// - `clientClosedServerClosed`: if the client terminates the RPC. case clientIdleServerIdle(pendingWriteState: PendingWriteState, readArity: MessageArity) /// The client has initiated an RPC and has not received initial metadata from the server. Holds /// the writing state for request stream and arity for the response stream. /// /// Valid transitions: /// - `clientActiveServerActive`: if the server acknowledges the RPC initiation, /// - `clientClosedServerIdle`: if the client closes the request stream, /// - `clientClosedServerClosed`: if the client terminates the RPC or the server terminates the /// RPC with a "trailers-only" response. case clientActiveServerIdle(writeState: WriteState, pendingReadState: PendingReadState) /// The client has indicated to the server that it has finished sending requests. The server /// has not yet sent response headers for the RPC. Holds the response stream arity. /// /// Valid transitions: /// - `clientClosedServerActive`: if the server acknowledges the RPC initiation, /// - `clientClosedServerClosed`: if the client terminates the RPC or the server terminates the /// RPC with a "trailers-only" response. case clientClosedServerIdle(pendingReadState: PendingReadState) /// The client has initiated the RPC and the server has acknowledged it. Messages may have been /// sent and/or received. Holds the request stream write state and response stream read state. /// /// Valid transitions: /// - `clientClosedServerActive`: if the client closes the request stream, /// - `clientClosedServerClosed`: if the client or server terminates the RPC. case clientActiveServerActive(writeState: WriteState, readState: ReadState) /// The client has indicated to the server that it has finished sending requests. The server /// has acknowledged the RPC. Holds the response stream read state. /// /// Valid transitions: /// - `clientClosedServerClosed`: if the client or server terminate the RPC. case clientClosedServerActive(readState: ReadState) /// The RPC has terminated. There are no valid transitions from this state. case clientClosedServerClosed /// This isn't a real state. See `withStateAvoidingCoWs`. case modifying } /// The current state of the state machine. internal private(set) var state: State /// The default user-agent string. private static let userAgent = "grpc-swift-nio/\(Version.versionString)" /// Creates a state machine representing a gRPC client's request and response stream state. /// /// - Parameter requestArity: The expected number of messages on the request stream. /// - Parameter responseArity: The expected number of messages on the response stream. init(requestArity: MessageArity, responseArity: MessageArity) { self.state = .clientIdleServerIdle( pendingWriteState: .init(arity: requestArity, contentType: .protobuf), readArity: responseArity ) } /// Creates a state machine representing a gRPC client's request and response stream state. /// /// - Parameter state: The initial state of the state machine. init(state: State) { self.state = state } /// Initiates an RPC. /// /// The only valid state transition is: /// - `.clientIdleServerIdle` → `.clientActiveServerIdle` /// /// All other states will result in an `.invalidState` error. /// /// On success the state will transition to `.clientActiveServerIdle`. /// /// - Parameter requestHead: The client request head for the RPC. mutating func sendRequestHeaders( requestHead: _GRPCRequestHead ) -> Result<HPACKHeaders, SendRequestHeadersError> { return self.withStateAvoidingCoWs { state in state.sendRequestHeaders(requestHead: requestHead) } } /// Formats a request to send to the server. /// /// The client must be streaming in order for this to return successfully. Therefore the valid /// state transitions are: /// - `.clientActiveServerIdle` → `.clientActiveServerIdle` /// - `.clientActiveServerActive` → `.clientActiveServerActive` /// /// The client should not attempt to send requests once the request stream is closed, that is /// from one of the following states: /// - `.clientClosedServerIdle` /// - `.clientClosedServerActive` /// - `.clientClosedServerClosed` /// Doing so will result in a `.cardinalityViolation`. /// /// Sending a message when both peers are idle (in the `.clientIdleServerIdle` state) will result /// in a `.invalidState` error. /// /// - Parameter message: The serialized request to send to the server. /// - Parameter compressed: Whether the request should be compressed. /// - Parameter allocator: A `ByteBufferAllocator` to allocate the buffer into which the encoded /// request will be written. mutating func sendRequest( _ message: ByteBuffer, compressed: Bool, allocator: ByteBufferAllocator ) -> Result<ByteBuffer, MessageWriteError> { return self.withStateAvoidingCoWs { state in state.sendRequest(message, compressed: compressed, allocator: allocator) } } /// Closes the request stream. /// /// The client must be streaming requests in order to terminate the request stream. Valid /// states transitions are: /// - `.clientActiveServerIdle` → `.clientClosedServerIdle` /// - `.clientActiveServerActive` → `.clientClosedServerActive` /// /// The client should not attempt to close the request stream if it is already closed, that is /// from one of the following states: /// - `.clientClosedServerIdle` /// - `.clientClosedServerActive` /// - `.clientClosedServerClosed` /// Doing so will result in an `.alreadyClosed` error. /// /// Closing the request stream when both peers are idle (in the `.clientIdleServerIdle` state) /// will result in a `.invalidState` error. mutating func sendEndOfRequestStream() -> Result<Void, SendEndOfRequestStreamError> { return self.withStateAvoidingCoWs { state in state.sendEndOfRequestStream() } } /// Receive an acknowledgement of the RPC from the server. This **must not** be a "Trailers-Only" /// response. /// /// The server must be idle in order to receive response headers. The valid state transitions are: /// - `.clientActiveServerIdle` → `.clientActiveServerActive` /// - `.clientClosedServerIdle` → `.clientClosedServerActive` /// /// The response head will be parsed and validated against the gRPC specification. The following /// errors may be returned: /// - `.invalidHTTPStatus` if the status was not "200", /// - `.invalidContentType` if the "content-type" header does not start with "application/grpc", /// - `.unsupportedMessageEncoding` if the "grpc-encoding" header is not supported. /// /// It is not possible to receive response headers from the following states: /// - `.clientIdleServerIdle` /// - `.clientActiveServerActive` /// - `.clientClosedServerActive` /// - `.clientClosedServerClosed` /// Doing so will result in a `.invalidState` error. /// /// - Parameter headers: The headers received from the server. mutating func receiveResponseHeaders( _ headers: HPACKHeaders ) -> Result<Void, ReceiveResponseHeadError> { return self.withStateAvoidingCoWs { state in state.receiveResponseHeaders(headers) } } /// Read a response buffer from the server and return any decoded messages. /// /// If the response stream has an expected count of `.one` then this function is guaranteed to /// produce *at most* one `Response` in the `Result`. /// /// To receive a response buffer the server must be streaming. Valid states are: /// - `.clientClosedServerActive` → `.clientClosedServerActive` /// - `.clientActiveServerActive` → `.clientActiveServerActive` /// /// This function will read all of the bytes in the `buffer` and attempt to produce as many /// messages as possible. This may lead to a number of errors: /// - `.cardinalityViolation` if more than one message is received when the state reader is /// expects at most one. /// - `.leftOverBytes` if bytes remain in the buffer after reading one message when at most one /// message is expected. /// - `.deserializationFailed` if the message could not be deserialized. /// /// It is not possible to receive response headers from the following states: /// - `.clientIdleServerIdle` /// - `.clientClosedServerActive` /// - `.clientActiveServerActive` /// - `.clientClosedServerClosed` /// Doing so will result in a `.invalidState` error. /// /// - Parameter buffer: A buffer of bytes received from the server. mutating func receiveResponseBuffer( _ buffer: inout ByteBuffer, maxMessageLength: Int ) -> Result<[ByteBuffer], MessageReadError> { return self.withStateAvoidingCoWs { state in state.receiveResponseBuffer(&buffer, maxMessageLength: maxMessageLength) } } /// Receive the end of the response stream from the server and parse the results into /// a `GRPCStatus`. /// /// To close the response stream the server must be streaming or idle (since the server may choose /// to 'fast fail' the RPC). Valid states are: /// - `.clientActiveServerIdle` → `.clientClosedServerClosed` /// - `.clientActiveServerActive` → `.clientClosedServerClosed` /// - `.clientClosedServerIdle` → `.clientClosedServerClosed` /// - `.clientClosedServerActive` → `.clientClosedServerClosed` /// /// It is not possible to receive an end-of-stream if the RPC has not been initiated or has /// already been terminated. That is, in one of the following states: /// - `.clientIdleServerIdle` /// - `.clientClosedServerClosed` /// Doing so will result in a `.invalidState` error. /// /// - Parameter trailers: The trailers to parse. mutating func receiveEndOfResponseStream( _ trailers: HPACKHeaders ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> { return self.withStateAvoidingCoWs { state in state.receiveEndOfResponseStream(trailers) } } /// Receive a DATA frame with the end stream flag set. Determines whether it is safe for the /// caller to ignore the end stream flag or whether a synthesised status should be forwarded. /// /// Receiving a DATA frame with the end stream flag set is unexpected: the specification dictates /// that an RPC should be ended by the server sending the client a HEADERS frame with end stream /// set. However, we will tolerate end stream on a DATA frame if we believe the RPC has already /// completed (i.e. we are in the 'clientClosedServerClosed' state). In cases where we don't /// expect end of stream on a DATA frame we will emit a status with a message explaining /// the protocol violation. mutating func receiveEndOfResponseStream() -> GRPCStatus? { return self.withStateAvoidingCoWs { state in state.receiveEndOfResponseStream() } } /// Temporarily sets `self.state` to `.modifying` before calling the provided block and setting /// `self.state` to the `State` modified by the block. /// /// Since we hold state as associated data on our `State` enum, any modification to that state /// will trigger a copy on write for its heap allocated data. Temporarily setting the `self.state` /// to `.modifying` allows us to avoid an extra reference to any heap allocated data and therefore /// avoid a copy on write. @inline(__always) private mutating func withStateAvoidingCoWs<ResultType>( _ body: (inout State) -> ResultType ) -> ResultType { var state = State.modifying swap(&self.state, &state) defer { swap(&self.state, &state) } return body(&state) } } extension GRPCClientStateMachine.State { /// See `GRPCClientStateMachine.sendRequestHeaders(requestHead:)`. mutating func sendRequestHeaders( requestHead: _GRPCRequestHead ) -> Result<HPACKHeaders, SendRequestHeadersError> { let result: Result<HPACKHeaders, SendRequestHeadersError> switch self { case let .clientIdleServerIdle(pendingWriteState, responseArity): let headers = self.makeRequestHeaders( method: requestHead.method, scheme: requestHead.scheme, host: requestHead.host, path: requestHead.path, timeout: GRPCTimeout(deadline: requestHead.deadline), customMetadata: requestHead.customMetadata, compression: requestHead.encoding ) result = .success(headers) self = .clientActiveServerIdle( writeState: pendingWriteState.makeWriteState(messageEncoding: requestHead.encoding), pendingReadState: .init(arity: responseArity, messageEncoding: requestHead.encoding) ) case .clientActiveServerIdle, .clientClosedServerIdle, .clientClosedServerActive, .clientActiveServerActive, .clientClosedServerClosed: result = .failure(.invalidState) case .modifying: preconditionFailure("State left as 'modifying'") } return result } /// See `GRPCClientStateMachine.sendRequest(_:allocator:)`. mutating func sendRequest( _ message: ByteBuffer, compressed: Bool, allocator: ByteBufferAllocator ) -> Result<ByteBuffer, MessageWriteError> { let result: Result<ByteBuffer, MessageWriteError> switch self { case .clientActiveServerIdle(var writeState, let pendingReadState): result = writeState.write(message, compressed: compressed, allocator: allocator) self = .clientActiveServerIdle(writeState: writeState, pendingReadState: pendingReadState) case .clientActiveServerActive(var writeState, let readState): result = writeState.write(message, compressed: compressed, allocator: allocator) self = .clientActiveServerActive(writeState: writeState, readState: readState) case .clientClosedServerIdle, .clientClosedServerActive, .clientClosedServerClosed: result = .failure(.cardinalityViolation) case .clientIdleServerIdle: result = .failure(.invalidState) case .modifying: preconditionFailure("State left as 'modifying'") } return result } /// See `GRPCClientStateMachine.sendEndOfRequestStream()`. mutating func sendEndOfRequestStream() -> Result<Void, SendEndOfRequestStreamError> { let result: Result<Void, SendEndOfRequestStreamError> switch self { case let .clientActiveServerIdle(_, pendingReadState): result = .success(()) self = .clientClosedServerIdle(pendingReadState: pendingReadState) case let .clientActiveServerActive(_, readState): result = .success(()) self = .clientClosedServerActive(readState: readState) case .clientClosedServerIdle, .clientClosedServerActive, .clientClosedServerClosed: result = .failure(.alreadyClosed) case .clientIdleServerIdle: result = .failure(.invalidState) case .modifying: preconditionFailure("State left as 'modifying'") } return result } /// See `GRPCClientStateMachine.receiveResponseHeaders(_:)`. mutating func receiveResponseHeaders( _ headers: HPACKHeaders ) -> Result<Void, ReceiveResponseHeadError> { let result: Result<Void, ReceiveResponseHeadError> switch self { case let .clientActiveServerIdle(writeState, pendingReadState): result = self.parseResponseHeaders(headers, pendingReadState: pendingReadState) .map { readState in self = .clientActiveServerActive(writeState: writeState, readState: readState) } case let .clientClosedServerIdle(pendingReadState): result = self.parseResponseHeaders(headers, pendingReadState: pendingReadState) .map { readState in self = .clientClosedServerActive(readState: readState) } case .clientIdleServerIdle, .clientClosedServerActive, .clientActiveServerActive, .clientClosedServerClosed: result = .failure(.invalidState) case .modifying: preconditionFailure("State left as 'modifying'") } return result } /// See `GRPCClientStateMachine.receiveResponseBuffer(_:)`. mutating func receiveResponseBuffer( _ buffer: inout ByteBuffer, maxMessageLength: Int ) -> Result<[ByteBuffer], MessageReadError> { let result: Result<[ByteBuffer], MessageReadError> switch self { case var .clientClosedServerActive(readState): result = readState.readMessages(&buffer, maxLength: maxMessageLength) self = .clientClosedServerActive(readState: readState) case .clientActiveServerActive(let writeState, var readState): result = readState.readMessages(&buffer, maxLength: maxMessageLength) self = .clientActiveServerActive(writeState: writeState, readState: readState) case .clientIdleServerIdle, .clientActiveServerIdle, .clientClosedServerIdle, .clientClosedServerClosed: result = .failure(.invalidState) case .modifying: preconditionFailure("State left as 'modifying'") } return result } /// See `GRPCClientStateMachine.receiveEndOfResponseStream(_:)`. mutating func receiveEndOfResponseStream( _ trailers: HPACKHeaders ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> { let result: Result<GRPCStatus, ReceiveEndOfResponseStreamError> switch self { case .clientActiveServerIdle, .clientClosedServerIdle: result = self.parseTrailersOnly(trailers).map { status in self = .clientClosedServerClosed return status } case .clientActiveServerActive, .clientClosedServerActive: result = .success(self.parseTrailers(trailers)) self = .clientClosedServerClosed case .clientIdleServerIdle, .clientClosedServerClosed: result = .failure(.invalidState) case .modifying: preconditionFailure("State left as 'modifying'") } return result } /// See `GRPCClientStateMachine.receiveEndOfResponseStream()`. mutating func receiveEndOfResponseStream() -> GRPCStatus? { let status: GRPCStatus? switch self { case .clientIdleServerIdle: // Can't see end stream before writing on it. preconditionFailure() case .clientActiveServerIdle, .clientActiveServerActive, .clientClosedServerIdle, .clientClosedServerActive: self = .clientClosedServerClosed status = .init( code: .internalError, message: "Protocol violation: received DATA frame with end stream set" ) case .clientClosedServerClosed: // We've already closed. Ignore this. status = nil case .modifying: preconditionFailure("State left as 'modifying'") } return status } /// Makes the request headers (`Request-Headers` in the specification) used to initiate an RPC /// call. /// /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests /// /// - Parameter host: The host serving the RPC. /// - Parameter options: Any options related to the call. /// - Parameter requestID: A request ID associated with the call. An additional header will be /// added using this value if `options.requestIDHeader` is specified. private func makeRequestHeaders( method: String, scheme: String, host: String, path: String, timeout: GRPCTimeout, customMetadata: HPACKHeaders, compression: ClientMessageEncoding ) -> HPACKHeaders { var headers = HPACKHeaders() // The 10 is: // - 6 which are required and added just below, and // - 4 which are possibly added, depending on conditions. headers.reserveCapacity(10 + customMetadata.count) // Add the required headers. headers.add(name: ":method", value: method) headers.add(name: ":path", value: path) headers.add(name: ":authority", value: host) headers.add(name: ":scheme", value: scheme) headers.add(name: "content-type", value: "application/grpc") // Used to detect incompatible proxies, part of the gRPC specification. headers.add(name: "te", value: "trailers") switch compression { case let .enabled(configuration): // Request encoding. if let outbound = configuration.outbound { headers.add(name: GRPCHeaderName.encoding, value: outbound.name) } // Response encoding. if !configuration.inbound.isEmpty { headers.add(name: GRPCHeaderName.acceptEncoding, value: configuration.acceptEncodingHeader) } case .disabled: () } // Add the timeout header, if a timeout was specified. if timeout != .infinite { headers.add(name: GRPCHeaderName.timeout, value: String(describing: timeout)) } // Add user-defined custom metadata: this should come after the call definition headers. // TODO: make header normalization user-configurable. headers.add(contentsOf: customMetadata.lazy.map { name, value, indexing in (name.lowercased(), value, indexing) }) // Add default user-agent value, if `customMetadata` didn't contain user-agent if !customMetadata.contains(name: "user-agent") { headers.add(name: "user-agent", value: GRPCClientStateMachine.userAgent) } return headers } /// Parses the response headers ("Response-Headers" in the specification) from the server into /// a `ReadState`. /// /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses /// /// - Parameter headers: The headers to parse. private func parseResponseHeaders( _ headers: HPACKHeaders, pendingReadState: PendingReadState ) -> Result<ReadState, ReceiveResponseHeadError> { // From: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses // // "Implementations should expect broken deployments to send non-200 HTTP status codes in // responses as well as a variety of non-GRPC content-types and to omit Status & Status-Message. // Implementations must synthesize a Status & Status-Message to propagate to the application // layer when this occurs." let statusHeader = headers.first(name: ":status") let responseStatus = statusHeader .flatMap(Int.init) .map { code in HTTPResponseStatus(statusCode: code) } ?? .preconditionFailed guard responseStatus == .ok else { return .failure(.invalidHTTPStatus(statusHeader)) } let contentTypeHeader = headers.first(name: "content-type") guard contentTypeHeader.flatMap(ContentType.init) != nil else { return .failure(.invalidContentType(contentTypeHeader)) } let result: Result<ReadState, ReceiveResponseHeadError> // What compression mechanism is the server using, if any? if let encodingHeader = headers.first(name: GRPCHeaderName.encoding) { // Note: the server is allowed to encode messages using an algorithm which wasn't included in // the 'grpc-accept-encoding' header. If the client still supports that algorithm (despite not // permitting the server to use it) then it must still decode that message. Ideally we should // log a message here if that was the case but we don't hold that information. if let compression = CompressionAlgorithm(rawValue: encodingHeader) { result = .success(pendingReadState.makeReadState(compression: compression)) } else { // The algorithm isn't one we support. result = .failure(.unsupportedMessageEncoding(encodingHeader)) } } else { // No compression was specified, this is fine. result = .success(pendingReadState.makeReadState(compression: nil)) } return result } /// Parses the response trailers ("Trailers" in the specification) from the server into /// a `GRPCStatus`. /// /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses /// /// - Parameter trailers: Trailers to parse. private func parseTrailers(_ trailers: HPACKHeaders) -> GRPCStatus { // Extract the "Status" and "Status-Message" let code = self.readStatusCode(from: trailers) ?? .unknown let message = self.readStatusMessage(from: trailers) return .init(code: code, message: message) } private func readStatusCode(from trailers: HPACKHeaders) -> GRPCStatus.Code? { return trailers.first(name: GRPCHeaderName.statusCode) .flatMap(Int.init) .flatMap(GRPCStatus.Code.init) } private func readStatusMessage(from trailers: HPACKHeaders) -> String? { return trailers.first(name: GRPCHeaderName.statusMessage) .map(GRPCStatusMessageMarshaller.unmarshall) } /// Parses a "Trailers-Only" response from the server into a `GRPCStatus`. /// /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses /// /// - Parameter trailers: Trailers to parse. private func parseTrailersOnly( _ trailers: HPACKHeaders ) -> Result<GRPCStatus, ReceiveEndOfResponseStreamError> { // We need to check whether we have a valid HTTP status in the headers, if we don't then we also // need to check whether we have a gRPC status as it should take preference over a synthesising // one from the ":status". // // See: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md let statusHeader = trailers.first(name: ":status") guard let status = statusHeader.flatMap(Int.init).map({ HTTPResponseStatus(statusCode: $0) }) else { return .failure(.invalidHTTPStatus(statusHeader)) } guard status == .ok else { if let code = self.readStatusCode(from: trailers) { let message = self.readStatusMessage(from: trailers) return .failure(.invalidHTTPStatusWithGRPCStatus(.init(code: code, message: message))) } else { return .failure(.invalidHTTPStatus(statusHeader)) } } // Only validate the content-type header if it's present. This is a small deviation from the // spec as the content-type is meant to be sent in "Trailers-Only" responses. However, if it's // missing then we should avoid the error and propagate the status code and message sent by // the server instead. if let contentTypeHeader = trailers.first(name: "content-type"), ContentType(value: contentTypeHeader) == nil { return .failure(.invalidContentType(contentTypeHeader)) } // We've verified the status and content type are okay: parse the trailers. return .success(self.parseTrailers(trailers)) } }
apache-2.0
42f3cbee8bdc9b954c36b10503f386a4
38.82959
100
0.709031
4.482087
false
false
false
false
xeo-it/contacts-sample
totvs-contacts-test/Models/User.swift
1
2520
// // User.swift // zipbooks-ios // // Created by Francesco Pretelli on 30/01/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import RealmSwift import ObjectMapper import Foundation class User: Object,Mappable { dynamic var homePage: String? var address = List<Address>() dynamic var imageUrl: String? var emails = List<Email>() var phone = List<Phone>() dynamic var companyDetails: CompanyDetails? dynamic var age: Int = 0 dynamic var position: String? dynamic var name: String? // MARK: Mappable required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { homePage <- map["homePage"] address <- (map["address"], ArrayTransform<Address>()) imageUrl <- map["imageUrl"] emails <- (map["emails"], ArrayTransform<Email>()) phone <- (map["phone"], ArrayTransform<Phone>()) companyDetails <- map["companyDetails"] age <- map["age"] position <- map["position"] name <- map["name"] } } class Address: Object,Mappable { dynamic var city: String? dynamic var address3: String? dynamic var country: String? dynamic var address1: String? dynamic var address2: String? dynamic var zipcode: Int = 0 dynamic var state: String? // MARK: Mappable required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { city <- map["city"] address3 <- map["address3"] country <- map["country"] address1 <- map["address1"] address2 <- map["address2"] zipcode <- map["zipcode"] state <- map["state"] } } class CompanyDetails: Object,Mappable { dynamic var location: String? dynamic var name: String? // MARK: Mappable required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { location <- map["location"] name <- map["name"] } } class Email: Object,Mappable { dynamic var email: String? dynamic var label: String? // MARK: Mappable required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { email <- map["email"] label <- map["label"] } } class Phone: Object,Mappable { dynamic var number: String? dynamic var type: String? // MARK: Mappable required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { number <- map["number"] type <- map["type"] } }
mit
271135119f28a4af74aa495c41247f5f
20.913043
61
0.59865
3.905426
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/Views/TableViewCells/QueryInputCell.swift
1
2681
// // QueryInputCell.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 8/31/17. // import UIKit final class QueryInputCell: UITableViewCell { // MARK: - Properties static var reuseIdentifier: String { return "QueryInputCell" } var delegate: UITextViewDelegate? { didSet { textInput.delegate = delegate } } let textInput: InputTextView = { let textView = InputTextView() textView.autocapitalizationType = .none textView.autocorrectionType = .no textView.returnKeyType = .done textView.keyboardType = .asciiCapable textView.font = UIFont.systemFont(ofSize: 12) textView.placeholder = "limit=10&where={\"name\":\"John Doe\"}" return textView }() // MARK: - Initialization override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubviews() setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup private func addSubviews() { addSubview(textInput) } private func setupConstraints() { textInput.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 4, leftConstant: 12, bottomConstant: 4, rightConstant: 12, widthConstant: 0, heightConstant: 0) } }
mit
ecf636a7a2a1d257175748aefc94965c
32.5
204
0.675373
4.802867
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/CryptoCurrencySelection/LocalizationConstants+CryptoCurrencySelection.swift
1
2249
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization extension LocalizationConstants { enum CryptoCurrencySelection { static let errorTitle = NSLocalizedString( "Something went wrong", comment: "Title for list loading error" ) static let errorButtonTitle = NSLocalizedString( "Retry", comment: "Retry CTA button title" ) static let errorDescription = NSLocalizedString( "Couldn't load a list of available cryptocurrencies: %@", comment: "Description for list loading error" ) static let title = NSLocalizedString( "Want to Buy Crypto?", comment: "Buy list header title" ) static let description = NSLocalizedString( "Select the crypto you want to buy and link a debit or credit card.", comment: "Buy list header description" ) static let searchPlaceholder = NSLocalizedString( "Search", comment: "Search text field placeholder" ) static let emptyListTitle = NSLocalizedString( "No purchasable pairs found", comment: "Buy empty list title" ) static let retryButtonTitle = NSLocalizedString( "Retry", comment: "Retry list loading button title" ) static let notNowButtonTitle = NSLocalizedString( "Not Now", comment: "Not now button title" ) static let cancelButtonTitle = NSLocalizedString( "Cancel", comment: "Cancel button title" ) } enum MajorProductBlocked { public static let title = NSLocalizedString( "Trading Restricted", comment: "EU_5_SANCTION card title." ) public static let ctaButtonLearnMore = NSLocalizedString( "Learn More", comment: "EU_5_SANCTION card CTA button title." ) public static let defaultMessage = NSLocalizedString( "Default message for inelibility", comment: "This operation cannot be performed at this time. Please try again later." ) } }
lgpl-3.0
dfd3500d9fbadc89d3bb1dd5dc806436
29.378378
95
0.591192
5.564356
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00439-swift-constraints-constraintsystem-gettypeofmemberreference.swift
11
708
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func g<U -> { class A : P { let t: B(t: String { }(t: C> (") convenience init() { var b: String { enum A { } class func g: A? { class C<H : C { self.init<T.b = { var e: P> T { var e: T> { } [T.E == e!.E == { } class B<U : d where A.h> V { struct d: Int { } deinit { } let d<T> { } } } } } } } let g = a(self.init(t:
apache-2.0
7ed6c001045905d3bd55db6b4c560179
17.631579
78
0.631356
2.712644
false
false
false
false
dannys42/DTSImage
Sources/DTSPixel.swift
1
2171
// // DTSPixel.swift // Pods // // Created by Danny Sung on 12/01/2016. // // import Foundation public protocol DTSPixel { init() init(red: Float, green: Float, blue: Float) init(red: Float, green: Float, blue: Float, alpha: Float) } public extension DTSPixel { init(red: Float, green: Float, blue: Float) { self.init(red: red, green: green, blue: blue, alpha: 1.0) } static func white() -> Self { return self.init(red: 1.0, green: 1.0, blue: 1.0) } static func black() -> Self { return self.init(red: 0.0, green: 0.0, blue: 0.0) } } /// A speical DTSPixel type that is composed of an array of ComponentTypes public enum DTSPixelComponentAlphaPosition { case none case first case last } public protocol DTSPixelComponentArray: DTSPixel { associatedtype ComponentType var values: [ComponentType] { get set } init?(components: [ComponentType]) static var alphaPosition: DTSPixelComponentAlphaPosition { get } static var numberOfComponentsPerPixel: Int { get } static var componentMin: ComponentType { get } static var componentMax: ComponentType { get } } extension DTSPixelComponentArray { public init?(components: [ComponentType]) { let newComponents: [ComponentType] switch Self.alphaPosition { case .none: newComponents = components case .first: if components.count < Self.numberOfComponentsPerPixel { newComponents = [Self.componentMax] + components } else { newComponents = components } case .last: if components.count < Self.numberOfComponentsPerPixel { newComponents = components + [Self.componentMax] } else { newComponents = components } } guard components.count >= Self.numberOfComponentsPerPixel else { return nil } var values: [ComponentType] = [] for n in 0..<Self.numberOfComponentsPerPixel { values[n] = newComponents[n] } self.init() self.values = values } }
mit
52952b38931c951e687d117aaaa37154
27.194805
85
0.613082
4.385859
false
false
false
false
banxi1988/BXPhotoViewer
Example/BXPhotoViewer/ViewController.swift
1
2413
// // ViewController.swift // BXPhotoViewer // // Created by banxi1988 on 11/10/2015. // Copyright (c) 2015 banxi1988. All rights reserved. // import UIKit import BXPhotoViewer import Photos class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var showPhotoCell: UITableViewCell! @IBOutlet weak var compressPhotoCell: UITableViewCell! @IBOutlet weak var chooseAssetThenCompress: UITableViewCell! func showPhoto(){ let url = "http://ww4.sinaimg.cn/large/72973f93gw1exmgz9wywcj216o1kwnfs.jpg" let image = UIImage(named: "karry.jpg")! let photos : [BXPhotoViewable] = [url,image] let vc = BXPhotoViewerViewController(photos:photos) showViewController(vc, sender: self) } func showCompressPhoto(){ let image = UIImage(named: "karry.jpg")! showCompressImage(image) } func showCompressPhoto(asset:PHAsset){ PHCachingImageManager().requestImageDataForAsset(asset, options: nil) { (data, name, orintation, info) -> Void in NSLog("requestedImage:isMainThread:\(NSThread.isMainThread()))") self.showCompressImage(UIImage(data: data!)!) } } func showCompressImage(image:UIImage){ let vc = BXPhotoInteractiveCompressViewController() vc.image = image presentViewController(vc, animated: true, completion: nil) } func chooseAssetThenCompressAsset(){ let successBlock :ALImageFetchingInteractorSuccess = { (assets:[PHAsset]) in self.showCompressPhoto(assets[0]) } ALImageFetchingInteractor().onSuccess(successBlock).fetch() } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) switch cell!{ case showPhotoCell: showPhoto() case compressPhotoCell: showCompressPhoto() case chooseAssetThenCompress: chooseAssetThenCompressAsset() default:break } } } extension ViewController:BXPhotoInteractiveCompressViewControllerDelegate{ func photoInteractiveCompressViewControllerDidCanceled(controller: BXPhotoInteractiveCompressViewController) { } func photoInteractiveCompressViewController(controller:BXPhotoInteractiveCompressViewController,compressionQuality:CGFloat, compressedImage:UIImage){ } }
mit
e221924e9dc52f79a2e9be597a6e1436
26.420455
151
0.723995
4.604962
false
false
false
false
getsentry/sentry-swift
Tests/SentryTests/Integrations/OutOfMemory/SentryOutOfMemoryTrackerTests.swift
1
9342
import XCTest #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) class SentryOutOfMemoryTrackerTests: XCTestCase { private static let dsnAsString = TestConstants.dsnAsString(username: "SentryOutOfMemoryTrackerTests") private static let dsn = TestConstants.dsn(username: "SentryOutOfMemoryTrackerTests") private class Fixture { let options: Options let client: TestClient! let crashWrapper: TestSentryCrashWrapper let fileManager: SentryFileManager let currentDate = TestCurrentDateProvider() let sysctl = TestSysctl() let dispatchQueue = TestSentryDispatchQueueWrapper() init() { options = Options() options.dsn = SentryOutOfMemoryTrackerTests.dsnAsString options.releaseName = TestData.appState.releaseName client = TestClient(options: options) crashWrapper = TestSentryCrashWrapper.sharedInstance() let hub = SentryHub(client: client, andScope: nil, andCrashWrapper: crashWrapper, andCurrentDateProvider: currentDate) SentrySDK.setCurrentHub(hub) fileManager = try! SentryFileManager(options: options, andCurrentDateProvider: currentDate) } func getSut() -> SentryOutOfMemoryTracker { return getSut(fileManager: self.fileManager) } func getSut(fileManager: SentryFileManager) -> SentryOutOfMemoryTracker { let appStateManager = SentryAppStateManager(options: options, crashWrapper: crashWrapper, fileManager: fileManager, currentDateProvider: currentDate, sysctl: sysctl) let logic = SentryOutOfMemoryLogic(options: options, crashAdapter: crashWrapper, appStateManager: appStateManager) return SentryOutOfMemoryTracker(options: options, outOfMemoryLogic: logic, appStateManager: appStateManager, dispatchQueueWrapper: dispatchQueue, fileManager: fileManager) } } private var fixture: Fixture! private var sut: SentryOutOfMemoryTracker! override func setUp() { super.setUp() fixture = Fixture() sut = fixture.getSut() } override func tearDown() { super.tearDown() sut.stop() fixture.fileManager.deleteAllFolders() clearTestState() } func testStart_StoresAppState() { sut.start() let actual = fixture.fileManager.readAppState() let appState = SentryAppState(releaseName: fixture.options.releaseName ?? "", osVersion: UIDevice.current.systemVersion, vendorId: TestData.someUUID, isDebugging: false, systemBootTimestamp: fixture.sysctl.systemBootTimestamp) XCTAssertEqual(appState, actual) XCTAssertEqual(1, fixture.dispatchQueue.dispatchAsyncCalled) } func testGoToForeground_SetsIsActive() { sut.start() goToForeground() XCTAssertTrue(fixture.fileManager.readAppState()?.isActive ?? false) goToBackground() XCTAssertFalse(fixture.fileManager.readAppState()?.isActive ?? true) XCTAssertEqual(3, fixture.dispatchQueue.dispatchAsyncCalled) } func testGoToForeground_WhenAppStateNil_NothingIsStored() { sut.start() fixture.fileManager.deleteAppState() goToForeground() XCTAssertNil(fixture.fileManager.readAppState()) } func testDifferentAppVersions_NoOOM() { givenPreviousAppState(appState: SentryAppState(releaseName: "0.9.0", osVersion: UIDevice.current.systemVersion, vendorId: TestData.someUUID, isDebugging: false, systemBootTimestamp: fixture.currentDate.date())) sut.start() assertNoOOMSent() } func testDifferentOSVersions_NoOOM() { givenPreviousAppState(appState: SentryAppState(releaseName: fixture.options.releaseName ?? "", osVersion: "1.0.0", vendorId: TestData.someUUID, isDebugging: false, systemBootTimestamp: fixture.currentDate.date())) sut.start() assertNoOOMSent() } func testDifferentVendorId_NoOOM() { givenPreviousAppState(appState: SentryAppState(releaseName: fixture.options.releaseName ?? "", osVersion: "1.0.0", vendorId: "0987654321", isDebugging: false, systemBootTimestamp: fixture.currentDate.date())) sut.start() assertNoOOMSent() } func testIsDebugging_NoOOM() { fixture.crashWrapper.internalIsBeingTraced = true sut.start() goToForeground() goToBackground() terminateApp() sut.start() assertNoOOMSent() } func testTerminatedNormally_NoOOM() { sut.start() goToForeground() goToBackground() terminateApp() sut.start() assertNoOOMSent() } func testCrashReport_NoOOM() { let appState = SentryAppState(releaseName: TestData.appState.releaseName, osVersion: UIDevice.current.systemVersion, vendorId: TestData.someUUID, isDebugging: false, systemBootTimestamp: fixture.currentDate.date()) givenPreviousAppState(appState: appState) fixture.crashWrapper.internalCrashedLastLaunch = true sut.start() assertNoOOMSent() } func testAppWasInBackground_NoOOM() { sut.start() goToForeground() goToBackground() sut.stop() sut.start() assertNoOOMSent() } func testAppWasInForeground_OOM() { sut.start() goToForeground() sut.start() assertOOMEventSent() } func testANR_NoOOM() { sut.start() goToForeground() update(appState: { appState in appState.isANROngoing = true }) sut.start() assertNoOOMSent() } func testAppOOM_WithOnlyHybridSdkDidBecomeActive() { sut.start() TestNotificationCenter.hybridSdkDidBecomeActive() sut.start() assertOOMEventSent() } func testAppOOM_Foreground_And_HybridSdkDidBecomeActive() { sut.start() goToForeground() TestNotificationCenter.hybridSdkDidBecomeActive() sut.start() assertOOMEventSent() } func testAppOOM_HybridSdkDidBecomeActive_and_Foreground() { sut.start() TestNotificationCenter.hybridSdkDidBecomeActive() goToForeground() sut.start() assertOOMEventSent() } func testTerminateApp_RunsOnMainThread() { sut.start() TestNotificationCenter.willTerminate() // 1 for start XCTAssertEqual(1, fixture.dispatchQueue.dispatchAsyncCalled) } func testStartThenStop_NoOOM() { sut.start() goToForeground() sut.stop() sut.start() assertNoOOMSent() } func testStop_StopsObserving_NoMoreFileManagerInvocations() throws { let fileManager = try TestFileManager(options: Options(), andCurrentDateProvider: TestCurrentDateProvider()) sut = fixture.getSut(fileManager: fileManager) sut.start() sut.stop() TestNotificationCenter.hybridSdkDidBecomeActive() goToForeground() terminateApp() XCTAssertEqual(1, fileManager.readAppStateInvocations.count) } private func givenPreviousAppState(appState: SentryAppState) { fixture.fileManager.store(appState) } private func update(appState: (SentryAppState) -> Void) { if let currentAppState = fixture.fileManager.readAppState() { appState(currentAppState) fixture.fileManager.store(currentAppState) } } private func goToForeground() { TestNotificationCenter.willEnterForeground() TestNotificationCenter.didBecomeActive() } private func goToBackground() { TestNotificationCenter.willResignActive() TestNotificationCenter.didEnterBackground() } private func terminateApp() { TestNotificationCenter.willTerminate() sut.stop() } private func assertOOMEventSent() { XCTAssertEqual(1, fixture.client.captureCrashEventInvocations.count) let crashEvent = fixture.client.captureCrashEventInvocations.first?.event XCTAssertEqual(SentryLevel.fatal, crashEvent?.level) XCTAssertEqual([], crashEvent?.breadcrumbs) XCTAssertEqual(1, crashEvent?.exceptions?.count) let exception = crashEvent?.exceptions?.first XCTAssertEqual("The OS most likely terminated your app because it overused RAM.", exception?.value) XCTAssertEqual("OutOfMemory", exception?.type) XCTAssertNotNil(exception?.mechanism) XCTAssertEqual(false, exception?.mechanism?.handled) XCTAssertEqual("out_of_memory", exception?.mechanism?.type) } private func assertNoOOMSent() { XCTAssertEqual(0, fixture.client.captureCrashEventInvocations.count) } } #endif
mit
f37ab28d5b5753b51491f7333c186fe8
30.883959
234
0.638728
5.21317
false
true
false
false
apple/swift
lib/ASTGen/Sources/ASTGen/Generics.swift
2
3364
import CASTBridging import SwiftParser import SwiftSyntax extension ASTGenVisitor { func visit(_ node: GenericParameterClauseSyntax) -> ASTNode { let lAngleLoc = self.base.advanced(by: node.leftAngleBracket.position.utf8Offset).raw let whereLoc = node.genericWhereClause.map { self.base.advanced(by: $0.whereKeyword.position.utf8Offset).raw } let rAngleLoc = self.base.advanced(by: node.rightAngleBracket.position.utf8Offset).raw return .misc( self.withBridgedParametersAndRequirements(node) { params, reqs in return GenericParamList_create(self.ctx, lAngleLoc, params, whereLoc, reqs, rAngleLoc) }) } func visit(_ node: GenericParameterSyntax) -> ASTNode { var nodeName = node.name.text let name = nodeName.withUTF8 { buf in return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) } let nameLoc = self.base.advanced(by: node.name.position.utf8Offset).raw let ellipsisLoc = node.ellipsis.map { self.base.advanced(by: $0.position.utf8Offset).raw } return .decl( GenericTypeParamDecl_create( self.ctx, self.declContext, name, nameLoc, ellipsisLoc, node.indexInParent / 2, ellipsisLoc != nil)) } } extension ASTGenVisitor { private func withBridgedParametersAndRequirements<T>( _ node: GenericParameterClauseSyntax, action: (BridgedArrayRef, BridgedArrayRef) -> T ) -> T { var params = [UnsafeMutableRawPointer]() var requirements = [BridgedRequirementRepr]() for param in node.genericParameterList { let loweredParameter = self.visit(param).rawValue params.append(loweredParameter) guard let requirement = param.inheritedType else { continue } let loweredRequirement = self.visit(requirement) GenericTypeParamDecl_setInheritedType(self.ctx, loweredParameter, loweredRequirement.rawValue) } if let nodeRequirements = node.genericWhereClause?.requirementList { for requirement in nodeRequirements { switch requirement.body { case .conformanceRequirement(let conformance): let firstType = self.visit(conformance.leftTypeIdentifier).rawValue let separatorLoc = self.base.advanced(by: conformance.colon.position.utf8Offset).raw let secondType = self.visit(conformance.rightTypeIdentifier).rawValue requirements.append( BridgedRequirementRepr( SeparatorLoc: separatorLoc, Kind: .typeConstraint, FirstType: firstType, SecondType: secondType)) case .sameTypeRequirement(let sameType): let firstType = self.visit(sameType.leftTypeIdentifier).rawValue let separatorLoc = self.base.advanced(by: sameType.equalityToken.position.utf8Offset).raw let secondType = self.visit(sameType.rightTypeIdentifier).rawValue requirements.append( BridgedRequirementRepr( SeparatorLoc: separatorLoc, Kind: .sameType, FirstType: firstType, SecondType: secondType)) case .layoutRequirement(_): fatalError("Cannot handle layout requirements!") } } } return params.withBridgedArrayRef { params in return requirements.withBridgedArrayRef { reqs in return action(params, reqs) } } } }
apache-2.0
3323fd15fc322af73b2b6b1f248274c8
38.116279
100
0.691439
4.503347
false
false
false
false
icetime17/CSSwiftExtension
CSSwiftExtension/CSSwiftExtension/MyTableViewController.swift
1
1677
// // MyTableViewController.swift // CSSwiftExtension // // Created by Chris Hu on 17/01/16. // Copyright © 2016年 com.icetime17. All rights reserved. // import UIKit class MyTableViewController: UIViewController { var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() initTableView() } func initTableView() { tableView = UITableView(frame: view.bounds, style: .plain) view.addSubview(tableView) tableView.dataSource = self tableView.delegate = self // tableView.cs.registerNib(MyTableViewCell.self) tableView.register(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "MyTableViewCell") tableView.rowHeight = 100 } } extension MyTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.cs.dequeueReusableCell(forIndexPath: indexPath) as MyTableViewCell let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as! MyTableViewCell cell.myImageView.image = UIImage(named: "Model.jpg") cell.myLabel.text = "cell - \(indexPath.row)" CS_Print(cell.myLabel.text!) return cell } } extension MyTableViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
mit
b938ba5e2e4392c3c42d16f5b584ff86
26.9
119
0.66129
5.027027
false
false
false
false
ichenwanbing/CDYTV
DouYuTV/DouYuTV/Tools/UIBarButtonItem+Extension.swift
1
1071
// // UIBarButtonItem+Extension.swift // DouYuTV // // Created by Mac on 16/10/20. // Copyright © 2016年 Mac. All rights reserved. // import UIKit extension UIBarButtonItem{ //在扩展系统类的方法时建议用便利构造方法代替类方法 //1. convenience开头 2.必须要明确的调用系统设计的的构造函数函数 convenience init(imageName:String ,highlightedImageName:String = "",size:CGSize = CGSize.zero) { //如果外面没有穿值取等号后面的默认值 而且会多一个只有imageName参数的构造函数方便调用 let btn = UIButton() btn.setImage(UIImage.init(named: imageName), for: .normal) if highlightedImageName != "" { btn.setImage(UIImage.init(named: highlightedImageName), for: .highlighted) } if size == CGSize.zero { btn.sizeToFit() }else{ btn.frame = CGRect(origin: .zero, size: size) } //调用系统设计的构造函数 self.init(customView:btn) } }
mit
bf6dc32aea2c5e0135b147ff67f7ea33
26.5625
100
0.615646
3.675
false
false
false
false
josmoss/TIY-Assignments
FoodPin/FoodPin/RestaurantTableViewController.swift
1
5699
// // RestaurantTableViewController.swift // FoodPin // // Created by Simon Ng on 14/8/15. // Copyright © 2015 AppCoda. All rights reserved. // import UIKit class RestaurantTableViewController: UITableViewController { var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "Thai Cafe"] var restaurantImages = ["cafedeadend.jpg", "homei.jpg", "teakha.jpg", "cafeloisl.jpg", "petiteoyster.jpg", "forkeerestaurant.jpg", "posatelier.jpg", "bourkestreetbakery.jpg", "haighschocolate.jpg", "palominoespresso.jpg", "upstate.jpg", "traif.jpg", "grahamavenuemeats.jpg", "wafflewolf.jpg", "fiveleaves.jpg", "cafelore.jpg", "confessional.jpg", "barrafina.jpg", "donostia.jpg", "royaloak.jpg", "thaicafe.jpg"] var restaurantLocations = ["Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Hong Kong", "Sydney", "Sydney", "Sydney", "New York", "New York", "New York", "New York", "New York", "New York", "New York", "London", "London", "London", "London"] var restaurantTypes = ["Coffee & Tea Shop", "Cafe", "Tea House", "Austrian / Causual Drink", "French", "Bakery", "Bakery", "Chocolate", "Cafe", "American / Seafood", "American", "American", "Breakfast & Brunch", "Coffee & Tea", "Coffee & Tea", "Latin American", "Spanish", "Spanish", "Spanish", "British", "Thai"] var restaurantIsVisited = [Bool](count: 21, repeatedValue: false) override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurantNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RestaurantTableViewCell // Configure the cell... cell.nameLabel.text = restaurantNames[indexPath.row] cell.thumbnailImageView.image = UIImage(named: restaurantImages[indexPath.row]) cell.locationLabel.text = restaurantLocations[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] if restaurantIsVisited[indexPath.row] { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let optionMenu = UIAlertController(title: nil, message: "What do you want to do?", preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) optionMenu.addAction(cancelAction) let callActionHandler = { (action:UIAlertAction!) -> Void in let alertMessage = UIAlertController(title: "Service Unavailable", message: "Sorry, the call feature is not available yet. Please retry later.", preferredStyle: .Alert) alertMessage.addAction(UIAlertAction(title: "OK", style: .Default, handler:nil)) self.presentViewController(alertMessage, animated: true, completion: nil) } let callAction = UIAlertAction(title: "Call " + "123-000-\(indexPath.row)", style: UIAlertActionStyle.Default, handler: callActionHandler) optionMenu.addAction(callAction) let isVisitedTitle = (restaurantIsVisited[indexPath.row]) ? "I haven't been here" : "I've been here" let isVisitedAction = UIAlertAction(title: isVisitedTitle, style: .Default, handler: { (action:UIAlertAction!) -> Void in let cell = tableView.cellForRowAtIndexPath(indexPath) self.restaurantIsVisited[indexPath.row] = (self.restaurantIsVisited[indexPath.row]) ? false : true cell?.accessoryType = (self.restaurantIsVisited[indexPath.row]) ? .Checkmark : .None }) optionMenu.addAction(isVisitedAction) tableView.deselectRowAtIndexPath(indexPath, animated: false) self.presentViewController(optionMenu, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
24ecd83baf28c0258b96055013bdee97
46.882353
415
0.652685
4.551118
false
false
false
false
Hendrik44/pi-weather-app
Pi-WeatherTv/LiveDataViewController.swift
1
4959
// // FirstViewController.swift // Pi-WeatherTv // // Created by Hendrik on 22.09.16. // Copyright © 2016 JG-Bits UG (haftungsbeschränkt). All rights reserved. // import UIKit import FontAwesome @IBDesignable class LiveDataViewController: UIViewController { @IBOutlet weak var temperatureView: CircleView! @IBOutlet weak var humidityView: CircleView! @IBOutlet weak var pressureView: CircleView! @IBOutlet weak var timestampLabel: UILabel! var timer:Timer? #if os(iOS) let tabBarIconSize:CGFloat = 30 #elseif os(tvOS) let tabBarIconSize:CGFloat = 60 #endif override func viewDidLoad() { super.viewDidLoad() var tabImages:[[UIImage]] = [ [UIImage.fontAwesomeIcon(name: .thermometerHalf, style: .solid, textColor: UIColor.gray, size: CGSize(width: tabBarIconSize, height: tabBarIconSize)).withRenderingMode(.alwaysOriginal), UIImage.fontAwesomeIcon(name: .thermometerHalf, style: .solid, textColor: UIColor(hex: 0x2781B4), size: CGSize(width: tabBarIconSize, height: tabBarIconSize)).withRenderingMode(.alwaysOriginal)], [UIImage.fontAwesomeIcon(name: .chartLine, style: .solid, textColor: UIColor.gray, size: CGSize(width: tabBarIconSize, height: tabBarIconSize)).withRenderingMode(.alwaysOriginal), UIImage.fontAwesomeIcon(name: .chartLine, style: .solid, textColor: UIColor(hex: 0x2781B4), size: CGSize(width: tabBarIconSize, height: tabBarIconSize)).withRenderingMode(.alwaysOriginal)], [UIImage.fontAwesomeIcon(name: .cog, style: .solid, textColor: UIColor.gray, size: CGSize(width: tabBarIconSize, height: tabBarIconSize)).withRenderingMode(.alwaysOriginal), UIImage.fontAwesomeIcon(name: .cog, style: .solid, textColor: UIColor(hex: 0x2781B4), size: CGSize(width: tabBarIconSize, height: tabBarIconSize)).withRenderingMode(.alwaysOriginal)] ] var count = 0 for tabItem in self.tabBarController!.tabBar.items! { tabItem.image = tabImages[count][0] tabItem.selectedImage = tabImages[count][1] count += 1 } } override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { self.tabBarController?.tabBar.isHidden = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refresh() timer = Timer.scheduledTimer(timeInterval: AppSettings.sharedInstance.refreshDataInterval, target: self, selector: #selector(refresh), userInfo: nil, repeats: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer?.invalidate() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func refresh() { APIController().liveDataForSensorType(.all) { (sensorData, timestamp, error) in if error == nil && sensorData != nil && timestamp != nil { if let temperature = sensorData?[.temperature] { self.temperatureView.textLabel.text = "\(temperature) °C" } if let humidity = sensorData?[.humidity] { self.humidityView.textLabel.text = "\(humidity) %" } if let pressure = sensorData?[.pressure] { self.pressureView.textLabel.text = "\(pressure) hPa" } self.timestampLabel.text = "\(timestamp!)" } else { self.timestampLabel.text = "Fehler beim Abrufen der Messwerte" } } } }
mit
75ed3df266057adf355743c7b7db7ac0
40.647059
110
0.495561
6.014563
false
false
false
false
adamontherun/Study-iOS-With-Adam-Live
ARKitFindModels/ARKitFindModels/ViewController.swift
1
2028
//😘 it is 8/16/17 import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene(named: "art.scnassets/house.scn")! // Set the scene to the view sceneView.scene = scene } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingConfiguration() // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // MARK: - ARSCNViewDelegate /* // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() return node } */ func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } }
mit
0b1ce4abeec92a2f883759263b14e963
26.364865
103
0.62321
5.517711
false
true
false
false
nathawes/swift
test/Interpreter/SDK/libc.swift
5
2345
/* magic */ // Do not edit the line above. // RUN: %empty-directory(%t) // RUN: %target-run-simple-swift %s %t | %FileCheck %s // REQUIRES: executable_test // TODO: rdar://problem/33388782 // REQUIRES: CPU=x86_64 #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #elseif os(Windows) import MSVCRT let S_IRUSR: Int32 = ucrt._S_IREAD let S_IWUSR: Int32 = 0 let S_IXUSR: Int32 = 0 let S_IRGRP: Int32 = 0o0040 let S_IROTH: Int32 = 0o0004 #else #error("Unsupported platform") #endif let sourcePath = CommandLine.arguments[1] let tempPath = CommandLine.arguments[2] + "/libc.txt" // CHECK: Hello world fputs("Hello world", stdout) // CHECK: 4294967295 print("\(UINT32_MAX)") // CHECK: the magic word is ///* magic */// let sourceFile = open(sourcePath, O_RDONLY) assert(sourceFile >= 0) var bytes = UnsafeMutablePointer<CChar>.allocate(capacity: 12) var readed = read(sourceFile, bytes, 11) close(sourceFile) assert(readed == 11) bytes[11] = CChar(0) print("the magic word is //\(String(cString: bytes))//") // CHECK: O_CREAT|O_EXCL returned errno *17* let errFile = open(sourcePath, O_RDONLY | O_CREAT | O_EXCL) if errFile != -1 { print("O_CREAT|O_EXCL failed to return an error") } else { let e = errno print("O_CREAT|O_EXCL returned errno *\(e)*") } // CHECK-NOT: error // CHECK: created mode *{{33216|33060}}* *{{33216|33060}}* let tempFile = open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR) if tempFile == -1 { let e = errno print("error: open(tempPath \(tempPath)) returned -1, errno \(e)") abort() } let written = write(tempFile, bytes, 11) if (written != 11) { print("error: write(tempFile) returned \(written), errno \(errno)") abort() } var err: Int32 var statbuf1 = stat() err = fstat(tempFile, &statbuf1) if err != 0 { let e = errno print("error: fstat returned \(err), errno \(e)") abort() } close(tempFile) var statbuf2 = stat() err = stat(tempPath, &statbuf2) if err != 0 { let e = errno print("error: stat returned \(err), errno \(e)") abort() } print("created mode *\(statbuf1.st_mode)* *\(statbuf2.st_mode)*") #if os(Windows) assert(statbuf1.st_mode == S_IFREG | S_IRUSR | S_IRGRP | S_IROTH) #else assert(statbuf1.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR) #endif assert(statbuf1.st_mode == statbuf2.st_mode)
apache-2.0
79d23e591862d468d855db463b5a1c9d
22.45
72
0.660981
2.902228
false
false
false
false
xedin/swift
test/SourceKit/ExpressionType/filtered.swift
16
2777
// RUN: %sourcekitd-test -req=collect-type %s -req-opts=expectedtypes='s:8filtered4ProtP;s:8filtered5Prot1P' -- %s | %FileCheck %s -check-prefix=BOTH // RUN: %sourcekitd-test -req=collect-type %s -req-opts=expectedtypes='s:8filtered5Prot1P' -- %s | %FileCheck %s -check-prefix=PROTO1 // RUN: %sourcekitd-test -req=collect-type %s -req-opts=expectedtypes='s:8filtered6Proto2P' -- %s | %FileCheck %s -check-prefix=PROTO2 protocol Prot {} protocol Prot1 {} class Clas: Prot { var value: Clas { return self } func getValue() -> Clas { return self } } struct Stru: Prot, Prot1 { var value: Stru { return self } func getValue() -> Stru { return self } } class C {} func ArrayC(_ a: [C]) { _ = a.count _ = a.description.count.advanced(by: 1).description _ = a[0] } func ArrayClas(_ a: [Clas]) { _ = a[0].value.getValue().value } func ArrayClas(_ a: [Stru]) { _ = a[0].value.getValue().value } protocol Proto2 {} class Proto2Conformer: Proto2 {} func foo(_ c: Proto2Conformer) { _ = c } // BOTH: <ExpressionTypes> // BOTH: (503, 507): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (545, 549): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (609, 613): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (651, 655): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (811, 838): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (811, 832): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (811, 821): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (811, 815): Clas // BOTH: conforming to: s:8filtered4ProtP // BOTH: (877, 904): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (877, 898): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (877, 887): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: (877, 881): Stru // BOTH: conforming to: s:8filtered4ProtP // BOTH: conforming to: s:8filtered5Prot1P // BOTH: </ExpressionTypes> // PROTO1: <ExpressionTypes> // PROTO1: (609, 613): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (651, 655): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (877, 904): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (877, 898): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (877, 887): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: (877, 881): Stru // PROTO1: conforming to: s:8filtered5Prot1P // PROTO1: </ExpressionTypes> // PROTO2: <ExpressionTypes> // PROTO2: (999, 1000): Proto2Conformer // PROTO2: conforming to: s:8filtered6Proto2P // PROTO2: </ExpressionTypes>
apache-2.0
ae76fd9ffad574edf5a3f68409d4bbba
29.184783
149
0.686352
2.799395
false
false
false
false
michals92/iOS_skautIS
skautIS/UnitsVC.swift
1
2090
// // UnitsVC.swift // skautIS // // Copyright (c) 2015, Michal Simik // All rights reserved. // import UIKit import SWXMLHash class UnitsVC: UIViewController { //variables @IBOutlet weak var unitsSetting: UISwitch! @IBOutlet weak var childUnitsSetting: UISwitch! @IBOutlet weak var isNearSetting: UISwitch! var storage = Storage() var isMyUnit:Bool = false var isNear:Bool = false var includeChildUnits:Bool = false /** Initial method. Sets switches off. */ override func viewDidLoad() { super.viewDidLoad() unitsSetting.setOn(false, animated: true) childUnitsSetting.setOn(false, animated: true) isNearSetting.setOn(false, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Performs segue to map */ @IBAction func showUnitsOnMap(sender: AnyObject) { self.performSegueWithIdentifier("showMapSegue", sender: self) } /* Prepares atributtes that are passed to map */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "showMapSegue"){ let vc = segue.destinationViewController as! MapVC vc.unit = storage.loader("unit") vc.includeChildUnits = includeChildUnits vc.isNear = self.isNear vc.isMyUnit = self.isMyUnit } } //three switch methods @IBAction func unitsState(sender: UISwitch) { if sender.on { isMyUnit = true } else { isMyUnit = false } } @IBAction func childUnitsState(sender: UISwitch) { if sender.on { includeChildUnits = true } else { includeChildUnits = false } } @IBAction func isNear(sender: UISwitch) { if sender.on { isNear = true } else { isNear = false } } }
bsd-3-clause
bde847175ba46b6ecf3ed4562f662853
22.483146
81
0.572249
4.634146
false
false
false
false
pauljeannot/SnapSliderFilters
SnapSliderFilters/Classes/SNSlider.swift
1
7442
// // SNSlider.swift // Pods // // Created by Paul Jeannot on 04/05/2016. // // import UIKit open class SNSlider: UIView { fileprivate var slider:UIScrollView fileprivate var numberOfPages:Int fileprivate var startingIndex:Int fileprivate var data = [SNFilter]() fileprivate let slideAxis: SlideAxis open weak var dataSource:SNSliderDataSource? public init(frame: CGRect, slideAxis: SlideAxis = .horizontal) { self.slideAxis = slideAxis numberOfPages = 3 startingIndex = 0 slider = UIScrollView(frame: CGRect(origin: CGPoint.zero, size: frame.size)) super.init(frame: frame) self.slider.delegate = self self.slider.isPagingEnabled = true self.slider.bounces = false self.slider.showsHorizontalScrollIndicator = false self.slider.showsVerticalScrollIndicator = false self.slider.layer.zPosition = 1 self.addSubview(self.slider) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func reloadData() { self.cleanData() self.loadData() self.presentData() } open func slideShown() -> SNFilter { let index = slideAxis.index(with: slider) return data[Int(index)] } fileprivate func cleanData() { for v in subviews { let filter = v as? SNFilter if filter != nil { v.removeFromSuperview() } } for s in slider.subviews { let sticker = s as? SNSticker if sticker != nil { s.removeFromSuperview() } } data.removeAll() } fileprivate func loadData() { self.numberOfPages = dataSource!.numberOfSlides(self) self.startingIndex = dataSource!.startAtIndex(self) self.slider.contentSize = slideAxis.contentSize(with: self) var filter = dataSource!.slider(self, slideAtIndex:self.numberOfPages-1).copy() as! SNFilter data.append(filter) for i in 0..<self.numberOfPages { let filter = dataSource!.slider(self, slideAtIndex:i) data.append(filter) } filter = dataSource!.slider(self, slideAtIndex:0).copy() as! SNFilter data.append(filter) self.slider.scrollRectToVisible(slideAxis.rect(at: startingIndex, in: self), animated:false); } fileprivate func presentData() { for i in 0..<data.count { weak var filter:SNFilter! = data[i] filter.layer.zPosition = 0 filter.mask(filter.frame) switch slideAxis { case .horizontal: filter.updateMask(filter.frame, newXPosition: slideAxis.positionOfPage(at: (i-startingIndex-2), in: self)) case .vertical: filter.updateMask(filter.frame, newYPosition: slideAxis.positionOfPage(at: (i-startingIndex-2), in: self)) } self.addSubview(filter) for s in data[i].stickers { switch slideAxis { case .horizontal: s.frame.origin.x = s.frame.origin.x + slideAxis.positionOfPage(at: i - 1, in: self) case .vertical: s.frame.origin.y = s.frame.origin.y + slideAxis.positionOfPage(at: i - 1, in: self) } self.slider.addSubview(s) } } } } // MARK: - Scroll View Delegate extension SNSlider: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { for i in 0..<data.count { switch slideAxis { case .horizontal: data[i].updateMask(data[i].frame, newXPosition: slideAxis.positionOfPage(at: i - 1, in: self) - scrollView.contentOffset.x) case .vertical: data[i].updateMask(data[i].frame, newYPosition: slideAxis.positionOfPage(at: i - 1, in: self) - scrollView.contentOffset.y) } } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { switch slideAxis { case .horizontal: if (scrollView.contentOffset.x == slideAxis.positionOfPage(at: -1, in: self)) { self.slider.scrollRectToVisible(slideAxis.rect(at: numberOfPages - 1, in: self), animated:false); } else if (scrollView.contentOffset.x == slideAxis.positionOfPage(at: numberOfPages, in: self)) { self.slider.scrollRectToVisible(slideAxis.rect(at: 0, in: self), animated:false); } case .vertical: if (scrollView.contentOffset.y == slideAxis.positionOfPage(at: -1, in: self)) { self.slider.scrollRectToVisible(slideAxis.rect(at: numberOfPages - 1, in: self), animated:false); } else if (scrollView.contentOffset.y == slideAxis.positionOfPage(at: numberOfPages, in: self)) { self.slider.scrollRectToVisible(slideAxis.rect(at: 0, in: self), animated:false); } } } } extension SNSlider { public enum SlideAxis { case horizontal case vertical func contentSize(with slider: SNSlider) -> CGSize { switch self { case .horizontal: return CGSize(width: slider.frame.width*(CGFloat(slider.numberOfPages + 2)), height: slider.frame.height) case .vertical: return CGSize(width: slider.frame.width, height: slider.frame.height * (CGFloat(slider.numberOfPages + 2))) } } func index(with slider: UIScrollView) -> Int { switch self { case .horizontal: return Int(slider.contentOffset.x / slider.frame.size.width) case .vertical: return Int(slider.contentOffset.y / slider.frame.size.height) } } func rect(at index: Int, in slider: SNSlider) -> CGRect { switch self { case .horizontal: return CGRect(x: positionOfPage(at: index, in: slider), y: 0.0, width: slider.frame.width, height: slider.frame.height) case .vertical: return CGRect(x: 0.0, y: positionOfPage(at: index, in: slider), width: slider.frame.width, height: slider.frame.height) } } func positionOfPage(at index: Int, in slider: SNSlider) -> CGFloat { switch self { case .horizontal: return slider.frame.size.width * CGFloat(index) + slider.frame.size.width case .vertical: return slider.frame.size.height + slider.frame.size.height * CGFloat(index) } } } }
mit
b67f2ecaa4c46761ec95f5c76e7be71c
35.302439
139
0.536684
4.782776
false
false
false
false
yaozongchao/ComplicateTableDemo
ComplicateUI/KDTableViewObject.swift
1
1202
// // KDTableViewObject.swift // ComplicateUI // // Created by 姚宗超 on 2017/3/7. // Copyright © 2017年 姚宗超. All rights reserved. // import UIKit import SwiftyJSON struct KDTableViewObject { var collectArray = [KDCollectCellObject]() var tableArray = [KDTableCellObject]() static func createObject(jsonStr: String?) -> KDTableViewObject? { guard let innerJson = jsonStr else { return nil } var model = KDTableViewObject.init() let json = JSON.init(parseJSON: innerJson) let arrayTable = json["table"].arrayValue for tableJson in arrayTable { var item = KDTableCellObject.init(id: "1") item.bgColor = UIColor.yellow item.title = tableJson["title"].stringValue model.tableArray.append(item) } let arrayCollect = json["collect"].arrayValue for collectJson in arrayCollect { var item = KDCollectCellObject.init(id: "1") item.bgColor = UIColor.yellow item.title = collectJson["title"].stringValue model.collectArray.append(item) } return model } }
mit
0fafc3b7c5101b1822c90f9018929da9
27.261905
70
0.604886
4.332117
false
false
false
false
soapyigu/LeetCode_Swift
Array/MajorityElementII.swift
1
1380
/** * Question Link: https://leetcode.com/problems/majority-element-ii/ * Primary idea: traverse the array and track the majority element accordingly, do not * forget to verify they are valid after first iteration * * Time Complexity: O(n), Space Complexity: O(1) * */ class MajorityElementII { func majorityElement(_ nums: [Int]) -> [Int] { var num0: Int? var num1: Int? var count0 = 0 var count1 = 0 var res = [Int]() for num in nums { if let num0 = num0, num0 == num { count0 += 1 } else if let num1 = num1, num1 == num { count1 += 1 } else if count0 == 0 { num0 = num count0 = 1 } else if count1 == 0 { num1 = num count1 = 1 } else { count0 -= 1 count1 -= 1 } } count0 = 0 count1 = 0 for num in nums { if num == num0 { count0 += 1 } if num == num1 { count1 += 1 } } if count0 > nums.count / 3 { res.append(num0!) } if count1 > nums.count / 3 { res.append(num1!) } return res } }
mit
6681c043f128a0b1ee1457c33155ba6b
23.660714
86
0.413768
4.259259
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Timetable/Main/Views/Week/TimetableWeekView.swift
1
2591
// // TimetableWeekView.swift // HTWDD // // Created by Chris Herlemann on 15.12.20. // Copyright © 2020 HTW Dresden. All rights reserved. // import UIKit import JZCalendarWeekView protocol TimetableWeekViewDelegate: AnyObject { func export(_ lessonEvent: LessonEvent) } class TimetableWeekView: JZBaseWeekView { var isDarkMode: Bool { if #available(iOS 13.0, *) { return self.traitCollection.userInterfaceStyle == .dark } else { return false } } weak var delegate: TimetableWeekViewDelegate? override func registerViewClasses() { super.registerViewClasses() self.collectionView.register(UINib(nibName: "LessonCell", bundle: nil), forCellWithReuseIdentifier: "LessonCell") } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LessonCell", for: indexPath) as? LessonCell, let event = getCurrentEvent(with: indexPath) as? LessonEvent { cell.configureCell(event: event) cell.exportDelegate = self return cell } preconditionFailure("LessonCell should be casted") } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cell = super.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath) switch kind { case JZSupplementaryViewKinds.currentTimeline: break default: cell.backgroundColor = isDarkMode ? .black : .white cell.tintColor = .white } return cell } override func setup() { super.setup() setColors() } private func setColors() { if isDarkMode { collectionView.backgroundColor = .black } else { collectionView.backgroundColor = .white } collectionView.reloadData() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setColors() } } extension TimetableWeekView: LessonCellExportDelegate { func export(_ lessonEvent: LessonEvent) { delegate?.export(lessonEvent) } }
gpl-2.0
44274c59ed22258b208b1c7245477c56
27.461538
171
0.637452
5.581897
false
false
false
false
neoreeps/rest-tester
REST Tester/AddFieldsViewController.swift
1
4514
// // HeaderViewController.swift // REST Tester // // Created by Kenny Speer on 10/11/16. // Copyright © 2016 Kenny Speer. All rights reserved. // import UIKit class AddFieldsViewController: UITableViewController { // set the caller from the caller for access here weak var caller: ViewController? @IBOutlet weak var dataTable: UITableView! @IBOutlet var addFieldsTitle: UINavigationItem! @IBOutlet var key: UITextField! @IBOutlet var value: UITextField! // var used to reference temp array data; init them all var headerFields = [[String]]() var dataFields = [[String]]() var tableData = [[String]]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // dataTable.delegate = self // dataTable.dataSource = self // register cell class or through interface builder // self.dataTable.register(UITableViewCell.self, forCellReuseIdentifier: "AddFieldsCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getTableData() -> [[String]] { if addFieldsTitle.title?.lowercased().range(of: "header") != nil { print("TD1: \(headerFields.description))") return headerFields } else if addFieldsTitle.title?.lowercased().range(of: "body") != nil { print("TD2: \(dataFields.description))") return dataFields } else { return [["", ""]] } } @IBAction func clearRow(_ sender: AnyObject) { print("TAG: \(sender.tag)") let tableData = getTableData() if tableData.description == headerFields.description { headerFields.remove(at: sender.tag!) } else if tableData.description == dataFields.description { dataFields.remove(at: sender.tag!) } DispatchQueue.main.async { // do UI updates here self.dataTable.reloadData() } } // add button which actually adds data to lists @IBAction func addFields(_ sender: AnyObject) { // don't let the user add empty fields if key.text == "" || value.text == "" { return } // don't use getTableData here since we can't distinguish and need a // reference to the actual table (it is copied between calls) if addFieldsTitle.title?.lowercased().range(of: "header") != nil { headerFields.append([key.text!, value.text!]) } else if addFieldsTitle.title?.lowercased().range(of: "body") != nil { dataFields.append([key.text!, value.text!]) } print("TABLE UPDATE: \(tableData)") DispatchQueue.main.async { // do UI updates here self.dataTable.reloadData() } key.text = nil value.text = nil } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let tableData = getTableData() if tableView == dataTable { print("FOUND TABLE: \(tableData.count) cells") return tableData.count } return Int() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tableData = getTableData() print("TABLE: \(tableView.description)") if tableView == dataTable { let cell = dataTable.dequeueReusableCell(withIdentifier: "AddFieldsCell", for: indexPath) as! AddFieldsCell let row = indexPath.row print("COUNT: \(tableData[row].count)") cell.key.text = tableData[row][0] cell.value.text = tableData[row][1] cell.clearButton.tag = row return cell } return UITableViewCell() } @IBAction func doneButton(_ sender: AnyObject) { caller!.headerFields = self.headerFields caller!.dataFields = self.dataFields self.dismiss(animated: true, completion: nil) } }
apache-2.0
c96ee0d1b8593f8d86e09e0cc8881df9
30.559441
119
0.58409
4.964796
false
false
false
false
wfleming/SwiftLint
Source/SwiftLintFramework/Extensions/File+Cache.swift
2
3625
// // File+Cache.swift // SwiftLint // // Created by Nikolaj Schumacher on 2015-05-26. // Copyright (c) 2015 Realm. All rights reserved. // import Foundation import SourceKittenFramework private var responseCache = Cache({file in Request.EditorOpen(file).send()}) private var structureCache = Cache({file in Structure(sourceKitResponse: responseCache.get(file))}) private var syntaxMapCache = Cache({file in SyntaxMap(sourceKitResponse: responseCache.get(file))}) private var syntaxKindsByLinesCache = Cache({file in file.syntaxKindsByLine()}) private var _allDeclarationsByType = [String: [String]]() private var queueForRebuild = [Structure]() private struct Cache<T> { private var values = [String: T]() private var factory: File -> T private init(_ factory: File -> T) { self.factory = factory } private mutating func get(file: File) -> T { let key = file.path ?? NSUUID().UUIDString if let value = values[key] { return value } let value = factory(file) values[key] = value if let structure = value as? Structure { queueForRebuild.append(structure) } return value } private mutating func invalidate(file: File) { if let key = file.path { values.removeValueForKey(key) } } private mutating func clear() { values.removeAll(keepCapacity: false) } } extension File { internal var structure: Structure { return structureCache.get(self) } internal var syntaxMap: SyntaxMap { return syntaxMapCache.get(self) } internal var syntaxKindsByLines: [[SyntaxKind]] { return syntaxKindsByLinesCache.get(self) } public func invalidateCache() { responseCache.invalidate(self) structureCache.invalidate(self) syntaxMapCache.invalidate(self) syntaxKindsByLinesCache.invalidate(self) } internal static func clearCaches() { queueForRebuild = [] _allDeclarationsByType = [:] responseCache.clear() structureCache.clear() syntaxMapCache.clear() syntaxKindsByLinesCache.clear() } internal static var allDeclarationsByType: [String: [String]] { if !queueForRebuild.isEmpty { rebuildAllDeclarationsByType() } return _allDeclarationsByType } } private func dictFromKeyValuePairs<Key: Hashable, Value>(pairs: [(Key, Value)]) -> [Key: Value] { var dict = [Key: Value]() for pair in pairs { dict[pair.0] = pair.1 } return dict } private func substructureForDict(dict: [String: SourceKitRepresentable]) -> [[String: SourceKitRepresentable]]? { return (dict["key.substructure"] as? [SourceKitRepresentable])?.flatMap { $0 as? [String: SourceKitRepresentable] } } private func rebuildAllDeclarationsByType() { let allDeclarationsByType = queueForRebuild.flatMap { structure -> (String, [String])? in guard let firstSubstructureDict = substructureForDict(structure.dictionary)?.first, name = firstSubstructureDict["key.name"] as? String, kind = (firstSubstructureDict["key.kind"] as? String).flatMap(SwiftDeclarationKind.init) where kind == .Protocol, let substructure = substructureForDict(firstSubstructureDict) else { return nil } return (name, substructure.flatMap({ $0["key.name"] as? String })) } allDeclarationsByType.forEach { _allDeclarationsByType[$0.0] = $0.1 } queueForRebuild = [] }
mit
b6131394c253a697cd6578065ebe7bbc
29.462185
100
0.647448
4.351741
false
false
false
false
harry-iOS/HYCalendar
HYCalendarExample/Pods/HYCalendar/HYCalendar/HYCalendar/CalnedarView/CalendarHeaderCell.swift
2
1070
// // CalendarHeaderCell.swift // CalendarPOC // // Created by Harry on 14/11/16. // Copyright © 2016 TTND. All rights reserved. // import UIKit class CalendarHeaderCell: UICollectionViewCell { var label : UILabel! var string : String? override init(frame: CGRect) { super.init(frame: frame) customInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) customInit() } private func customInit() { label = UILabel(frame:self.bounds) label.autoresizingMask = [.flexibleWidth, .flexibleHeight] label.center = self.contentView.center label.textAlignment = NSTextAlignment.center label.textColor = HeaderCellTextColor label.font = HeaderCellTextFont self.contentView.addSubview(label) self.backgroundColor = UIColor.clear isUserInteractionEnabled = false } override func prepareForReuse() { label.text = "" } func configureTitle(_ title:String) { label.text = title } }
mit
4486b3718f410be1a05cfcfa47c5822f
22.23913
66
0.641721
4.529661
false
false
false
false
zpz1237/NirZhihuNews
Pods/Alamofire/Source/MultipartFormData.swift
1
28404
// MultipartFormData.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation #if os(iOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif /** Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well and the w3 form documentation. - http://www.ietf.org/rfc/rfc2388.txt - http://www.ietf.org/rfc/rfc2045.txt - http://www.w3.org/TR/html401/interact/forms.html#h-17.13 */ public class MultipartFormData { // MARK: - Helper Types /** Used to specify whether encoding was successful. */ public enum EncodingResult { case Success(NSData) case Failure(NSError) } struct EncodingCharacters { static let CRLF = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case Initial, Encapsulated, Final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { let boundaryText: String switch boundaryType { case .Initial: boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" case .Encapsulated: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" case .Final: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" } return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } } class BodyPart { let headers: [String: String] let bodyStream: NSInputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: NSError? private let streamBufferSize: Int // MARK: - Lifecycle /** Creates a multipart form data object. - returns: The multipart form data object. */ public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /** * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more * information, please refer to the following article: * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html */ self.streamBufferSize = 1024 } // MARK: - Body Parts /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. */ public func appendBodyPart(data data: NSData, name: String) { let headers = contentHeaders(name: name) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, mimeType: String) { let headers = contentHeaders(name: name, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary The filename in the `Content-Disposition` HTTP header is generated from the last path component of the `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the system associated MIME type. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String) { if let fileName = fileURL.lastPathComponent, pathExtension = fileURL.pathExtension { let mimeType = mimeTypeForPathExtension(pathExtension) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: AlamofireErrorDomain, code: NSURLErrorBadURL, userInfo: userInfo) setBodyPartError(error) } } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - Content-Type: #{mimeType} (HTTP Header) - Encoded file data - Multipart form boundary - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) var isDirectory: ObjCBool = false var error: NSError? if !fileURL.fileURL { error = errorWithCode(NSURLErrorBadURL, failureReason: "The URL does not point to a file URL: \(fileURL)") } else { do { try fileURL.checkResourceIsReachableAndReturnError(nil) if NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!, isDirectory: &isDirectory) && isDirectory { error = errorWithCode(NSURLErrorBadURL, failureReason: "The URL is a directory, not a file: \(fileURL)") } } catch _ { error = errorWithCode(NSURLErrorBadURL, failureReason: "The URL is not reachable: \(fileURL)") } } if let error = error { setBodyPartError(error) return } let length: UInt64 // if let path = fileURL.path, attributes = NSFileManager.defaultManager().attributesOfItemAtPath(path), // fileSize = (attributes[NSFileSize] as? NSNumber)?.unsignedLongLongValue // { // length = fileSize // } else { // let failureReason = "Could not fetch attributes from the URL: \(fileURL)" // let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason) // // setBodyPartError(error) // // return // } if let path = fileURL.path { do{ let attributes = try NSFileManager.defaultManager().attributesOfItemAtPath(path) let fileSize = (attributes[NSFileSize] as? NSNumber)?.unsignedLongLongValue length = fileSize! }catch _{ let failureReason = "Could not fetch attributes from the URL: \(fileURL)" let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } } else { let failureReason = "Could not fetch attributes from the URL: \(fileURL)" let error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } if let stream = NSInputStream(URL: fileURL) { appendBodyPart(stream: stream, length: length, headers: headers) } else { let failureReason = "Failed to create an input stream from the URL: \(fileURL)" let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) setBodyPartError(error) } } /** Creates a body part from the stream and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. */ public func appendBodyPart(stream stream: NSInputStream, length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part with the headers, stream and length and appends it to the multipart form data object. The body part data will be encoded using the following format: - HTTP headers - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter headers: The HTTP headers for the body part. */ public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /** Encodes all the appended body parts into a single `NSData` object. It is important to note that this method will load all the appended body parts into memory all at the same time. This method should only be used when the encoded data will have a small memory footprint. For large data cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - returns: EncodingResult containing an `NSData` object if the encoding succeeded, an `NSError` otherwise. */ public func encode() -> EncodingResult { if let bodyPartError = bodyPartError { return .Failure(bodyPartError) } let encoded = NSMutableData() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedDataResult = encodeBodyPart(bodyPart) switch encodedDataResult { case .Failure: return encodedDataResult case let .Success(data): encoded.appendData(data) } } return .Success(encoded) } /** Writes the appended body parts into the given file URL asynchronously and calls the `completionHandler` when finished. This process is facilitated by reading and writing with input and output streams, respectively. Thus, this approach is very memory efficient and should be used for large body part data. - parameter fileURL: The file URL to write the multipart form data into. - parameter completionHandler: A closure to be executed when writing is finished. */ public func writeEncodedDataToDisk(fileURL: NSURL, completionHandler: (NSError?) -> Void) { if let bodyPartError = bodyPartError { completionHandler(bodyPartError) return } var error: NSError? if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason) } if let error = error { completionHandler(error) return } let outputStream: NSOutputStream if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) completionHandler(error) return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true var error: NSError? for bodyPart in self.bodyParts { if let writeError = self.writeBodyPart(bodyPart, toOutputStream: outputStream) { error = writeError break } } outputStream.close() outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) dispatch_async(dispatch_get_main_queue()) { completionHandler(error) } } } // MARK: - Private - Body Part Encoding private func encodeBodyPart(bodyPart: BodyPart) -> EncodingResult { let encoded = NSMutableData() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.appendData(initialData) let headerData = encodeHeaderDataForBodyPart(bodyPart) encoded.appendData(headerData) let bodyStreamResult = encodeBodyStreamDataForBodyPart(bodyPart) switch bodyStreamResult { case .Failure: return bodyStreamResult case let .Success(data): encoded.appendData(data) } if bodyPart.hasFinalBoundary { encoded.appendData(finalBoundaryData()) } return .Success(encoded) } private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" } headerText += EncodingCharacters.CRLF return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) -> EncodingResult { let inputStream = bodyPart.bodyStream inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? let encoded = NSMutableData() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if inputStream.streamError != nil { error = inputStream.streamError break } if bytesRead > 0 { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason) break } else { break } } inputStream.close() inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { return .Failure(error) } return .Success(encoded) } // MARK: - Private - Writing Body Part to Output Stream private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? { if let error = writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) { return error } if let error = writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) { return error } if let error = writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) { return error } if let error = writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) { return error } return nil } private func writeInitialBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return writeData(initialData, toOutputStream: outputStream) } private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? { let headerData = encodeHeaderDataForBodyPart(bodyPart) return writeData(headerData, toOutputStream: outputStream) } private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? { var error: NSError? let inputStream = bodyPart.bodyStream inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if inputStream.streamError != nil { error = inputStream.streamError break } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0..<bytesRead]) } if let writeError = writeBuffer(&buffer, toOutputStream: outputStream) { error = writeError break } } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason) break } else { break } } inputStream.close() inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) return error } private func writeFinalBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? { if bodyPart.hasFinalBoundary { return writeData(finalBoundaryData(), toOutputStream: outputStream) } return nil } // MARK: - Private - Writing Buffered Data to Output Stream private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) -> NSError? { var buffer = [UInt8](count: data.length, repeatedValue: 0) data.getBytes(&buffer, length: data.length) return writeBuffer(&buffer, toOutputStream: outputStream) } private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) -> NSError? { var error: NSError? var bytesToWrite = buffer.count while bytesToWrite > 0 { if outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if outputStream.streamError != nil { error = outputStream.streamError break } if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" error = errorWithCode(AlamofireOutputStreamWriteFailed, failureReason: failureReason) break } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten..<buffer.count]) } } else if outputStream.streamError != nil { error = outputStream.streamError break } } return error } // MARK: - Private - Mime Type private func mimeTypeForPathExtension(pathExtension: String) -> String { let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)!.takeRetainedValue() if let contentType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType) { return contentType.takeRetainedValue() as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(name name: String) -> [String: String] { return ["Content-Disposition": "form-data; name=\"\(name)\""] } private func contentHeaders(name name: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"", "Content-Type": "\(mimeType)" ] } private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", "Content-Type": "\(mimeType)" ] } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) } private func encapsulatedBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) } private func finalBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(error: NSError) { if bodyPartError == nil { bodyPartError = error } } private func errorWithCode(code: Int, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: AlamofireErrorDomain, code: code, userInfo: userInfo) } }
mit
4fd69db372bab54314df1853373ea771
38.33795
133
0.645659
5.176235
false
false
false
false
piglikeYoung/iOS8-day-by-day
35-coremotion/LocoMotion/LocoMotion/MotionActivityCell.swift
21
2660
// // Copyright 2014 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import CoreMotion class MotionActivityCell: UITableViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var pedometerLabel: UILabel! var activity: Activity? { didSet { prepareCellForActivity(activity) } } var dateFormatter: NSDateFormatter? var lengthFormatter: NSLengthFormatter? var pedometer: CMPedometer? // MARK:- Utility methods private func prepareCellForActivity(activity: Activity?) { if let activity = activity { var imageName = "" switch activity.type { case .Cycling: imageName = "cycle" pedometerLabel.text = "" case .Running: imageName = "run" requestPedometerData() case .Walking: imageName = "walk" requestPedometerData() default: imageName = "" pedometerLabel.text = "" } iconImageView.image = UIImage(named: imageName) titleLabel.text = "\(dateFormatter!.stringFromDate(activity.startDate)) - \(dateFormatter!.stringFromDate(activity.endDate))" } } private func requestPedometerData() { pedometer?.queryPedometerDataFromDate(activity?.startDate, toDate: activity?.endDate) { (data, error) -> Void in if error != nil { println("There was an error requesting data from the pedometer: \(error)") } else { dispatch_async(dispatch_get_main_queue()) { self.pedometerLabel.text = self.constructPedometerString(data) } } } } private func constructPedometerString(data: CMPedometerData) -> String { var pedometerString = "" if CMPedometer.isStepCountingAvailable() { pedometerString += "\(data.numberOfSteps) steps | " } if CMPedometer.isDistanceAvailable() { pedometerString += "\(lengthFormatter!.stringFromMeters(data.distance as! Double)) | " } if CMPedometer.isFloorCountingAvailable() { pedometerString += "\(data.floorsAscended) floors" } return pedometerString } }
apache-2.0
067b7f66c0756aa7ab41d0068d6dbc63
28.555556
131
0.676316
4.433333
false
false
false
false
SimoKutlin/tweetor
tweetor/TwitterDeserializer.swift
1
822
// // TwitterDeserializer.swift // tweetor // // Created by simo.kutlin on 03.05.17. // Copyright © 2017 simo.kutlin All rights reserved. // import Foundation import SwiftyJSON open class TwitterDeserializer { var error: String = "" var objects: [Tweet] = [] open func deserialize(_ responseData: Any?) -> TwitterDeserializer { let response = TwitterDeserializer() guard let data = responseData else { response.error = "No Data returned - Response data is nil." return response } let JSONdata = JSON(data) let tweets = JSONdata["statuses"] let results: [Tweet] = Tweet.collection(tweets) response.objects = results return response } }
mit
878e1c0a3695556b69a63b5c63529ad0
22.457143
72
0.574909
4.664773
false
false
false
false
alisidd/iOS-WeJ
Pods/M13Checkbox/Sources/DefaultValues.swift
1
1623
// // ConstantValues.swift // M13Checkbox // // Created by Andrea Antonioni on 30/07/17. // Copyright © 2017 Brandon McQuilkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation // A set of default values used to initialize the object struct DefaultValues { static let animation: M13Checkbox.Animation = .stroke static let markType: M13Checkbox.MarkType = .checkmark static let boxType: M13Checkbox.BoxType = .circle static let checkState: M13Checkbox.CheckState = .unchecked static let controller: M13CheckboxController = M13CheckboxStrokeController() }
gpl-3.0
dad92c9972fcd9d546dcbbbbbbb004b9
63.88
464
0.775586
4.581921
false
false
false
false
Quick/Nimble
Sources/Nimble/Matchers/ContainElementSatisfying.swift
2
2231
public func containElementSatisfying<S: Sequence>( _ predicate: @escaping ((S.Element) -> Bool), _ predicateDescription: String = "" ) -> Predicate<S> { return Predicate.define { actualExpression in let message: ExpectationMessage if predicateDescription == "" { message = .expectedTo("find object in collection that satisfies predicate") } else { message = .expectedTo("find object in collection \(predicateDescription)") } if let sequence = try actualExpression.evaluate() { for object in sequence where predicate(object) { return PredicateResult(bool: true, message: message) } return PredicateResult(bool: false, message: message) } return PredicateResult(status: .fail, message: message) } } #if canImport(Darwin) import class Foundation.NSObject import struct Foundation.NSFastEnumerationIterator import protocol Foundation.NSFastEnumeration extension NMBPredicate { @objc public class func containElementSatisfyingMatcher(_ predicate: @escaping ((NSObject) -> Bool)) -> NMBPredicate { return NMBPredicate { actualExpression in let value = try actualExpression.evaluate() guard let enumeration = value as? NSFastEnumeration else { let message = ExpectationMessage.fail( "containElementSatisfying must be provided an NSFastEnumeration object" ) return NMBPredicateResult(status: .fail, message: message.toObjectiveC()) } let message = ExpectationMessage .expectedTo("find object in collection that satisfies predicate") .toObjectiveC() var iterator = NSFastEnumerationIterator(enumeration) while let item = iterator.next() { guard let object = item as? NSObject else { continue } if predicate(object) { return NMBPredicateResult(status: .matches, message: message) } } return NMBPredicateResult(status: .doesNotMatch, message: message) } } } #endif
apache-2.0
ebd81d733ab6d711c126c8529f288555
36.813559
122
0.620798
5.691327
false
false
false
false
ruilin/RLMap
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Gallery/Photos/PhotosViewController.swift
4
8553
import UIKit @objc(MWMPhotosViewController) final class PhotosViewController: MWMViewController { var referenceViewForPhotoWhenDismissingHandler: ((GalleryItemModel) -> UIView?)? private let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey: 16.0]) private(set) var photos: GalleryModel fileprivate let transitionAnimator = PhotosTransitionAnimator() fileprivate let interactiveAnimator = PhotosInteractionAnimator() fileprivate let overlayView = PhotosOverlayView(frame: CGRect.zero) private var overlayViewHidden = false private lazy var singleTapGestureRecognizer: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(handleSingleTapGestureRecognizer(_:))) }() private lazy var panGestureRecognizer: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(handlePanGestureRecognizer(_:))) }() fileprivate var interactiveDismissal = false private var currentPhotoViewController: PhotoViewController? { return pageViewController.viewControllers?.first as? PhotoViewController } fileprivate var currentPhoto: GalleryItemModel? { return currentPhotoViewController?.photo } init(photos: GalleryModel, initialPhoto: GalleryItemModel? = nil, referenceView: UIView? = nil) { self.photos = photos super.init(nibName: nil, bundle: nil) initialSetupWithInitialPhoto(initialPhoto) transitionAnimator.startingView = referenceView transitionAnimator.endingView = currentPhotoViewController?.scalingView.imageView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func initialSetupWithInitialPhoto(_ initialPhoto: GalleryItemModel? = nil) { overlayView.photosViewController = self setupPageViewController(initialPhoto: initialPhoto) modalPresentationStyle = .custom transitioningDelegate = self modalPresentationCapturesStatusBarAppearance = true overlayView.photosViewController = self } private func setupPageViewController(initialPhoto: GalleryItemModel? = nil) { pageViewController.view.backgroundColor = UIColor.clear pageViewController.delegate = self pageViewController.dataSource = self if let photo = initialPhoto { let photoViewController = initializePhotoViewController(photo: photo) pageViewController.setViewControllers([photoViewController], direction: .forward, animated: false, completion: nil) } overlayView.photo = initialPhoto } fileprivate func initializePhotoViewController(photo: GalleryItemModel) -> PhotoViewController { let photoViewController = PhotoViewController(photo: photo) singleTapGestureRecognizer.require(toFail: photoViewController.doubleTapGestureRecognizer) return photoViewController } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() view.tintColor = UIColor.white view.backgroundColor = UIColor.black pageViewController.view.backgroundColor = UIColor.clear pageViewController.view.addGestureRecognizer(singleTapGestureRecognizer) pageViewController.view.addGestureRecognizer(panGestureRecognizer) addChildViewController(pageViewController) view.addSubview(pageViewController.view) pageViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] pageViewController.didMove(toParentViewController: self) setupOverlayView() } private func setupOverlayView() { overlayView.photo = currentPhoto overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight] overlayView.frame = view.bounds view.addSubview(overlayView) setOverlayHidden(false, animated: false) } private func setOverlayHidden(_ hidden: Bool, animated: Bool) { overlayViewHidden = hidden overlayView.setHidden(hidden, animated: animated) { [weak self] in self?.setNeedsStatusBarAppearanceUpdate() } } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { guard presentedViewController == nil else { super.dismiss(animated: flag, completion: completion) return } transitionAnimator.startingView = currentPhotoViewController?.scalingView.imageView if let currentPhoto = currentPhoto { transitionAnimator.endingView = referenceViewForPhotoWhenDismissingHandler?(currentPhoto) } else { transitionAnimator.endingView = nil } let overlayWasHiddenBeforeTransition = overlayView.isHidden setOverlayHidden(true, animated: true) super.dismiss(animated: flag) { [weak self] in guard let s = self else { return } let isStillOnscreen = s.view.window != nil if isStillOnscreen && !overlayWasHiddenBeforeTransition { s.setOverlayHidden(false, animated: true) } completion?() } } // MARK: - Gesture Recognizers @objc private func handlePanGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) { if gestureRecognizer.state == .began { interactiveDismissal = true dismiss(animated: true, completion: nil) } else { interactiveDismissal = false interactiveAnimator.handlePanWithPanGestureRecognizer(gestureRecognizer, viewToPan: pageViewController.view, anchorPoint: CGPoint(x: view.bounds.midX, y: view.bounds.midY)) } } @objc private func handleSingleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) { setOverlayHidden(!overlayView.isHidden, animated: true) } //MARK: - Orientations override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } // MARK: - Status Bar override var prefersStatusBarHidden: Bool { return overlayViewHidden } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } } extension PhotosViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitionAnimator.dismissing = false return transitionAnimator } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitionAnimator.dismissing = true return transitionAnimator } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if interactiveDismissal { interactiveAnimator.animator = transitionAnimator interactiveAnimator.shouldAnimateUsingAnimator = transitionAnimator.endingView != nil interactiveAnimator.viewToHideWhenBeginningTransition = overlayView return interactiveAnimator } return nil } } extension PhotosViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let photoViewController = viewController as? PhotoViewController, let photoIndex = photos.items.index(where: { $0 === photoViewController.photo }), photoIndex - 1 >= 0 else { return nil } let newPhoto = photos.items[photoIndex - 1] return initializePhotoViewController(photo: newPhoto) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let photoViewController = viewController as? PhotoViewController, let photoIndex = photos.items.index(where: { $0 === photoViewController.photo }), photoIndex + 1 < photos.items.count else { return nil } let newPhoto = photos.items[photoIndex + 1] return initializePhotoViewController(photo: newPhoto) } } extension PhotosViewController: UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed { if let currentPhoto = currentPhoto { overlayView.photo = currentPhoto } } } }
apache-2.0
c1cb8faa2f6978b51f9b50e44a2dcd20
37.701357
188
0.755875
5.779054
false
false
false
false
MaddTheSane/WWDC
WWDC/About.swift
1
1947
// // About.swift // WWDC // // Created by Guilherme Rambo on 20/12/15. // Copyright © 2015 Guilherme Rambo. All rights reserved. // import Foundation import Alamofire private let _sharedAboutInfo = About() class About { class var sharedInstance: About { return _sharedAboutInfo } private struct Constants { static let contributorsURL = "https://api.github.com/repos/insidegui/WWDC/contributors" } var infoTextChangedCallback: (newText: String) -> () = { _ in } var infoText = "" { didSet { mainQ { self.infoTextChangedCallback(newText: self.infoText) } } } /// Loads the list of contributors from the GitHub repository and builds the infoText func load() { Alamofire.request(.GET, Constants.contributorsURL).responseJSON { response in switch response.result { case .Success(_): self.parseResponse(response) default: print("Unable to download about window contribution info") } } } private func parseResponse(response: Response<AnyObject, NSError>) { guard let rawData = response.data else { return } let jsonData = JSON(data: rawData) guard let contributors = jsonData.array else { return } var contributorNames = [String]() for contributor in contributors { if let name = contributor["login"].string { contributorNames.append(name) } } buildInfoText(contributorNames) } private func buildInfoText(names: [String]) { var text = "Contributors (GitHub usernames):\n" var prefix = "" for name in names { text.appendContentsOf("\(prefix)\(name)") prefix = ", " } infoText = text } }
bsd-2-clause
b8c846d7924f43141d3e19c19a87a39c
25.671233
95
0.567831
4.989744
false
false
false
false
crashoverride777/Swift-2-iAds-AdMob-CustomAds-Helper
Sources/Internal/SwiftyAdsConsentManager.swift
2
6510
// The MIT License (MIT) // // Copyright (c) 2015-2021 Dominik Ringler // // 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 GoogleMobileAds import UserMessagingPlatform /* The SDK is designed to be used in a linear fashion. The steps for using the SDK are: Request the latest consent information. Check if consent is required. Check if a form is available and if so load a form. Present the form. Provide a way for users to change their consent. */ protocol SwiftyAdsConsentManagerType: AnyObject { var consentStatus: SwiftyAdsConsentStatus { get } func requestUpdate(completion: @escaping SwiftyAdsConsentResultHandler) func showForm(from viewController: UIViewController, completion: @escaping SwiftyAdsConsentResultHandler) } final class SwiftyAdsConsentManager { // MARK: - Properties private let consentInformation: UMPConsentInformation private let configuration: SwiftyAdsConfiguration private let environment: SwiftyAdsEnvironment private let consentStatusDidChange: (SwiftyAdsConsentStatus) -> Void private var form: UMPConsentForm? // MARK: - Initialization init(consentInformation: UMPConsentInformation, configuration: SwiftyAdsConfiguration, environment: SwiftyAdsEnvironment, consentStatusDidChange: @escaping (SwiftyAdsConsentStatus) -> Void ) { self.consentInformation = consentInformation self.configuration = configuration self.environment = environment self.consentStatusDidChange = consentStatusDidChange } } // MARK: - SwiftyAdsConsentManagerType extension SwiftyAdsConsentManager: SwiftyAdsConsentManagerType { var consentStatus: SwiftyAdsConsentStatus { consentInformation.consentStatus } func requestUpdate(completion: @escaping SwiftyAdsConsentResultHandler) { // Create a UMPRequestParameters object. let parameters = UMPRequestParameters() // Set UMPDebugSettings if in development environment. switch environment { case .production: break case .development(let testDeviceIdentifiers, let consentConfiguration): let debugSettings = UMPDebugSettings() debugSettings.testDeviceIdentifiers = testDeviceIdentifiers debugSettings.geography = consentConfiguration.geography parameters.debugSettings = debugSettings if case .resetOnLaunch = consentConfiguration { consentInformation.reset() } case .debug(let testDeviceIdentifiers, let geography, let resetConsentInfo): let debugSettings = UMPDebugSettings() debugSettings.testDeviceIdentifiers = testDeviceIdentifiers debugSettings.geography = geography parameters.debugSettings = debugSettings if resetConsentInfo { consentInformation.reset() } } // Update parameters for under age of consent. parameters.tagForUnderAgeOfConsent = configuration.isTaggedForUnderAgeOfConsent // Request an update to the consent information. // The first time we request consent information, even if outside of EEA, the status // may return `.required` as the ATT alert has not yet been displayed and we are using // Google Choices ATT message. consentInformation.requestConsentInfoUpdate(with: parameters) { [weak self] error in guard let self = self else { return } // Handle error if let error = error { completion(.failure(error)) return } // The consent information state was updated and we can now check if a form is available. switch self.consentInformation.formStatus { case .available: DispatchQueue.main.async { UMPConsentForm.load { [weak self ] (form, error) in guard let self = self else { return } if let error = error { completion(.failure(error)) return } self.form = form completion(.success(self.consentStatus)) } } case .unavailable: completion(.success(self.consentStatus)) case .unknown: completion(.success(self.consentStatus)) @unknown default: completion(.success(self.consentStatus)) } } } func showForm(from viewController: UIViewController, completion: @escaping SwiftyAdsConsentResultHandler) { // Ensure form is loaded guard let form = form else { completion(.failure(SwiftyAdsError.consentFormNotAvailable)) return } // Present the form form.present(from: viewController) { [weak self] error in guard let self = self else { return } /// Handle error if let error = error { completion(.failure(error)) return } /// Fire status did change handler self.consentStatusDidChange(self.consentStatus) /// Fire completion handler completion(.success(self.consentStatus)) } } }
mit
857bb54dfda06db673d3a55f1b511025
37.52071
111
0.65192
5.447699
false
true
false
false
LiLe2015/DouYuLive
DouYuLive/DouYuLive/Classes/Main/View/PageTitleView.swift
1
6270
// // PageTitleView.swift // DouYuLive // // Created by LiLe on 2016/11/10. // Copyright © 2016年 LiLe. All rights reserved. // import UIKit // MARK:- 定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView: PageTitleView, selectedIndex index:Int) } // MARK:- 定义常量 private let kScrollLineH: CGFloat = 2 private let kNormalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0) // MARK:- 定义PageTitleView类 class PageTitleView: UIView { // MARK:- 定义属性 private var currentIndex: Int = 0 private var titles: [String] weak var delegate: PageTitleViewDelegate? // MARK:- 懒加载属性 private lazy var titleLabels: [UILabel] = [UILabel]() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() private lazy var scrollLine: UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orangeColor() return scrollLine }() // MARK:- 自定义构造函数 init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) // 设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面 extension PageTitleView { private func setupUI() { // 1.添加UIScrollView addSubview(scrollView) scrollView.frame = bounds // 2.添加title对应的Label setupTitleLabels() // 3.设置底线和滚动的滑块 setupBottomMenuAndScrollLine() } private func setupTitleLabels() { // 0.确定label的一些值 let labelW: CGFloat = frame.width / CGFloat(titles.count) let labelH: CGFloat = frame.height - kScrollLineH let labelY: CGFloat = 0 for (index, title) in titles.enumerate() { // 1.创建UILabel let label = UILabel() // 2.设置Label的属性 label.text = title label.tag = index label.font = UIFont.systemFontOfSize(16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .Center // 3.设置label的frame let labelX: CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) // 4.将label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) // 5.给Label添加手势 label.userInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_:))) label.addGestureRecognizer(tapGes) } } private func setupBottomMenuAndScrollLine() { // 1.添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGrayColor() let lineH:CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) // 2.添加scrollLine // 2.1获取第一个Label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) // 2.2.设置scrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } // MARK:- 监听Label的点击 extension PageTitleView { @objc private func titleLabelClick(tapGes: UITapGestureRecognizer) { // 1.获取当前Label guard let currentLabel = tapGes.view as? UILabel else { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.滚动条位置发生变化 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animateWithDuration(0.15) { self.scrollLine.frame.origin.x = scrollLineX } // 6.通知代理 delegate?.pageTitleView(self, selectedIndex: currentIndex) } } // MARK:- 对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.3.变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex } }
mit
4124a80cdd80dbe1fa79e4c46cbb7134
32.418079
174
0.615723
4.664826
false
false
false
false
HTWDD/HTWGrades
HTWGrades/HTWGrades/GradesModel.swift
1
3647
// // GradesModel.swift // HTWGrades // // Created by Benjamin Herzog on 23/11/15. // Copyright © 2015 HTW Dresden. All rights reserved. // import Foundation import Alamofire import ObjectMapper let getPos = "https://wwwqis.htw-dresden.de/appservice/getcourses" let getGrade = "https://wwwqis.htw-dresden.de/appservice/getgrades" class GradesModel { init() { } func start(completion: ([String: [Grade]] -> Void)? = nil) { loadCourses { success, data in if !success { print("course error") return } for course in data { self.loadGrades(course) { success, grades in if !success { print("grade error") return } completion?(self.groupGrades(grades)) } } } } private func groupGrades(grades: [Grade]) -> [String: [Grade]] { var result = [String: [Grade]]() for grade in grades { if result[grade.semester] == nil { result[grade.semester] = [] } result[grade.semester]?.append(grade) } return result } private func loadCourses(completion: (success: Bool, data: [Course]) -> Void) { Alamofire.request(.POST, getPos, parameters: ["sNummer": sNummer, "RZLogin": Passwort]) .responseJSON { response in guard let coursesArray = response.result.value as? [[String: String]] else { completion(success: false, data: []) return } let courses = coursesArray.map { element in return Mapper<Course>().map(element) }.filter { $0 != nil }.map { $0! } completion(success: true, data: courses) } } private func loadGrades(course: Course, completion: (success: Bool, data: [Grade]) -> Void) { Alamofire.request(.POST, getGrade, parameters: ["sNummer": sNummer, "RZLogin": Passwort, "AbschlNr": course.AbschlNr, "POVersion": course.POVersion, "StgNr": course.StgNr]) .responseJSON { jsonResponse in guard let allGrades = jsonResponse.result.value as? [[String: String]] else { completion(success: false, data: []) return } let grades = allGrades.map { Mapper<Grade>().map($0) }.filter { $0 != nil }.map { $0! } completion(success: true, data: grades) } } } struct Course: Mappable { var AbschlNr: String var POVersion: String var StgNr: String init?(_ map: Map) { AbschlNr = map["AbschlNr"].valueOrFail() POVersion = map["POVersion"].valueOrFail() StgNr = map["StgNr"].valueOrFail() if !map.isValid { return nil } } mutating func mapping(map: Map) { } } struct Grade: Mappable, CustomStringConvertible { var nr: Int = 0 var subject: String var state: String var credits: Double = 0 var grade: Double = 0 var semester: String init?(_ map: Map) { subject = map["PrTxt"].valueOr("") state = map["Status"].valueOr("") semester = map["Semester"].valueOrFail() if !map.isValid { return nil } } mutating func mapping(map: Map) { let stringToIntTransform = TransformOf<Int, String>(fromJSON: { $0.map { Int($0) ?? 0 } }, toJSON: { "\($0 ?? 0)" }) let stringToDoubleTransform = TransformOf<Double, String>(fromJSON: { $0.map { Double($0) ?? 0 } }, toJSON: { "\($0 ?? 0)" }) nr <- (map["PrNr"], stringToIntTransform) credits <- (map["EctsCredits"], stringToDoubleTransform) grade <- (map["PrNote"], stringToDoubleTransform) grade /= 100 } var description: String { return "\nGrade:\n\tNr: \(nr)\n\tFach: \(subject)\n\tCredtis: \(credits)\n\tNote: \(grade)" } }
apache-2.0
5d85de3807c559977b7113b8f3b9059b
20.963855
174
0.598738
3.48566
false
false
false
false
suominentoni/nearest-departures
HSL Nearest Departures/LoadingIndicator.swift
1
1628
// // LoadingIndicator.swift // HSL Nearest Departures // // Created by Toni Suominen on 11/08/16. // Copyright © 2016 Toni Suominen. All rights reserved. // import UIKit open class LoadingIndicator: UIView { override init(frame: CGRect) { super.init(frame: frame) animateLoadingCircle() } required public init?(coder aDecoder: NSCoder) { fatalError("Not coder compliant") } fileprivate func animateLoadingCircle() { let rectShape = CAShapeLayer() rectShape.bounds = bounds rectShape.position = CGPoint(x: center.x, y: center.y) rectShape.path = UIBezierPath(ovalIn: rectShape.bounds).cgPath rectShape.lineWidth = 4.0 rectShape.strokeColor = UIColor.lightGray.cgColor rectShape.fillColor = UIColor.clear.cgColor rectShape.strokeStart = 0 rectShape.strokeEnd = 0.0 let end = CABasicAnimation(keyPath: "strokeEnd") end.duration = 2 end.fromValue = 0 end.toValue = 1.0 end.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) let start = CABasicAnimation(keyPath: "strokeStart") start.beginTime = 0.5 start.duration = 1.5 start.fromValue = 0 start.toValue = 1.0 start.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) let group = CAAnimationGroup() group.duration = 2 group.animations = [end, start] group.repeatCount = HUGE rectShape.add(group, forKey: nil) layer.addSublayer(rectShape) } }
mit
696b27b466a3acce29703bb0798f95ad
29.12963
99
0.654579
4.482094
false
false
false
false
Snowgan/WeiboDemo
WeiboDemo/XLWeiboPicsLayout.swift
1
1139
// // XLWeiboPicsLayout.swift // WeiboDemo // // Created by Jennifer on 16/2/16. // Copyright © 2016 Snowgan. All rights reserved. // import Foundation class XLWeiboPicsLayout { let statusData: XLPicStatus var picsOrigin: [CGPoint] { var origins = [CGPoint]() let picsCount = statusData.picsURL.count let rows = (picsCount - 1) / 3 + 1 let cols = (picsCount == 4) ? 2 : ((rows > 1) ? 3 : picsCount) for i in 0..<rows { for j in 0..<cols { if i*cols+j < picsCount { let origX = (homePicInset + homePicWH) * CGFloat(j) + kWeiboCellMargin let origY = (homePicInset + homePicWH) * CGFloat(i) origins.append(CGPoint(x: origX, y: origY)) } } } return origins } var picsHeight: CGFloat { if !picsOrigin.isEmpty { return picsOrigin.last!.y + homePicWH + kWeiboCellMargin } else { return 0 } } init(withStatusData status: XLPicStatus) { statusData = status } }
mit
8af421c9a6601f5cc98cada1b94ea8ca
24.886364
90
0.525483
3.89726
false
false
false
false
serp1412/LazyTransitions
LazyTransitionsTests/TransitionProgressCalculatorTests.swift
1
7064
// // TransitionProgressCalculatorTests.swift // LazyTransitions // // Created by Serghei Catraniuc on 12/2/16. // Copyright © 2016 BeardWare. All rights reserved. // import XCTest @testable import LazyTransitions class TransitionProgressCalculatorTests: XCTestCase { let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 400)) func testCalculateProgress_TopToBottomTransition_PanningDown() { let translation = CGPoint(x: 0, y: 10) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .topToBottom) XCTAssert(progress == 0.02500000037252903) } func testCalculateProgress_TopToBottomTransition_PanningUp() { let translation = CGPoint(x: 0, y: -10) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .topToBottom) XCTAssert(progress == 0) } func testCalculateProgress_TopToBottomTransition_PanningDown_BeyondViewBounds() { let translation = CGPoint(x: 0, y: 450) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .topToBottom) XCTAssert(progress == 1) } func testCalculateProgress_BottomToTop_PanningDown() { let translation = CGPoint(x: 0, y: 10) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .bottomToTop) XCTAssert(progress == 0) } func testCalculateProgress_BottomToTop_PanningUp() { let translation = CGPoint(x: 0, y: -10) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .bottomToTop) XCTAssert(progress == 0.02500000037252903) } func testCalculateProgress_BottomToTopTransition_PanningDown_BeyondViewBounds() { let translation = CGPoint(x: 0, y: -450) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .bottomToTop) XCTAssert(progress == 1) } func testCalculateProgress_LeftToRightTransition_PanningRight() { let translation = CGPoint(x: 10, y: 0) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .leftToRight) XCTAssert(progress == 0.05000000074505806) } func testCalculateProgress_LeftToRightTransition_PanningLeft() { let translation = CGPoint(x: -10, y: 0) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .leftToRight) XCTAssert(progress == 0) } func testCalculateProgress_LeftToRightTransition_PanningRight_BeyondViewBounds() { let translation = CGPoint(x: 220, y: 0) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .leftToRight) XCTAssert(progress == 1) } func testCalculateProgress_RightToLeftTransition_PanningRight() { let translation = CGPoint(x: 10, y: 0) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .rightToLeft) XCTAssert(progress == 0) } func testCalculateProgress_RightToLeftTransition_PanningLeft() { let translation = CGPoint(x: -10, y: 0) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .rightToLeft) XCTAssert(progress == 0.05000000074505806) } func testCalculateProgress_RightToLeftTransition_PanningLeft_BeyondViewBounds() { let translation = CGPoint(x: -220, y: 0) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: .zero, with: .rightToLeft) XCTAssert(progress == 1) } func testCalculateProgress_ReactingToTranslationOffset() { let translation = CGPoint(x: 20, y: 10) let translationOffset = CGPoint(x: 10, y: 10) let progress = TransitionProgressCalculator.progress(for: view, withGestureTranslation: translation, withTranslationOffset: translationOffset, with: .leftToRight) XCTAssert(progress == 0.05000000074505806) } }
bsd-2-clause
2f7c77efd8399d72b44ad7ec22930911
48.391608
99
0.480816
6.4977
false
true
false
false
SeptAi/EmoticonManage
EmoticonManage/EmoticonManage/KeyViewController.swift
1
3591
// // KeyViewController.swift // EmoticonManage // // Created by J on 2016/12/18. // Copyright © 2016年 J. All rights reserved. // import UIKit // 表情键盘 class KeyViewController: UIViewController { @IBOutlet weak var textView: UITextView! lazy var emoticonView:CZEmoticonInputView = CZEmoticonInputView.inputView { [weak self](em) in // 获取点击表情 self?.insertEmoticon(em: em) } var emoticonText:String{ // 1.获取textView的属性文本 guard let attrStr = textView.attributedText else{ return "" } // 2.需要获取熟悉爱那个文本中的图片 /* 遍历范围;选项[];闭包 */ var result = String() attrStr.enumerateAttributes(in: NSRange.init(location: 0, length: attrStr.length), options: []) { (dict, range, _) in if let attachment = dict["NSAttachment"] as? CZEmoticonAttachment{ result += attachment.chs ?? "" print("图片\(attachment)") }else{ let subStr = (attrStr.string as NSString).substring(with: range) result += subStr } } return result } @IBAction func show(_ sender: UIBarButtonItem) { print(emoticonText) } func insertEmoticon(em:CZEmoticon?) { // 1.判断表情是否为空 guard let em = em else{ // 删除文本 textView.deleteBackward() return } // 1.emoji if let emoji = em.emoji, let textRange = textView.selectedTextRange{ // UITextRange仅用在此处 textView.replace(textRange, withText: emoji) return } // 剩余为图片表情 // 插入字符的显示,跟随前一个字符属性,但本身没有属性 let imageText = em.imageText(font: textView.font!) // 1.获取当前textView的属性文本 let attrStrM = NSMutableAttributedString(attributedString: textView.attributedText) // 2.将当前的属性文本插入到当前光标位置 attrStrM.replaceCharacters(in: textView.selectedRange, with: imageText) // 3.重新设置属性文本 // 记录光标位置 let range = textView.selectedRange // 设置文本 textView.attributedText = attrStrM // 恢复光标位置 textView.selectedRange = NSRange.init(location: range.location + 1, length: 0) } override func viewDidLoad() { super.viewDidLoad() // 输入视图 // 视图刚刚加载,还没有显示,系统默认键盘没有生效,可以不刷新视图 textView.inputView = emoticonView textView.reloadInputViews() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) textView.becomeFirstResponder() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c64ff251e6bc4f2b7d0bdd68f2ef02e2
28.962963
125
0.589308
4.629471
false
false
false
false
mgfigueroa/Pterattack
Pterattack/Pterattack/Boss.swift
1
584
// // Boss.swift // Pterattack // // Created by Clement on 12/4/15. // // import Foundation import SpriteKit class Boss : SKSpriteNode { var level = -1 var health = -1 var enrageTimer = -1 override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) level = 1 health = 1000 enrageTimer = 120 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
06284c102479dda31d69d89ed9c6c662
16.69697
70
0.549658
3.86755
false
false
false
false
inacioferrarini/York
Classes/Extensions/NSObjectExtensions.swift
1
1792
// The MIT License (MIT) // // Copyright (c) 2016 Inácio Ferrarini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public extension NSObject { public class func simpleClassName() -> String { let fullClassName: String = NSStringFromClass(object_getClass(self)) let classNameComponents = fullClassName.characters.split {$0 == "."}.map(String.init) return classNameComponents.last! } public func instanceSimpleClassName() -> String { let fullClassName: String = NSStringFromClass(object_getClass(self)) let classNameComponents = fullClassName.characters.split {$0 == "."}.map(String.init) return classNameComponents.last! } }
mit
c24c0354db4f800b62da162202227c7f
43.775
93
0.717476
4.639896
false
false
false
false
bravelocation/yeltzland-ios
watchkitapp Extension/Views/GamesListView.swift
1
3193
// // FixtureListView.swift // watchkitapp Extension // // Created by John Pollard on 25/10/2019. // Copyright © 2019 John Pollard. All rights reserved. // import SwiftUI struct GamesListView: View { @ObservedObject var fixtureData: FixtureData var selection: FixtureData.FixtureSelection var body: some View { VStack { if self.fixtureData.state != .isLoading && self.fixtureData.fixturesAvailable(selection: self.selection) == false { Text("No games").padding() } List(self.fixtureData.allFixtures(selection: self.selection, reverseOrder: selection == .resultsOnly), id: \.self) { fixture in HStack { Group { if fixture.status == .fixture || fixture.status == .inProgress { FixtureView(fixture: fixture, teamImage: self.fixtureData.teamImage(fixture)) } else { ResultView(fixture: fixture, teamImage: self.fixtureData.teamImage(fixture), resultColor: self.resultColor(fixture)) } } Spacer() } .listRowPlatterColor(Color("dark-blue")) } .listStyle(CarouselListStyle()) } .overlay( Button(action: { self.fixtureData.refreshData() }, label: { Image(systemName: "arrow.clockwise") .font(.footnote) .padding() }) .frame(width: 24.0, height: 24.0, alignment: .center) .background(Color.gray.opacity(0.5)) .cornerRadius(12), alignment: .topTrailing ) .foregroundColor(Color("light-blue")) .onAppear { self.fixtureData.refreshData() } .navigationBarTitle(Text(self.fixtureData.state == .isLoading ? "Loading ..." : self.navTitle)) } var navTitle: String { switch self.selection { case .resultsOnly: return "Results" case .fixturesOnly: return "Fixtures" default: return "" } } func resultColor(_ fixture: TimelineFixture) -> Color { switch fixture.result { case .win: return Color("watch-fixture-win") case .lose: return Color("watch-fixture-lose") default: return Color("watch-fixture-draw") } } } #if DEBUG struct GamesListView_Previews: PreviewProvider { static var previews: some View { Group { GamesListView( fixtureData: AllGamesData(fixtureManager: PreviewFixtureManager(), gameScoreManager: PreviewGameScoreManager(), useResults: false) ) GamesListView( fixtureData: AllGamesData(fixtureManager: PreviewFixtureManager(), gameScoreManager: PreviewGameScoreManager(), useResults: true) ) } } } #endif
mit
4b95bbe627d2d49259534ae9a88e97a7
31.571429
146
0.52381
5.058637
false
false
false
false
augmify/ModelRocket
ModelRocket/PropertyArray.swift
6
5104
// PropertyArray.swift // // Copyright (c) 2015 Oven Bits, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation final public class PropertyArray<T : JSONTransformable>: PropertyDescription { typealias PropertyType = T /// Backing store for property data public var values: [PropertyType] = [] /// Post-processing closure. public var postProcess: (([PropertyType]) -> Void)? /// JSON parameter key public var key: String /// Type information public var type: String { return "\(PropertyType.self)" } /// Specify whether value is required public var required = false public var count: Int { return values.count } public var isEmpty: Bool { return values.isEmpty } public var first: PropertyType? { return values.first } public var last: PropertyType? { return values.last } // MARK: Initialization /// Initialize with JSON property key public init(key: String, defaultValues: [PropertyType] = [], required: Bool = false, postProcess: (([PropertyType]) -> Void)? = nil) { self.key = key self.values = defaultValues self.required = required self.postProcess = postProcess } // MARK: Transform /// Extract object from JSON and return whether or not the value was extracted public func fromJSON(json: JSON) -> Bool { var jsonValue: JSON = json let keyPaths = key.componentsSeparatedByString(".") for key in keyPaths { jsonValue = jsonValue[key] } values.removeAll(keepCapacity: false) for object in jsonValue.array ?? [] { if let property = PropertyType.fromJSON(object) as? PropertyType { values.append(property) } } return !values.isEmpty } /// Convert object to JSON public func toJSON() -> AnyObject? { var jsonArray: [AnyObject] = [] for value in values { jsonArray.append(value.toJSON()) } return jsonArray } /// Perform initialization post-processing public func initPostProcess() { postProcess?(values) } // MARK: Coding /// Encode public func encode(coder: NSCoder) { let objectArray = values.map { $0 as? AnyObject }.filter { $0 != nil }.map { $0! } coder.encodeObject(objectArray, forKey: key) } public func decode(decoder: NSCoder) { let decodedObjects = decoder.decodeObjectForKey(key) as? [AnyObject] values.removeAll(keepCapacity: false) for object in decodedObjects ?? [] { if let value = object as? PropertyType { values.append(value) } } } } // MARK:- Printable extension PropertyArray: Printable { public var description: String { return "PropertyArray<\(type)> (key: \(key), count: \(values.count), required: \(required))" } } // MARK:- DebugPrintable extension PropertyArray: DebugPrintable { public var debugDescription: String { return description } } // MARK:- CollectionType extension PropertyArray: CollectionType { public func generate() -> IndexingGenerator<[PropertyType]> { return values.generate() } public var startIndex: Int { return 0 } public var endIndex: Int { return values.count } public subscript(index: Int) -> PropertyType { return values[index] } } // MARK:- Sliceable extension PropertyArray: Sliceable { public subscript (subRange: Range<Int>) -> ArraySlice<PropertyType> { return values[subRange] } } // MARK:- Hashable extension PropertyArray: Hashable { public var hashValue: Int { return key.hashValue } } // MARK:- Equatable extension PropertyArray: Equatable {} public func ==<T>(lhs: PropertyArray<T>, rhs: PropertyArray<T>) -> Bool { return lhs.key == rhs.key }
mit
559ec1c67e4b820c085d0aa8194b0bbe
27.043956
138
0.636951
4.756757
false
false
false
false
randymarsh77/scope
Tests/ScopeTests/ScopeTests.swift
1
872
import XCTest @testable import Scope class ScopeTests: XCTestCase { // Dispose should nil the callback func testDisposeCleanup() { let scope = Scope {} scope.dispose() XCTAssertNil(scope.disposeFunc) } // Dispose should call the callback func testDispose() { var x = 0 let scope = Scope { x += 1 } scope.dispose() XCTAssertEqual(x, 1) scope.dispose() XCTAssertEqual(x, 1, "Multiple Dispose should be safe, but a noop") } // Transfer should create a new scope with the same callback, // leaving the original scope without a callback func testTransfer() { var x = 0 let scope = Scope { x += 1 } let transferred = scope.transfer() scope.dispose() XCTAssertEqual(x, 0, "Scope should have been transferred") transferred.dispose() XCTAssertEqual(x, 1, "Transferred scope should call the original callback") } }
mit
edb50c3f0310b5910d84a0bee105c9da
22.567568
77
0.686927
3.603306
false
true
false
false
2794129697/-----mx
CoolXuePlayer/LoadMoreFooterView.swift
1
2717
// // ProductFooterView.swift // CoolXuePlayer // // Created by lion-mac on 15/6/11. // Copyright (c) 2015年 lion-mac. All rights reserved. // import Foundation protocol LoadMoreFooterViewDelegate{ func footerRefreshTableData(Vedio) } class LoadMoreFooterView:UIView{ // var delegate:ProductViewController! var delegate:LoadMoreFooterViewDelegate! @IBOutlet weak var nlLabel: UILabel! @IBOutlet weak var busy: UIActivityIndicatorView! @IBOutlet weak var moreView: UIView! @IBOutlet weak var btn: UIButton! //静态属性 class var loadMoreFooterView:LoadMoreFooterView{ get{ //var nib:UINib = UINib(nibName: "ProductFooterView", bundle:NSBundle.mainBundle()) //var footerView:ProductFooterView = nib.instantiateWithOwner(nil, options: nil).last as! ProductFooterView //return footerView return NSBundle.mainBundle().loadNibNamed("LoadMoreFooterView", owner: nil, options: nil).first as! LoadMoreFooterView } } @IBAction func doLoaderData(sender: UIButton) { println("load more") self.btn.hidden = true self.moreView.hidden = false self.busy.startAnimating() // var keyString : NSString = "one two three four five" // var keys : NSArray = keyString.componentsSeparatedByString(" ") // // // var valueString : NSString = "alpha bravo charlie delta echo" // var values : NSArray = valueString.componentsSeparatedByString(" ") // var dict:NSDictionary = NSDictionary(objects: keys as [AnyObject], forKeys: values as [AnyObject]) var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_MSEC.hashValue * 1000)) dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in var dict:NSDictionary = NSDictionary(dictionary: [ "affix":"c", "author":"c", "cover":"c", "createTimer":"c", "defaultCover":"c", "desc":"c", "id":9790, "name":"c", "playCost":"c", "tags":"c", "vedioUrl":"c", ]) var newVedio:Vedio = Vedio(dictVedio: dict) // self.delegate.channelList.append(newVedio) // self.delegate.productTableView.reloadData() self.delegate.footerRefreshTableData(newVedio) self.btn.hidden = false self.moreView.hidden = true self.busy.stopAnimating() } } override func awakeFromNib() { self.moreView.hidden = true } }
lgpl-3.0
b1a5c91e770da74f52a8c5f7f9a29098
34.168831
130
0.594385
4.452303
false
false
false
false
swift-tweets/tweetup-kit
Sources/TweetupKit/Gist.swift
1
1747
import Foundation import PromiseK internal struct Gist { static func createGist(description: String, code: Code, accessToken: String) -> Promise<() throws -> String> { let session = URLSession(configuration: .ephemeral, delegate: nil, delegateQueue: .current) var request = URLRequest(url: URL(string: "https://api.github.com/gists")!) request.httpMethod = "POST" request.addValue("token \(accessToken)", forHTTPHeaderField: "Authorization") let files: [String: Any] = [ code.fileName: [ "content": code.body ] ] let json: [String: Any] = [ "description": description, "public": false, "files": files ] let data = try! JSONSerialization.data(withJSONObject: json) return Promise { fulfill in let task = session.uploadTask(with: request, from: data) { responseData, response, error in if let error = error { fulfill { throw error }; return } guard let response = response as? HTTPURLResponse else { fatalError("Never reaches here.") } let responseJson: [String: Any] = try! JSONSerialization.jsonObject(with: responseData!) as! [String: Any] // never fails guard response.statusCode == 201 else { fulfill { throw APIError(response: response, json: responseJson) } return } guard let id = responseJson["id"] as? String else { fatalError("Never reaches here.") } fulfill { id } } task.resume() } } }
mit
b97fee8dbcded68e5b1424df4e3903f7
41.609756
137
0.544934
5.168639
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 1.playgroundbook/Contents/Chapters/Document7.playgroundchapter/Pages/Exercise2.playgroundpage/Sources/Assessments.swift
1
2950
// // Assessments.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // let solution = "```swift\nwhile !isBlocked {\n if isOnClosedSwitch {\n toggleSwitch()\n }\n moveForward()\n}\n```" import PlaygroundSupport public func assessmentPoint() -> AssessmentResults { let checker = ContentsChecker(contents: PlaygroundPage.current.text) pageIdentifier = "Creating_Smarter_While_Loops" var hints = [ "Just like the previous puzzle, you need to carry out a set of actions while a certain condition is true.", "One approach is to move forward while Byte is not blocked.", "On each tile, use an `if` statement to determine whether or not Byte is on a closed switch.", ] var success = "### Incredible work! \nUsing `while` loops is already making your code simpler. By pairing a while loop and [conditional code](glossary://conditional%20code), you can write programs that are much more adaptable. \n\n[**Next Page**](@next)" if !checker.didUseWhileLoop { success = "### Almost! \nYou completed the puzzle, but you didn’t use a `while` loop. It took \(checker.numberOfStatements) lines of code to complete this puzzle, but if you’d used a `while` loop, you could have solved it in as few as 4!" hints[0] = "Add a `while` loop by tapping `while` in the shortcut bar. Then add a condition that allows Byte to move forward until reaching the end of the third platform." } let contents = checker.loopNodes.map { $0.condition } for element in contents { if !element.contains("!isBlocked") && checker.didUseWhileLoop { hints[0] = "While Byte is *not* blocked, check for a closed switch and move forward." } else if element.contains("!isBlocked") && checker.didUseWhileLoop && !checker.didUseConditionalStatement { hints[0] = "Each time your loop runs, you need to check if Byte is on a closed switch. If so, toggle the switch. Be careful not to toggle any open switches." } else if element.contains("!isBlocked") && checker.didUseWhileLoop && checker.didUseConditionalStatement { success = "### Incredible work! \nUsing `while` loops is already making your code simpler. By pairing a `while` loop and [conditional code](glossary://conditional%20code), you can write code that is much more adaptable. \n\n[**Next Page**](@next)" hints[0] = "Inside your `while` loop, write an `if` statement that begins like this: `if isOnClosedSwitch {`" } if world.commandQueue.containsIncorrectToggleCommand(for: actor) { hints[0] = "For each of Byte’s forward moves, use an `if` statement to make sure there’s a closed switch on the tile before toggling the switch." } } return updateAssessment(successMessage: success, failureHints: hints, solution: solution) }
mit
7616368b6f7a50769d279fe5299be58d
52.490909
259
0.672672
4.263768
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Extensions/EmojiView/EmojiViewSetEmoji.swift
1
546
// // EmojiViewSetEmoji.swift // Rocket.Chat // // Created by Matheus Cardoso on 10/3/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // extension EmojiView { func setEmoji(_ emoji: Emoji) { if case let .custom(imageUrl) = emoji.type, let url = URL(string: imageUrl) { ImageManager.loadImage(with: url, into: emojiImageView) emojiLabel.text = "" } else { emojiLabel.text = Emojione.transform(string: emoji.shortname) emojiImageView.image = nil } } }
mit
109a32cb222fd7adb30a950ac2d7a32c
27.684211
85
0.612844
3.758621
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/Model/QiscusClient.swift
1
11139
// // QiscusMe.swift // QiscusSDK // // Created by Ahmad Athaullah on 9/8/16. // Copyright © 2016 Ahmad Athaullah. All rights reserved. // import UIKit import SwiftyJSON /// contain sdk user information open class QiscusClient: NSObject { public static var inBackgroundSync:Bool{ set{ let userData = UserDefaults.standard userData.set(inBackgroundSync, forKey: "qiscus_in_backgroundSync") } get{ let userData = UserDefaults.standard if let inBackgroundSync = userData.value(forKey: "qiscus_in_backgroundSync") as? Bool { return inBackgroundSync } return false } } public static var hasRegisteredDeviceToken: Bool { set { let userData = UserDefaults.standard userData.set(hasRegisteredDeviceToken, forKey: "has_register_device_token") } get { let userData = UserDefaults.standard if let hasRegisteredDeviceToken = userData.value(forKey: "has_register_device_token") as? Bool { return hasRegisteredDeviceToken } return false } } public static var needBackgroundSync:Bool{ set{ let userData = UserDefaults.standard userData.set(needBackgroundSync, forKey: "qiscus_needBackgroundSync") } get{ let userData = UserDefaults.standard if let needBackgroundSync = userData.value(forKey: "qiscus_needBackgroundSync") as? Bool { return needBackgroundSync } return false } } open static let shared = QiscusClient() let userData = UserDefaults.standard open class var isLoggedIn:Bool { get{ return (Qiscus.client.token != "") } } open class var canReconnect:Bool{ get{ return (Qiscus.client.userKey != "" && Qiscus.client.email != "") } } public var id = 0 public var email = "" public var userName = "" public var avatarUrl = "" public var rtKey = "" public var token = "" public var extras = "" public var userKey = "" public var appId = "" public var baseUrl = "" public var realtimeServer:String = "mqtt.qiscus.com" public var realtimePort:Int = 1883 public var realtimeSSL:Bool = false public var lastCommentId = Int(0) public var lastEventId = "" public var lastKnownCommentId = Int(0) public var paramEmail = "" public var paramPass = "" public var paramUsername = "" public var paramAvatar = "" public var paramExtras = "" open var deviceToken:String = ""{ didSet{ let userData = UserDefaults.standard userData.set(deviceToken, forKey: "qiscus_device_token") } } fileprivate override init(){ if let userId = userData.value(forKey: "qiscus_id") as? Int { self.id = userId } if let userEmail = userData.value(forKey: "qiscus_email") as? String { self.email = userEmail } if let extras = userData.value(forKey: "qiscus_extras") as? String{ self.extras = extras } if let appId = userData.value(forKey: "qiscus_appId") as? String { self.appId = appId } if let realtimeServer = userData.value(forKey: "qiscus_realtimeServer") as? String{ self.realtimeServer = realtimeServer } if let realtimePort = userData.value(forKey: "qiscus_realtimePort") as? Int{ self.realtimePort = realtimePort } if let realtimeSSL = userData.value(forKey: "qiscus_realtimeSSL") as? Bool{ self.realtimeSSL = realtimeSSL } if let name = userData.value(forKey: "qiscus_username") as? String { self.userName = name } if let avatar = userData.value(forKey: "qiscus_avatar_url") as? String { self.avatarUrl = avatar } if let key = userData.value(forKey: "qiscus_rt_key") as? String { self.rtKey = key } if let userToken = userData.value(forKey: "qiscus_token") as? String { self.token = userToken } if let key = userData.value(forKey: "qiscus_user_key") as? String{ self.userKey = key } if let url = userData.value(forKey: "qiscus_base_url") as? String{ self.baseUrl = url } if let lastComment = userData.value(forKey: "qiscus_lastComment_id") as? Int{ self.lastCommentId = lastComment } if let lastEvent = userData.value(forKey: "qiscus_lastEvent_id") as? String{ self.lastEventId = lastEvent } if let lastComment = userData.value(forKey: "qiscus_lastKnownComment_id") as? Int{ self.lastKnownCommentId = lastComment } if let dToken = userData.value(forKey: "qiscus_device_token") as? String{ self.deviceToken = dToken } if let paramEmail = userData.value(forKey: "qiscus_param_email") as? String{ self.paramEmail = paramEmail } if let paramPass = userData.value(forKey: "qiscus_param_pass") as? String{ self.paramPass = paramPass } if let paramUsername = userData.value(forKey: "qiscus_param_username") as? String{ self.paramUsername = paramUsername } if let paramAvatar = userData.value(forKey: "qiscus_param_avatar") as? String{ self.paramAvatar = paramAvatar } if let paramExtras = userData.value(forKey: "qiscus_param_extras") as? String{ self.paramExtras = paramExtras } } open class func saveData(fromJson json:JSON, reconnect:Bool = false)->QiscusClient{ Qiscus.printLog(text: "jsonFron saveData: \(json)") Qiscus.client.id = json["id"].intValue Qiscus.client.email = json["email"].stringValue Qiscus.client.userName = json["username"].stringValue Qiscus.client.avatarUrl = json["avatar"].stringValue Qiscus.client.rtKey = json["rtKey"].stringValue Qiscus.client.token = json["token"].stringValue var extrasData = json["extras"] var extras = "" if !(extrasData.isEmpty){ extras = "\(extrasData)" } Qiscus.client.extras = extras Qiscus.client.userData.set(json["id"].intValue, forKey: "qiscus_id") Qiscus.client.userData.set(json["email"].stringValue, forKey: "qiscus_email") Qiscus.client.userData.set(json["username"].stringValue, forKey: "qiscus_username") Qiscus.client.userData.set(json["avatar"].stringValue, forKey: "qiscus_avatar_url") Qiscus.client.userData.set(json["rtKey"].stringValue, forKey: "qiscus_rt_key") Qiscus.client.userData.set(json["token"].stringValue, forKey: "qiscus_token") Qiscus.client.userData.set(extras, forKey: "extras") if !reconnect { Qiscus.client.userData.set(json["last_comment_id"].intValue, forKey: "qiscus_lastComment_id") Qiscus.client.userData.set(json["last_comment_id"].intValue, forKey: "qiscus_lastKnownComment_id") }else{ if json["last_comment_id"].intValue > Qiscus.client.lastCommentId { Qiscus.sync() } } if let lastComment = Qiscus.client.userData.value(forKey: "qiscus_lastComment_id") as? Int{ Qiscus.client.lastCommentId = lastComment if lastComment == 0 { Qiscus.client.lastCommentId = json["last_comment_id"].intValue Qiscus.client.userData.set(json["last_comment_id"].intValue, forKey: "qiscus_lastComment_id") Qiscus.client.userData.set(json["last_comment_id"].intValue, forKey: "qiscus_lastKnownComment_id") } }else{ Qiscus.client.lastCommentId = json["last_comment_id"].intValue Qiscus.client.userData.set(json["last_comment_id"].intValue, forKey: "qiscus_lastComment_id") Qiscus.client.userData.set(json["last_comment_id"].intValue, forKey: "qiscus_lastKnownComment_id") } if let lastComment = Qiscus.client.userData.value(forKey: "qiscus_lastKnownComment_id") as? Int{ Qiscus.client.lastKnownCommentId = lastComment } return Qiscus.client } public class func updateLastCommentId(commentId:Int){ if Qiscus.client.lastCommentId < commentId { Qiscus.client.lastCommentId = commentId Qiscus.client.userData.set(commentId, forKey: "qiscus_lastComment_id") } if Qiscus.client.lastKnownCommentId < commentId { Qiscus.client.lastKnownCommentId = commentId Qiscus.client.userData.set(commentId, forKey: "qiscus_lastKnownComment_id") } } public class func updateLastKnownCommentId(commentId:Int){ if Qiscus.client.lastKnownCommentId < commentId { Qiscus.client.lastKnownCommentId = commentId Qiscus.client.userData.set(commentId, forKey: "qiscus_lastKnownComment_id") } } public class func clear(){ Qiscus.client.id = 0 Qiscus.client.email = "" Qiscus.client.userName = "" Qiscus.client.avatarUrl = "" Qiscus.client.rtKey = "" Qiscus.client.token = "" Qiscus.client.lastCommentId = 0 Qiscus.client.lastEventId = "" Qiscus.client.extras = "" Qiscus.client.userData.removeObject(forKey: "qiscus_id") Qiscus.client.userData.removeObject(forKey: "qiscus_email") Qiscus.client.userData.removeObject(forKey: "qiscus_username") Qiscus.client.userData.removeObject(forKey: "qiscus_avatar_url") Qiscus.client.userData.removeObject(forKey: "qiscus_rt_key") Qiscus.client.userData.removeObject(forKey: "qiscus_token") Qiscus.client.userData.removeObject(forKey: "qiscus_lastComment_id") Qiscus.client.userData.removeObject(forKey: "qiscus_lastKnownComment_id") Qiscus.client.userData.removeObject(forKey: "qiscus_lastEvent_id") Qiscus.client.userData.removeObject(forKey: "qiscus_extras") } public class func update(lastEventId eventId: String){ guard let newId = Int64(eventId) else {return} if Qiscus.client.lastEventId == "" { Qiscus.client.lastEventId = eventId Qiscus.client.userData.set(eventId, forKey: "qiscus_lastEvent_id") }else{ if let currentId = Int64(Qiscus.client.lastEventId) { if currentId < newId { Qiscus.client.lastEventId = eventId Qiscus.client.userData.set(eventId, forKey: "qiscus_lastEvent_id") } } else { Qiscus.client.lastEventId = eventId Qiscus.client.userData.set(eventId, forKey: "qiscus_lastEvent_id") } } } }
mit
107657b43c6c48508c1597e9a2452f9a
38.637011
114
0.608278
4.302047
false
false
false
false
ben-ng/swift
test/Constraints/dictionary_literal.swift
9
4158
// RUN: %target-typecheck-verify-swift final class DictStringInt : ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class Dictionary<K, V> : ExpressibleByDictionaryLiteral { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(_ d: DictStringInt) {} func useDict<K, V>(_ d: Dictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt(["Hello" : 1]) useDictStringInt(["Hello" : 1, "World" : 2]) useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} useDictStringInt([4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}} useDictStringInt([nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}} useDictStringInt([7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [1 : 2, 1.5 : 2.5] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' cannot be used with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}} var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}} class A { } class B : A { } class C : A { } func testDefaultExistentials() { let _ = ["a" : 1, "b" : 2.5, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}} let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"] let d2 = [:] // expected-error@-1{{empty collection literal requires an explicit type}} let _: Int = d2 // expected-error{{value of type 'Dictionary<AnyHashable, Any>'}} let _ = ["a": 1, "b": ["a", 2, 3.14159], "c": ["a": 2, "b": 3.5]] // expected-error@-3{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}} let d3 = ["b" : B(), "c" : C()] let _: Int = d3 // expected-error{{value of type 'Dictionary<String, A>'}} let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}} let _ = ["a" : "hello", 17 : "string"] // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}} }
apache-2.0
c74149b9e160b24763f4885da2f4b76a
43.234043
200
0.655604
3.511824
false
false
false
false
nineteen-apps/swift
lessons-01/lesson3/Sources/main.swift
1
1778
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-06-20 by Ronaldo Faria Lima // This file purpose: Demonstração de value types e reference types import Foundation struct ValueType { var state = 0 } class ReferenceType { var state = 0 } func changeStructValue(data: ValueType) { var myData = data myData.state = 2 } func changeClassValue(data: ReferenceType) { data.state = 2 } var myValType = ValueType() var myRefType = ReferenceType() myValType.state = 10 myRefType.state = 10 changeStructValue(data: myValType) changeClassValue(data: myRefType) print("Value Type: \(myValType.state) - Reference type: \(myRefType.state)")
mit
b2b93600cab76b5c283235e775fc9b16
31.290909
81
0.743806
4.0181
false
false
false
false
adrfer/swift
test/decl/protocol/req/optional.swift
2
5942
// RUN: %target-parse-verify-swift // ----------------------------------------------------------------------- // Declaring optional requirements // ----------------------------------------------------------------------- @objc class ObjCClass { } @objc protocol P1 { optional func method(x: Int) // expected-note 2{{requirement 'method' declared here}} optional var prop: Int { get } // expected-note 2{{requirement 'prop' declared here}} optional subscript (i: Int) -> ObjCClass? { get } // expected-note 2{{requirement 'subscript' declared here}} } // ----------------------------------------------------------------------- // Providing witnesses for optional requirements // ----------------------------------------------------------------------- // One does not have provide a witness for an optional requirement class C1 : P1 { } // ... but it's okay to do so. class C2 : P1 { @objc func method(x: Int) { } @objc var prop: Int = 0 @objc subscript (c: ObjCClass) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // "Near" matches. // ----------------------------------------------------------------------- class C3 : P1 { func method(x: Int) { } // expected-warning@-1{{non-@objc method 'method' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} var prop: Int = 0 // expected-warning@-1{{non-@objc property 'prop' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} // expected-warning@+1{{non-@objc subscript cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C4 { } extension C4 : P1 { func method(x: Int) { } // expected-warning@-1{{non-@objc method 'method' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} var prop: Int { return 5 } // expected-warning@-1{{non-@objc property 'prop' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} // expected-warning@+1{{non-@objc subscript cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C5 : P1 { } extension C5 { func method(x: Int) { } var prop: Int { return 5 } subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C6 { } extension C6 : P1 { @nonobjc func method(x: Int) { } @nonobjc var prop: Int { return 5 } @nonobjc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // Using optional requirements // ----------------------------------------------------------------------- // Optional method references in generics. func optionalMethodGeneric<T : P1>(t: T) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .None // ... and that we can call it. methodRef!(5) } // Optional property references in generics. func optionalPropertyGeneric<T : P1>(t: T) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .None // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in generics. func optionalSubscriptGeneric<T : P1>(t: T) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .None // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // Optional method references in existentials. func optionalMethodExistential(t: P1) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .None // ... and that we can call it. methodRef!(5) } // Optional property references in existentials. func optionalPropertyExistential(t: P1) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .None // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in existentials. func optionalSubscriptExistential(t: P1) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .None // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // ----------------------------------------------------------------------- // Restrictions on the application of optional // ----------------------------------------------------------------------- // optional cannot be used on non-protocol declarations optional var optError: Int = 10 // expected-error{{'optional' can only be applied to protocol members}} optional struct optErrorStruct { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } optional class optErrorClass { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int = 0 // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } protocol optErrorProtocol { optional func foo(x: Int) // expected-error{{'optional' can only be applied to members of an @objc protocol}} optional associatedtype Assoc // expected-error{{'optional' modifier cannot be applied to this declaration}} {{3-12=}} } @objc protocol optionalInitProto { optional init() // expected-error{{'optional' cannot be applied to an initializer}} }
apache-2.0
741c520328e4709399936bb56c8ad6d8
27.430622
126
0.581454
4.11781
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/CS193p/iOS11/EmojiArt/EmojiArtDocumentTableViewController.swift
1
3065
// // EmojiArtDocumentTableViewController.swift // EmojiArt // // Created by 朱双泉 on 2018/5/15. // Copyright © 2018 Castie!. All rights reserved. // import UIKit class EmojiArtDocumentTableViewController: UITableViewController { var emojiArtDocuments = ["One", "Two", "Three"] // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return emojiArtDocuments.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DocumentCell", for: indexPath) // Configure the cell... cell.textLabel?.text = emojiArtDocuments[indexPath.row] return cell } @IBAction func newEmojiArt(_ sender: UIBarButtonItem) { emojiArtDocuments += ["Untitled".madeUnique(withRespectTo: emojiArtDocuments)] tableView.reloadData() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if splitViewController?.preferredDisplayMode != .primaryOverlay { splitViewController?.preferredDisplayMode = .primaryOverlay } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source emojiArtDocuments.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
1e882fc789dfdeb076764241dcac2922
32.23913
136
0.670373
5.165541
false
false
false
false
DeveloperLx/LxProjectTemplate
LxProjectTemplateDemo/Pods/PromiseKit/Categories/Social/SLComposeViewController+Promise.swift
6
1035
import Social.SLComposeViewController import UIKit.UIViewController #if !COCOAPODS import PromiseKit #endif /** To import this `UIViewController` category: use_frameworks! pod "PromiseKit/Social" And then in your sources: import PromiseKit */ extension UIViewController { public func promiseViewController(vc: SLComposeViewController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<Void> { presentViewController(vc, animated: animated, completion: completion) return Promise { fulfill, reject in vc.completionHandler = { result in if result == .Cancelled { reject(SLComposeViewController.Error.Cancelled) } else { fulfill() } } } } } extension SLComposeViewController { public enum Error: CancellableErrorType { case Cancelled public var cancelled: Bool { switch self { case .Cancelled: return true } } } }
mit
83152e6c1f5b5849740828e054d2cf67
24.875
141
0.621256
5.280612
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/iOS Collection/Business/Business/H5/H5ViewController.swift
1
4393
// // H5ViewController.swift // Business // // Created by 朱双泉 on 2018/11/22. // Copyright © 2018 Castie!. All rights reserved. // import UIKit //http://c.m.163.com/nc/article/BVEGO8UT05299OU6/full.html class H5ViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! var jsBridge: WebViewJavascriptBridge? override func viewDidLoad() { super.viewDidLoad() title = "H5" WebViewJavascriptBridge.enableLogging() jsBridge = WebViewJavascriptBridge(webView) jsBridge?.setWebViewDelegate(self) jsBridge?.registerHandler("ObjC Echo", handler: { (data, responseCallback) in print("ObjC Echo") }) if let url = URL(string: "http://c.m.163.com/nc/article/BVEGO8UT05299OU6/full.html") { let request = URLRequest(url: url) let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in if (error == nil) { DispatchQueue.main.async { let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : Any] self.dealWithJsonData(jsonData: jsonData) } } } dataTask.resume() } } func dealWithJsonData(jsonData: [String : Any]?) { let allData = jsonData?["BVEGO8UT05299OU6"] as? [String : Any] if var body = allData?["body"] as? String, let title = allData?["title"] as? String, let source = allData?["source"] as? String, let articleTags = allData?["articleTags"] as? String, let ptime = allData?["ptime"] as? String, let img = allData?["img"] as? [[String: Any]] { for i in 0..<img.count { let imgItem = img[i] let src = imgItem["src"] as? String ?? "" let ref = imgItem["ref"] as? String ?? "" let alt = imgItem["alt"] as? String ?? "" let imgHtml = "<div class=\"img-html\">" + "<img src=\"\(src)\" width=\"20%\">" + "<div class=\"img-title\">\(alt)</div>" + "</div>" body = body.replacingOccurrences(of: ref, with: imgHtml) } let titleHtml = "<div id=\"title\">\(title)</div>" let subTitleHtml = "<div id='subTitle'>" + "<span class='source'>\(source)</span>" + "<span class='articleTags'>\(articleTags)</span>" + "<span class='ptime'>\(ptime)</span>" + "</div>" if let css = Bundle.main.url(forResource: "H5.css", withExtension: nil), let js = Bundle.main.url(forResource: "H5.js", withExtension: nil) { let cssHtml = "<link href='\(css)' rel='stylesheet'>" let jsHtml = "<script src='\(js)'></script>" let html = "<html>" + "<head>\(cssHtml)</head>" + "<body>\(titleHtml)\(subTitleHtml)\(body)\(jsHtml)</body>" + "</html>" webView.loadHTMLString(html, baseURL: nil) } } } @objc func openCamera() { let photoVc = UIImagePickerController() photoVc.sourceType = .photoLibrary present(photoVc, animated: true, completion: nil) } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { let urlString = request.url?.absoluteString let urlHeader = "business://" let urlIndex = urlHeader.index(urlHeader.startIndex, offsetBy: urlHeader.count) let range = urlString?.range(of: urlHeader) let upperBound = range?.upperBound if upperBound != nil { if let method = urlString?[urlIndex...] { let sel = Selector(String(method)) perform(sel) } } return true } func webViewDidFinishLoad(_ webView: UIWebView) { let jsString = "alert('load success')" webView.stringByEvaluatingJavaScript(from: jsString) } }
mit
a5cdbe96d595560394adf9e9b78ed1d5
37.814159
131
0.523028
4.573514
false
false
false
false
tensorflow/swift-models
Datasets/CoLA/DataUtilities.swift
1
1647
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif public func extract(zipFileAt source: URL, to destination: URL) throws { print("Extracting file at '\(source.path)'.") let process = Process() process.environment = ProcessInfo.processInfo.environment process.executableURL = URL(fileURLWithPath: "/bin/bash") process.arguments = ["-c", "unzip -d \(destination.path) \(source.path)"] try process.run() process.waitUntilExit() } public func extract(tarGZippedFileAt source: URL, to destination: URL) throws { print("Extracting file at '\(source.path)'.") try FileManager.default.createDirectory( at: destination, withIntermediateDirectories: false) let process = Process() process.environment = ProcessInfo.processInfo.environment process.executableURL = URL(fileURLWithPath: "/bin/bash") process.arguments = ["-c", "tar -C \(destination.path) -xzf \(source.path)"] try process.run() process.waitUntilExit() }
apache-2.0
0d3f4ac7b62005c1955fbe84fa8dadd0
38.238095
80
0.726776
4.41555
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/DynamicProgramming/62_UniquePaths.swift
1
757
// // 62_UniquePaths.swift // LeetcodeSwift // // Created by yansong li on 2016-09-12. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:62 Unique Paths URL: https://leetcode.com/problems/unique-paths/ Space: O(mn) Time: O(mn) */ class UniquePaths_Solution { func uniquePaths(_ m: Int, _ n: Int) -> Int { var pathsMatrix = Array(repeating: Array(repeating: 0, count: n), count: m) guard m > 1 || n > 1 else { return m * n } for i in 0..<m { for j in 0..<n { if i == 0 || j == 0 { pathsMatrix[i][j] = 1 } else { pathsMatrix[i][j] = pathsMatrix[i][j - 1] + pathsMatrix[i - 1][j] } } } return pathsMatrix[m - 1][n - 1] } }
mit
86147e00dadd290261144043213c37e6
20.6
79
0.546296
2.964706
false
false
false
false
scinfu/SwiftSoup
Sources/String.swift
1
7448
// // String.swift // SwifSoup // // Created by Nabil Chatbi on 21/04/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation extension String { subscript (i: Int) -> Character { return self[self.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } init<S: Sequence>(_ ucs: S)where S.Iterator.Element == UnicodeScalar { var s = "" s.unicodeScalars.append(contentsOf: ucs) self = s } func unicodeScalar(_ i: Int) -> UnicodeScalar { let ix = unicodeScalars.index(unicodeScalars.startIndex, offsetBy: i) return unicodeScalars[ix] } func string(_ offset: Int, _ count: Int) -> String { let truncStart = self.unicodeScalars.count-offset return String(self.unicodeScalars.suffix(truncStart).prefix(count)) } static func split(_ value: String, _ offset: Int, _ count: Int) -> String { let start = value.index(value.startIndex, offsetBy: offset) let end = value.index(value.startIndex, offsetBy: count+offset) #if swift(>=4) return String(value[start..<end]) #else let range = start..<end return value.substring(with: range) #endif } func isEmptyOrWhitespace() -> Bool { if(self.isEmpty) { return true } return (self.trimmingCharacters(in: CharacterSet.whitespaces) == "") } func startsWith(_ string: String) -> Bool { return self.hasPrefix(string) } func indexOf(_ substring: String, _ offset: Int ) -> Int { if(offset > count) {return -1} let maxIndex = self.count - substring.count if(maxIndex >= 0) { for index in offset...maxIndex { let rangeSubstring = self.index(self.startIndex, offsetBy: index)..<self.index(self.startIndex, offsetBy: index + substring.count) #if swift(>=4) let selfSubstring = self[rangeSubstring] #else let selfSubstring = self.substring(with: rangeSubstring) #endif if selfSubstring == substring { return index } } } return -1 } func indexOf(_ substring: String) -> Int { return self.indexOf(substring, 0) } func trim() -> String { // trimmingCharacters() in the stdlib is not very efficiently // implemented, perhaps because it always creates a new string. // Avoid actually calling it if it's not needed. guard count > 0 else { return self } let (firstChar, lastChar) = (first!, last!) if firstChar.isWhitespace || lastChar.isWhitespace || firstChar == "\n" || lastChar == "\n" { return trimmingCharacters(in: .whitespacesAndNewlines) } return self } func equalsIgnoreCase(string: String?) -> Bool { if let string = string { return caseInsensitiveCompare(string) == .orderedSame } return false } static func toHexString(n: Int) -> String { return String(format: "%2x", n) } func insert(string: String, ind: Int) -> String { return String(self.prefix(ind)) + string + String(self.suffix(self.count-ind)) } func charAt(_ i: Int) -> Character { return self[i] as Character } func substring(_ beginIndex: Int) -> String { return String.split(self, beginIndex, self.count-beginIndex) } func substring(_ beginIndex: Int, _ count: Int) -> String { return String.split(self, beginIndex, count) } func regionMatches(ignoreCase: Bool, selfOffset: Int, other: String, otherOffset: Int, targetLength: Int ) -> Bool { if ((otherOffset < 0) || (selfOffset < 0) || (selfOffset > self.count - targetLength) || (otherOffset > other.count - targetLength)) { return false } for i in 0..<targetLength { let charSelf: Character = self[i+selfOffset] let charOther: Character = other[i+otherOffset] if(ignoreCase) { if(charSelf.lowercase != charOther.lowercase) { return false } } else { if(charSelf != charOther) { return false } } } return true } func startsWith(_ input: String, _ offset: Int) -> Bool { if ((offset < 0) || (offset > count - input.count)) { return false } for i in 0..<input.count { let charSelf: Character = self[i+offset] let charOther: Character = input[i] if(charSelf != charOther) {return false} } return true } func replaceFirst(of pattern: String, with replacement: String) -> String { if let range = self.range(of: pattern) { return self.replacingCharacters(in: range, with: replacement) } else { return self } } func replaceAll(of pattern: String, with replacement: String, options: NSRegularExpression.Options = []) -> String { do { let regex = try NSRegularExpression(pattern: pattern, options: []) let range = NSRange(0..<self.utf16.count) return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacement) } catch { return self } } func equals(_ s: String?) -> Bool { if(s == nil) {return false} return self == s! } } extension String.Encoding { func canEncode(_ string: String) -> Bool { return string.cString(using: self) != nil } public func displayName() -> String { switch self { case String.Encoding.ascii: return "US-ASCII" case String.Encoding.nextstep: return "nextstep" case String.Encoding.japaneseEUC: return "EUC-JP" case String.Encoding.utf8: return "UTF-8" case String.Encoding.isoLatin1: return "csISOLatin1" case String.Encoding.symbol: return "MacSymbol" case String.Encoding.nonLossyASCII: return "nonLossyASCII" case String.Encoding.shiftJIS: return "shiftJIS" case String.Encoding.isoLatin2: return "csISOLatin2" case String.Encoding.unicode: return "unicode" case String.Encoding.windowsCP1251: return "windows-1251" case String.Encoding.windowsCP1252: return "windows-1252" case String.Encoding.windowsCP1253: return "windows-1253" case String.Encoding.windowsCP1254: return "windows-1254" case String.Encoding.windowsCP1250: return "windows-1250" case String.Encoding.iso2022JP: return "iso2022jp" case String.Encoding.macOSRoman: return "macOSRoman" case String.Encoding.utf16: return "UTF-16" case String.Encoding.utf16BigEndian: return "UTF-16BE" case String.Encoding.utf16LittleEndian: return "UTF-16LE" case String.Encoding.utf32: return "UTF-32" case String.Encoding.utf32BigEndian: return "UTF-32BE" case String.Encoding.utf32LittleEndian: return "UTF-32LE" default: return self.description } } }
mit
56766810fbe80878cdbdc9bdb7fa9da0
33.16055
146
0.583188
4.339744
false
false
false
false
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/Foundation/Scheduler/YJScheduler.swift
1
7854
// // YJScheduler.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/5/30. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import Foundation /// 发布后执行方处理完毕的回调 public typealias YJSPublishHandler = (_ data: Any?) -> Void /// 订阅回调 public typealias YJSSubscribeHandler = (_ data: Any?, _ publishHandler: YJSPublishHandler?) -> Void /// 能否拦截 public typealias YJSInterceptCanHandler = (_ topic: String) -> Bool /// 拦截回调 public typealias YJSInterceptHandler = (_ topic: String, _ data: Any?, _ publishHandler: YJSPublishHandler?) -> Void /// 调度器单例 public let YJSchedulerS = YJScheduler() /// 调度器 open class YJScheduler: NSObject { /// 调度器初始化启动加载 public var loadScheduler: YJDispatchWork? private lazy var workQueue: YJDispatchQueue = { let queue = DispatchQueue(label: "com.yjcocoa.scheduler.work") return YJDispatchQueue(queue: queue, maxConcurrent: 1) }() private lazy var serialQueue: YJDispatchQueue = { let queue = DispatchQueue(label: "com.yjcocoa.scheduler.serial") return YJDispatchQueue(queue: queue, maxConcurrent: 1) }() private lazy var concurrentQueue: YJDispatchQueue = { let queue = DispatchQueue(label: "com.yjcocoa.scheduler.concurrent", attributes: DispatchQueue.Attributes.concurrent) return YJDispatchQueue(queue: queue, maxConcurrent: 8) }() private var isInitSub = false private var subDict = Dictionary<String, Array<YJSchedulerSubscribe>>() private var intArray = [YJSchedulerIntercept]() } extension YJScheduler { /// 调度队列 public enum Queue: Int { /// 子队列 case `default` /// 主队列 case main } } // MARK: subscribe extension YJScheduler { /** * 订阅 * - Parameter topic: 主题 * - Parameter subscriber: 订阅者,自动释放(传入nil代表永不释放) * - Parameter queue: 回调执行的队列, 默认子线程 * - Parameter handler: 接受发布方传输的数据 */ public func subscribe(topic: String, subscriber: AnyObject? = nil, queue: YJScheduler.Queue = .default, handler: @escaping YJSSubscribeHandler) { YJLogVerbose("[YJScheduler] \(String(describing: subscriber)) 订阅 \(topic)") let target = YJSchedulerSubscribe(topic: topic, subscriber: subscriber ?? self, queue: queue, completionHandler: handler) self.workQueue.async { [unowned self] in guard let newSubscriber = target.subscriber else { return } let subArray = self.subDict[topic] ?? [] var newArray = [target] for item in subArray { if let oldSubscriber = item.subscriber { if !oldSubscriber.isEqual(newSubscriber) || self.isEqual(newSubscriber) { newArray.append(item) } } else { YJLogVerbose("[YJScheduler] 自动取消订阅: \(item.topic)") } } self.subDict[topic] = newArray } } /** * 取消订阅 * - Parameter topic: 主题 * - Parameter subscriber: 订阅者 * - Parameter queue: 回调执行的队列 * - Parameter handler: 接受发布方传输的数据 */ public func removeSubscribe(topic: String? = nil, subscriber: AnyObject) { func removeSubscribe(topic: String, array: Array<YJSchedulerSubscribe>) { var newArray = Array<YJSchedulerSubscribe>() for item in array { if item.subscriber != nil && !subscriber.isEqual(item.subscriber) { newArray.append(item) } } self.subDict[topic] = newArray } self.workQueue.async { [unowned self] in if let topic = topic { removeSubscribe(topic: topic, array: self.subDict[topic] ?? []) } else { for (topic, array) in self.subDict { removeSubscribe(topic: topic, array: array) } } } } } // MARK: intercept extension YJScheduler { /** * 拦截发布信息 * - Parameter interceptor 拦截者 * - Parameter canHandler 能否拦截 * - Parameter handler 拦截后执行的操作 */ public func intercept(interceptor: AnyObject?, canHandler: @escaping YJSInterceptCanHandler, completion handler: @escaping YJSInterceptHandler) { let item = YJSchedulerIntercept(interceptor: interceptor ?? self, canHandler: canHandler, completionHandler: handler) self.workQueue.async { [unowned self] in self.intArray.append(item) } } } // MARK: publish extension YJScheduler { /** * @abstract 能否发布 * * @param topic 主题 * * @return BOOL */ @discardableResult public func canPublish(topic: String) -> Bool { self.initLoadScheduler() for item in self.intArray { if item.interceptor != nil && item.canHandler(topic) { return true } } let array = self.subDict[topic] ?? [] for item in array { if item.subscriber != nil { return true } } return false } /** * @abstract 发布信息 * * @param topic 主题 * @param data 携带的数据 * @param serial yes串行发布no并行发布 * @param handler 接受方处理数据后的回调 */ public func publish(topic: String, data: Any? = nil, serial: Bool = false, completion handler: YJSPublishHandler? = nil) { self.initLoadScheduler() YJLogVerbose("[YJScheduler] 发布\(topic), data:\(data ?? "nil")") self.workQueue.async { [unowned self] in for item in self.intArray { if item.interceptor != nil && item.canHandler(topic) { item.completionHandler(topic, data, handler) return } } let subArray = self.subDict[topic] ?? [] for item in subArray { guard let subscriber = item.subscriber else { continue } let block: YJDispatchWork = { if item.subscriber == nil { return } item.completionHandler(data, handler) } if item.queue == .main { DispatchQueue.asyncMain(block) } else { let queue = serial ? self.serialQueue : self.concurrentQueue queue.async(block) } _ = subscriber.hash } } } private func initLoadScheduler() { if self.isInitSub { return } self.isInitSub = true self.workQueue.sync { self.loadScheduler?() } } } // MARK: - /// 调度器订阅 @objcMembers private class YJSchedulerSubscribe : NSObject { let topic: String weak var subscriber: AnyObject? let queue: YJScheduler.Queue let completionHandler: YJSSubscribeHandler init(topic: String, subscriber: AnyObject, queue: YJScheduler.Queue, completionHandler: @escaping YJSSubscribeHandler) { self.topic = topic self.subscriber = subscriber self.queue = queue self.completionHandler = completionHandler } } /// 调度器拦截 private struct YJSchedulerIntercept { weak var interceptor: AnyObject? let canHandler: YJSInterceptCanHandler let completionHandler: YJSInterceptHandler }
mit
1790f4a2edfc468f17274e35a31b445d
30.773504
150
0.583457
4.287774
false
false
false
false
blinkmeoff/MAGAHelpers
MAGAHelpers/Classes/UIView+Anchors.swift
1
3116
// // UIView+Anchors.swift // Pods // // Created Magurean Igor on 03/10/17. // // import UIKit extension UIView { public func fillSuperview() { translatesAutoresizingMaskIntoConstraints = false if let superview = superview { leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true topAnchor.constraint(equalTo: superview.topAnchor).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true } } public func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false _ = anchorWithReturnAnchors(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant, widthConstant: widthConstant, heightConstant: heightConstant) } public func anchorWithReturnAnchors(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var anchors = [NSLayoutConstraint]() if let top = top { anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant)) } if let left = left { anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant)) } if let bottom = bottom { anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant)) } if let right = right { anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant)) } if widthConstant > 0 { anchors.append(widthAnchor.constraint(equalToConstant: widthConstant)) } if heightConstant > 0 { anchors.append(heightAnchor.constraint(equalToConstant: heightConstant)) } anchors.forEach({$0.isActive = true}) return anchors } public func anchorCenterXToSuperview(constant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false if let anchor = superview?.centerXAnchor { centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true } } public func anchorCenterYToSuperview(constant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false if let anchor = superview?.centerYAnchor { centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true } } public func anchorCenterSuperview() { anchorCenterXToSuperview() anchorCenterYToSuperview() } }
mit
66f3e3f7baa73a24860c18fcc8aff966
37
370
0.720154
5.074919
false
false
false
false
justin999/gitap
gitap/ReposTableViewDelegate.swift
1
1697
// // ReposTableViewDelegate.swift // gitap // // Created by Koichi Sato on 12/25/16. // Copyright © 2016 Koichi Sato. All rights reserved. // import UIKit class ReposTableViewDelegate: NSObject { let stateController: StateController init(tableView: UITableView, stateController: StateController) { self.stateController = stateController super.init() tableView.delegate = self } } extension ReposTableViewDelegate: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) var repo: Repo? switch indexPath.section { case reposSection.privateSection.rawValue: repo = stateController.reposDictionary["private"]?[indexPath.row] case reposSection.publicSection.rawValue: repo = stateController.reposDictionary["public"]?[indexPath.row] default: repo = nil } guard let selectedRepo = repo else { return } stateController.selectedRepo = selectedRepo let vc = CreateIssuesViewController() vc.stateController = stateController stateController.viewController.performSegue(withIdentifier: "presentEditIssue", sender: nil) } @objc func newIssueButtonTapped() { Utils.addButtonTapped(stateController: stateController) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } }
mit
6c89c69ad5caccacfca0520ed84c8168
30.407407
100
0.670991
5.283489
false
false
false
false
voidException/AlamofireImage
Tests/BaseTestCase.swift
16
2705
// BaseTestCase.swift // // Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import AlamofireImage import Foundation import XCTest class BaseTestCase : XCTestCase { let timeout = 5.0 var manager: Manager! // MARK: - Setup and Teardown override func setUp() { super.setUp() manager = { let configuration: NSURLSessionConfiguration = { let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() let defaultHeaders = Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders configuration.HTTPAdditionalHeaders = defaultHeaders return configuration }() return Manager(configuration: configuration) }() } override func tearDown() { super.tearDown() manager.session.finishTasksAndInvalidate() manager = nil } // MARK: - Resources func URLForResource(fileName: String, withExtension: String) -> NSURL { let bundle = NSBundle(forClass: BaseTestCase.self) return bundle.URLForResource(fileName, withExtension: withExtension)! } func imageForResource(fileName: String, withExtension ext: String) -> Image { let URL = URLForResource(fileName, withExtension: ext) let data = NSData(contentsOfURL: URL)! #if os(iOS) let image = Image.af_threadSafeImageWithData(data, scale: UIScreen.mainScreen().scale)! #elseif os(OSX) let image = Image(data: data)! #endif return image } }
mit
f6a54f3d26012106b3d7a03e8e5f1c2b
34.592105
103
0.69464
5.152381
false
true
false
false
naokits/my-programming-marathon
JunkCodes/CurrentPlatform.swift
1
532
// // CurrentPlatfome.swift // // Created by Naoki Tsutsui on 3/3/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import Foundation // platform-dependent import frameworks to get device details // valid values for os(): OSX, iOS, watchOS, tvOS, Linux #if os(iOS) private let PLATFORM = "iOS" import UIKit #elseif os(OSX) private let PLATFORM = "OSX" #elseif os(tvOS) private let PLATFORM = "tvOS" #elseif os(Linux) private let PLATFORM = "Linux" #else private let PLATFORM = "" #endif
mit
fd30926cdd84fc4601bb78c442b4b8e7
20.24
61
0.681733
3.54
false
false
false
false