repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nicolas-miari/Kanji-Checker
Code/KanjiChecker/View/MainViewController.swift
1
1763
// // MainViewController.swift // KanjiChecker // // Created by Nicolás Miari on 2020/04/08. // Copyright © 2020 Nicolás Miari. All rights reserved. // import Cocoa class CheckerViewController: NSViewController { // MARK: - GUI @IBOutlet private weak var textView: NSTextView! @IBOutlet private weak var audiencePopupButton: NSPopUpButton! @IBOutlet private weak var checkButton: NSButton! var progressViewController: ProgressViewController? let checker = Checker() // MARK: - NSViewController override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // MARK: - Control Actions @IBAction func check(_ sender: Any) { guard let storyboard = self.storyboard else { fatalError("FUCK YOU") } guard let progress = storyboard.instantiateController(withIdentifier: "Progress") as? ProgressViewController else { fatalError("Fuck You") } let text = textView.string let grade = audiencePopupButton.indexOfSelectedItem progress.appearHandler = { [unowned self] in // Begin task... self.checker.highlightInput(text, grade: grade, progress: { (value) in progress.setProgress(value) }, completion: {[unowned self](result) in self.textView.textStorage?.setAttributedString(result) self.dismiss(progress) }) } progress.cancelHandler = { [unowned self] in self.dismiss(progress) } presentAsSheet(progress) } @IBAction func audienceChanged(_ sender: Any) { textView.string = textView.attributedString().string } }
mit
b7066e76568dec0d2ac93fceb9a25e07
26.936508
123
0.633523
4.957746
false
false
false
false
practicalswift/swift
benchmark/single-source/StrComplexWalk.swift
4
1965
//===--- StrComplexWalk.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let StrComplexWalk = BenchmarkInfo( name: "StrComplexWalk", runFunction: run_StrComplexWalk, tags: [.validation, .api, .String], legacyFactor: 10) @inline(never) public func run_StrComplexWalk(_ N: Int) { var s = "निरन्तरान्धकारिता-दिगन्तर-कन्दलदमन्द-सुधारस-बिन्दु-सान्द्रतर-घनाघन-वृन्द-सन्देहकर-स्यन्दमान-मकरन्द-बिन्दु-बन्धुरतर-माकन्द-तरु-कुल-तल्प-कल्प-मृदुल-सिकता-जाल-जटिल-मूल-तल-मरुवक-मिलदलघु-लघु-लय-कलित-रमणीय-पानीय-शालिका-बालिका-करार-विन्द-गलन्तिका-गलदेला-लवङ्ग-पाटल-घनसार-कस्तूरिकातिसौरभ-मेदुर-लघुतर-मधुर-शीतलतर-सलिलधारा-निराकरिष्णु-तदीय-विमल-विलोचन-मयूख-रेखापसारित-पिपासायास-पथिक-लोकान्" let ref_result = 379 for _ in 1...200*N { var count = 0 for _ in s.unicodeScalars { count += 1 } CheckResults(count == ref_result) } }
apache-2.0
cea4bcbeb94a2a7f1ed43cb136aaf291
40.09375
391
0.585551
2.145188
false
false
false
false
seongkyu-sim/BaseVCKit
BaseVCKit/Classes/protocols/AppActivityObserverable.swift
1
3692
// // AppActivityObserverable.swift // BaseVCKit // // Created by frank on 2016. 5. 10.. // Copyright © 2016년 colavo. All rights reserved. // import Foundation // MARK: - AppActivityObserverable public enum AppActivityType: String { case didBecomeActive = "didBecomeActive" case willEnterForeground = "willEnterForeground" case didEnterBackground = "didEnterBackground" } public protocol AppActivityObserverable: class { func addObserver(appActivityTypes: [AppActivityType]) func removeObserver(appActivityTypes: [AppActivityType]) func appActivityUpdated(appActivityType: AppActivityType) } public extension AppActivityObserverable { private var appDidBecomeActiveOb: NSObjectProtocol { return associatedObject(self, key: "appDidEnterBackgroundObserver", initial: observerInitial(appActivityType: .didBecomeActive)) } private var appWillEnterForegroundOb: NSObjectProtocol { return associatedObject(self, key: "appDidEnterBackgroundObserver", initial: observerInitial(appActivityType: .willEnterForeground)) } private var appDidEnterBackgroundOb: NSObjectProtocol { return associatedObject(self, key: "appDidEnterBackgroundObserver", initial: observerInitial(appActivityType: .didEnterBackground)) } private func observerInitial(appActivityType: AppActivityType) -> (() -> NSObjectProtocol) { let notiName: NSNotification.Name! switch appActivityType { case .didBecomeActive: notiName = UIApplication.didBecomeActiveNotification case .willEnterForeground: notiName = UIApplication.willEnterForegroundNotification case .didEnterBackground: notiName = UIApplication.didEnterBackgroundNotification } let using: ((Notification) -> ()) = { [weak self] (notification) in self?.appActivityUpdated(appActivityType: appActivityType) } let initial: () -> NSObjectProtocol = { return NotificationCenter.default.addObserver(forName: notiName, object: nil, queue: OperationQueue.main, using: using) } return initial } func addObserver(appActivityTypes: [AppActivityType]) { for type in appActivityTypes { addObserver(appActivityType: type) } } func addObserver(appActivityType: AppActivityType) { switch appActivityType { case .didBecomeActive: _ = appDidBecomeActiveOb case .willEnterForeground: _ = appWillEnterForegroundOb case .didEnterBackground: print("") _ = appDidEnterBackgroundOb } } func removeObserver(appActivityTypes: [AppActivityType]) { for type in appActivityTypes { removeObserver(appActivityType: type) } } func removeObserver(appActivityType: AppActivityType) { var ob: NSObjectProtocol? switch appActivityType { case .didBecomeActive: ob = appDidBecomeActiveOb case .willEnterForeground: ob = appWillEnterForegroundOb case .didEnterBackground: ob = appDidEnterBackgroundOb } if let ob = ob { NotificationCenter.default.removeObserver(ob) } } func appActivityUpdated(appActivityType: AppActivityType) {} } // Association private func associatedObject<T: AnyObject>(_ host: AnyObject, key: UnsafeRawPointer, initial: () -> T) -> T { var value = objc_getAssociatedObject(host, key) as? T if value == nil { value = initial() objc_setAssociatedObject(host, key, value, .OBJC_ASSOCIATION_RETAIN) } return value! }
mit
269a06f814cbb6fb5052ac1925e9cb68
32.844037
140
0.683925
5.330925
false
false
false
false
DigNeurosurgeon/TREMOR12
TREMOR12/InfoViewController.swift
1
1747
// // InfoViewController.swift // TremorDBS // // Created by Pieter Kubben on 29-05-15. // Copyright (c) 2015 DigitalNeurosurgeon.com. All rights reserved. // import UIKit class InfoViewController: UIViewController { @IBOutlet weak var infoWebView: UIWebView! override func viewDidLoad() { super.viewDidLoad() loadInfoContentInWebview(infoWebView) } func loadInfoContentInWebview(webView: UIWebView) { let infoHTMLString = "<body style=\"font-family: Arial; \"> " + "<h3>Maastricht DBS team</h3>" + "<ul>" + "<li>Prof. Yasin Temel, MD, PhD</li>" + "<li>Linda Ackermans, MD, PhD</li>" + "<li>Pieter Kubben, MD, PhD</li>" + "<li>Mark Kuijf, MD, PhD</li>" + "<li>Maayke Oosterloo, MD, PhD</li>" + "<li>Albert Leentjens, MD, PhD</li>" + "<li>Annelien Duits, PhD</li>" + "<li>Nicole Bakker</li>" + // "<li></li>" + "</ul>" + "<h3>Design &amp; development</h3>" + "<ul>" + "<li>Pieter Kubben, MD, PhD</li>" + "</ul>" + "<h3>Contact</h3>" + "<ul>" + "<li><a style=\"color: #800000;\" href=\"http://dign.eu\">Website</a></li><br/>" + "<li><a style=\"color: #800000;\" href=\"mailto:[email protected]\">Email</a></li><br/>" + "<li><a style=\"color: #800000;\" href=\"http://twitter.com/DigNeurosurgeon\">Twitter</a></li><br/>" + "</ul>" + "</body>" webView.loadHTMLString(infoHTMLString, baseURL: nil) } }
gpl-3.0
56cd6dbec00784395015c7e793ebbd92
31.962264
118
0.475673
3.529293
false
false
false
false
huonw/swift
test/expr/unary/keypath/keypath.swift
1
20070
// RUN: %target-swift-frontend -typecheck -parse-as-library %s -verify struct Sub: Hashable { static func ==(_: Sub, _: Sub) -> Bool { return true } var hashValue: Int { return 0 } } struct OptSub: Hashable { static func ==(_: OptSub, _: OptSub) -> Bool { return true } var hashValue: Int { return 0 } } struct NonHashableSub {} struct Prop { subscript(sub: Sub) -> A { get { return A() } set { } } subscript(optSub: OptSub) -> A? { get { return A() } set { } } subscript(nonHashableSub: NonHashableSub) -> A { get { return A() } set { } } subscript(a: Sub, b: Sub) -> A { get { return A() } set { } } subscript(a: Sub, b: NonHashableSub) -> A { get { return A() } set { } } var nonMutatingProperty: B { get { fatalError() } nonmutating set { fatalError() } } } struct A: Hashable { init() { fatalError() } var property: Prop var optProperty: Prop? let optLetProperty: Prop? subscript(sub: Sub) -> A { get { return self } set { } } static func ==(_: A, _: A) -> Bool { fatalError() } var hashValue: Int { fatalError() } } struct B {} struct C<T> { var value: T subscript() -> T { get { return value } } subscript(sub: Sub) -> T { get { return value } set { } } subscript<U: Hashable>(sub: U) -> U { get { return sub } set { } } subscript<X>(noHashableConstraint sub: X) -> X { get { return sub } set { } } } extension Array where Element == A { var property: Prop { fatalError() } } protocol P { var member: String { get } } extension B : P { var member : String { return "Member Value" } } struct Exactly<T> {} func expect<T>(_ x: inout T, toHaveType _: Exactly<T>.Type) {} func testKeyPath(sub: Sub, optSub: OptSub, nonHashableSub: NonHashableSub, x: Int) { var a = \A.property expect(&a, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var b = \A.[sub] expect(&b, toHaveType: Exactly<WritableKeyPath<A, A>>.self) var c = \A.[sub].property expect(&c, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var d = \A.optProperty? expect(&d, toHaveType: Exactly<KeyPath<A, Prop?>>.self) var e = \A.optProperty?[sub] expect(&e, toHaveType: Exactly<KeyPath<A, A?>>.self) var f = \A.optProperty! expect(&f, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var g = \A.property[optSub]?.optProperty![sub] expect(&g, toHaveType: Exactly<KeyPath<A, A?>>.self) var h = \[A].property expect(&h, toHaveType: Exactly<KeyPath<[A], Prop>>.self) var i = \[A].property.nonMutatingProperty expect(&i, toHaveType: Exactly<ReferenceWritableKeyPath<[A], B>>.self) var j = \[A].[x] expect(&j, toHaveType: Exactly<WritableKeyPath<[A], A>>.self) var k = \[A: B].[A()] expect(&k, toHaveType: Exactly<WritableKeyPath<[A: B], B?>>.self) var l = \C<A>.value expect(&l, toHaveType: Exactly<WritableKeyPath<C<A>, A>>.self) // expected-error@+1{{generic parameter 'T' could not be inferred}} _ = \C.value // expected-error@+1{{}} _ = \(() -> ()).noMember let _: PartialKeyPath<A> = \.property let _: KeyPath<A, Prop> = \.property let _: WritableKeyPath<A, Prop> = \.property // expected-error@+1{{ambiguous}} (need to improve diagnostic) let _: ReferenceWritableKeyPath<A, Prop> = \.property // FIXME: shouldn't be ambiguous // expected-error@+1{{ambiguous}} let _: PartialKeyPath<A> = \.[sub] let _: KeyPath<A, A> = \.[sub] let _: WritableKeyPath<A, A> = \.[sub] // expected-error@+1{{ambiguous}} (need to improve diagnostic) let _: ReferenceWritableKeyPath<A, A> = \.[sub] let _: PartialKeyPath<A> = \.optProperty? let _: KeyPath<A, Prop?> = \.optProperty? // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, Prop?> = \.optProperty? // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, Prop?> = \.optProperty? let _: PartialKeyPath<A> = \.optProperty?[sub] let _: KeyPath<A, A?> = \.optProperty?[sub] // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, A?> = \.optProperty?[sub] // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, A?> = \.optProperty?[sub] let _: KeyPath<A, Prop> = \.optProperty! let _: KeyPath<A, Prop> = \.optLetProperty! let _: KeyPath<A, Prop?> = \.property[optSub]?.optProperty! let _: KeyPath<A, A?> = \.property[optSub]?.optProperty![sub] let _: PartialKeyPath<C<A>> = \.value let _: KeyPath<C<A>, A> = \.value let _: WritableKeyPath<C<A>, A> = \.value // expected-error@+1{{ambiguous}} (need to improve diagnostic) let _: ReferenceWritableKeyPath<C<A>, A> = \.value let _: PartialKeyPath<C<A>> = \C.value let _: KeyPath<C<A>, A> = \C.value let _: WritableKeyPath<C<A>, A> = \C.value // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<C<A>, A> = \C.value let _: PartialKeyPath<Prop> = \.nonMutatingProperty let _: KeyPath<Prop, B> = \.nonMutatingProperty let _: WritableKeyPath<Prop, B> = \.nonMutatingProperty let _: ReferenceWritableKeyPath<Prop, B> = \.nonMutatingProperty var m = [\A.property, \A.[sub], \A.optProperty!] expect(&m, toHaveType: Exactly<[PartialKeyPath<A>]>.self) // FIXME: shouldn't be ambiguous // expected-error@+1{{ambiguous}} var n = [\A.property, \.optProperty, \.[sub], \.optProperty!] expect(&n, toHaveType: Exactly<[PartialKeyPath<A>]>.self) // FIXME: shouldn't be ambiguous // expected-error@+1{{ambiguous}} let _: [PartialKeyPath<A>] = [\.property, \.optProperty, \.[sub], \.optProperty!] var o = [\A.property, \C<A>.value] expect(&o, toHaveType: Exactly<[AnyKeyPath]>.self) let _: AnyKeyPath = \A.property let _: AnyKeyPath = \C<A>.value let _: AnyKeyPath = \.property // expected-error{{ambiguous}} let _: AnyKeyPath = \C.value // expected-error{{cannot convert}} (need to improve diagnostic) let _: AnyKeyPath = \.value // expected-error{{ambiguous}} let _ = \Prop.[nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \Prop.[sub, sub] let _ = \Prop.[sub, nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \C<Int>.[] let _ = \C<Int>.[sub] let _ = \C<Int>.[noHashableConstraint: sub] let _ = \C<Int>.[noHashableConstraint: nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} } func testKeyPathInGenericContext<H: Hashable, X>(hashable: H, anything: X) { let _ = \C<Int>.[hashable] let _ = \C<Int>.[noHashableConstraint: hashable] let _ = \C<Int>.[noHashableConstraint: anything] // expected-error{{subscript index of type 'X' in a key path must be Hashable}} } func testDisembodiedStringInterpolation(x: Int) { \(x) // expected-error{{string interpolation}} expected-error{{}} \(x, radix: 16) // expected-error{{string interpolation}} expected-error{{}} _ = \(Int, Int).0 // expected-error{{cannot reference tuple elements}} } func testNoComponents() { let _: KeyPath<A, A> = \A // expected-error{{must have at least one component}} let _: KeyPath<C, A> = \C // expected-error{{must have at least one component}} expected-error{{}} } struct TupleStruct { var unlabeled: (Int, String) var labeled: (foo: Int, bar: String) } func tupleComponent() { // TODO: Customized diagnostic let _ = \(Int, String).0 // expected-error{{}} let _ = \(Int, String).1 // expected-error{{}} let _ = \TupleStruct.unlabeled.0 // expected-error{{}} let _ = \TupleStruct.unlabeled.1 // expected-error{{}} let _ = \(foo: Int, bar: String).0 // expected-error{{}} let _ = \(foo: Int, bar: String).1 // expected-error{{}} let _ = \(foo: Int, bar: String).foo // expected-error{{}} let _ = \(foo: Int, bar: String).bar // expected-error{{}} let _ = \TupleStruct.labeled.0 // expected-error{{}} let _ = \TupleStruct.labeled.1 // expected-error{{}} let _ = \TupleStruct.labeled.foo // expected-error{{}} let _ = \TupleStruct.labeled.bar // expected-error{{}} } struct Z { } func testKeyPathSubscript(readonly: Z, writable: inout Z, kp: KeyPath<Z, Int>, wkp: WritableKeyPath<Z, Int>, rkp: ReferenceWritableKeyPath<Z, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink let pkp: PartialKeyPath = rkp var anySink1 = readonly[keyPath: pkp] expect(&anySink1, toHaveType: Exactly<Any>.self) var anySink2 = writable[keyPath: pkp] expect(&anySink2, toHaveType: Exactly<Any>.self) readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign to immutable}} writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign to immutable}} let akp: AnyKeyPath = pkp var anyqSink1 = readonly[keyPath: akp] expect(&anyqSink1, toHaveType: Exactly<Any?>.self) var anyqSink2 = writable[keyPath: akp] expect(&anyqSink2, toHaveType: Exactly<Any?>.self) readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign to immutable}} writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign to immutable}} } struct ZwithSubscript { subscript(keyPath kp: KeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: WritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: ReferenceWritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: PartialKeyPath<ZwithSubscript>) -> Any { return 0 } } struct NotZ {} func testKeyPathSubscript(readonly: ZwithSubscript, writable: inout ZwithSubscript, wrongType: inout NotZ, kp: KeyPath<ZwithSubscript, Int>, wkp: WritableKeyPath<ZwithSubscript, Int>, rkp: ReferenceWritableKeyPath<ZwithSubscript, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: subscript is get-only}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: subscript is get-only}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: subscript is get-only}} // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: wkp] = sink // FIXME: silently falls back to keypath application, which seems inconsistent readonly[keyPath: rkp] = sink // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: rkp] = sink let pkp: PartialKeyPath = rkp var anySink1 = readonly[keyPath: pkp] expect(&anySink1, toHaveType: Exactly<Any>.self) var anySink2 = writable[keyPath: pkp] expect(&anySink2, toHaveType: Exactly<Any>.self) readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: subscript is get-only}} writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: subscript is get-only}} let akp: AnyKeyPath = pkp var anyqSink1 = readonly[keyPath: akp] expect(&anyqSink1, toHaveType: Exactly<Any?>.self) var anyqSink2 = writable[keyPath: akp] expect(&anyqSink2, toHaveType: Exactly<Any?>.self) // FIXME: silently falls back to keypath application, which seems inconsistent readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign to immutable}} // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign to immutable}} _ = wrongType[keyPath: kp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: wkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: rkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: pkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: akp] } func testKeyPathSubscriptMetatype(readonly: Z.Type, writable: inout Z.Type, kp: KeyPath<Z.Type, Int>, wkp: WritableKeyPath<Z.Type, Int>, rkp: ReferenceWritableKeyPath<Z.Type, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptTuple(readonly: (Z,Z), writable: inout (Z,Z), kp: KeyPath<(Z,Z), Int>, wkp: WritableKeyPath<(Z,Z), Int>, rkp: ReferenceWritableKeyPath<(Z,Z), Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptLValue(base: Z, kp: inout KeyPath<Z, Z>) { _ = base[keyPath: kp] } func testKeyPathSubscriptExistentialBase(concreteBase: inout B, existentialBase: inout P, kp: KeyPath<P, String>, wkp: WritableKeyPath<P, String>, rkp: ReferenceWritableKeyPath<P, String>, pkp: PartialKeyPath<P>, s: String) { _ = concreteBase[keyPath: kp] _ = concreteBase[keyPath: wkp] _ = concreteBase[keyPath: rkp] _ = concreteBase[keyPath: pkp] concreteBase[keyPath: kp] = s // expected-error{{}} concreteBase[keyPath: wkp] = s // expected-error{{}} concreteBase[keyPath: rkp] = s concreteBase[keyPath: pkp] = s // expected-error{{}} _ = existentialBase[keyPath: kp] _ = existentialBase[keyPath: wkp] _ = existentialBase[keyPath: rkp] _ = existentialBase[keyPath: pkp] existentialBase[keyPath: kp] = s // expected-error{{}} existentialBase[keyPath: wkp] = s existentialBase[keyPath: rkp] = s existentialBase[keyPath: pkp] = s // expected-error{{}} } struct AA { subscript(x: Int) -> Int { return x } subscript(labeled x: Int) -> Int { return x } var c: CC? = CC() } class CC { var i = 0 } func testKeyPathOptional() { _ = \AA.c?.i _ = \AA.c!.i // SR-6198 let path: KeyPath<CC,Int>! = \CC.i let cc = CC() _ = cc[keyPath: path] } func testLiteralInAnyContext() { let _: AnyKeyPath = \A.property let _: AnyObject = \A.property let _: Any = \A.property let _: Any? = \A.property } func testMoreGeneralContext<T, U>(_: KeyPath<T, U>, with: T.Type) {} func testLiteralInMoreGeneralContext() { testMoreGeneralContext(\.property, with: A.self) } func testLabeledSubscript() { let _: KeyPath<AA, Int> = \AA.[labeled: 0] let _: KeyPath<AA, Int> = \.[labeled: 0] let k = \AA.[labeled: 0] // TODO: These ought to work without errors. let _ = \AA.[keyPath: k] // expected-error{{}} let _ = \AA.[keyPath: \AA.[labeled: 0]] // expected-error{{}} } func testInvalidKeyPathComponents() { let _ = \.{return 0} // expected-error* {{}} } class X { class var a: Int { return 1 } static var b = 2 } func testStaticKeyPathComponent() { _ = \X.a // expected-error{{}} _ = \X.Type.a // expected-error{{cannot refer to static member}} _ = \X.b // expected-error{{}} _ = \X.Type.b // expected-error{{cannot refer to static member}} } class Bass: Hashable { static func ==(_: Bass, _: Bass) -> Bool { return false } var hashValue: Int { return 0 } } class Treble: Bass { } struct BassSubscript { subscript(_: Bass) -> Int { fatalError() } subscript(_: @autoclosure () -> String) -> Int { fatalError() } } func testImplicitConversionInSubscriptIndex() { _ = \BassSubscript.[Treble()] _ = \BassSubscript.["hello"] // expected-error{{must be Hashable}} } // SR-6106 func sr6106() { class B {} class A { var b: B? = nil } class C { var a: A? func myFunc() { let _ = \C.a?.b } } } // SR-6744 func sr6744() { struct ABC { let value: Int func value(adding i: Int) -> Int { return value + i } } let abc = ABC(value: 0) func get<T>(for kp: KeyPath<ABC, T>) -> T { return abc[keyPath: kp] } _ = get(for: \.value) } struct VisibilityTesting { private(set) var x: Int fileprivate(set) var y: Int let z: Int // Key path exprs should not get special dispensation to write to lets // in init contexts init() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) // Allow WritableKeyPath for Swift 3/4 only. expect(&zRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) } func inPrivateContext() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&zRef, toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self) } } struct VisibilityTesting2 { func inFilePrivateContext() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z // Allow WritableKeyPath for Swift 3/4 only. expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&zRef, toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self) } } protocol PP {} class Base : PP { var i: Int = 0 } class Derived : Base {} func testSubtypeKeypathClass(_ keyPath: ReferenceWritableKeyPath<Base, Int>) { testSubtypeKeypathClass(\Derived.i) } func testSubtypeKeypathProtocol(_ keyPath: ReferenceWritableKeyPath<PP, Int>) { testSubtypeKeypathProtocol(\Base.i) // expected-error {{type 'PP' has no member 'i'}} } func testSyntaxErrors() { // expected-note{{}} _ = \. ; // expected-error{{expected member name following '.'}} _ = \.a ; _ = \[a ; _ = \[a]; _ = \? ; _ = \! ; _ = \. ; // expected-error{{expected member name following '.'}} _ = \.a ; _ = \[a ; _ = \[a,; _ = \[a:; _ = \[a]; _ = \.a?; _ = \.a!; _ = \A ; _ = \A, ; _ = \A< ; _ = \A. ; // expected-error{{expected member name following '.'}} _ = \A.a ; _ = \A[a ; _ = \A[a]; _ = \A? ; _ = \A! ; _ = \A. ; // expected-error{{expected member name following '.'}} _ = \A.a ; _ = \A[a ; _ = \A[a,; _ = \A[a:; _ = \A[a]; _ = \A.a?; _ = \A.a!; } // expected-error@+1{{}}
apache-2.0
8755b003f5cb9de979e548378721c407
32.787879
149
0.637519
3.758427
false
true
false
false
abury/ABSocialButton
ABSocialButtonDemo/ABSocialButton.swift
1
1760
// // ABSocialButton.swift // ABSocialButton // // Created by Aron Bury on 4/07/2015. // Copyright (c) 2015 Aron Bury. All rights reserved. // import UIKit enum ABSocialServiceType : Int { case Facebook case Twitter case Instagram case GooglePlus } class ABSocialButton: UIButton { let socialIconLabel : UIImageView; var socialService : ABSocialServiceType { didSet { self.updateLayout() } } //MARK: Init Methods required init(coder aDecoder: NSCoder) { socialIconLabel = UIImageView() socialIconLabel.backgroundColor = UIColor.purpleColor() socialService = ABSocialServiceType.Facebook super.init(coder: aDecoder) addSubview(socialIconLabel) } //MARK: UIVIew overides override func layoutSubviews() { super.layoutSubviews() layoutImageView() } private func layoutImageView() { let iconHeight : CGFloat = 30.0 let topPosition = (self.frame.size.height - iconHeight) / 2 socialIconLabel.frame = CGRectMake(10, topPosition, iconHeight, iconHeight) } //MARK: Custom Methods func updateLayout() { self.setBackgroundColor() self.setSocialIconLogo() } private func setBackgroundColor() { switch socialService { case .Facebook: self.backgroundColor = UIColor.blueColor() case .Twitter: self.backgroundColor = UIColor.blueColor() case .Instagram: self.backgroundColor = UIColor.brownColor() case .GooglePlus: self.backgroundColor = UIColor.redColor() } } private func setSocialIconLogo() { } }
mit
2db13d2af9de8721844f0dcfa5fb5575
23.109589
83
0.614773
4.743935
false
false
false
false
Dwarven/ShadowsocksX-NG
ShadowsocksX-NG/UserRulesController.swift
2
1792
// // UserRulesController.swift // ShadowsocksX-NG // // Created by 周斌佳 on 16/8/1. // Copyright © 2016年 qiuyuzhou. All rights reserved. // import Cocoa class UserRulesController: NSWindowController { @IBOutlet var userRulesView: NSTextView! override func windowDidLoad() { super.windowDidLoad() let fileMgr = FileManager.default if !fileMgr.fileExists(atPath: PACUserRuleFilePath) { let src = Bundle.main.path(forResource: "user-rule", ofType: "txt") try! fileMgr.copyItem(atPath: src!, toPath: PACUserRuleFilePath) } let str = try? String(contentsOfFile: PACUserRuleFilePath, encoding: String.Encoding.utf8) userRulesView.string = str! } @IBAction func didCancel(_ sender: AnyObject) { window?.performClose(self) } @IBAction func didOK(_ sender: AnyObject) { if let str = userRulesView?.string { do { try str.data(using: String.Encoding.utf8)?.write(to: URL(fileURLWithPath: PACUserRuleFilePath), options: .atomic) if GeneratePACFile() { // Popup a user notification let notification = NSUserNotification() notification.title = "PAC has been updated by User Rules.".localized NSUserNotificationCenter.default .deliver(notification) } else { let notification = NSUserNotification() notification.title = "It's failed to update PAC by User Rules.".localized NSUserNotificationCenter.default .deliver(notification) } } catch {} } window?.performClose(self) } }
gpl-3.0
4131c2c4356b597dd06db7f34f073962
32.641509
129
0.588895
4.858311
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/DetailController.swift
1
1056
// // DetailController.swift // DingshanSwift // // Created by song jufeng on 15/7/15. // Copyright (c) 2015年 song jufeng. All rights reserved. // import UIKit class DetailController:UIViewController { override func loadView() { super.loadView() self.view.backgroundColor = UIColor.whiteColor() let btn1 = UIButton(frame: CGRect(x:100,y:100,width:100,height:100)); btn1.backgroundColor = UIColor.grayColor() let ccount = self.navigationController?.childViewControllers.count let labelText:String = String(format:"layer No.%d", ccount!) btn1.setTitle(labelText, forState: UIControlState.Normal) btn1.addTarget(self, action:Selector("onTapBtn:"), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(btn1) } func onTapBtn(sender:UIButton) { print(sender, terminator: "") let detail = DetailController() self.navigationController?.pushViewController(detail, animated: true) } }
mit
a1f3ca2bb124a11a3f5946e0839450bb
29.142857
107
0.66129
4.447257
false
false
false
false
moltin/ios-swift-example
MoltinSwiftExample/MoltinSwiftExample/CartTableViewCell.swift
1
2697
// // CartTableViewCell.swift // MoltinSwiftExample // // Created by Dylan McKee on 16/08/2015. // Copyright (c) 2015 Moltin. All rights reserved. // import UIKit protocol CartTableViewCellDelegate { func cartTableViewCellSetQuantity(_ cell: CartTableViewCell, quantity: Int) } class CartTableViewCell: UITableViewCell { @IBOutlet weak var itemImageView:UIImageView? @IBOutlet weak var itemTitleLabel:UILabel? @IBOutlet weak var itemPriceLabel:UILabel? @IBOutlet weak var itemQuantityLabel:UILabel? @IBOutlet weak var itemQuantityStepper:UIStepper? var delegate:CartTableViewCellDelegate? var productId:String? var quantity:Int { get { if (self.itemQuantityStepper != nil) { return Int(self.itemQuantityStepper!.value) } return 0 } set { self.setItemQuantity(quantity) } } 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 } func setItemDictionary(_ itemDict: NSDictionary) { itemTitleLabel?.text = itemDict.value(forKey: "title") as? String itemPriceLabel?.text = itemDict.value(forKeyPath: "totals.post_discount.formatted.with_tax") as? String if let qty:NSNumber = itemDict.value(forKeyPath: "quantity") as? NSNumber { _ = "Qty. \(qty.intValue)" self.itemQuantityStepper?.value = qty.doubleValue } var imageUrl = "" if let images = itemDict.object(forKey: "images") as? NSArray { if (images.firstObject != nil) { imageUrl = (images.firstObject as! NSDictionary).value(forKeyPath: "url.https") as! String } } itemImageView?.sd_setImage(with: URL(string: imageUrl)) } @IBAction func stepperValueChanged(_ sender: AnyObject){ let value = Int(itemQuantityStepper!.value) setItemQuantity(value) } func setItemQuantity(_ quantity: Int) { let itemQuantityText = "Qty. \(quantity)" itemQuantityLabel?.text = itemQuantityText itemQuantityStepper?.value = Double(quantity) // Notify delegate, if there is one, too... if (delegate != nil) { delegate?.cartTableViewCellSetQuantity(self, quantity: quantity) } } }
mit
2ee13b4d8bd05ccf94c52137932796b8
26.520408
111
0.597701
4.877034
false
false
false
false
meteochu/HanekeSwift
Haneke/String+Haneke.swift
1
1558
// // String+Haneke.swift // Haneke // // Created by Hermes Pique on 8/30/14. // Copyright (c) 2014 Haneke. All rights reserved. // import Foundation extension String { func escapedFilename() -> String { return [ "\0":"%00", ":":"%3A", "/":"%2F" ].reduce(self.components(separatedBy: "%").joined(separator: "%25")) { str, m in str.components(separatedBy: m.0).joined(separator: m.1) } } func MD5String() -> String { guard let data = self.data(using: String.Encoding.utf8) else { return self } let MD5Calculator = MD5(data as Data) let MD5Data = MD5Calculator.calculate() as NSData let resultBytes = MD5Data.bytes.assumingMemoryBound(to: CUnsignedChar.self) let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length) let MD5String = NSMutableString() for c in resultEnumerator { MD5String.appendFormat("%02x", c) } return MD5String as String } func MD5Filename() -> String { let MD5String = self.MD5String() // NSString.pathExtension alone could return a query string, which can lead to very long filenames. let pathExtension = NSURL(string: self)?.pathExtension ?? (self as NSString).pathExtension if pathExtension.characters.count > 0 { return (MD5String as NSString).appendingPathExtension(pathExtension) ?? MD5String } else { return MD5String as String } } }
apache-2.0
4cf844ae92c3c7d27edeada5d7d893bd
30.795918
130
0.621309
4.210811
false
false
false
false
dabaosod011/Practise
iOS/Calculator/Calculator/CalculatorBrain.swift
1
2862
// // CalculatorBrain.swift // Calculator // // Created by Hai Xiao on 03/11/2017. // Copyright © 2017 Hai Xiao. All rights reserved. // import Foundation struct CalculatorBrain: CustomStringConvertible { var description: String{ get{ return "I am the CalculatorBrain." } } mutating func addUnaryOperation(named symbol: String, _ operation: @escaping (Double) -> Double){ opeartions[symbol] = Operation.unaryOperation(operation) } private var accumulator: Double? private enum Operation { case constant(Double) case unaryOperation((Double) -> Double) case binaryOperation((Double, Double) -> Double) case equals } private var opeartions: Dictionary<String , Operation> = [ "π": Operation.constant(Double.pi), "e": Operation.constant(M_E), "√": Operation.unaryOperation(sqrt), "cos": Operation.unaryOperation(cos), "±": Operation.unaryOperation({ -$0 }), "+": Operation.binaryOperation({ $0 + $1 }), "−": Operation.binaryOperation({ $0 - $1 }), "×": Operation.binaryOperation({ $0 * $1 }), "÷": Operation.binaryOperation({ $0 / $1 }), "=": Operation.equals ] mutating func performOperation(_ symbol: String) { if let operation = opeartions[symbol] { switch operation { case .constant(let associatedConstantValue): accumulator = associatedConstantValue case .unaryOperation(let function): if accumulator != nil { accumulator = function(accumulator!) } case .binaryOperation(let function): if accumulator != nil { pendingBinaryOperation = PendingBinaryOperation(function: function, firstOperand: accumulator!) accumulator = nil } case .equals: performPendingBinaryOperation() } } } private mutating func performPendingBinaryOperation() { if pendingBinaryOperation != nil && accumulator != nil { accumulator = pendingBinaryOperation!.perform(with: accumulator!) pendingBinaryOperation = nil } } private var pendingBinaryOperation: PendingBinaryOperation? private struct PendingBinaryOperation { let function: (Double, Double) -> Double let firstOperand: Double func perform(with secondOperand: Double) -> Double { return function(firstOperand, secondOperand) } } mutating func setOperand(_ operand: Double) { accumulator = operand } var result: Double? { get { return accumulator } // no set, so this is read-only variable value. } }
apache-2.0
28b47a07b356817703c238c8210aecfd
29.351064
115
0.589204
5.094643
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Search/ZSAikanHtmlParser.swift
1
5394
// // ZSAikanHtmlParser.swift // zhuishushenqi // // Created by caony on 2020/1/8. // Copyright © 2020 QS. All rights reserved. // import UIKit class ZSAikanHtmlParser { static func string(node:OCGumboNode, aikanString:String, text:Bool) ->String { let regs = aikanString.components(separatedBy: "@") if regs.count != 4 { return "" } let reg1 = regs[1] if reg1.length > 0 { let obj = self.elementArray(node: node, regexString: reg1) if obj.count > 0 { let reg2 = regs[2] let reg2Value = Int(reg2) ?? 0 var regNode:OCGumboNode? if obj.count > reg2Value { regNode = obj[reg2Value] as? OCGumboNode let reg3 = regs[3] if reg3 == "own:" { let text = regNode?.query(""); let resultNode = text?.lastObject as? OCGumboNode return resultNode?.text() ?? ""; } else if reg3.length >= 5 { let sub3 = reg3.nsString.substring(to: 4) if sub3 == "abs:" { let reg3Last = reg3.nsString.substring(from: 4) let attr = regNode?.attr(reg3Last) ?? ""; return attr } } else if reg3.length > 0 { let sub3 = reg3.nsString.substring(to: 1) if sub3 == ":" { let text = regNode?.text() ?? "" let reg3Last = reg3.nsString.substring(from: 1) let matchString = self.matchString(string: text, regString: reg3Last) return matchString; } else { let attr = regNode?.attr(sub3) ?? "" return attr } } if text { let text = regNode?.text() ?? "" return text } else { let html = regNode?.html() ?? "" return html } } } } else { let reg3 = regs[3] if reg3 == "own:" { let text = node.query("") let resultNode = text?.lastObject as? OCGumboNode return resultNode?.text() ?? "" } else if reg3.length >= 5 { let sub3 = reg3.nsString.substring(to: 4) if sub3 == "abs:" { let reg3Last = reg3.nsString.substring(from: 4) let attr = node.attr(reg3Last) ?? "" return attr } } else if reg3.length > 0 { let sub3 = reg3.nsString.substring(to: 1) if sub3 == ":" { let text = node.text() ?? "" let reg3Last = reg3.nsString.substring(from: 1) let matchString = self.matchString(string: text, regString: reg3Last) return matchString; } else { let attr = node.attr(sub3) ?? "" return attr } } if text { let text = node.text() ?? "" return text } else { let html = node.html() ?? "" return html } } return "" } static func matchString(string:String, regString:String) ->String { if string.length > 0 { let reg = try! NSRegularExpression(pattern: regString, options: NSRegularExpression.Options.caseInsensitive) let results = reg.matches(in: string, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, string.length)) var resultString = "" var range1String = "" if results.count > 0 { for index in 0..<results.count { let result = results[index] let range = result.range let subString = string.nsString.substring(with: range) resultString.append(subString) if result.numberOfRanges >= 2 { let range1 = result.range(at: 1) range1String = string.nsString.substring(with: range1) } } } if results.count > 0 { resultString.append(string.nsString.substring(from: 0)) } return range1String } return "" } static func elementArray(node:OCGumboNode, regexString:String) ->OCQueryObject { let regs = regexString.components(separatedBy: " ") var next:OCQueryObject = [] if regs.count > 0 { for index in 0..<regs.count { var reg = regs[index] reg = reg.replacingOccurrences(of: "=", with: " ") if index > 0 { next = next.find(reg) ?? []; } else { next = node.query(reg) ?? []; } } } return next } }
mit
ab93f174758ce689d26013349c2ce80f
37.798561
148
0.432412
4.772566
false
false
false
false
debugsquad/metalic
metalic/Metal/Premium/MetalFilterPremiumSelfer.swift
1
10105
import MetalPerformanceShaders import CoreImage import UIKit class MetalFilterPremiumSelfer:MetalFilter { private var bokehSize:Int private var sizeRatio:Int private var dilate:MPSImageDilate? private var gaussian:MPSImageGaussianBlur? private let kFunctionName:String = "filter_premiumSelfer" private let kFacesTextureIndex:Int = 2 private let kBokehTextureIndex:Int = 3 private let kMinImageSize:Int = 640 private let kMinBokehSize:Int = 12 private let kMinSizeRatio:Int = 2 private let kRepeatingElement:Float = 1 private let kGaussSigma:Float = 10 required init(device:MTLDevice) { bokehSize = 0 sizeRatio = kMinSizeRatio super.init(device:device, functionName:kFunctionName) } override func encode(commandBuffer:MTLCommandBuffer, sourceTexture:MTLTexture, destinationTexture: MTLTexture) { let sourceWidth:Int = sourceTexture.width let sourceHeight:Int = sourceTexture.height generateDilate(sourceTexture:sourceTexture) generateGaussian(sourceTexture:sourceTexture) let textureDescriptor:MTLTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat:sourceTexture.pixelFormat, width:sourceWidth, height:sourceHeight, mipmapped:false) let bokehTexture:MTLTexture = device.makeTexture(descriptor:textureDescriptor) dilate?.encode( commandBuffer:commandBuffer, sourceTexture:sourceTexture, destinationTexture:bokehTexture) gaussian?.encode( commandBuffer:commandBuffer, sourceTexture:bokehTexture, destinationTexture:destinationTexture) super.encode( commandBuffer:commandBuffer, sourceTexture:sourceTexture, destinationTexture:destinationTexture) } override func specialConfig(commandEncoder:MTLComputeCommandEncoder) { let context:CIContext = CIContext() let options:[String:Any] = [ CIDetectorAccuracy:CIDetectorAccuracyHigh ] guard let detector:CIDetector = CIDetector( ofType:CIDetectorTypeFace, context:context, options:options), let sourceTexture:MTLTexture = sourceTexture, let uiImage:UIImage = sourceTexture.exportImage(), let image:CIImage = CIImage(image:uiImage) else { return } let sourceWidth:Int = sourceTexture.width let sourceHeight:Int = sourceTexture.height let maxWidth:Int = sourceWidth - 1 let maxHeight:Int = sourceHeight - 1 let sourceSize:Int = sourceWidth * sourceHeight let sizeOfFloat:Int = MemoryLayout.size(ofValue:kRepeatingElement) var textureArray:[Float] = Array( repeating:kRepeatingElement, count:sourceSize) let bytesPerRow:Int = sizeOfFloat * sourceWidth let region:MTLRegion = MTLRegionMake2D( 0, 0, sourceWidth, sourceHeight) let textureDescriptor:MTLTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat:MTLPixelFormat.r32Float, width:sourceWidth, height:sourceHeight, mipmapped:false) let facesTexture:MTLTexture = device.makeTexture(descriptor:textureDescriptor) let features:[CIFeature] = detector.features(in:image) let faceRadius:Int = bokehSize * sizeRatio let faceRadiusFloat:Float = Float(faceRadius) for feature:CIFeature in features { if let faceFeature:CIFaceFeature = feature as? CIFaceFeature { let faceFeatureX:Int = Int(faceFeature.bounds.origin.x) let faceFeatureW:Int = Int(faceFeature.bounds.size.width) let faceFeatureH:Int = Int(faceFeature.bounds.size.height) let faceFeatureY:Int = sourceHeight - (Int(faceFeature.bounds.origin.y) + faceFeatureH) let faceFeatureMaxX:Int = faceFeatureX + faceFeatureW let faceFeatureMaxY:Int = faceFeatureY + faceFeatureH let faceFeatureW_2:Int = Int(round(Float(faceFeatureW) / 2.0)) let faceFeatureH_2:Int = Int(round(Float(faceFeatureH) / 2.0)) let faceFeatureCenterX:Int = faceFeatureX + faceFeatureW_2 let faceFeatureCenterY:Int = faceFeatureY + faceFeatureH_2 let faceFeatureRadius:Int = min(faceFeatureW_2, faceFeatureH_2) var minX:Int = faceFeatureX - faceRadius var maxX:Int = faceFeatureMaxX + faceRadius var minY:Int = faceFeatureY - faceRadius var maxY:Int = faceFeatureMaxY + faceRadius if minX < 0 { minX = 0 } if maxX > maxWidth { maxX = maxWidth } if minY < 0 { minY = 0 } if maxY > maxHeight { maxY = maxHeight } for indexVr:Int in minY ..< maxY { let deltaY:Int = indexVr - faceFeatureCenterY let deltaY2:Int = deltaY * deltaY let currentRow:Int = sourceWidth * indexVr for indexHr:Int in minX ..< maxX { let pixelIndex:Int = currentRow + indexHr let currentWeight:Float = textureArray[pixelIndex] if currentWeight > 0 { let deltaX:Int = indexHr - faceFeatureCenterX let deltaX2:Int = deltaX * deltaX let deltaSum:Int = deltaX2 + deltaY2 let hyp:Int = Int(sqrt(Float(deltaSum))) let deltaRadius:Int = hyp - faceFeatureRadius let pixelWeight:Float if deltaRadius > faceRadius { pixelWeight = 1 } else if deltaRadius > 0 { let deltaRadiusFloat:Float = Float(deltaRadius) pixelWeight = deltaRadiusFloat / faceRadiusFloat } else { pixelWeight = 0 } if pixelWeight < currentWeight { textureArray[pixelIndex] = pixelWeight } } } } } } let bytes:UnsafeRawPointer = UnsafeRawPointer(textureArray) facesTexture.replace( region:region, mipmapLevel:0, withBytes:bytes, bytesPerRow:bytesPerRow) commandEncoder.setTexture(facesTexture, at:kFacesTextureIndex) commandEncoder.setTexture(destinationTexture, at:kBokehTextureIndex) } //MARK: private private func generateDilate(sourceTexture:MTLTexture) { let sourceWidth:Int = sourceTexture.width let sourceHeight:Int = sourceTexture.height let minSize:Int = min(sourceWidth, sourceHeight) if minSize <= kMinImageSize { bokehSize = kMinBokehSize sizeRatio = kMinSizeRatio } else { sizeRatio = minSize / kMinImageSize bokehSize = kMinBokehSize * sizeRatio } if bokehSize % 2 == 0 { bokehSize += 1 } var probe:[Float] = [] let bokehSizeFloat:Float = Float(bokehSize) let midSize:Float = bokehSizeFloat / 2.0 for indexHr:Int in 0 ..< bokehSize { let indexHrFloat:Float = Float(indexHr) let xPos:Float = abs(indexHrFloat - midSize) for indexVr:Int in 0 ..< bokehSize { let indexVrFloat:Float = Float(indexVr) let yPos:Float = abs(indexVrFloat - midSize) let hypotPos:Float = hypot(xPos, yPos) let probeElement:Float if hypotPos < midSize { probeElement = 0 } else { probeElement = 1 } probe.append(probeElement) } } dilate = MPSImageDilate( device:device, kernelWidth:bokehSize, kernelHeight:bokehSize, values:probe) } private func generateGaussian(sourceTexture:MTLTexture) { let sourceWidth:Int = sourceTexture.width let sourceHeight:Int = sourceTexture.height let minSize:Int = min(sourceWidth, sourceHeight) let gaussSigma:Float if minSize <= kMinImageSize { gaussSigma = kGaussSigma } else { let gaussSizeRatio:Float = Float(minSize / kMinImageSize) gaussSigma = kGaussSigma * gaussSizeRatio } gaussian = MPSImageGaussianBlur( device:device, sigma:gaussSigma) } }
mit
6c8388bc67570fd32a9d45be86b5dc04
34.332168
114
0.523404
5.692958
false
false
false
false
tbkka/swift-protobuf
Sources/protoc-gen-swift/OneofGenerator.swift
3
17542
// Sources/protoc-gen-swift/OneofGenerator.swift - Oneof handling // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// This class represents a single Oneof in the proto and generates an efficient /// algebraic enum to store it in memory. /// // ----------------------------------------------------------------------------- import Foundation import SwiftProtobufPluginLibrary import SwiftProtobuf class OneofGenerator { /// Custom FieldGenerator that caches come calculated strings, and bridges /// all methods over to the OneofGenerator. class MemberFieldGenerator: FieldGeneratorBase, FieldGenerator { private weak var oneof: OneofGenerator! private(set) var group: Int let swiftName: String let dottedSwiftName: String let swiftType: String let swiftDefaultValue: String let protoGenericType: String let comments: String var isGroupOrMessage: Bool { switch fieldDescriptor.type { case .group, .message: return true default: return false } } // Only valid on message fields. var messageType: Descriptor { return fieldDescriptor.messageType } init(descriptor: FieldDescriptor, namer: SwiftProtobufNamer) { precondition(descriptor.oneofIndex != nil) // Set after creation. oneof = nil group = -1 let names = namer.messagePropertyNames(field: descriptor, prefixed: ".", includeHasAndClear: false) swiftName = names.name dottedSwiftName = names.prefixed swiftType = descriptor.swiftType(namer: namer) swiftDefaultValue = descriptor.swiftDefaultValue(namer: namer) protoGenericType = descriptor.protoGenericType comments = descriptor.protoSourceComments() super.init(descriptor: descriptor) } func setParent(_ oneof: OneofGenerator, group: Int) { self.oneof = oneof self.group = group } // MARK: Forward all the FieldGenerator methods to the OneofGenerator func generateInterface(printer p: inout CodePrinter) { oneof.generateInterface(printer: &p, field: self) } func generateStorage(printer p: inout CodePrinter) { oneof.generateStorage(printer: &p, field: self) } func generateStorageClassClone(printer p: inout CodePrinter) { oneof.generateStorageClassClone(printer: &p, field: self) } func generateDecodeFieldCase(printer p: inout CodePrinter) { oneof.generateDecodeFieldCase(printer: &p, field: self) } func generateFieldComparison(printer p: inout CodePrinter) { oneof.generateFieldComparison(printer: &p, field: self) } func generateRequiredFieldCheck(printer p: inout CodePrinter) { // Oneof members are all optional, so no need to forward this. } func generateIsInitializedCheck(printer p: inout CodePrinter) { oneof.generateIsInitializedCheck(printer: &p, field: self) } func generateTraverse(printer p: inout CodePrinter) { oneof.generateTraverse(printer: &p, field: self) } } private let oneofDescriptor: OneofDescriptor private let generatorOptions: GeneratorOptions private let namer: SwiftProtobufNamer private let usesHeapStorage: Bool private let fields: [MemberFieldGenerator] private let fieldsSortedByNumber: [MemberFieldGenerator] // The fields in number order and group into ranges as they are grouped in the parent. private let fieldSortedGrouped: [[MemberFieldGenerator]] private let swiftRelativeName: String private let swiftFullName: String private let comments: String private let swiftFieldName: String private let underscoreSwiftFieldName: String private let storedProperty: String init(descriptor: OneofDescriptor, generatorOptions: GeneratorOptions, namer: SwiftProtobufNamer, usesHeapStorage: Bool) { precondition(!descriptor.isSynthetic) self.oneofDescriptor = descriptor self.generatorOptions = generatorOptions self.namer = namer self.usesHeapStorage = usesHeapStorage comments = descriptor.protoSourceComments() swiftRelativeName = namer.relativeName(oneof: descriptor) swiftFullName = namer.fullName(oneof: descriptor) let names = namer.messagePropertyName(oneof: descriptor) swiftFieldName = names.name underscoreSwiftFieldName = names.prefixed if usesHeapStorage { storedProperty = "_storage.\(underscoreSwiftFieldName)" } else { storedProperty = "self.\(swiftFieldName)" } fields = descriptor.fields.map { return MemberFieldGenerator(descriptor: $0, namer: namer) } fieldsSortedByNumber = fields.sorted {$0.number < $1.number} // Bucked these fields in continuous chunks based on the other fields // in the parent and the parent's extension ranges. Insert the `start` // from each extension range as an easy way to check for them being // mixed in between the fields. var parentNumbers = descriptor.containingType.fields.map { Int($0.number) } parentNumbers.append(contentsOf: descriptor.containingType.extensionRanges.map { Int($0.start) }) var parentNumbersIterator = parentNumbers.sorted(by: { $0 < $1 }).makeIterator() var nextParentFieldNumber = parentNumbersIterator.next() var grouped = [[MemberFieldGenerator]]() var currentGroup = [MemberFieldGenerator]() for f in fieldsSortedByNumber { let nextFieldNumber = f.number if nextParentFieldNumber != nextFieldNumber { if !currentGroup.isEmpty { grouped.append(currentGroup) currentGroup.removeAll() } while nextParentFieldNumber != nextFieldNumber { nextParentFieldNumber = parentNumbersIterator.next() } } currentGroup.append(f) nextParentFieldNumber = parentNumbersIterator.next() } if !currentGroup.isEmpty { grouped.append(currentGroup) } self.fieldSortedGrouped = grouped // Now that self is fully initialized, set the parent references. var group = 0 for g in fieldSortedGrouped { for f in g { f.setParent(self, group: group) } group += 1 } } func fieldGenerator(forFieldNumber fieldNumber: Int) -> FieldGenerator { for f in fields { if f.number == fieldNumber { return f } } fatalError("Can't happen") } func generateMainEnum(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet // Repeat the comment from the oneof to provide some context // to this enum we generated. p.print( "\n", comments, "\(visibility)enum \(swiftRelativeName): Equatable {\n") p.indent() // Oneof case for each ivar for f in fields { p.print( f.comments, "case \(f.swiftName)(\(f.swiftType))\n") } // A helper for isInitialized let fieldsToCheck = fields.filter { $0.isGroupOrMessage && $0.messageType.containsRequiredFields() } if !fieldsToCheck.isEmpty { p.print( "\n", "fileprivate var isInitialized: Bool {\n") p.indent() if fieldsToCheck.count == 1 { let f = fieldsToCheck.first! p.print( "guard case \(f.dottedSwiftName)(let v) = self else {return true}\n", "return v.isInitialized\n") } else if fieldsToCheck.count > 1 { p.print( "// The use of inline closures is to circumvent an issue where the compiler\n", "// allocates stack space for every case branch when no optimizations are\n", "// enabled. https://github.com/apple/swift-protobuf/issues/1034\n", "switch self {\n") for f in fieldsToCheck { p.print("case \(f.dottedSwiftName): return {\n") p.indent() p.print("guard case \(f.dottedSwiftName)(let v) = self else { preconditionFailure() }\n") p.print("return v.isInitialized\n") p.outdent() p.print("}()\n") } // If there were other cases, add a default. if fieldsToCheck.count != fields.count { p.print("default: return true\n") } p.print("}\n") } p.outdent() p.print("}\n") } // Equatable conformance p.print("\n") p.outdent() p.print("#if !swift(>=4.1)\n") p.indent() p.print( "\(visibility)static func ==(lhs: \(swiftFullName), rhs: \(swiftFullName)) -> Bool {\n") p.indent() p.print( "// The use of inline closures is to circumvent an issue where the compiler\n", "// allocates stack space for every case branch when no optimizations are\n", "// enabled. https://github.com/apple/swift-protobuf/issues/1034\n", "switch (lhs, rhs) {\n") for f in fields { p.print( "case (\(f.dottedSwiftName), \(f.dottedSwiftName)): return {\n") p.indent() p.print( "guard case \(f.dottedSwiftName)(let l) = lhs, case \(f.dottedSwiftName)(let r) = rhs else { preconditionFailure() }\n", "return l == r\n") p.outdent() p.print( "}()\n") } if fields.count > 1 { // A tricky edge case: If the oneof only has a single case, then // the case pattern generated above is exhaustive and generating a // default produces a compiler error. If there is more than one // case, then the case patterns are not exhaustive (because we // don't compare mismatched pairs), and we have to include a // default. p.print("default: return false\n") } p.print("}\n") p.outdent() p.print("}\n") p.outdent() p.print("#endif\n") p.print("}\n") } private func gerenateOneofEnumProperty(printer p: inout CodePrinter) { let visibility = generatorOptions.visibilitySourceSnippet p.print("\n", comments) if usesHeapStorage { p.print( "\(visibility)var \(swiftFieldName): \(swiftRelativeName)? {\n") p.indent() p.print( "get {return _storage.\(underscoreSwiftFieldName)}\n", "set {_uniqueStorage().\(underscoreSwiftFieldName) = newValue}\n") p.outdent() p.print("}\n") } else { p.print( "\(visibility)var \(swiftFieldName): \(swiftFullName)? = nil\n") } } // MARK: Things brindged from MemberFieldGenerator func generateInterface(printer p: inout CodePrinter, field: MemberFieldGenerator) { // First field causes the oneof enum to get generated. if field === fields.first { gerenateOneofEnumProperty(printer: &p) } let getter = usesHeapStorage ? "_storage.\(underscoreSwiftFieldName)" : swiftFieldName let setter = usesHeapStorage ? "_uniqueStorage().\(underscoreSwiftFieldName)" : swiftFieldName let visibility = generatorOptions.visibilitySourceSnippet p.print( "\n", field.comments, "\(visibility)var \(field.swiftName): \(field.swiftType) {\n") p.indent() p.print("get {\n") p.indent() p.print( "if case \(field.dottedSwiftName)(let v)? = \(getter) {return v}\n", "return \(field.swiftDefaultValue)\n") p.outdent() p.print( "}\n", "set {\(setter) = \(field.dottedSwiftName)(newValue)}\n") p.outdent() p.print("}\n") } func generateStorage(printer p: inout CodePrinter, field: MemberFieldGenerator) { // First field causes the output. guard field === fields.first else { return } if usesHeapStorage { p.print("var \(underscoreSwiftFieldName): \(swiftFullName)?\n") } else { // When not using heap stroage, no extra storage is needed because // the public property for the oneof is the storage. } } func generateStorageClassClone(printer p: inout CodePrinter, field: MemberFieldGenerator) { // First field causes the output. guard field === fields.first else { return } p.print("\(underscoreSwiftFieldName) = source.\(underscoreSwiftFieldName)\n") } func generateDecodeFieldCase(printer p: inout CodePrinter, field: MemberFieldGenerator) { p.print("case \(field.number): try {\n") p.indent() if field.isGroupOrMessage { // Messages need to fetch the current value so new fields are merged into the existing // value p.print( "var v: \(field.swiftType)?\n", "if let current = \(storedProperty) {\n") p.indent() p.print( "try decoder.handleConflictingOneOf()\n", "if case \(field.dottedSwiftName)(let m) = current {v = m}\n") p.outdent() p.print("}\n") } else { p.print( "if \(storedProperty) != nil {try decoder.handleConflictingOneOf()}\n", "var v: \(field.swiftType)?\n") } p.print( "try decoder.decodeSingular\(field.protoGenericType)Field(value: &v)\n", "if let v = v {\(storedProperty) = \(field.dottedSwiftName)(v)}\n") p.outdent() p.print("}()\n") } func generateTraverse(printer p: inout CodePrinter, field: MemberFieldGenerator) { // First field in the group causes the output. let group = fieldSortedGrouped[field.group] guard field === group.first else { return } if group.count == 1 { p.print("if case \(field.dottedSwiftName)(let v)? = \(storedProperty) {\n") p.indent() p.print("try visitor.visitSingular\(field.protoGenericType)Field(value: v, fieldNumber: \(field.number))\n") p.outdent() } else { p.print( "// The use of inline closures is to circumvent an issue where the compiler\n", "// allocates stack space for every case branch when no optimizations are\n", "// enabled. https://github.com/apple/swift-protobuf/issues/1034\n", "switch \(storedProperty) {\n") for f in group { p.print("case \(f.dottedSwiftName)?: try {\n") p.indent() p.print("guard case \(f.dottedSwiftName)(let v)? = \(storedProperty) else { preconditionFailure() }\n") p.print("try visitor.visitSingular\(f.protoGenericType)Field(value: v, fieldNumber: \(f.number))\n") p.outdent() p.print("}()\n") } if fieldSortedGrouped.count == 1 { // Cover not being set. p.print("case nil: break\n") } else { // Multiple groups, cover other cases (or not being set). p.print("default: break\n") } } p.print("}\n") } func generateFieldComparison(printer p: inout CodePrinter, field: MemberFieldGenerator) { // First field causes the output. guard field === fields.first else { return } let lhsProperty: String let otherStoredProperty: String if usesHeapStorage { lhsProperty = "_storage.\(underscoreSwiftFieldName)" otherStoredProperty = "rhs_storage.\(underscoreSwiftFieldName)" } else { lhsProperty = "lhs.\(swiftFieldName)" otherStoredProperty = "rhs.\(swiftFieldName)" } p.print("if \(lhsProperty) != \(otherStoredProperty) {return false}\n") } func generateIsInitializedCheck(printer p: inout CodePrinter, field: MemberFieldGenerator) { // First field causes the output. guard field === fields.first else { return } // Confirm there is message field with required fields. let firstRequired = fields.first { $0.isGroupOrMessage && $0.messageType.containsRequiredFields() } guard firstRequired != nil else { return } p.print("if let v = \(storedProperty), !v.isInitialized {return false}\n") } }
apache-2.0
0773c758e5d19e115a0ee1f5ca08ed6f
37.553846
136
0.579238
4.787664
false
false
false
false
Eflet/Charts
ChartsRealm/Classes/Data/RealmLineRadarDataSet.swift
4
2269
// // RealmLineRadarDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics import Charts import Realm import Realm.Dynamic public class RealmLineRadarDataSet: RealmLineScatterCandleRadarDataSet, ILineRadarChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// The color that is used for filling the line surface area. private var _fillColor = NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0) /// The color that is used for filling the line surface area. public var fillColor: NSUIColor { get { return _fillColor } set { _fillColor = newValue fill = nil } } /// The object that is used for filling the area below the line. /// **default**: nil public var fill: ChartFill? /// The alpha value that is used for filling the line surface, /// **default**: 0.33 public var fillAlpha = CGFloat(0.33) private var _lineWidth = CGFloat(1.0) /// line width of the chart (min = 0.2, max = 10) /// /// **default**: 1 public var lineWidth: CGFloat { get { return _lineWidth } set { if (newValue < 0.2) { _lineWidth = 0.2 } else if (newValue > 10.0) { _lineWidth = 10.0 } else { _lineWidth = newValue } } } public var drawFilledEnabled = false public var isDrawFilledEnabled: Bool { return drawFilledEnabled } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmLineRadarDataSet copy.fillColor = fillColor copy._lineWidth = _lineWidth copy.drawFilledEnabled = drawFilledEnabled return copy } }
apache-2.0
1178ff90dabed4fae3045e3a3f45b446
22.645833
107
0.568973
4.593117
false
false
false
false
catloafsoft/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Low-Frequency Oscillating of Parameters.xcplaygroundpage/Contents.swift
1
1162
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Low-Frequency Oscillation of Parameters //: ### Often times we want rhythmic changing of parameters that varying in a standard way. This is tradition done with Low-Frequency Oscillators, LFOs. import XCPlayground import AudioKit let frequencyLFO = AKOperation.square(frequency: 1).scale(minimum: 440, maximum: 880) let carrierLFO = AKOperation.triangle(frequency: 1).scale(minimum: 1, maximum: 2) let modulatingMultiplierLFO = AKOperation.sawtooth(frequency: 1).scale(minimum: 0.1, maximum: 2) let modulatingIndexLFO = AKOperation.reverseSawtooth(frequency: 1).scale(minimum: 0.1, maximum: 20) let fm = AKOperation.fmOscillator( baseFrequency: frequencyLFO, carrierMultiplier: carrierLFO, modulatingMultiplier: modulatingMultiplierLFO, modulationIndex: modulatingIndexLFO, amplitude: 1) let generator = AKOperationGenerator(operation: fm) AudioKit.output = generator AudioKit.start() generator.start() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
ffb59d919af7f23349684f1aa7071a6a
37.733333
153
0.756454
3.834983
false
false
false
false
HWdan/DYTV
DYTV/DYTV/Classes/Main/Controller/BaseViewController.swift
1
1348
// // BaseViewController.swift // DYTV // // Created by hegaokun on 2017/4/12. // Copyright © 2017年 AAS. All rights reserved. // import UIKit class BaseViewController: UIViewController { //MARK:- 定义属性 var contentView: UIView? //MARK:- 懒加载 fileprivate lazy var animImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "img_loading_1")) imageView.center = self.view.center imageView.center.y = (kStausBarH + kNavigationBarH + kTitleViewH + kTabbarH) * 1.7 imageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX return imageView }() //MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } //MARK:- 设置 UI extension BaseViewController { func setupUI() { //隐藏内容的 View contentView?.isHidden = true view.addSubview(animImageView) animImageView.startAnimating() view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } func loadDtaaFinished() { animImageView.stopAnimating() animImageView.isHidden = true contentView?.isHidden = false } }
mit
a785c5d52437b6198265a76fa57f3abd
25.714286
104
0.629488
4.334437
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0156.xcplaygroundpage/Contents.swift
1
8972
/*: # Class and Subtype existentials * Proposal: [SE-0156](0156-subclass-existentials.md) * Authors: [David Hart](http://github.com/hartbit), [Austin Zheng](http://github.com/austinzheng) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Implemented (Swift 4)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170320/034123.html) * Bug: [SR-4296](https://bugs.swift.org/browse/SR-4296) ## Introduction This proposal brings more expressive power to the type system by allowing Swift to represent existentials of classes and subtypes which conform to protocols. [Mailing list discussion](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170123/031066.html) ## Motivation Currently, the only existentials which can be represented in Swift are conformances to a set of protocols, using the `&` protocol composition syntax: ```swift Protocol1 & Protocol2 ``` On the other hand, Objective-C is capable of expressing existentials of classes and subclasses conforming to protocols with the following syntax: ```objc id<Protocol1, Protocol2> Base<Protocol>* ``` We propose to provide similar expressive power to Swift, which will also improve the bridging of those types from Objective-C. ## Proposed solution The proposal keeps the existing `&` syntax but allows one of the elements to be either `AnyObject` or of class type. The equivalent to the above Objective-C types would look like this: ```swift AnyObject & Protocol1 & Protocol2 Base & Protocol ``` As in Objective-C, the first line is an existential of classes which conform to `Protocol1` and `Protocol2`, and the second line is an existential of subtypes of `Base` which conform to `Protocol`. Here are the new proposed rules for what is valid in a existential conjunction syntax: ### 1. An element in the protocol composition syntax can be the `AnyObject` keyword to enforce a class constraint: ```swift protocol P {} struct S : P {} class C : P {} class D { } let t: AnyObject & P = S() // Compiler error: S is not of class type let u: AnyObject & P = C() // Compiles successfully let v: P & AnyObject = C() // Compiles successfully let w: P & AnyObject = D() // Compiler error: class D does not conform to protocol P ``` ### 2. An element in the protocol composition syntax can be a class type to enforce the existential to be a subtype of the class: ```swift protocol P {} struct S {} class C {} class D : P {} class E : C, P {} let u: S & P // Compiler error: S is not of class type let v: C & P = D() // Compiler error: D is not a subtype of C let w: C & P = E() // Compiles successfully ``` ### 3. If a protocol composition contains both a class type and `AnyObject`, the class type supersedes the `AnyObject` constraint: ```swift protocol P {} class C {} class D : C, P { } let u: AnyObject & C & P = D() // Okay: D is a subclass of C and conforms to P let v: C & P = u // Okay: C & P is equivalent to AnyObject & C & P let w: AnyObject & C & P = v // Okay: AnyObject & C & P is equivalent to C & P ``` ### 4. If a protocol composition contains two class types, either the class types must be the same or one must be a subclass of the other. In the latter case, the subclass type supersedes the superclass type: ```swift protocol P {} class C {} class D : C { } class E : C { } class F : D, P { } let t: C & D & P = F() // Okay: F is a subclass of D and conforms to P let u: D & P = t // Okay: D & P is equivalent to C & D & P let v: C & D & P = u // Okay: C & D & P is equivalent to D & P let w: D & E & P // Compiler error: D is not a subclass of E or vice-versa ``` ### 5. When a protocol composition type contains one or more typealiases, the validity of the type is determined by expanding the typealiases into their component protocols, class types, and `AnyObject` constraints, then following the rules described above: ```swift class C {} class D : C {} class E {} protocol P1 {} protocol P2 {} typealias TA1 = AnyObject & P1 typealias TA2 = AnyObject & P2 typealias TA3 = C & P2 typealias TA4 = D & P2 typealias TA5 = E & P2 typealias TA5 = TA1 & TA2 // Expansion: typealias TA5 = AnyObject & P1 & AnyObject & P2 // Normalization: typealias TA5 = AnyObject & P1 & P2 // TA5 is valid typealias TA6 = TA1 & TA3 // Expansion: typealias TA6 = AnyObject & P1 & C & P2 // Normalization (AnyObject < C): typealias TA6 = C & P1 & P2 // TA6 is valid typealias TA7 = TA3 & TA4 // Expansion: typealias TA7 = C & P2 & D & P2 // Normalization (C < D): typealias TA7 = D & P2 // TA7 is valid typealias TA8 = TA4 & TA5 // Expansion: typealias TA8 = D & P2 & E & P2 // Normalization: typealias TA8 = D & E & P2 // TA8 is invalid because the D and E constraints are incompatible ``` ## `class` and `AnyObject` This proposal merges the concepts of `class` and `AnyObject`, which now have the same meaning: they represent an existential for classes. To get rid of the duplication, we suggest only keeping `AnyObject` around. To reduce source-breakage to a minimum, `class` could be redefined as `typealias class = AnyObject` and give a deprecation warning on `class` for the first version of Swift this proposal is implemented in. Later, `class` could be removed in a subsequent version of Swift. ## Inheritance clauses and `typealias` To improve readability and reduce confusion, a class conforming to a typealias which contains a class type constraint does not implicitly inherit the class type: inheritance should stay explicit. Here are a few examples to remind what the current rules are and to make the previous sentence clearer: The proposal does not change the rule which forbids using the protocol composition syntax in the inheritance clause: ```swift protocol P1 {} protocol P2 {} class C {} class D : P1 & P2 {} // Compiler error class E : C & P1 {} // Compiler error ``` Class `D` in the previous example does not inherit a base class so it can be expressed using the inheritance/conformance syntax or through a typealias: ```swift class D : P1, P2 {} // Valid typealias P12 = P1 & P2 class D : P12 {} // Valid ``` Class `E` above inherits a base class. The inheritance must be explicitly declared in the inheritance clause and can't be implicitly derived from a typealias: ```swift class E : C, P1 {} // Valid typealias CP1 = C & P1 class E : CP1 {} // Compiler error: class 'E' does not inherit from class 'C' class E : C, CP1 {} // Valid: the inheritance is explicitly declared ``` ## Source compatibility This change will not break Swift 3 compatibility mode because Objective-C types will continue to be imported as before. But in Swift 4 mode, all types bridged from Objective-C which use the equivalent Objective-C existential syntax could break code which does not meet the new protocol requirements. For example, the following Objective-C code: ```objc @interface MyViewController - (void)setup:(nonnull UIViewController<UITableViewDataSource,UITableViewDelegate>*)tableViewController; @end ``` is imported into Swift-3 mode as: ```swift class MyViewController { func setup(tableViewController: UIViewController) {} } ``` which allows calling the function with an invalid parameter: ```swift let myViewController = MyViewController() myViewController.setup(UIViewController()) ``` The previous code continues to compile but still crashs if the Objective-C code calls a method of `UITableViewDataSource` or `UITableViewDelegate`. But if this proposal is accepted and implemented as-is, the Objective-C code will be imported in Swift 4 mode as: ```swift class MyViewController { func setup(tableViewController: UIViewController & UITableViewDataSource & UITableViewDelegate) {} } ``` That would then cause the Swift code run in version 4 mode to fail to compile with an error which states that `UIViewController` does not conform to the `UITableViewDataSource` and `UITableViewDelegate` protocols. ## Alternatives considered An alternative solution to the `class`/`AnyObject` duplication was to keep both, redefine `AnyObject` as `typealias AnyObject = class` and favor the latter when used as a type name. The [reviewed version of the proposal](https://github.com/apple/swift-evolution/blob/78da25ec4acdc49ad9b68fb58300e49c33bc6355/proposals/0156-subclass-existentials.md) included rules that required the class type (or `AnyObject`) to be first within the protocol composition, e.g., `AnyObject & Protocol1` was well-formed but `Protocol1 & AnyObject` would produce a compiler error. When accepting this proposal, the core team removed these rules; see the decision notes at the top for more information. ## Acknowledgements Thanks to [Austin Zheng](http://github.com/austinzheng) and [Matthew Johnson](https://github.com/anandabits) who brought a lot of attention to existentials in this mailing-list and from whom most of the ideas in the proposal come from. ---------- [Previous](@previous) | [Next](@next) */
mit
3fc5a255f267767393c5770ba08e1e6a
39.053571
484
0.732724
3.858925
false
false
false
false
mmick66/KDDragAndDropCollectionView
Classes/KDDragAndDropCollectionView.swift
1
15735
/* * KDDragAndDropCollectionView.swift * Created by Michael Michailidis on 10/04/2015. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit public protocol KDDragAndDropCollectionViewDataSource : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath) -> Void /* optional */ func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool /* optional */ func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool /* optional */ func collectionView(_ collectionView: UICollectionView, stylingRepresentationView: UIView) -> UIView? } extension KDDragAndDropCollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, stylingRepresentationView: UIView) -> UIView? { return nil } func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool { return true } func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool { return true } } open class KDDragAndDropCollectionView: UICollectionView, KDDraggable, KDDroppable { required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public var draggingPathOfCellBeingDragged : IndexPath? var iDataSource : UICollectionViewDataSource? var iDelegate : UICollectionViewDelegate? override open func awakeFromNib() { super.awakeFromNib() } override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) } // MARK : KDDraggable public func canDragAtPoint(_ point : CGPoint) -> Bool { if let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource, let indexPathOfPoint = self.indexPathForItem(at: point) { return dataSource.collectionView(self, cellIsDraggableAtIndexPath: indexPathOfPoint) } return false } public func representationImageAtPoint(_ point : CGPoint) -> UIView? { guard let indexPath = self.indexPathForItem(at: point) else { return nil } guard let cell = self.cellForItem(at: indexPath) else { return nil } UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0) cell.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(image: image) imageView.frame = cell.frame return imageView } public func stylingRepresentationView(_ view: UIView) -> UIView? { guard let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return nil } return dataSource.collectionView(self, stylingRepresentationView: view) } public func dataItemAtPoint(_ point : CGPoint) -> AnyObject? { guard let indexPath = self.indexPathForItem(at: point) else { return nil } guard let dragDropDS = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return nil } return dragDropDS.collectionView(self, dataItemForIndexPath: indexPath) } public func startDraggingAtPoint(_ point : CGPoint) -> Void { self.draggingPathOfCellBeingDragged = self.indexPathForItem(at: point) self.reloadData() } public func stopDragging() -> Void { if let idx = self.draggingPathOfCellBeingDragged { if let cell = self.cellForItem(at: idx) { cell.isHidden = false } } self.draggingPathOfCellBeingDragged = nil self.reloadData() } public func dragDataItem(_ item : AnyObject) -> Void { guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return } guard let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else { return } dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath) if self.animating { self.deleteItems(at: [existngIndexPath]) } else { self.animating = true self.performBatchUpdates({ () -> Void in self.deleteItems(at: [existngIndexPath]) }, completion: { complete -> Void in self.animating = false self.reloadData() }) } } // MARK : KDDroppable public func canDropAtRect(_ rect : CGRect) -> Bool { return (self.indexPathForCellOverlappingRect(rect) != nil) } public func indexPathForCellOverlappingRect( _ rect : CGRect) -> IndexPath? { var overlappingArea : CGFloat = 0.0 var cellCandidate : UICollectionViewCell? let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource let visibleCells = self.visibleCells if visibleCells.count == 0 { return IndexPath(row: 0, section: 0) } if isHorizontal && rect.origin.x > self.contentSize.width || !isHorizontal && rect.origin.y > self.contentSize.height { if dataSource?.collectionView(self, cellIsDroppableAtIndexPath: IndexPath(row: visibleCells.count - 1, section: 0)) == true { return IndexPath(row: visibleCells.count - 1, section: 0) } return nil } for visible in visibleCells { let intersection = visible.frame.intersection(rect) if (intersection.width * intersection.height) > overlappingArea { overlappingArea = intersection.width * intersection.height cellCandidate = visible } } if let cellRetrieved = cellCandidate, let indexPath = self.indexPath(for: cellRetrieved), dataSource?.collectionView(self, cellIsDroppableAtIndexPath: indexPath) == true { return self.indexPath(for: cellRetrieved) } return nil } fileprivate var currentInRect : CGRect? public func willMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void { let dragDropDataSource = self.dataSource as! KDDragAndDropCollectionViewDataSource // its guaranteed to have a data source if let _ = dragDropDataSource.collectionView(self, indexPathForDataItem: item) { // if data item exists return } if let indexPath = self.indexPathForCellOverlappingRect(rect) { dragDropDataSource.collectionView(self, insertDataItem: item, atIndexPath: indexPath) self.draggingPathOfCellBeingDragged = indexPath self.animating = true self.performBatchUpdates({ () -> Void in self.insertItems(at: [indexPath]) }, completion: { complete -> Void in self.animating = false // if in the meantime we have let go if self.draggingPathOfCellBeingDragged == nil { self.reloadData() } }) } currentInRect = rect } public var isHorizontal : Bool { return (self.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .horizontal } public var animating: Bool = false public var paging : Bool = false func checkForEdgesAndScroll(_ rect : CGRect) -> Void { if paging == true { return } let currentRect : CGRect = CGRect(x: self.contentOffset.x, y: self.contentOffset.y, width: self.bounds.size.width, height: self.bounds.size.height) var rectForNextScroll : CGRect = currentRect if isHorizontal { let leftBoundary = CGRect(x: -30.0, y: 0.0, width: 30.0, height: self.frame.size.height) let rightBoundary = CGRect(x: self.frame.size.width, y: 0.0, width: 30.0, height: self.frame.size.height) if rect.intersects(leftBoundary) == true { rectForNextScroll.origin.x -= self.bounds.size.width * 0.5 if rectForNextScroll.origin.x < 0 { rectForNextScroll.origin.x = 0 } } else if rect.intersects(rightBoundary) == true { rectForNextScroll.origin.x += self.bounds.size.width * 0.5 if rectForNextScroll.origin.x > self.contentSize.width - self.bounds.size.width { rectForNextScroll.origin.x = self.contentSize.width - self.bounds.size.width } } } else { // is vertical let topBoundary = CGRect(x: 0.0, y: -30.0, width: self.frame.size.width, height: 30.0) let bottomBoundary = CGRect(x: 0.0, y: self.frame.size.height, width: self.frame.size.width, height: 30.0) if rect.intersects(topBoundary) == true { rectForNextScroll.origin.y -= self.bounds.size.height * 0.5 if rectForNextScroll.origin.y < 0 { rectForNextScroll.origin.y = 0 } } else if rect.intersects(bottomBoundary) == true { rectForNextScroll.origin.y += self.bounds.size.height * 0.5 if rectForNextScroll.origin.y > self.contentSize.height - self.bounds.size.height { rectForNextScroll.origin.y = self.contentSize.height - self.bounds.size.height } } } // check to see if a change in rectForNextScroll has been made if currentRect.equalTo(rectForNextScroll) == false { self.paging = true self.scrollRectToVisible(rectForNextScroll, animated: true) let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.paging = false } } } public func didMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void { let dragDropDS = self.dataSource as! KDDragAndDropCollectionViewDataSource // guaranteed to have a ds if let existingIndexPath = dragDropDS.collectionView(self, indexPathForDataItem: item), let indexPath = self.indexPathForCellOverlappingRect(rect) { if indexPath.item != existingIndexPath.item { dragDropDS.collectionView(self, moveDataItemFromIndexPath: existingIndexPath, toIndexPath: indexPath) self.animating = true self.performBatchUpdates({ () -> Void in self.moveItem(at: existingIndexPath, to: indexPath) }, completion: { (finished) -> Void in self.animating = false self.reloadData() }) self.draggingPathOfCellBeingDragged = indexPath } } // Check Paging var normalizedRect = rect normalizedRect.origin.x -= self.contentOffset.x normalizedRect.origin.y -= self.contentOffset.y currentInRect = normalizedRect self.checkForEdgesAndScroll(normalizedRect) } public func didMoveOutItem(_ item : AnyObject) -> Void { guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource, let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else { return } dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath) if self.animating { self.deleteItems(at: [existngIndexPath]) } else { self.animating = true self.performBatchUpdates({ () -> Void in self.deleteItems(at: [existngIndexPath]) }, completion: { (finished) -> Void in self.animating = false; self.reloadData() }) } if let idx = self.draggingPathOfCellBeingDragged { if let cell = self.cellForItem(at: idx) { cell.isHidden = false } } self.draggingPathOfCellBeingDragged = nil currentInRect = nil } public func dropDataItem(_ item : AnyObject, atRect : CGRect) -> Void { // show hidden cell if let index = draggingPathOfCellBeingDragged, let cell = self.cellForItem(at: index), cell.isHidden == true { cell.alpha = 1 cell.isHidden = false } currentInRect = nil self.draggingPathOfCellBeingDragged = nil self.reloadData() } }
mit
2fac70d9177dca39cc5029b824f566c6
35.339492
179
0.594789
5.473043
false
false
false
false
j-chao/venture
source/venture/AddEventVC.swift
1
4010
// // AddEventVC.swift // venture // // Created by Justin Chao on 3/24/17. // Copyright © 2017 Group1. All rights reserved. // import UIKit import Firebase class AddEventVC: UIViewController { var ref: FIRDatabaseReference! = FIRDatabase.database().reference() let userID = FIRAuth.auth()?.currentUser?.uid @IBOutlet weak var eventDesc: UITextField! @IBOutlet weak var eventLoc: UITextField! @IBOutlet weak var eventTime: UIDatePicker! @IBOutlet weak var eventDateLbl: UILabel! var eventDate:Date! var eventDateStr:String! var eventDescStr:String! var eventLocStr:String! var fromFoodorPlace:Bool! var fromFlight:Bool! var flightTime:Date? override func viewDidLoad() { self.setBackground() super.viewDidLoad() eventTime.backgroundColor = .white eventTime.setValue(0.8, forKeyPath: "alpha") eventDesc.attributedPlaceholder = NSAttributedString(string: "event description", attributes: [NSForegroundColorAttributeName:UIColor.lightGray]) eventLoc.attributedPlaceholder = NSAttributedString(string: "event address", attributes: [NSForegroundColorAttributeName:UIColor.lightGray]) let dateTitle = stringLongFromDate(date: eventDate) self.eventDateStr = dateTitle self.eventDateLbl.text = dateTitle if fromFoodorPlace == true { eventDesc.text = eventDescStr eventLoc.text = eventLocStr } else if fromFlight == true { eventDesc.text = eventDescStr let code = eventLocStr! eventLoc.text = self.airportAddress(code: code) eventTime.date = flightTime! } } func airportAddress (code:String) -> String { if code == "DFW " { return "2400 Aviation Dr, DFW Airport, TX 75261" } else if code == "LAX " { return "1 World Way, Los Angeles, CA 90045" } else if code == "SFO " { return "San Francisco, CA 94128" } else if code == "ORD " { return "10000 W O'Hare Ave, Chicago, IL 60666" } else if code == "JFK " { return "Queens, NY 11430" } else { return code + " (airport address not supported)" } } @IBAction func addEventButton(_ sender: Any) { if eventDesc.text!.isEmpty || eventLoc.text!.isEmpty { self.presentAllFieldsAlert() } else { let eventTimeStr = stringTimefromDateToFIR(date: eventTime.date) self.addEvent(eventDesc:eventDesc.text!, eventLoc:eventLoc.text!, eventTime:eventTimeStr) for vc in self.navigationController!.viewControllers as Array { if vc .isKind(of: TripPageVC.self) { self.navigationController!.popToViewController(vc, animated: true) break } } } } func addEvent (eventDesc:String, eventLoc:String, eventTime:String) { let eventRef = self.ref.child("users/\(self.userID!)/trips/\(passedTrip)/\(self.eventDateStr!)/\(eventTime)") eventRef.child("eventTime").setValue(eventTime) eventRef.child("eventDesc").setValue(eventDesc) eventRef.child("eventLoc").setValue(eventLoc) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func presentAllFieldsAlert() { let alert = UIAlertController(title: "Error", message: "Please fill out all fields." , preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action:UIAlertAction) in } alert.addAction(OKAction) self.present(alert, animated: true, completion:nil) return } }
mit
78a034831372ffbb6657320113df7185
34.477876
153
0.621103
4.571266
false
false
false
false
teeeeeegz/DuckDuckDefine-iOS
DuckDuckDefine/DefinitionViewController.swift
1
1184
// // DefinitionViewController.swift // DuckDuckDefine // // Created by Michael Tigas on 12/3/17. // Copyright © 2017 Michael Tigas. All rights reserved. // import UIKit import Alamofire import Kingfisher /** ViewController which displays information relating to a returned Definition */ class DefinitionViewController: UIViewController { @IBOutlet weak var imageView: RoundedImageView! @IBOutlet weak var descriptionLabel: UILabel! var definition: SearchDefinition? override func viewDidLoad() { super.viewDidLoad() initVC() } /** Initialise ViewController properties/functionality */ private func initVC() { if let heading = definition?.heading { title = heading } if let description = definition?.abstractText { descriptionLabel.text = description } if let imageUrl = definition?.imageUrl { imageView.kf.indicatorType = .activity imageView.kf.setImage(with: imageUrl) } } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } }
mit
82c6485ddfb061863bf19099e7a5d010
23.142857
76
0.638208
5.304933
false
false
false
false
pisces/OrangeRealm
OrangeRealm/Classes/AbstractRealmManager.swift
1
6709
// // AbstractRealmManager.swift // OrangeRealm // // Created by Steve Kim on 23/4/17. // import Realm import RealmSwift open class AbstractRealmManager { // MARK: - Constants public static let queue = DispatchQueue(label: Const.name) public let notificationManager = RealmNotificationManager() private struct Const { static let name = "pisces.orange.RealmManager" } // MARK: - Properties private var isUseSerialQueue: Bool = true public var realm: Realm { var realm: Realm! perform { do { realm = try Realm(configuration: self.createConfiguration()) } catch { do { try FileManager.default.removeItem(at: self.fileURL) } catch { print("AbstractRealmManager remove realm error \(error.localizedDescription)") } realm = try! Realm(configuration: self.createConfiguration()) self.clear() self.recover() } } return realm } // MARK: - Con(De)structor public init(isUseSerialQueue: Bool = true) { self.isUseSerialQueue = isUseSerialQueue configure() } // MARK: - Abstract open var schemaVersion: UInt64 { fatalError("schemaVersion has not been implemented") } open var fileURL: URL { fatalError("fileURL has not been implemented") } open var objectTypes: [Object.Type]? { fatalError("fileURL has not been implemented") } open func deleteAll(_ realm: Realm) { fatalError("deleteAll() has not been implemented") } open func process(forMigration migration: Migration, oldSchemaVersion: UInt64) { fatalError("process(forMigration:oldSchemaVersion:) has not been implemented") } open func recover() { fatalError("recover has not been implemented") } // MARK: - Public methods open class var shared: AbstractRealmManager { struct Static { static let instance = AbstractRealmManager() } return Static.instance } public func array<T: Object>(forResults results: Results<T>, unlink: Bool = false) -> [T] { return results.map({return unlink ? T(value: $0, schema: RLMSchema()) : $0}) } public func clear() { notificationManager.removeAll() try? transaction { (realm) in self.deleteAll(realm) } } public func initialize() { } public func objects<T: Object>(_ where: String? = nil, sortProperty: Any? = nil, ascending: Bool = true, limit: Int = -1, max: Int = -1, unlink: Bool = false, filter: ((T) -> Bool)? = nil) -> [T] { return query(`where`, sortProperty: sortProperty, ascending: ascending, limit: limit, max: max, unlink: unlink, filter: filter).objects } public func perform(execution: @escaping () -> ()) { if !isUseSerialQueue || DispatchQueue.isCurrentQueue(queue: AbstractRealmManager.queue) { execution() } else { AbstractRealmManager.queue.sync { execution() } } } public func query<T: Object>(_ where: String? = nil, sortProperty: Any? = nil, ascending: Bool = true, limit: Int = -1, max: Int = -1, unlink: Bool = false, filter: ((T) -> Bool)? = nil) -> RealmQueryResult<T> { var results: Results<T>! var objects: [T] = [] perform { results = self.results(`where`, sortProperty: sortProperty, ascending: ascending) let elements = self.array(forResults: results, unlink: unlink) if let filter = filter { for element in elements { if filter(element) { objects.append(element) } } } else { objects = elements } if limit > -1 { objects = objects.count > limit ? Array(objects[0..<limit]) : objects } } return RealmQueryResult(notificationManager: notificationManager, objects: objects, results: results, max: max) } public func results<T: Object>(_ where: String? = nil, sortProperty: Any? = nil, ascending: Bool = true) -> Results<T> { var results: Results<T>! perform { results = self.realm.objects(T.self) if let `where` = `where` { results = results.filter(`where`) } if let properties = sortProperty as? [String] { for property in properties { results = results.sorted(byKeyPath: property, ascending: ascending) } } else if let sortProperty = sortProperty as? String { results = results.sorted(byKeyPath: sortProperty, ascending: ascending) } } return results } public func transaction(_ realm: Realm? = nil, execution: @escaping (Realm) -> ()) throws { var _error: Error? perform { let realm = realm == nil ? self.realm : realm! if realm.isInWriteTransaction { execution(realm) } else { do { realm.beginWrite() execution(realm) try realm.commitWrite() } catch { realm.cancelWrite() _error = error } } } if let error = _error { throw error } } // MARK: - Internal methods internal func configure() { } internal func createConfiguration() -> Realm.Configuration { return Realm.Configuration( fileURL: fileURL, schemaVersion: schemaVersion, migrationBlock: { (migration, oldSchemaVersion) in if oldSchemaVersion < self.schemaVersion { self.process(forMigration: migration, oldSchemaVersion: oldSchemaVersion) } }, objectTypes: objectTypes ) } } extension List where Element: Object { subscript() -> [Element] { get { return Array(self) } } } extension DispatchQueue { public class func isCurrentQueue(queue: DispatchQueue) -> Bool { return queue.label == String(validatingUTF8: __dispatch_queue_get_label(nil))! } }
mit
03ba43fee14c90061a4672bcc3c75ed3
29.775229
215
0.536593
5.017951
false
false
false
false
thelowlypeon/bikeshare-kit
BikeshareKit/BikeshareKit/Common/NSDateExtension.swift
1
569
// // NSDateExtension.swift // BikeshareKit // // Created by Peter Compernolle on 12/19/15. // Copyright © 2015 Out of Something, LLC. All rights reserved. // import Foundation private var APIDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" formatter.timeZone = TimeZone(identifier: "UTC") return formatter }() extension Date { public static func fromAPIString(_ string: String?) -> Date? { return string != nil ? APIDateFormatter.date(from: string!) : nil } }
mit
e6e4dc6e21bd1f3ab79e8970bec617aa
24.818182
73
0.684859
3.617834
false
false
false
false
kcmannem/swift-context
src/example.swift
1
809
@_silgen_name("_ctx_prepare") func prepareContext(using buffer: UnsafeMutableRawPointer, and stack: UnsafeMutableRawPointer, running fn: ()->Void) -> Int @_silgen_name("_ctx_switch") func switchContext(from prev: UnsafeMutableRawPointer, to new: UnsafeMutableRawPointer) var x = 0 var func_reg_buf = UnsafeMutableRawPointer.allocate(bytes: 100, alignedTo: 4) var stack_buf = UnsafeMutableRawPointer.allocate(bytes: 8000, alignedTo: 4) var main_reg_buf = UnsafeMutableRawPointer.allocate(bytes: 100, alignedTo: 4) func hello() { switchContext(from: func_reg_buf, to: main_reg_buf) } for i in 0...100000000 { x = prepareContext(using: func_reg_buf, and: stack_buf, running: hello) switchContext(from: main_reg_buf, to: func_reg_buf) }
mit
278104606feb81bbdab22cddd28850eb
35.772727
78
0.692213
3.889423
false
false
false
false
cyrilwei/Tabby2D
Tabby2D-TiledMap/Tiles/TBTiledScene.swift
1
2512
// // TBTiledScene.swift // Tabby2D // // Created by Cyril Wei on 1/1/16. // Copyright © 2016 Cyril Wei. All rights reserved. // import SpriteKit public class TBTiledScene: TBScene { private var map: TBTiledMap? public var atlasName: String { return map?.atlases.first?.name ?? "" } public func loadMap(map: TBTiledMap) { self.map = map } public override func didMoveToView(view: SKView) { super.didMoveToView(view) anchorPoint = CGPoint(x: 0.5, y: 0.5) addMapNodes() } private func addMapNodes() { guard let map = map else { return } let halfTileWidth = map.tileWidth / 2.0 let halfTileHeight = map.tileHeight / 2.0 let tileSize = CGSize(width: map.tileWidth, height: map.tileHeight) let atlas = SKTextureAtlas(named: atlasName) let atlasTiles = map.atlases.first?.tiles ?? [String]() var currentMapXOffset: Int = 0 var currentMapYOffset: Int = 0 for segmentIndex in map.layout.layout { guard let segment = map.segments.filter({ $0.id == segmentIndex }).first else { continue } for layer in segment.layers { let layerNode = SKNode() layerNode.zPosition = layer.zPosition layerNode.position = CGPoint(x: CGFloat(layer.xOffset - layer.yOffset + currentMapXOffset - currentMapYOffset) * halfTileWidth, y: CGFloat(layer.xOffset + layer.yOffset + currentMapXOffset + currentMapYOffset) * halfTileHeight) self.addChild(layerNode, toLayer: layer.baseWorldLayer) for y in 0..<layer.height { for x in 0..<layer.width { let tileIndex = layer.data[y * layer.width + x] - 1 if tileIndex < 0 { continue } let node = SKSpriteNode(texture: atlas.textureNamed(atlasTiles[tileIndex]), size: tileSize) node.userInteractionEnabled = false node.position = CGPoint(x: CGFloat(x - y) * halfTileWidth, y: CGFloat(x + y) * halfTileHeight) layerNode.addChild(node) } } } currentMapXOffset += map.segmentWidth currentMapYOffset = 0 } } }
mit
f4311fcf1b9c926c2bf83974d06c734d
32.945946
243
0.539227
4.590494
false
false
false
false
krin-san/SwiftCalc
SwiftCalc/Model/Operations.swift
1
1527
// // Operations.swift // SwiftCalc // // Created by Krin-San on 30.10.14. // import Foundation // MARK: - Enumerations public enum KeypadButton: String { case Dot = "." case Calculate = "=" case Backspace = "⌫" case Reset = "C" } public enum SpecialOperator: Int { case OpeningBracket = 1 case ClosingBracket } public enum OperationCode: Int { case Add = 1 case Subtract case Multiply case Divide case Pow case Sqrt case Sin case Cos } public enum Priority: Int { case Low = 0 case Medium case High } // MARK: - Operations public let specialOperators: [SpecialOperator: SCEquationObject] = [ .OpeningBracket: SCEquationObject("("), .ClosingBracket: SCEquationObject(")"), ] public let operationsList: [OperationCode: SCOperation] = [ .Add: SCOperation("+", priority: .Low, operandsCount: 2) { return $0[0] + $0[1] }, .Subtract: SCOperation("-", priority: .Low, operandsCount: 2) { return $0[0] - $0[1] }, .Multiply: SCOperation("*", priority: .Medium, operandsCount: 2) { return $0[0] * $0[1] }, .Divide: SCOperation("/", priority: .Medium, operandsCount: 2) { return $0[0] / $0[1] }, .Pow: SCOperation("^", priority: .High, operandsCount: 2) { return pow($0[0], $0[1]) }, .Sqrt: SCOperation("√", priority: .High, operandsCount: 1) { return sqrt($0[0]) }, .Sin: SCOperation("Sin", priority: .High, operandsCount: 1) { return sin($0[0].rad) }, .Cos: SCOperation("Cos", priority: .High, operandsCount: 1) { return cos($0[0].rad) }, ]
gpl-3.0
a76d2df3ba831592f6190437a4be9289
25.719298
95
0.638214
2.998031
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Kingfisher/Sources/Image/Placeholder.swift
9
3190
// // Placeholder.swift // Kingfisher // // Created by Tieme van Veen on 28/08/2017. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Represents a placeholder type which could be set while loading as well as /// loading finished without getting an image. public protocol Placeholder { /// How the placeholder should be added to a given image view. func add(to imageView: ImageView) /// How the placeholder should be removed from a given image view. func remove(from imageView: ImageView) } /// Default implementation of an image placeholder. The image will be set or /// reset directly for `image` property of the image view. extension Image: Placeholder { /// How the placeholder should be added to a given image view. public func add(to imageView: ImageView) { imageView.image = self } /// How the placeholder should be removed from a given image view. public func remove(from imageView: ImageView) { imageView.image = nil } } /// Default implementation of an arbitrary view as placeholder. The view will be /// added as a subview when adding and be removed from its super view when removing. /// /// To use your customize View type as placeholder, simply let it conforming to /// `Placeholder` by `extension MyView: Placeholder {}`. extension Placeholder where Self: View { /// How the placeholder should be added to a given image view. public func add(to imageView: ImageView) { imageView.addSubview(self) translatesAutoresizingMaskIntoConstraints = false centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true heightAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true widthAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true } /// How the placeholder should be removed from a given image view. public func remove(from imageView: ImageView) { removeFromSuperview() } }
mit
445b2a9387cf3cdd07b12730f0298941
40.973684
84
0.733856
4.596542
false
false
false
false
xwu/swift
test/Parse/self_rebinding.swift
1
4407
// RUN: %target-typecheck-verify-swift class Writer { private var articleWritten = 47 func stop() { let rest: () -> Void = { [weak self] in let articleWritten = self?.articleWritten ?? 0 guard let `self` = self else { return } self.articleWritten = articleWritten } fatalError("I'm running out of time") rest() } func nonStop() { let write: () -> Void = { [weak self] in self?.articleWritten += 1 if let self = self { self.articleWritten += 1 } if let `self` = self { self.articleWritten += 1 } guard let self = self else { return } self.articleWritten += 1 } write() } } struct T { var mutable: Int = 0 func f() { // expected-error @+2 {{keyword 'self' cannot be used as an identifier here}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} let self = self } } class MyCls { func something() {} func test() { // expected-warning @+1 {{initialization of immutable value 'self' was never used}} let `self` = Writer() // Even if `self` is shadowed, something() // this should still refer `MyCls.something`. } } // MARK: fix method called 'self' can be confused with regular 'self' https://bugs.swift.org/browse/SR-4559 func funcThatReturnsSomething(_ any: Any) -> Any { any } struct TypeWithSelfMethod { let property = self // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{20-20=TypeWithSelfMethod.}} // Existing warning expected, not confusable let property2 = self() // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let propertyFromClosure: () = { print(self) // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{15-15=TypeWithSelfMethod.}} }() let propertyFromFunc = funcThatReturnsSomething(self) // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{53-53=TypeWithSelfMethod.}} let propertyFromFunc2 = funcThatReturnsSomething(TypeWithSelfMethod.self) // OK func `self`() { } } /// Test fix_unqualified_access_member_named_self doesn't appear for computed var called `self` /// it can't currently be referenced as a static member -- unlike a method with the same name struct TypeWithSelfComputedVar { let property = self // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let propertyFromClosure: () = { print(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} }() let propertyFromFunc = funcThatReturnsSomething(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} var `self`: () { () } } /// Test fix_unqualified_access_member_named_self doesn't appear appear for property called `self` /// it can't currently be referenced as a static member -- unlike a method with the same name struct TypeWithSelfProperty { let property = self // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let propertyFromClosure: () = { print(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} }() let propertyFromFunc = funcThatReturnsSomething(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}} let `self`: () = () }
apache-2.0
853da4002ea01afbcc7a05557ca957f5
36.347458
261
0.647379
4.533951
false
false
false
false
ahoppen/swift
stdlib/public/core/StringGuts.swift
1
13977
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // // StringGuts is a parameterization over String's representations. It provides // functionality and guidance for efficiently working with Strings. // @frozen public // SPI(corelibs-foundation) struct _StringGuts: @unchecked Sendable { @usableFromInline internal var _object: _StringObject @inlinable @inline(__always) internal init(_ object: _StringObject) { self._object = object _invariantCheck() } // Empty string @inlinable @inline(__always) init() { self.init(_StringObject(empty: ())) } } // Raw extension _StringGuts { @inlinable @inline(__always) internal var rawBits: _StringObject.RawBitPattern { return _object.rawBits } } // Creation extension _StringGuts { @inlinable @inline(__always) internal init(_ smol: _SmallString) { self.init(_StringObject(smol)) } @inlinable @inline(__always) internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { self.init(_StringObject(immortal: bufPtr, isASCII: isASCII)) } @inline(__always) internal init(_ storage: __StringStorage) { self.init(_StringObject(storage)) } internal init(_ storage: __SharedStringStorage) { self.init(_StringObject(storage)) } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { self.init(_StringObject( cocoa: cocoa, providesFastUTF8: providesFastUTF8, isASCII: isASCII, length: length)) } } // Queries extension _StringGuts { // The number of code units @inlinable @inline(__always) internal var count: Int { return _object.count } @inlinable @inline(__always) internal var isEmpty: Bool { return count == 0 } @inlinable @inline(__always) internal var isSmall: Bool { return _object.isSmall } @inline(__always) internal var isSmallASCII: Bool { return _object.isSmall && _object.smallIsASCII } @inlinable @inline(__always) internal var asSmall: _SmallString { return _SmallString(_object) } @inlinable @inline(__always) internal var isASCII: Bool { return _object.isASCII } @inlinable @inline(__always) internal var isFastASCII: Bool { return isFastUTF8 && _object.isASCII } @inline(__always) internal var isNFC: Bool { return _object.isNFC } @inline(__always) internal var isNFCFastUTF8: Bool { // TODO(String micro-performance): Consider a dedicated bit for this return _object.isNFC && isFastUTF8 } internal var hasNativeStorage: Bool { return _object.hasNativeStorage } internal var hasSharedStorage: Bool { return _object.hasSharedStorage } // Whether this string has breadcrumbs internal var hasBreadcrumbs: Bool { return hasSharedStorage || (hasNativeStorage && _object.nativeStorage.hasBreadcrumbs) } } // extension _StringGuts { // Whether we can provide fast access to contiguous UTF-8 code units @_transparent @inlinable internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) } // A String which does not provide fast access to contiguous UTF-8 code units @inlinable @inline(__always) internal var isForeign: Bool { return _slowPath(_object.isForeign) } @inlinable @inline(__always) internal func withFastUTF8<R>( _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { _internalInvariant(isFastUTF8) if self.isSmall { return try _SmallString(_object).withUTF8(f) } defer { _fixLifetime(self) } return try f(_object.fastUTF8) } @inlinable @inline(__always) internal func withFastUTF8<R>( range: Range<Int>, _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { wholeUTF8 in return try f(UnsafeBufferPointer(rebasing: wholeUTF8[range])) } } @inlinable @inline(__always) internal func withFastCChar<R>( _ f: (UnsafeBufferPointer<CChar>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { utf8 in return try utf8.withMemoryRebound(to: CChar.self, f) } } } // Internal invariants extension _StringGuts { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) || arch(arm64_32) || arch(wasm32) _internalInvariant(MemoryLayout<String>.size == 12, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #else _internalInvariant(MemoryLayout<String>.size == 16, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #endif } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { _object._dump() } } // C String interop extension _StringGuts { @inlinable @inline(__always) // fast-path: already C-string compatible internal func withCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { if _slowPath(!_object.isFastZeroTerminated) { return try _slowWithCString(body) } return try self.withFastCChar { return try body($0.baseAddress._unsafelyUnwrappedUnchecked) } } @inline(never) // slow-path @usableFromInline internal func _slowWithCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { _internalInvariant(!_object.isFastZeroTerminated) return try String(self).utf8CString.withUnsafeBufferPointer { let ptr = $0.baseAddress._unsafelyUnwrappedUnchecked return try body(ptr) } } } extension _StringGuts { // Copy UTF-8 contents. Returns number written or nil if not enough space. // Contents of the buffer are unspecified if nil is returned. @inlinable internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? { let ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked if _fastPath(self.isFastUTF8) { return self.withFastUTF8 { utf8 in guard utf8.count <= mbp.count else { return nil } let utf8Start = utf8.baseAddress._unsafelyUnwrappedUnchecked ptr.initialize(from: utf8Start, count: utf8.count) return utf8.count } } return _foreignCopyUTF8(into: mbp) } @_effects(releasenone) @usableFromInline @inline(never) // slow-path internal func _foreignCopyUTF8( into mbp: UnsafeMutableBufferPointer<UInt8> ) -> Int? { #if _runtime(_ObjC) // Currently, foreign means NSString if let res = _cocoaStringCopyUTF8(_object.cocoaObject, into: UnsafeMutableRawBufferPointer(start: mbp.baseAddress, count: mbp.count)) { return res } // If the NSString contains invalid UTF8 (e.g. unpaired surrogates), we // can get nil from cocoaStringCopyUTF8 in situations where a character by // character loop would get something more useful like repaired contents var ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked var numWritten = 0 for cu in String(self).utf8 { guard numWritten < mbp.count else { return nil } ptr.initialize(to: cu) ptr += 1 numWritten += 1 } return numWritten #else fatalError("No foreign strings on Linux in this version of Swift") #endif } @inline(__always) internal var utf8Count: Int { if _fastPath(self.isFastUTF8) { return count } return String(self).utf8.count } } // Index extension _StringGuts { @usableFromInline internal typealias Index = String.Index @inlinable @inline(__always) internal var startIndex: String.Index { // The start index is always `Character` aligned. Index(_encodedOffset: 0)._characterAligned._encodingIndependent } @inlinable @inline(__always) internal var endIndex: String.Index { // The end index is always `Character` aligned. markEncoding(Index(_encodedOffset: self.count)._characterAligned) } } // Encoding extension _StringGuts { /// Returns whether this string has a UTF-8 storage representation. /// If this returns false, then the string is encoded in UTF-16. /// /// This always returns a value corresponding to the string's actual encoding. @_alwaysEmitIntoClient @inline(__always) internal var isUTF8: Bool { _object.isUTF8 } @_alwaysEmitIntoClient // Swift 5.7 @inline(__always) internal func markEncoding(_ i: String.Index) -> String.Index { isUTF8 ? i._knownUTF8 : i._knownUTF16 } /// Returns true if the encoding of the given index isn't known to be in /// conflict with this string's encoding. /// /// If the index was created by code that was built on a stdlib below 5.7, /// then this check may incorrectly return true on a mismatching index, but it /// is guaranteed to never incorrectly return false. If all loaded binaries /// were built in 5.7+, then this method is guaranteed to always return the /// correct value. @_alwaysEmitIntoClient @inline(__always) internal func hasMatchingEncoding(_ i: String.Index) -> Bool { i._hasMatchingEncoding(isUTF8: isUTF8) } /// Return an index whose encoding can be assumed to match that of `self`, /// trapping if `i` has an incompatible encoding. /// /// If `i` is UTF-8 encoded, but `self` is an UTF-16 string, then trap. /// /// If `i` is UTF-16 encoded, but `self` is an UTF-8 string, then transcode /// `i`'s offset to UTF-8 and return the resulting index. This allows the use /// of indices from a bridged Cocoa string after the string has been converted /// to a native Swift string. (Such indices are technically still considered /// invalid, but we allow this specific case to keep compatibility with /// existing code that assumes otherwise.) /// /// Detecting an encoding mismatch isn't always possible -- older binaries did /// not set the flags that this method relies on. However, false positives /// cannot happen: if this method detects a mismatch, then it is guaranteed to /// be a real one. @_alwaysEmitIntoClient @inline(__always) internal func ensureMatchingEncoding(_ i: Index) -> Index { if _fastPath(hasMatchingEncoding(i)) { return i } return _slowEnsureMatchingEncoding(i) } @_alwaysEmitIntoClient @inline(never) @_effects(releasenone) internal func _slowEnsureMatchingEncoding(_ i: Index) -> Index { // Attempt to recover from mismatched encodings between a string and its // index. if isUTF8 { // Attempt to use an UTF-16 index on a UTF-8 string. // // This can happen if `self` was originally verbatim-bridged, and someone // mistakenly attempts to keep using an old index after a mutation. This // is technically an error, but trapping here would trigger a lot of // broken code that previously happened to work "fine" on e.g. ASCII // strings. Instead, attempt to convert the offset to UTF-8 code units by // transcoding the string. This can be slow, but it often results in a // usable index, even if non-ASCII characters are present. (UTF-16 // breadcrumbs help reduce the severity of the slowdown.) // FIXME: Consider emitting a runtime warning here. // FIXME: Consider performing a linked-on-or-after check & trapping if the // client executable was built on some particular future Swift release. let utf16 = String.UTF16View(self) var r = utf16.index(utf16.startIndex, offsetBy: i._encodedOffset) if i.transcodedOffset != 0 { r = r.encoded(offsetBy: i.transcodedOffset) } else { // Preserve alignment bits if possible. r = r._copyingAlignment(from: i) } return r._knownUTF8 } // Attempt to use an UTF-8 index on a UTF-16 string. This is rarer, but it // can still happen when e.g. people apply an index they got from // `AttributedString` on the original (bridged) string that they constructed // it from. let utf8 = String.UTF8View(self) var r = utf8.index(utf8.startIndex, offsetBy: i._encodedOffset) if i.transcodedOffset != 0 { r = r.encoded(offsetBy: i.transcodedOffset) } else { // Preserve alignment bits if possible. r = r._copyingAlignment(from: i) } return r._knownUTF16 } } // Old SPI(corelibs-foundation) extension _StringGuts { @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousASCII: Bool { return !isSmall && isFastUTF8 && isASCII } @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousUTF16: Bool { return false } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startASCII: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!) } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { fatalError("Not contiguous UTF-16") } } @available(*, deprecated) public // SPI(corelibs-foundation) func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let bytesToCopy = UTF8._nullCodeUnitOffset(in: s) + 1 // +1 for the terminating NUL let result = [CChar](unsafeUninitializedCapacity: bytesToCopy) { buf, initedCount in buf.baseAddress!.assign(from: s, count: bytesToCopy) initedCount = bytesToCopy } return result }
apache-2.0
71c2e44e01a369cfb70945cfb437637d
30.765909
86
0.68069
4.223935
false
false
false
false
asm-products/line-ninja-ios
proof_of_concept/Alamofire/Example/MasterViewController.swift
22
2903
// MasterViewController.swift // // Copyright (c) 2014 Alamofire (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 UIKit import Alamofire class MasterViewController: UITableViewController { @IBOutlet weak var titleImageView: UIImageView! var detailViewController: DetailViewController? = nil var objects = NSMutableArray() override func awakeFromNib() { super.awakeFromNib() self.navigationItem.titleView = self.titleImageView } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers.last?.topViewController as? DetailViewController } } // MARK: - UIStoryboardSegue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let detailViewController = segue.destinationViewController.topViewController as? DetailViewController { func requestForSegue(segue: UIStoryboardSegue) -> Request? { switch segue.identifier as String! { case "GET": return Alamofire.request(.GET, "http://httpbin.org/get") case "POST": return Alamofire.request(.POST, "http://httpbin.org/post") case "PUT": return Alamofire.request(.PUT, "http://httpbin.org/put") case "DELETE": return Alamofire.request(.DELETE, "http://httpbin.org/delete") default: return nil } } if let request = requestForSegue(segue) { detailViewController.request = request } } } }
agpl-3.0
da98b9aa373436072d8962ae08aa32e9
37.706667
114
0.657251
5.365989
false
false
false
false
Daniseijo/AplicacionPFC
AplicacionPFC/ViewController.swift
1
1001
// // ViewController.swift // AplicacionPFC // // Created by Daniel Seijo Sánchez on 26/9/15. // Copyright © 2015 Daniel Seijo Sánchez. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var barButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent // Do any additional setup after loading the view, typically from a nib. if self.revealViewController() != nil { barButton.target = self.revealViewController() barButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
2fd07373d995d3e104a1ea5730391e30
28.352941
94
0.687375
5.170984
false
false
false
false
dabaosod011/Practise
iOS/Cassini/Cassini/DemoURL.swift
1
923
// // DemoURL.swift // Cassini // // Created by Hai Xiao on 04/12/2017. // Copyright © 2017 Hai Xiao. All rights reserved. // import Foundation struct DemoURL { static let stanford = URL(string: "http://museum.stanford.edu/view/images/Thinker_000.jpg") static var NASA: Dictionary<String,URL> = { let NASAURLStrings = [ "Cassini" : "http://www.jpl.nasa.gov/images/cassini/20090202/pia03883-full.jpg", "Earth" : "http://www.nasa.gov/sites/default/files/wave_earth_mosaic_3.jpg", "Saturn" : "http://www.nasa.gov/sites/default/files/saturn_collage.jpg" ] var urls = Dictionary<String,URL>() for (key, value) in NASAURLStrings { urls[key] = URL(string: value) } return urls }() static let baidu = URL(string: "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png") }
apache-2.0
6adbf3b633915a474f79f531dec1b26f
31.928571
126
0.626898
3.125424
false
false
false
false
TalntsApp/media-picker-ios
MediaPicker/List/MediaList.swift
1
10637
import UIKit import AVFoundation import Photos import Runes import Argo import Signals /** MediaList ---- List view controller of media from gallery */ public class MediaList: UICollectionViewController, PHPhotoLibraryChangeObserver { static var authorizationStatus: PHAuthorizationStatus { return PHPhotoLibrary.authorizationStatus() } static func requestAuthorization(closure: Bool -> Void) { switch self.authorizationStatus { case .Authorized: async(.Main) { () -> Void in closure(true) } default: PHPhotoLibrary.requestAuthorization({ status -> Void in async(.Main) { closure(status == .Authorized) } }) } } var assets: [AssetsSection] = [] { didSet { if oldValue != assets { if let collectionView = self.collectionView { asyncWith(collectionView, priority: .Main) { [weak self] in collectionView.reloadData() if let asset = self?.assets.first?.assets.first where asset != oldValue.first?.assets.first { let indexPath = NSIndexPath(forItem: 0, inSection: 0) self?.selectionHandle(indexPath, asset) collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .CenteredVertically) } } } } } } private(set) var photosOnly: Bool = false /** Designated initializer - parameter photosOnly: Set to `true` if you want just photos in the list, without videos. Default: `false`. */ public init(photosOnly: Bool = false) { let bundle = NSBundle(forClass: MediaList.self) super.init(nibName: "MediaList", bundle: bundle) self.photosOnly = photosOnly } /// Just calls super's implementation override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } /// Just calls super's implementation required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Setups list cells and reusable views override public func viewDidLoad() { super.viewDidLoad() setupAssetsUpdate() setupLayout() self.collectionView?.registerCell(AssetsCell) self.collectionView?.registerReusableView(MediaListTitleView) self.edgesForExtendedLayout = UIRectEdge.None } private func setupLayout() { if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout, let collectionWidth = self.collectionView?.frame.width { let width = min(collectionWidth, self.view.frame.width, self.view.frame.height) Animate(duration: 30, options: UIViewAnimationOptions.CurveEaseOut) .animation { let itemsNumber: CGFloat = 4 let interNumber: CGFloat = max(itemsNumber - 1, 1.0) let distance:CGFloat = 1.0/interNumber let itemWidth = min(150, floor((width - itemsNumber * distance)/itemsNumber)) layout.itemSize = CGSize(width: itemWidth, height: itemWidth) layout.minimumInteritemSpacing = distance layout.minimumLineSpacing = 2 * distance layout.headerReferenceSize = CGSize(width: width, height: 44) } .fire() } } /// Updates cell size override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let collectionView = self.collectionView, let layout = self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout { let itemHeight = layout.itemSize.height var inset = collectionView.contentInset inset.bottom = collectionView.bounds.height - itemHeight if collectionView.contentInset != inset { collectionView.contentInset = inset } if collectionView.numberOfSections() > 0 && collectionView.numberOfItemsInSection(0) > 0 && collectionView.indexPathsForSelectedItems()?.first == nil { collectionView.selectItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), animated: false, scrollPosition: .None) } } } /// Updates list upon attachment to superview override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil) { [weak self] _ in if let `self` = self, let collectionView = self.collectionView { collectionView.synced { self.setupLayout() collectionView.reloadData() } } } } private var assetsSignal: Signal<[AssetsSection]>? private func setupAssetsUpdate() { MediaList.requestAuthorization { success in if success { self.assetsSignal = getAssets(self.photosOnly).reduce([]) { (acc, val) in return acc + [val] } self.assetsSignal?.listen(self) {[weak self] asset -> Void in self?.assets = asset } } } } /// Updates list on gallery change public func photoLibraryDidChange(changeInstance: PHChange) { self.setupAssetsUpdate() } /// - Returns: The number of folders in gallery override public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return self.assets.count } /// - Returns: The number of objects in folder override public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.assets[section].assets.count } /// - Returns: `MediaListTitleView` for folder title override public func collectionView( collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath ) -> UICollectionReusableView { let titleView = collectionView.dequeueReusableSupplementaryViewOfKind( kind, withReuseIdentifier: MediaListTitleView.defaultIdentifier, forIndexPath: indexPath ) as! MediaListTitleView return titleView } /// Setups title in `MediaListTitleView` override public func collectionView( collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, atIndexPath indexPath: NSIndexPath ) { let titleView = view as! MediaListTitleView let name = self.assets[indexPath.section].name titleView.titleLabel.text = name } /// - Returns: Cell for media item override public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(AssetsCell.defaultIdentifier, forIndexPath: indexPath) as! AssetsCell return cell } /// Setups cell info override public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let assetsCell = cell as! AssetsCell let asset = self.assets[indexPath.section].assets[indexPath.item] assetsCell.setupPreview(asset) } /// Handles media item selection override public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let asset = self.assets[indexPath.section].assets[indexPath.item] collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Top, animated: false) selectionHandle(indexPath, asset) } /// - Returns: `true` override public func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } let selectionSignal: Signal<(NSIndexPath, PHAsset)> = Signal() private func selectionHandle(indexPath: NSIndexPath, _ asset: PHAsset) { async(.Main) { [weak self] in self?.collectionView?.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .CenteredVertically) if let selectionSignal = self?.selectionSignal { selectionSignal.fire(indexPath, asset) } } } let scrollSignal: Signal<CGFloat> = Signal() /// Reacts on list scrolling and emit value of `scrollSignal` override public func scrollViewDidScroll(scrollView: UIScrollView) { asyncWith(scrollView, priority: .Main) { [weak self] in let offset = -scrollView.contentOffset.y self?.scrollSignal.fire(offset) } } } // UICollectionView extensions extension UICollectionView { func registerCell<CellType: RegisterableCollectionViewCell>( cellType: CellType.Type = CellType.self, identifier: String = CellType.self.defaultIdentifier ) -> CellType.Type { cellType.self.registerAtCollectionView(self, identifier: identifier) return cellType } func registerReusableView<ViewType: RegisterableReusableView>( viewType: ViewType.Type = ViewType.self, kind: ReusableViewKind = .Header, identifier: String = ViewType.self.defaultIdentifier ) -> ViewType.Type { viewType.self.registerAtCollectionView(self, kind: kind, identifier: identifier) return viewType } }
mit
64f48638f26f06b821c1e28198ae9e49
36.322807
162
0.610981
5.922606
false
false
false
false
hetefe/HTF_sina_swift
sina_htf/sina_htf/Classes/Module/Main/VisitorLoginView/VisitorLoginView.swift
1
7440
// // VisitorLoginView.swift // sina_htf // // Created by 赫腾飞 on 15/12/13. // Copyright © 2015年 hetefe. All rights reserved. // import UIKit //MARK:- 定义协议 protocol VisitorLoginViewDelegate: NSObjectProtocol { //用户将要登录 func userWillLogin() //用户将要注册 func userWillRegister() } class VisitorLoginView: UIView { weak var visitorViewDelegate : VisitorLoginViewDelegate? func setupInfo(tipText:String, imageName: String?){ tipLable.text = tipText if let name = imageName { circleView.image = UIImage(named: name) largeIcon.hidden = true //将Circle移动到视图的最顶层 bringSubviewToFront(circleView) }else{ //就是首页 //开始动画 startAnimation() } } //MARK:- 设置方可师徒中的房子周边的动画效果 private func startAnimation(){ let anim = CABasicAnimation(keyPath: "transform.rotation") anim.repeatCount = MAXFLOAT anim.duration = 10.0 anim.toValue = 2 * M_PI //当动画完毕后或者页面失去活跃状态 动画不移除 anim.removedOnCompletion = false circleView.layer.addAnimation(anim, forKey: nil) } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:- 添加视图中的子控件 并进行布局操作 private func setupUI(){ addSubview(circleView) addSubview(backView) addSubview(largeIcon) addSubview(tipLable) addSubview(loginBtn) addSubview(registerBtn) //使用自动布局 for subView in subviews { subView.translatesAutoresizingMaskIntoConstraints = false } addConstraint(NSLayoutConstraint(item: largeIcon, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: largeIcon, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: -60)) //添加圆圈的约束 addConstraint(NSLayoutConstraint(item: circleView, attribute: .CenterX, relatedBy: .Equal, toItem: largeIcon, attribute: .CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: circleView, attribute: .CenterY, relatedBy: .Equal, toItem: largeIcon, attribute: .CenterY, multiplier: 1, constant: 0)) //Lable addConstraint(NSLayoutConstraint(item: tipLable, attribute: .CenterX, relatedBy: .Equal, toItem: circleView, attribute: .CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: tipLable, attribute: .Top, relatedBy: .Equal, toItem: circleView, attribute: .Bottom, multiplier: 1, constant: 16)) //If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute. addConstraint(NSLayoutConstraint(item: tipLable, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 240)) addConstraint(NSLayoutConstraint(item: tipLable, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 60)) //按钮的约束 addConstraint(NSLayoutConstraint(item: loginBtn, attribute: .Left, relatedBy: .Equal, toItem: tipLable, attribute: .Left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: .Top, relatedBy: .Equal, toItem: tipLable, attribute: .Bottom, multiplier: 1, constant: 20)) //If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute. addConstraint(NSLayoutConstraint(item: loginBtn, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 35)) //注册 addConstraint(NSLayoutConstraint(item: registerBtn, attribute: .Right, relatedBy: .Equal, toItem: tipLable, attribute: .Right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: registerBtn, attribute: .Top, relatedBy: .Equal, toItem: tipLable, attribute: .Bottom, multiplier: 1, constant: 20)) //If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute. addConstraint(NSLayoutConstraint(item: registerBtn, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100)) addConstraint(NSLayoutConstraint(item: registerBtn, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 35)) //设置背景视图的约束 可视化的布局语言 //OC 中可选项 一般使用 按位 或枚举选项 swift中直接指定数组 //metrics:约束数值字典 [String: 数值], addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[backView]-0-|", options: [], metrics: nil, views: ["backView": backView])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[backView]-(-35)-[regBtn]", options: [], metrics: nil, views: ["backView": backView,"regBtn":registerBtn])) //设置视图的背景颜色 //UIColor(white: <#T##CGFloat#>, alpha: <#T##CGFloat#>) 设置灰度颜色 backgroundColor = UIColor(white: 0.93, alpha: 1) //添加点击事件 registerBtn.addTarget(self, action: "registerBtnDidClick", forControlEvents: .TouchUpInside) loginBtn.addTarget(self, action: "loginBtnDidClick", forControlEvents: .TouchUpInside) } /** 按钮的监听事件 */ //MARK:- 按钮的监听事件??? @objc private func registerBtnDidClick(){ visitorViewDelegate?.userWillRegister() } @objc private func loginBtnDidClick(){ visitorViewDelegate?.userWillLogin() } //MARK:- 懒加载所有的子视图 private lazy var backView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) private lazy var largeIcon : UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) private lazy var circleView : UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) //适用自定义Lable private lazy var tipLable: UILabel = UILabel(title: "关注一些人,回这里看看有什么惊喜,关注一些人,回这里看看有什么惊喜", color: UIColor.darkGrayColor(), fontSize: 14) private lazy var registerBtn: UIButton = UIButton(backImageNameN: "common_button_white_disable", backImageNameH: nil, color: themeColor, title: "注册",fontOfSize: 15) private lazy var loginBtn: UIButton = UIButton(backImageNameN: "common_button_white_disable", backImageNameH: nil, color: themeColor, title: "登录",fontOfSize: 15) }
mit
12d48083771a7c1f73c19dfcdc13da8d
44.379085
184
0.67478
4.579815
false
false
false
false
alexruperez/AVPlayerItemHomeOutput
Core/HomeManager.swift
1
5034
// // HomeManager.swift // AVPlayerItemHomeOutput // // Created by Alex Rupérez on 14/5/17. // Copyright © 2017 alexruperez. All rights reserved. // import HomeKit class HomeManager { static let shared = HomeManager() private let manager = HMHomeManager() private var primaryHome: HMHome? { return manager.primaryHome } var hasPrimaryHome: Bool { return primaryHome != nil } private var lightbulbServices: [HMService]? { return primaryHome?.servicesWithTypes([HMServiceTypeLightbulb]) } var updating = [HMCharacteristic: Bool]() func send(_ pixelBuffer: CVPixelBuffer, colors: UInt) { guard hasPrimaryHome && colors > 0 else { return } var samples = [[UInt8]]() let image = CIImage(cvPixelBuffer: pixelBuffer) let extent = image.extent for i in 0..<colors { for j in 0..<colors { let inputExtent = CIVector(x: (extent.size.width / CGFloat(colors)) * CGFloat(i), y: (extent.size.height / CGFloat(colors)) * CGFloat(j), z: extent.size.width / CGFloat(colors), w: extent.size.height / CGFloat(colors)) guard let outputImage = CIFilter(name: "CIAreaAverage", withInputParameters: [kCIInputImageKey: image, kCIInputExtentKey: inputExtent])?.outputImage else { break } var bitmap = [UInt8](repeating: 0, count: 4) CIContext().render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: kCIFormatRGBA8, colorSpace: CGColorSpaceCreateDeviceRGB()) samples.append(bitmap) } } send(diff(samples, number: Int(colors))) } func send(_ colors: [UIColor]) { guard let lightbulbServices = lightbulbServices, colors.count > 0 else { return } var colorIndex = 0 for lightbulbService in lightbulbServices { var HSBA = [CGFloat](repeating: 0, count: 4) colors[colorIndex % colors.count].getHue(&HSBA[0], saturation: &HSBA[1], brightness: &HSBA[2], alpha: &HSBA[3]) for characteristic in lightbulbService.characteristics { guard updating[characteristic] == nil || updating[characteristic] == false else { break } switch characteristic.characteristicType { case HMCharacteristicTypePowerState: update(characteristic, floatValue: 1) case HMCharacteristicTypeBrightness: update(characteristic, floatValue: Float(HSBA[2])) case HMCharacteristicTypeSaturation: update(characteristic, floatValue: Float(HSBA[1])) case HMCharacteristicTypeHue: update(characteristic, floatValue: Float(HSBA[0])) default: break } } colorIndex += 1 } } } extension HomeManager { func update(_ characteristic: HMCharacteristic, floatValue: Float) { let value = NSNumber(value: Int(floatValue * (characteristic.metadata?.maximumValue?.floatValue ?? (floatValue > 1 ? 100 : 1)))) guard characteristic.value as? Float != value.floatValue else { return } updating[characteristic] = true characteristic.writeValue(value, completionHandler: { error in self.unlock(characteristic, error) }) } func unlock(_ characteristic: HMCharacteristic, _ error: Error?) { if error != nil { let deadline: DispatchTime = .now() + .seconds(1) DispatchQueue.global().asyncAfter(deadline: deadline, execute: { [weak self] in self?.updating[characteristic] = false }) } else { self.updating[characteristic] = false } } func top(_ colors: [UIColor: CGFloat], number: Int) -> [UIColor] { return colors.sorted(by: { $0.1 > $1.1 }).prefix(number).map({ $0.0 }) } func diff(_ colors: [[UInt8]], number: Int) -> [UIColor] { var diffColors = [UIColor: CGFloat]() for components in colors { for diffComponents in colors { guard components != diffComponents || number == 1 else { break } let diffRed = abs(CGFloat(components[0]) - CGFloat(diffComponents[0])) let diffGreen = abs(CGFloat(components[1]) - CGFloat(diffComponents[1])) let diffBlue = abs(CGFloat(components[2]) - CGFloat(diffComponents[2])) let color = UIColor(red: CGFloat(components[0]) / 255, green: CGFloat(components[1]) / 255, blue: CGFloat(components[2]) / 255, alpha: CGFloat(components[3]) / 255) diffColors[color] = (diffColors[color] ?? 0) + diffRed + diffGreen + diffBlue } } return top(diffColors, number: number) } }
mit
b6c90ef10487bd793de06feda4e5d286
39.910569
234
0.584857
4.587056
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/fbb/FBEdgeOverlap.swift
3
3784
// // FBEdgeOverlap.swift // Swift VectorBoolean for iOS // // Based on part of FBContourOverlap - Created by Andrew Finnell on 11/7/12. // Copyright (c) 2012 Fortunate Bear, LLC. All rights reserved. // // Created by Leslie Titze on 2015-07-02. // Copyright (c) 2015 Leslie Titze. All rights reserved. // import UIKit let FBOverlapThreshold = isRunningOn64BitDevice ? 1e-2 : 1e-1 class FBEdgeOverlap { var edge1 : FBBezierCurve var edge2 : FBBezierCurve fileprivate var _range : FBBezierIntersectRange var range : FBBezierIntersectRange { return _range } init(range: FBBezierIntersectRange, edge1: FBBezierCurve, edge2: FBBezierCurve) { _range = range self.edge1 = edge1 self.edge2 = edge2 } //- (BOOL) fitsBefore:(FBEdgeOverlap *)nextOverlap func fitsBefore(_ nextOverlap: FBEdgeOverlap) -> Bool { if FBAreValuesCloseWithOptions(range.parameterRange1.maximum, value2: 1.0, threshold: FBOverlapThreshold) { // nextOverlap should start at 0 of the next edge let nextEdge = edge1.next return nextOverlap.edge1 == nextEdge && FBAreValuesCloseWithOptions(nextOverlap.range.parameterRange1.minimum, value2: 0.0, threshold: FBOverlapThreshold) } // nextOverlap should start at about maximum on the same edge return nextOverlap.edge1 == edge1 && FBAreValuesCloseWithOptions(nextOverlap.range.parameterRange1.minimum, value2: range.parameterRange1.maximum, threshold: FBOverlapThreshold) } //- (BOOL) fitsAfter:(FBEdgeOverlap *)previousOverlap func fitsAfter(_ previousOverlap: FBEdgeOverlap) -> Bool { if FBAreValuesCloseWithOptions(range.parameterRange1.minimum, value2: 0.0, threshold: FBOverlapThreshold) { // previousOverlap should end at 1 of the previous edge let previousEdge = edge1.previous return previousOverlap.edge1 == previousEdge && FBAreValuesCloseWithOptions(previousOverlap.range.parameterRange1.maximum, value2: 1.0, threshold: FBOverlapThreshold) } // previousOverlap should end at about the minimum on the same edge return previousOverlap.edge1 == edge1 && FBAreValuesCloseWithOptions(previousOverlap.range.parameterRange1.maximum, value2: range.parameterRange1.minimum, threshold: FBOverlapThreshold) } //- (void) addMiddleCrossing func addMiddleCrossing() { let intersection = _range.middleIntersection let ourCrossing = FBEdgeCrossing(intersection: intersection) let theirCrossing = FBEdgeCrossing(intersection: intersection) ourCrossing.counterpart = theirCrossing theirCrossing.counterpart = ourCrossing ourCrossing.fromCrossingOverlap = true theirCrossing.fromCrossingOverlap = true edge1.addCrossing(ourCrossing) edge2.addCrossing(theirCrossing) } //- (BOOL) doesContainParameter:(CGFloat)parameter onEdge:(FBBezierCurve *)edge startExtends:(BOOL)extendsBeforeStart endExtends:(BOOL)extendsAfterEnd func doesContainParameter(_ parameter: Double, onEdge edge:FBBezierCurve, startExtends extendsBeforeStart: Bool, endExtends extendsAfterEnd: Bool) -> Bool { // By the time this is called, we know the crossing is on one of our edges. if extendsBeforeStart && extendsAfterEnd { // The crossing is on the edge somewhere, // and the overlap extends past this edge in both directions, // so it's safe to say the crossing is contained return true } var parameterRange : FBRange if edge == edge1 { parameterRange = _range.parameterRange1 } else { parameterRange = _range.parameterRange2 } let inLeftSide = extendsBeforeStart ? parameter >= 0.0 : parameter > parameterRange.minimum let inRightSide = extendsAfterEnd ? parameter <= 1.0 : parameter < parameterRange.maximum return inLeftSide && inRightSide } }
mit
6deb5993bcb02d75364af618f12eb6de
38.010309
189
0.744979
4.090811
false
false
false
false
ccortessanchez/Flo
Flo/Flo/GraphView.swift
1
5772
// // GraphView.swift // Flo // // Created by Carlos Cortés Sánchez on 26/09/2017. // Copyright © 2017 Carlos Cortés Sánchez. All rights reserved. // import UIKit @IBDesignable class GraphView: UIView { //start and end colors for gradient @IBInspectable var startColor: UIColor = .red @IBInspectable var endColor: UIColor = .green //weekly sample data var graphPoints = [4, 2, 6, 4, 5, 8, 3] private struct Constants { static let cornerRadiusSize = CGSize(width: 8.0, height: 8.0) static let margin: CGFloat = 20.0 static let topBorder: CGFloat = 60.0 static let bottomBorder: CGFloat = 50.0 static let colorAlpha: CGFloat = 0.3 static let circleDiameter: CGFloat = 5.0 } override func draw(_ rect: CGRect) { let width = rect.width let height = rect.height let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: Constants.cornerRadiusSize) path.addClip() //obtain current context //CG drawing methods need a context in order to draw let context = UIGraphicsGetCurrentContext()! let colors = [startColor.cgColor, endColor.cgColor] //all contexts have a color space let colorSpace = CGColorSpaceCreateDeviceRGB() //color stops describe where the colors in the gradient change over let colorLocations: [CGFloat] = [0.0, 1.0] //create the actual gradient, defining the color space, colors and color stops let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocations) //draw the gradient let startPoint = CGPoint.zero let endPoint = CGPoint(x:0, y: bounds.height) context.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: []) //calculate the x point let margin = Constants.margin let graphWidth = width - margin * 2 - 4 let columnXPoint = { (column: Int) -> CGFloat in //calculate the gap between points let spacing = graphWidth / CGFloat(self.graphPoints.count - 1) return CGFloat(column) * spacing + margin + 2 } //calculate the y point let topBorder = Constants.topBorder let bottomBorder = Constants.bottomBorder let graphHeight = height - topBorder - bottomBorder let maxValue = graphPoints.max()! let columnYPoint = { (graphPoint: Int) -> CGFloat in let y = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight return graphHeight + topBorder - y //flip the graph } //draw the line graph UIColor.white.setFill() UIColor.white.setStroke() //setup the points line let graphPath = UIBezierPath() //go to start of line graphPath.move(to: CGPoint(x: columnXPoint(0), y: columnYPoint(graphPoints[0]))) //add points for each item in the graphPoints array //at the correct (x,y) for the point for i in 1..<graphPoints.count { let nextPoint = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i])) graphPath.addLine(to: nextPoint) } //Create the clipping path for the graph gradient //save state of the context context.saveGState() //make a copy of the path let clippingPath = graphPath.copy() as! UIBezierPath //add lines to the copied path to complete the clip area clippingPath.addLine(to: CGPoint(x: columnXPoint(graphPoints.count - 1), y: height)) clippingPath.addLine(to: CGPoint(x: columnXPoint(0), y: height)) clippingPath.close() //add the clipping path to the context clippingPath.addClip() //check clipping path let highestYPoint = columnYPoint(maxValue) let graphStartPoint = CGPoint(x: margin, y: highestYPoint) let graphEndPoint = CGPoint(x: margin, y: bounds.height) context.drawLinearGradient(gradient!, start: graphStartPoint, end: graphEndPoint, options: []) context.restoreGState() //draw the line on top of the clipped gradient graphPath.lineWidth = 2.0 graphPath.stroke() //Draw the circles on top of the graph stroke for i in 0..<graphPoints.count { var point = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i])) point.x -= Constants.circleDiameter / 2 point.y -= Constants.circleDiameter / 2 let circle = UIBezierPath(ovalIn: CGRect(origin: point, size: CGSize(width: Constants.circleDiameter, height: Constants.circleDiameter))) circle.fill() } //Draw horizontal graph lines on top of everything let linePath = UIBezierPath() //top line linePath.move(to: CGPoint(x: margin, y: topBorder)) linePath.addLine(to: CGPoint(x: width - margin, y: topBorder)) //center line linePath.move(to: CGPoint(x: margin, y: graphHeight/2 + topBorder)) linePath.addLine(to: CGPoint(x: width - margin, y: graphHeight/2 + topBorder)) //bottom line linePath.move(to: CGPoint(x: margin, y: height - bottomBorder)) linePath.addLine(to: CGPoint(x: width - margin, y: height - bottomBorder)) let color = UIColor(white: 1.0, alpha: Constants.colorAlpha) color.setStroke() linePath.lineWidth = 1.0 linePath.stroke() } }
mit
5d32157b99591ee7f534fb25b8be590a
36.940789
149
0.609329
4.777962
false
false
false
false
danielcwj16/ConnectedAlarmApp
Pods/JTAppleCalendar/Sources/GlobalFunctionsAndExtensions.swift
5
2788
// // GlobalFunctionsAndExtensions.swift // // Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension Calendar { static let formatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy MM dd" dateFormatter.isLenient = true return dateFormatter }() func startOfMonth(for date: Date) -> Date? { guard let comp = dateFormatterComponents(from: date) else { return nil } return Calendar.formatter.date(from: "\(comp.year) \(comp.month) 01") } func endOfMonth(for date: Date) -> Date? { guard let comp = dateFormatterComponents(from: date), let day = self.range(of: .day, in: .month, for: date)?.count, let retVal = Calendar.formatter.date(from: "\(comp.year) \(comp.month) \(day)") else { return nil } return retVal } private func dateFormatterComponents(from date: Date) -> (month: Int, year: Int)? { // Setup the dateformatter to this instance's settings Calendar.formatter.timeZone = self.timeZone Calendar.formatter.locale = self.locale let comp = self.dateComponents([.year, .month], from: date) guard let month = comp.month, let year = comp.year else { return nil } return (month, year) } } extension Dictionary where Value: Equatable { func key(for value: Value) -> Key? { guard let index = index(where: { $0.1 == value }) else { return nil } return self[index].0 } }
mit
3e879b49a9633bb15f328f97aab21c4d
37.191781
98
0.651004
4.432432
false
false
false
false
jpalten/MMLanScan
MMLanScanSwiftDemo/MMLanScanSwiftDemo/MainVC.swift
1
6485
// // MainVC.swift // MMLanScanSwiftDemo // // Created by Michalis Mavris on 06/11/2016. // Copyright © 2016 Miksoft. All rights reserved. // import UIKit import Foundation class MainVC: UIViewController, MainPresenterDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableV: UITableView! @IBOutlet weak var navigationBarTitle: UINavigationItem! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var tableVTopContraint: NSLayoutConstraint! @IBOutlet weak var scanButton: UIBarButtonItem! private var myContext = 0 var presenter: MainPresenter! //MARK: - On Load Methods override func viewDidLoad() { super.viewDidLoad() //Init presenter. Presenter is responsible for providing the business logic of the MainVC (MVVM) self.presenter = MainPresenter(delegate:self) //Add observers to monitor specific values on presenter. On change of those values MainVC UI will be updated self.addObserversForKVO() } override func viewDidAppear(_ animated: Bool) { //Setting the title of the navigation bar with the SSID of the WiFi self.navigationBarTitle.title = self.presenter.ssidName() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - KVO Observers func addObserversForKVO ()->Void { self.presenter.addObserver(self, forKeyPath: "connectedDevices", options: .new, context:&myContext) self.presenter.addObserver(self, forKeyPath: "progressValue", options: .new, context:&myContext) self.presenter.addObserver(self, forKeyPath: "isScanRunning", options: .new, context:&myContext) } func removeObserversForKVO ()->Void { self.presenter.removeObserver(self, forKeyPath: "connectedDevices") self.presenter.removeObserver(self, forKeyPath: "progressValue") self.presenter.removeObserver(self, forKeyPath: "isScanRunning") } //MARK: - Button Action @IBAction func refresh(_ sender: Any) { //Shows the progress bar and start the scan. It's also setting the SSID name of the WiFi as navigation bar title self.showProgressBar() self.navigationBarTitle.title = self.presenter.ssidName() self.presenter.scanButtonClicked() } //MARK: - Show/Hide Progress Bar func showProgressBar()->Void { self.progressView.progress = 0 UIView.animate(withDuration: 0.5, animations: { self.tableVTopContraint.constant = 40 self.view.layoutIfNeeded() }, completion: nil) } func hideProgressBar()->Void { UIView.animate(withDuration: 0.5, animations: { self.tableVTopContraint.constant = 0 self.view.layoutIfNeeded() }, completion: nil) } //MARK: - Presenter Delegates //The delegates methods from Presenters.These methods help the MainPresenter to notify the MainVC for any kind of changes func mainPresenterIPSearchFinished() { self.hideProgressBar() self.showAlert(title: "Scan Finished", message: "Number of devices connected to the Local Area Network : \(self.presenter.connectedDevices.count)") } func mainPresenterIPSearchCancelled() { self.hideProgressBar() self.tableV.reloadData() } func mainPresenterIPSearchFailed() { self.hideProgressBar() self.showAlert(title: "Failed to scan", message: "Please make sure that you are connected to a WiFi before starting LAN Scan") } //MARK: - Alert Controller func showAlert(title:String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in} alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } //MARK: - UITableView Delegates func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.presenter.connectedDevices!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCell", for: indexPath) as! DeviceCell let device = self.presenter.connectedDevices[indexPath.row] cell.ipLabel.text = device.ipAddress cell.macAddressLabel.text = device.macAddress cell.hostnameLabel.text = device.hostname cell.brandLabel.text = device.brand return cell } //MARK: - KVO //This is the KVO function that handles changes on MainPresenter override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (context == &myContext) { switch keyPath! { case "connectedDevices": self.tableV.reloadData() case "progressValue": self.progressView.progress = self.presenter.progressValue case "isScanRunning": let isScanRunning = change?[.newKey] as! BooleanLiteralType self.scanButton.image = isScanRunning ? #imageLiteral(resourceName: "stopBarButton") : #imageLiteral(resourceName: "refreshBarButton") default: print("Not valid key for observing") } } } //MARK: - Deinit deinit { self.removeObserversForKVO() } /* // 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
2ae0ae44a4801a38471ac0b686d43f33
33.673797
155
0.645126
5.183054
false
false
false
false
JHStone/DYZB
DYZB/DYZB/Classes/Home/Controller/RecommendViewController.swift
1
3536
// // RecommendViewController.swift // DYZB // // Created by gujianhua on 2017/3/13. // Copyright © 2017年 谷建华. All rights reserved. // import UIKit fileprivate let normalItemID : String = "normalItemID" fileprivate let prettyItemID : String = "prettyItemID" fileprivate let headerViewID : String = "headerViewID" fileprivate let itemSpace : CGFloat = 10 fileprivate let kHeaderViewH : CGFloat = 50; class RecommendViewController: UIViewController { fileprivate lazy var collectionView : UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() let itemW = (screenW - 3 * itemSpace) / 2 let itemH = itemW / 4 * 3 layout.itemSize = CGSize(width: itemW, height: itemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = itemSpace layout.headerReferenceSize = CGSize(width: screenW, height: kHeaderViewH) let collection = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout) collection.dataSource = self collection.backgroundColor = UIColor.white collection.autoresizingMask = [.flexibleHeight , .flexibleWidth]; collection.contentInset = UIEdgeInsetsMake(0, 10, 49, 10) collection.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewID) collection.register(UINib.init(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: normalItemID) collection.register(UINib.init(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: prettyItemID) return collection }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.red setupUI() loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension RecommendViewController{ func setupUI(){ view.addSubview(collectionView) } } extension RecommendViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 12 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 8 } return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell : UICollectionViewCell; if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: prettyItemID, for: indexPath) }else{ cell = collectionView.dequeueReusableCell(withReuseIdentifier: normalItemID, for: indexPath) } return cell; } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerViewID, for: indexPath) return reusableView } } extension RecommendViewController{ func loadData(){ NetWorkTools.requestData(type: .MethodTypeGet, urlString: "http://httpbin.org", parameters: nil) { (result) in print(result) } } }
mit
9046903da66cba7d4c68368bc74505bc
34.626263
181
0.69691
5.563091
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Repositories/Implementations/InventoryRepository.swift
1
13490
// // InventoryRepository.swift // Habitica // // Created by Phillip on 25.08.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import Habitica_Database import Habitica_API_Client import ReactiveSwift class InventoryRepository: BaseRepository<InventoryLocalRepository> { let localUserRepository = UserLocalRepository() func getOwnedGear(userID: String? = nil) -> SignalProducer<ReactiveResults<[OwnedGearProtocol]>, ReactiveSwiftRealmError> { return currentUserIDProducer.skipNil().flatMap(.latest, {[weak self] (currentUserID) in return self?.localRepository.getOwnedGear(userID: userID ?? currentUserID) ?? SignalProducer.empty }) } func getGear(predicate: NSPredicate? = nil) -> SignalProducer<ReactiveResults<[GearProtocol]>, ReactiveSwiftRealmError> { return localRepository.getGear(predicate: predicate) } func getGear(keys: [String]) -> SignalProducer<ReactiveResults<[GearProtocol]>, ReactiveSwiftRealmError> { return localRepository.getGear(predicate: NSPredicate(format: "key IN %@", keys)) } func getOwnedItems(userID: String? = nil, itemType: String? = nil) -> SignalProducer<ReactiveResults<[OwnedItemProtocol]>, ReactiveSwiftRealmError> { return currentUserIDProducer.skipNil().flatMap(.latest, {[weak self] (currentUserID) in return self?.localRepository.getOwnedItems(userID: userID ?? currentUserID, itemType: itemType) ?? SignalProducer.empty }) } // swiftlint:disable:next large_tuple func getItems(keys: [ItemType: [String]]) -> SignalProducer<(eggs: ReactiveResults<[EggProtocol]>, food: ReactiveResults<[FoodProtocol]>, hatchingPotions: ReactiveResults<[HatchingPotionProtocol]>, special: ReactiveResults<[SpecialItemProtocol]>, quests: ReactiveResults<[QuestProtocol]>), ReactiveSwiftRealmError> { return localRepository.getItems(keys: keys).map { items in return (eggs: items.0, food: items.1, hatchingPotions: items.2, special: items.3, quests: items.4) } } func getFood(keys: [String]) -> SignalProducer<ReactiveResults<[FoodProtocol]>, ReactiveSwiftRealmError> { return localRepository.getFood(keys: keys) } func getItems(type: ItemType) -> SignalProducer<ReactiveResults<[ItemProtocol]>, ReactiveSwiftRealmError> { return localRepository.getItems(type: type) } func getSpecialItems(keys: [String]) ->SignalProducer<ReactiveResults<[SpecialItemProtocol]>, ReactiveSwiftRealmError> { return localRepository.getSpecialItems(keys: keys) } func getQuest(key: String) ->SignalProducer<QuestProtocol?, ReactiveSwiftRealmError> { return localRepository.getQuest(key: key) } func getQuests(keys: [String]) ->SignalProducer<ReactiveResults<[QuestProtocol]>, ReactiveSwiftRealmError> { return localRepository.getQuests(keys: keys) } func sell(item: ItemProtocol) -> Signal<UserProtocol?, Never> { let call = SellItemCall(item: item) return call.objectSignal.on(value: {[weak self]user in if let user = user, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, updateUser: user) } }) } func hatchPet(egg: EggProtocol, potion: HatchingPotionProtocol) -> Signal<UserItemsProtocol?, Never> { return hatchPet(egg: egg.key, potion: potion.key) } func hatchPet(egg: String?, potion: String?) -> Signal<UserItemsProtocol?, Never> { let call = HatchPetCall(egg: egg ?? "", potion: potion ?? "") return call.objectSignal.on(value: {[weak self]userItems in if let userItems = userItems, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, userItems: userItems) } }) } func inviteToQuest(quest: QuestProtocol) -> Signal<EmptyResponseProtocol?, Never> { let call = InviteToQuestCall(groupID: "party", quest: quest) return call.objectSignal } func equip(type: String, key: String) -> Signal<UserItemsProtocol?, Never> { let call = EquipCall(type: type, itemKey: key) return call.objectSignal.on(value: {[weak self]userItems in if let userItems = userItems, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, userItems: userItems) } }) } func buyObject(key: String, quantity: Int, price: Int, text: String) -> Signal<BuyResponseProtocol?, Never> { let call = BuyObjectCall(key: key, quantity: quantity) return call.habiticaResponseSignal.on(value: {[weak self]habiticaResponse in if let buyResponse = habiticaResponse?.data, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, price: price, buyResponse: buyResponse) if let armoire = buyResponse.armoire { guard let text = habiticaResponse?.message?.stripHTML().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) else { return } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { if armoire.type == "experience" { ToastManager.show(text: text, color: .yellow, duration: 4.0) } else if armoire.type == "food" { ToastManager.show(text: text, color: .gray, duration: 4.0) //TODO: Show images in armoire toasts /*ImageManager.getImage(name: "Pet_Food_\(armoire.dropText ?? "")", completion: { (image, _) in if let image = image { let toastView = ToastView(title: text, icon: image, background: .gray) ToastManager.show(toast: toastView) } })*/ } else if armoire.type == "gear" { ToastManager.show(text: text, color: .gray, duration: 4.0) //TODO: Show images in armoire toasts /*ImageManager.getImage(name: "shop_\(armoire.dropText ?? "")", completion: { (image, _) in if let image = image { let toastView = ToastView(title: text, icon: image, background: .gray) ToastManager.show(toast: toastView) } })*/ } } } else { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { ToastManager.show(text: L10n.purchased(text), color: .green) } } UINotificationFeedbackGenerator.oneShotNotificationOccurred(.success) } }).map({ habiticaResponse in return habiticaResponse?.data }) } func purchaseItem(purchaseType: String, key: String, value: Int, quantity: Int, text: String) -> Signal<UserProtocol?, Never> { let call = PurchaseItemCall(purchaseType: purchaseType, key: key, quantity: quantity) return call.objectSignal.on(value: {[weak self]updatedUser in if let updatedUser = updatedUser, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, balanceDiff: -(Float(value) / 4.0)) self?.localUserRepository.updateUser(id: userID, updateUser: updatedUser) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { ToastManager.show(text: L10n.purchased(text), color: .green) } }) } func purchaseHourglassItem(purchaseType: String, key: String, text: String) -> Signal<UserProtocol?, Never> { let call = PurchaseHourglassItemCall(purchaseType: purchaseType, key: key) return call.objectSignal.on(value: {[weak self]updatedUser in if let updatedUser = updatedUser, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, updateUser: updatedUser) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { ToastManager.show(text: L10n.purchased(text), color: .green) } }) } func purchaseMysterySet(identifier: String, text: String) -> Signal<UserProtocol?, Never> { let call = PurchaseMysterySetCall(identifier: identifier) return call.objectSignal.on(value: {[weak self]updatedUser in if let updatedUser = updatedUser, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, updateUser: updatedUser) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { ToastManager.show(text: L10n.purchased(text), color: .green) } }) } func openMysteryItem() -> Signal<GearProtocol?, Never> { let call = OpenMysteryItemCall() return call.objectSignal .skipNil() .flatMap(.latest, {[weak self] (gear) -> SignalProducer<GearProtocol?, Never> in let key = gear.key ?? "" return self?.localRepository.getGear(predicate: NSPredicate(format: "key == %@", key)).map({ (values, _) in return values.first }).flatMapError({ _ in return SignalProducer.empty }) ?? SignalProducer.empty }) .on(value: {[weak self] gear in if let key = gear?.key { self?.localRepository.receiveMysteryItem(userID: self?.currentUserId ?? "", key: key) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { ToastManager.show(text: L10n.receivedMysteryItem(gear?.text ?? ""), color: .green) } } }) } func purchaseQuest(key: String, text: String) -> Signal<UserProtocol?, Never> { let call = PurchaseQuestCall(key: key) return call.objectSignal.on(value: {[weak self]updatedUser in if let updatedUser = updatedUser, let userID = self?.currentUserId { self?.localUserRepository.updateUser(id: userID, updateUser: updatedUser) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) { ToastManager.show(text: L10n.purchased(text), color: .green) } }) } func togglePinnedItem(pinType: String, path: String) -> Signal<PinResponseProtocol?, Never> { let call = TogglePinnedItemCall(pinType: pinType, path: path) return call.objectSignal.on(value: {[weak self] pinResponse in if let pinResponse = pinResponse, let userID = self?.currentUserId { self?.localRepository.updatePinnedItems(userID: userID, pinResponse: pinResponse) } }) } func retrieveShopInventory(identifier: String) -> Signal<ShopProtocol?, Never> { let call = RetrieveShopInventoryCall(identifier: identifier, language: LanguageHandler.getAppLanguage().code) return call.objectSignal.on(value: {[weak self]shop in if let shop = shop { shop.identifier = identifier self?.localRepository.save(shop: shop) } }) } func getShop(identifier: String) -> SignalProducer<ShopProtocol?, ReactiveSwiftRealmError> { return localRepository.getShop(identifier: identifier) } func getShops() -> SignalProducer<ReactiveResults<[ShopProtocol]>, ReactiveSwiftRealmError> { return localRepository.getShops() } func feed(pet: PetProtocol, food: FoodProtocol) -> Signal<Int?, Never> { let call = FeedPetCall(pet: pet, food: food) call.habiticaResponseSignal.observeValues { response in if let message = response?.message { let toastView = ToastView(title: message, background: .green, delay: 1.0) ToastManager.show(toast: toastView) } } return call.objectSignal.on(value: {[weak self]petValue in if let userID = self?.currentUserId, let key = pet.key, let trained = petValue, let foodKey = food.key { self?.localRepository.updatePetTrained(userID: userID, key: key, trained: trained, consumedFood: foodKey) } }) } func getNewInAppReward() -> InAppRewardProtocol { return localRepository.getNewInAppReward() } func getLatestMysteryGear() -> SignalProducer<GearProtocol?, ReactiveSwiftRealmError> { return localRepository.getLatestMysteryGear() } }
gpl-3.0
d109a8136adfb2c6506065fecd14641d
46.496479
153
0.594929
4.768116
false
false
false
false
dalu93/SwiftHelpSet
Sources/UIKIt/SwiftyTableView.swift
1
4330
// // SwiftyTableView.swift // SwiftHelpSet // // Created by Luca D'Alberti on 7/14/16. // Copyright © 2016 dalu93. All rights reserved. // import UIKit public class SwiftyTableView: UITableView { fileprivate var _configureNumberOfSections: (() -> Int)? /// It is called everytime `numberOfSectionsInTableView(tableView: UITableView)` is called public func configureNumberOfSections(closure: @escaping (() -> Int)) -> Self { _configureNumberOfSections = closure return self } fileprivate var _numberOfRowsPerSection: ((_ section: Int) -> Int)? /// It is called everytime `tableView(tableView: UITableView, numberOfRowsInSection section: Int)` is called public func numberOfRowsPerSection(closure: @escaping ((_ section: Int) -> Int)) -> Self { _numberOfRowsPerSection = closure return self } fileprivate var _cellForIndexPath: ((_ indexPath: IndexPath) -> UITableViewCell)? /// It is called everytime `tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)` is called public func cellForIndexPath(closure: @escaping ((_ indexPath: IndexPath) -> UITableViewCell)) -> Self { _cellForIndexPath = closure return self } fileprivate var _onCellSelection: ((_ indexPath: IndexPath) -> ())? /// It is called everytime `tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)` is called public func onCellSelection(closure: @escaping ((_ indexPath: IndexPath) -> ())) -> Self { _onCellSelection = closure return self } fileprivate var _onScroll: ((_ scrollView: UIScrollView) -> ())? /// It is called everytime `scrollViewDidScroll(scrollView: UIScrollView)` is called public func onScroll(closure: @escaping ((_ scrollView: UIScrollView) -> ())) -> Self { _onScroll = closure return self } fileprivate var _footerInSection: ((_ section: Int) -> UIView?)? /// It is called everytime `tableView(tableView: UITableView, viewForFooterInSection section: Int)` is called public func footerInSection(closure: @escaping ((_ section: Int) -> UIView?)) -> Self { _footerInSection = closure return self } fileprivate var _headerInSection: ((_ section: Int) -> UIView?)? /// It is called everytime `tableView(tableView: UITableView, viewForHeaderInSection section: Int)` is called public func headerInSection(closure: @escaping ((_ section: Int) -> UIView?)) -> Self { _headerInSection = closure return self } override public init(frame: CGRect, style: UITableViewStyle) { super.init( frame: frame, style: style ) _setupProtocols() } required public init?(coder aDecoder: NSCoder) { super.init( coder: aDecoder ) _setupProtocols() } } // MARK: - Helpers private extension SwiftyTableView { func _setupProtocols() { self.delegate = self self.dataSource = self } } // MARK: - UITableViewDataSource extension SwiftyTableView: UITableViewDataSource { @nonobjc public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return _configureNumberOfSections?() ?? 0 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _numberOfRowsPerSection?(section) ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return _cellForIndexPath?(indexPath) ?? UITableViewCell() } } // MARK: - UITableViewDelegate extension SwiftyTableView: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { _onCellSelection?(indexPath) } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return _footerInSection?(section) } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return _headerInSection?(section) } public func scrollViewDidScroll(_ scrollView: UIScrollView) { _onScroll?(scrollView) } }
mit
da936f7789424557a8f03c9e72ed6899
34.483607
124
0.661585
5.203125
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureUserDeletion/Tests/FeatureUserDeletionUITests/FeatureUserDeletionSnapshotTests.swift
1
2047
import AnalyticsKitMock import ComposableArchitecture import ComposableArchitectureExtensions @testable import FeatureUserDeletionDomainMock @testable import FeatureUserDeletionUI import SnapshotTesting import SwiftUI import TestKit import XCTest final class FeatureUserDeletionSnapshotTests: XCTestCase { private var environment: UserDeletionEnvironment! private var mockEmailVerificationService: MockUserDeletionRepositoryAPI! private var analyticsRecorder: MockAnalyticsRecorder! private var userDeletionState: UserDeletionState! override func setUpWithError() throws { try super.setUpWithError() isRecording = false mockEmailVerificationService = MockUserDeletionRepositoryAPI() analyticsRecorder = MockAnalyticsRecorder() environment = UserDeletionEnvironment( mainQueue: .immediate, userDeletionRepository: mockEmailVerificationService, analyticsRecorder: analyticsRecorder, dismissFlow: {}, logoutAndForgetWallet: {} ) } override func tearDownWithError() throws { mockEmailVerificationService = nil environment = nil analyticsRecorder = nil try super.tearDownWithError() } func test_iPhoneSE_onAppear() throws { let view = UserDeletionView(store: buildStore()) assert(view, on: .iPhoneSe) } func test_iPhoneXsMax_onAppear() throws { let view = UserDeletionView(store: buildStore()) assert(view, on: .iPhoneXsMax) } // MARK: - Helpers private func buildStore( confirmViewState: DeletionConfirmState? = DeletionConfirmState(), route: RouteIntent<UserDeletionRoute>? = nil ) -> Store<UserDeletionState, UserDeletionAction> { .init( initialState: UserDeletionState( confirmViewState: confirmViewState, route: route ), reducer: UserDeletionModule.reducer, environment: environment ) } }
lgpl-3.0
20016e049cdfe175f5a540c9908498f8
30.015152
76
0.690278
5.532432
false
true
false
false
gowansg/firefox-ios
Utils/DeviceInfo.swift
2
1479
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit public class DeviceInfo { public class func appName() -> String { let localizedDict = NSBundle.mainBundle().localizedInfoDictionary let infoDict = NSBundle.mainBundle().infoDictionary let key = "CFBundleDisplayName" // E.g., "Fennec Nightly". return localizedDict?[key] as? String ?? infoDict?[key] as? String ?? "Firefox" } // I'd land a test for this, but it turns out it's hardly worthwhile -- both the // app name and the device name are variable, and the format string itself varies // by locale! public class func defaultClientName() -> String { // E.g., "Sarah's iPhone". let device = UIDevice.currentDevice().name let f = NSLocalizedString("%@ on %@", tableName: "Sync", comment: "A brief descriptive name for this app on this device, used for Send Tab and Synced Tabs. The first argument is the app name. The second argument is the device name.") return String(format: f, appName(), device) } public class func deviceModel() -> String { return UIDevice.currentDevice().model } public class func isSimulator() -> Bool { return UIDevice.currentDevice().model.contains("Simulator") } }
mpl-2.0
ae7c44b73862bff646dcc26bc92ee682
37.947368
241
0.651792
4.564815
false
false
false
false
tjw/swift
test/stdlib/NewStringAppending.swift
2
4022
// RUN: %target-run-stdlib-swift | %FileCheck %s // REQUIRES: executable_test // // Parts of this test depend on memory allocator specifics. The test // should be rewritten soon so it doesn't expose legacy components // like OpaqueString anyway, so we can just disable the failing // configuration // // Memory allocator specifics also vary across platforms. // REQUIRES: CPU=x86_64, OS=macosx import Foundation import Swift func hexAddrVal<T>(_ x: T) -> String { return "@0x" + String(UInt64(unsafeBitCast(x, to: Int.self)), radix: 16) } func hexAddr(_ x: AnyObject?) -> String { if let owner = x { if let y = owner as? _SwiftRawStringStorage { return ".native\(hexAddrVal(y))" } if let y = owner as? NSString { return ".cocoa\(hexAddrVal(y))" } else { return "?Uknown?\(hexAddrVal(owner))" } } return "nil" } func repr(_ x: NSString) -> String { return "\(NSStringFromClass(object_getClass(x)))\(hexAddr(x)) = \"\(x)\"" } func repr(_ x: _StringGuts) -> String { if x._isNative { return "Native(" + "owner: \(hexAddrVal(x._owner)), " + "count: \(x.count), " + "capacity: \(x.capacity))" } else if x._isCocoa { return "Cocoa(" + "owner: \(hexAddrVal(x._owner)), " + "count: \(x.count))" } else if x._isSmall { return "Cocoa(" + "owner: <tagged>, " + "count: \(x.count))" } else if x._isUnmanaged { return "Unmanaged(" + "count: \(x.count))" } return "?????" } func repr(_ x: String) -> String { return "String(\(repr(x._guts))) = \"\(x)\"" } // ===------- Appending -------=== // CHECK: --- Appending --- print("--- Appending ---") var s = "⓪" // start non-empty // To make this test independent of the memory allocator implementation, // explicitly request initial capacity. s.reserveCapacity(8) // CHECK-NEXT: String(Native(owner: @[[storage0:[x0-9a-f]+]], count: 1, capacity: 8)) = "⓪" print("\(repr(s))") // CHECK-NEXT: String(Native(owner: @[[storage0]], count: 2, capacity: 8)) = "⓪1" s += "1" print("\(repr(s))") // CHECK-NEXT: String(Native(owner: @[[storage0]], count: 8, capacity: 8)) = "⓪1234567" s += "234567" print("\(repr(s))") // -- expect a reallocation here // CHECK-NEXT: String(Native(owner: @[[storage1:[x0-9a-f]+]], count: 9, capacity: 16)) = "⓪12345678" // CHECK-NOT: @[[storage0]], s += "8" print("\(repr(s))") // CHECK-NEXT: String(Native(owner: @[[storage1]], count: 16, capacity: 16)) = "⓪123456789012345" s += "9012345" print("\(repr(s))") // -- expect a reallocation here // Appending more than the next level of capacity only takes as much // as required. I'm not sure whether this is a great idea, but the // point is to prevent huge amounts of fragmentation when a long // string is appended to a short one. The question, of course, is // whether more appends are coming, in which case we should give it // more capacity. It might be better to always grow to a multiple of // the current capacity when the capacity is exceeded. // CHECK-NEXT: String(Native(owner: @[[storage2:[x0-9a-f]+]], count: 48, capacity: 48)) // CHECK-NOT: @[[storage1]], s += s + s print("\(repr(s))") // -- expect a reallocation here // CHECK-NEXT: String(Native(owner: @[[storage3:[x0-9a-f]+]], count: 49, capacity: 96)) // CHECK-NOT: @[[storage2]], s += "C" print("\(repr(s))") var s1 = s // CHECK-NEXT: String(Native(owner: @[[storage3]], count: 49, capacity: 96)) print("\(repr(s1))") /// The use of later buffer capacity by another string forces /// reallocation; however, the original capacity is kept by intact // CHECK-NEXT: String(Native(owner: @[[storage4:[x0-9a-f]+]], count: 50, capacity: 96)) = "{{.*}}X" // CHECK-NOT: @[[storage3]], s1 += "X" print("\(repr(s1))") /// The original copy is left unchanged // CHECK-NEXT: String(Native(owner: @[[storage3]], count: 49, capacity: 96)) print("\(repr(s))") /// Appending to an empty string re-uses the RHS // CHECK-NEXT: @[[storage3]], var s2 = String() s2 += s print("\(repr(s2))")
apache-2.0
2175fefdfe077c39a43dc318ee76a555
27.439716
100
0.620948
3.249595
false
false
false
false
TouchInstinct/LeadKit
TITransitions/Sources/PanelTransition/Animations/PresentAnimation.swift
1
2023
// // Copyright (c) 2020 Touch Instinct // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the Software), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit open class PresentAnimation: BaseAnimation { override open func animator(using transitionContext: UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating { guard let toView = transitionContext.view(forKey: .to), let toController = transitionContext.viewController(forKey: .to) else { return UIViewPropertyAnimator() } let finalFrame = transitionContext.finalFrame(for: toController) toView.frame = finalFrame.offsetBy(dx: .zero, dy: finalFrame.height) let animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { toView.frame = finalFrame } animator.addCompletion { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } return animator } }
apache-2.0
04053ba7ef1e56981f748b7709b29069
42.042553
125
0.71132
5.007426
false
false
false
false
barbosa/clappr-ios
Pod/Classes/View/BorderView.swift
1
501
import UIKit @IBDesignable class BorderView: UIView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.CGColor } } }
bsd-3-clause
67c60ab333c65a7d2abcc44b3cc38d48
20.782609
52
0.57485
5.387097
false
false
false
false
ospr/UIPlayground
UIPlaygroundUI/SpringBoardViewController.swift
1
12970
// // SpringBoardViewController.swift // UIPlayground // // Created by Kip Nicol on 9/20/16. // Copyright © 2016 Kip Nicol. All rights reserved. // import UIKit import UIPlaygroundElements public class SpringBoardViewController: UIViewController { var selectedAppButton: UIButton? var appInfoItems = [[SpringBoardAppInfo]]() public var wallpaperImage: UIImage? { didSet { view.layoutIfNeeded() wallpaperView.image = prepareWallpaperImage(image: wallpaperImage) } } let containerView = UIView() let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) var pageViewSubViewControllers = [UIViewController]() let dockView = SpringBoardDockView() let wallpaperView = UIImageView() let backAppIconView = SpringBoardAppIconViewCell() public override var preferredStatusBarStyle: UIStatusBarStyle { // Have the presented view controller specify the status bar style if let presentedViewController = presentedViewController, !presentedViewController.isBeingDismissed { return presentedViewController.preferredStatusBarStyle } return .lightContent } public override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } public init() { super.init(nibName: nil, bundle: nil) title = "Spring Board" } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { view.clipsToBounds = true setupAppInfo() let appCollectionLayout = SpringBoardAppCollectionLayout(screen: UIScreen.main) pageViewSubViewControllers = appInfoItems.map({ (appInfoItems) -> SpringBoardAppCollectionViewController in let controller = SpringBoardAppCollectionViewController(appInfoItems: appInfoItems, appCollectionLayout: appCollectionLayout) controller.delegate = self return controller }) pageViewController.setViewControllers([pageViewSubViewControllers[0]], direction: .forward, animated: false, completion: nil) pageViewController.dataSource = self // Add wallpaper view view.addSubview(wallpaperView) wallpaperView.translatesAutoresizingMaskIntoConstraints = false wallpaperView.anchorConstraintsToFitSuperview() wallpaperView.contentMode = .scaleAspectFill // Add dock view view.addSubview(dockView) dockView.translatesAutoresizingMaskIntoConstraints = false dockView.heightAnchor.constraint(equalToConstant: 96).isActive = true dockView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true dockView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true dockView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true // Add container view for app collection view.addSubview(containerView) containerView.isOpaque = false containerView.translatesAutoresizingMaskIntoConstraints = false containerView.anchorConstraintsToFitSuperview() // Add page view pageViewController.willMove(toParentViewController: self) containerView.addSubview(pageViewController.view) addChildViewController(pageViewController) pageViewController.didMove(toParentViewController: self) pageViewController.view.translatesAutoresizingMaskIntoConstraints = false pageViewController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true pageViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true pageViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true // Add back app icon containerView.addSubview(backAppIconView) backAppIconView.appIconImage = UIImage(named: "BackIcon", inBundleForObject: self)! backAppIconView.appNameLabel.text = "Back" backAppIconView.appIconButtonView.addTarget(self, action: #selector(backButtonSelectedAction), for: .touchUpInside) backAppIconView.translatesAutoresizingMaskIntoConstraints = false backAppIconView.centerXAnchor.constraint(equalTo: dockView.centerXAnchor).isActive = true backAppIconView.bottomAnchor.constraint(equalTo: dockView.bottomAnchor, constant: -4).isActive = true // Constrain top of dock to bottom of page view dockView.topAnchor.constraint(equalTo: pageViewController.view.bottomAnchor, constant: appCollectionLayout.pageControlOfffset).isActive = true wallpaperImage = UIImage(named: "BackgroundWallpaper", inBundleForObject: self) } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setNeedsStatusBarAppearanceUpdate() } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsStatusBarAppearanceUpdate() } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: - Setup private func setupAppInfo() { appInfoItems = [ [ SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), ], [ SpringBoardAppInfo(appName: "UIPlayground", image: UIImage(named: "AppCard-UIPlayground-Icon", inBundleForObject: self)!), SpringBoardAppInfo(appName: "Overcast", image: UIImage(named: "AppCard-Overcast-Icon", inBundleForObject: self)!), ], [ SpringBoardAppInfo(appName: "DavisTrans", image: UIImage(named: "AppCard-DavisTrans-Icon", inBundleForObject: self)!), ], ] } // MARK: - Actions func backButtonSelectedAction(sender: UIButton) { if splitViewController!.isCollapsed { let _ = (splitViewController?.viewControllers.first as? UINavigationController)?.popViewController(animated: true) } else { let btn = splitViewController!.displayModeButtonItem let _ = btn.target?.perform(btn.action, with: btn) } } // MARK: - Working with wallpaper private func prepareWallpaperImage(image: UIImage?) -> UIImage? { guard let image = image else { return nil } let imageRect = CGRect(origin: .zero, size: image.size) return UIGraphicsImageRenderer(size: imageRect.size, scale: 0, opaque: true).image { (context) in // Resize image so that it's just big enough for the wallpaper view image.draw(in: imageRect) // Draw a transparent dark overlay to dim the image context.cgContext.setFillColor(UIColor.black.withAlphaComponent(0.1).cgColor) let path = UIBezierPath(rect: imageRect) path.fill() } } } extension SpringBoardViewController: ViewControllerNavigationBarHideable { public var prefersNavigationBarHidden: Bool { return true } } extension SpringBoardViewController: UIPageViewControllerDataSource { func nextPageViewControllerFor(viewController: UIViewController, before: Bool) -> UIViewController? { let currentIndex = pageViewSubViewControllers.index(of: viewController)! let nextIndex = max(0, min(pageViewSubViewControllers.count - 1, before ? currentIndex - 1 : currentIndex + 1)) let nextViewController = pageViewSubViewControllers[nextIndex] guard nextViewController !== viewController else { return nil } return nextViewController } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { return nextPageViewControllerFor(viewController: viewController, before: true) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { return nextPageViewControllerFor(viewController: viewController, before: false) } public func presentationCount(for pageViewController: UIPageViewController) -> Int { return appInfoItems.count } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let subView = pageViewController.viewControllers?.first else { return 0 } return pageViewSubViewControllers.index(of: subView)! } } extension SpringBoardViewController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SpringBoardAppLaunchTransitionAnimator(appIconButton: selectedAppButton!, springBoardViewController: self, isPresenting: true) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SpringBoardAppLaunchTransitionAnimator(appIconButton: selectedAppButton!, springBoardViewController: self, isPresenting: false) } } extension SpringBoardViewController: SpringBoardAppCollectionViewControllerDelegate { func springBoardAppCollectionViewController(_ viewController: SpringBoardAppCollectionViewController, didSelectAppInfo appInfo: SpringBoardAppInfo, selectedAppIconButton: UIButton) { selectedAppButton = selectedAppIconButton let viewController = SpringBoardLaunchedAppViewController() viewController.modalPresentationStyle = .custom viewController.transitioningDelegate = self present(viewController, animated: true, completion: nil) } func springBoardAppCollectionViewControllerDidUpdateEditMode(_ viewController: SpringBoardAppCollectionViewController) { // Enable edit mode for all app collection view controllers for viewController in pageViewSubViewControllers { if let appCollectionViewController = viewController as? SpringBoardAppCollectionViewController { appCollectionViewController.editModeEnabled = true } } } }
mit
e19d76dde1f51dfe9ebf2576dc8fa22f
47.211896
186
0.706068
5.493011
false
false
false
false
younata/Lepton
LeptonTests/ParserSpec.swift
1
1367
import Quick import Nimble import Lepton class ParserSpec: QuickSpec { override func spec() { let bundle = Bundle(for: ParserSpec.self) let str = try! String(contentsOfFile: bundle.path(forResource: "test", ofType: "opml")!, encoding: String.Encoding.utf8) describe("Parsing a string") { var parser: Parser! = nil beforeEach { parser = Parser(text: str) } it("pulls out regular feeds") { _ = parser.success {(items) in expect(items.count).to(equal(3)) if let feed = items.first { expect(feed.title).to(equal("nil")) expect(feed.summary).to(beNil()) expect(feed.xmlURL).to(equal("http://example.com/feedWithTag")) expect(feed.tags).to(equal(["a tag"])) } if let feed = items.last { expect(feed.title).to(equal("Feed With Title")) expect(feed.summary).to(beNil()) expect(feed.xmlURL).to(equal("http://example.com/feedWithTitle")) expect(feed.tags) == [] } } parser.main() } } } }
mit
250b4b8fdeebcb7f48e1a6b8e3da46de
34.973684
128
0.456474
4.81338
false
false
false
false
Gurpartap/Cheapjack
CheapjackExample/DownloadsViewController.swift
1
5272
// ViewController.swift // // Copyright (c) 2015 Gurpartap Singh // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Cheapjack import ReactiveCocoa enum DownloadsCellAction: String { case Download = "Download" case Pause = "Pause" case Resume = "Resume" case Remove = "Remove" case None = "..." } class DownloadsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! private lazy var viewModel = DownloadsViewModel() let downloadLinks = [ "sample_iPod.m4v (2.2 MB)": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1425/sample_iPod.m4v.zip", "sample_iTunes.mov (3 MB)": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1425/sample_iTunes.mov.zip", "sample_mpeg4.mp4 (236 KB)": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1425/sample_mpeg4.mp4.zip", "sample_3GPP.3gp (28 KB)": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1425/sample_3GPP.3gp.zip", "sample_3GPP2.3g2 (27 KB)": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1425/sample_3GPP2.3g2.zip", "sample_mpeg2.m2v (1.1 MB)": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1425/sample_mpeg2.m2v.zip" ] override func viewDidLoad() { super.viewDidLoad() Cheapjack.delegate = viewModel Cheapjack.downloadCompletionHandler = { (download, session, location) -> NSURL? in // Return NSURL of location to move the downloaded file to. // Or do it manually and return nil. return nil } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func addButtonPressed() { Cheapjack.removeAll() viewModel.downloads.value = Array<Download>() for (title, urlString) in downloadLinks { let url = NSURL(string: urlString)! let download = Download(title: title, url: url) viewModel.addDownload(download) } tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic) } // MARK:- UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.downloads.value.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DownloadsCell", forIndexPath: indexPath) as! DownloadsCell let download = viewModel.downloads.value[indexPath.row] let cellViewModel = download.viewModel let reuseSignal = prepareForReuseSignal(cell) DynamicProperty(object: cell.infoLabel, keyPath: "text") <~ cellViewModel.info.producer.takeUntil(reuseSignal).observeOn(UIScheduler()).map({ $0 }) DynamicProperty(object: cell.stateLabel, keyPath: "text") <~ cellViewModel.state.producer.takeUntil(reuseSignal).observeOn(UIScheduler()).map({ $0 }) DynamicProperty(object: cell.progressView, keyPath: "progress") <~ cellViewModel.progress.producer.takeUntil(reuseSignal).observeOn(UIScheduler()).map({ $0 }) DynamicProperty(object: cell.progressLabel, keyPath: "text") <~ cellViewModel.progressLabelText.producer.takeUntil(reuseSignal).observeOn(UIScheduler()).map({ $0 }) cellViewModel.nextAction.producer .takeUntil(reuseSignal) .observeOn(UIScheduler()) .start(next: { [weak cell] nextAction in cell?.actionButton.titleLabel?.text = nextAction.rawValue cell?.actionButton.setTitle(nextAction.rawValue, forState: .Normal) }) controlEventsSignal(cell.actionButton, controlEvents: .TouchUpInside) .takeUntil(reuseSignal) .start(next: { [weak download, weak cell] sender -> Void in if let actionText = cell?.actionButton.titleLabel?.text { if let action = DownloadsCellAction(rawValue: actionText) { switch action { case .Download, .Resume: download?.cheapjackDownload.resume() case .None: break case .Pause: download?.cheapjackDownload.pause({ (resumeData) -> Void in print("Got resume data") }) case .Remove: download?.cheapjackDownload.remove() self.viewModel.downloads.value.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } } }) return cell } }
mit
d250ab337ea92aad3097c0c95021e9fa
39.868217
166
0.742792
3.867938
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/iOS/NoteDetailCell.swift
1
1786
// // NoteDetailCell.swift // SwiftGL // // Created by jerry on 2015/12/4. // Copyright © 2015年 Jerry Chan. All rights reserved. // import UIKit import SwiftGL class NoteDetailCell:UITableViewCell{ @IBOutlet weak var title: UILabel! @IBOutlet weak var textView: UITextView! @IBOutlet weak var editButton: UIButton! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var iconButton: UIButton! @IBOutlet weak var titleEditTextField: UITextField! var strokeID:Int! var is_editing:Bool = false override func awakeFromNib() { super.awakeFromNib() textView.layer.borderColor = UIColor.lightGray.cgColor textView.layer.cornerRadius = 2 isEditing = false titleEditTextField.isHidden = true } @IBAction func editButtonTouched(_ sender: UIButton) { let note = NoteManager.instance.getNoteAtStroke(strokeID) //enter editing mode if is_editing == false { textView.isEditable = true textView.layer.borderWidth = 1 titleEditTextField.isHidden = false titleEditTextField.text = note?.title editButton.setImage(UIImage(named: "Pen-50"), for: UIControlState()) } else { textView.isEditable = false textView.layer.borderWidth = 0 titleEditTextField.isHidden = true NoteManager.instance.updateNote(strokeID, title: titleEditTextField.text!, description: textView.text) title.text = titleEditTextField.text! editButton.setImage(UIImage(named: "write"), for: UIControlState()) } is_editing = !is_editing } }
mit
9215a2a7954ab59e20ae088e3dd83d61
26.430769
114
0.616938
4.898352
false
false
false
false
15221758864/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendView.swift
1
7566
// // CBRecommendView.swift // TestKitchen // // Created by Ronie on 16/8/17. // Copyright © 2016年 Ronie. All rights reserved. // import UIKit class CBRecommendView: UIView, UITableViewDelegate, UITableViewDataSource { private var tbView: UITableView? var model: CBRecommendModel?{ didSet{ tbView?.reloadData() } } override init(frame: CGRect) { super.init(frame: CGRectZero) tbView = UITableView(frame: CGRectZero, style: .Plain) tbView?.delegate = self tbView?.dataSource = self tbView?.separatorStyle = .None self.addSubview(tbView!) tbView?.snp_makeConstraints(closure: { [weak self] (make) in make.edges.equalTo(self!) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CBRecommendView{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { var sectionNum = 1 if model?.data?.widgetList?.count > 0 { //广告的数据 sectionNum += (model?.data?.widgetList?.count)! } return sectionNum } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rowNum = 0 if section == 0 { //广告的数据 if model?.data?.banner?.count > 0 { rowNum = 1 } }else{ //其他的情况 let listModel = model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue == WidgeType.GuessYourLike.rawValue { //猜你喜欢 rowNum = 1 }else if listModel?.widget_type?.integerValue == WidgeType.RedPackage.rawValue{ //红包入口 rowNum = 1 }else if listModel?.widget_type?.integerValue == WidgeType.NewProduct.rawValue{ //今日新品 rowNum = 1 }else if listModel?.widget_type?.integerValue == WidgeType.Special.rawValue{ //早餐日记 健康一百岁等 rowNum = 1 }else if listModel?.widget_type?.integerValue == WidgeType.Scene.rawValue{ //全部场景 rowNum = 1 }else if listModel?.widget_type?.integerValue == WidgeType.Talent.rawValue{ //推荐达人 rowNum = (listModel?.widget_data?.count)!/4 } } return rowNum } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height: CGFloat = 0 if indexPath.section == 0 { //广告的高度 if model?.data?.banner?.count > 0 { height = 160 } }else{ //其他的情况 let listModel = model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue == WidgeType.GuessYourLike.rawValue { height = 80 }else if listModel?.widget_type?.integerValue == WidgeType.RedPackage.rawValue{ height = 80 }else if listModel?.widget_type?.integerValue == WidgeType.NewProduct.rawValue{ height = 300 //今日新品 }else if listModel?.widget_type?.integerValue == WidgeType.Special.rawValue{ //早餐日记 健康一百岁等 height = 200 }else if listModel?.widget_type?.integerValue == WidgeType.Scene.rawValue{ //全部场景 height = 60 }else if listModel?.widget_type?.integerValue == WidgeType.Talent.rawValue{ //推荐达人 height = 80 } } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() if indexPath.section == 0 { //广告 if model?.data?.banner?.count > 0 { cell = CBRecommendADCell.createAdCellFor(tableView, atIndexPath: indexPath, withModel: model!) } }else{ //其他的情况 let listModel = model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue == WidgeType.GuessYourLike.rawValue { //猜你喜欢 cell = CBRecommendLikeCell.createLikeCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!) }else if listModel?.widget_type?.integerValue == WidgeType.RedPackage.rawValue{ cell = CBRedPacketCell.createRedPacketCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!) }else if listModel?.widget_type?.integerValue == WidgeType.NewProduct.rawValue{ //新品 cell = CBRecommendNewCell.createNewCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!) }else if listModel?.widget_type?.integerValue == WidgeType.Special.rawValue{ //早餐日记,健康一百岁等 cell = CBSpecialCell.createSpecialCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!) }else if listModel?.widget_type?.integerValue == WidgeType.Scene.rawValue{ //全部场景 cell = CBSceneCell.createSceneCell(tableView, atIndexPath: indexPath, withListModel: listModel!) }else if listModel?.widget_type?.integerValue == WidgeType.Talent.rawValue{ //推荐达人 cell = CBTalentTableViewCell.createTalentCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!) } } return cell } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var headerView: UIView? = nil if section > 0 { //其他的情况 let listModel = model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue == WidgeType.GuessYourLike.rawValue { //猜你喜欢 headerView = CBSearchHeaderView(frame: CGRectMake(0, 0, kScreenWidth, 44)) }else if listModel?.widget_type?.integerValue == WidgeType.NewProduct.rawValue || listModel?.widget_type?.integerValue == WidgeType.Special.rawValue || listModel?.widget_type?.integerValue == WidgeType.Talent.rawValue{ //今日新品 let tmpView = CBHeaderView(frame: CGRectMake(0, 0, kScreenWidth, 44)) tmpView.configTitle((listModel?.title)!) headerView = tmpView } } return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { var height: CGFloat = 0 if section > 0 { //其他的情况 let listModel = model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue == WidgeType.GuessYourLike.rawValue || listModel?.widget_type?.integerValue == WidgeType.NewProduct.rawValue || listModel?.widget_type?.integerValue == WidgeType.Special.rawValue || listModel?.widget_type?.integerValue == WidgeType.Talent.rawValue{ //猜你喜欢 // // height = 44 } } return height } }
mit
e1c66a507a408430956b3da2514e816c
38.907104
300
0.580036
4.817282
false
false
false
false
natecook1000/swift
test/SILGen/inherited_protocol_conformance_multi_file_2.swift
2
5993
// -- Try all the permutations of file order possible. // Abc // RUN: %target-swift-emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_A // aBc // RUN: %target-swift-emit-silgen -enable-sil-ownership %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_B // abC // RUN: %target-swift-emit-silgen -enable-sil-ownership %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_C // Bac // RUN: %target-swift-emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_B // bAc // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_A // baC // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_C // OS X 10.9 // RUN: %target-swift-emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_C // cAb // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_A // caB // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_B // Acb // RUN: %target-swift-emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_A // aCb // RUN: %target-swift-emit-silgen -enable-sil-ownership %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_C // abC // RUN: %target-swift-emit-silgen -enable-sil-ownership %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_B // Bca // RUN: %target-swift-emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_B // bCa // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_C // bcA // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %s -module-name main | %FileCheck %s --check-prefix=FILE_A // Cba // RUN: %target-swift-emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_C // cBa // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_B // cbA // RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %s -module-name main | %FileCheck %s --check-prefix=FILE_A // FILE_A-NOT: sil [transparent] [thunk] @$S4main5ThingVSQAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW // FILE_A-NOT: sil [transparent] [thunk] @$S4main5ThingVSkAAsADP9hashValueSivgTW // FILE_A-NOT: sil_witness_table Thing: Hashable module main // FILE_A-NOT: sil_witness_table Thing: Equatable module main // FILE_B-NOT: sil [transparent] [thunk] @$S4main5ThingVSQAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW // FILE_B: sil private [transparent] [thunk] @$S4main5ThingVSHAASH9hashValueSivgTW // FILE_B-NOT: sil [transparent] [thunk] @$S4main5ThingVSQAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW // FILE_B-NOT: sil_witness_table hidden Thing: Equatable module main // FILE_B: sil_witness_table hidden Thing: Hashable module main // FILE_B-NOT: sil_witness_table hidden Thing: Equatable module main // FILE_C-NOT: sil [transparent] [thunk] @$S4main5ThingVSkAAsADP9hashValueSivgTW // FILE_C: sil private [transparent] [thunk] @$S4main5ThingVSQAASQ2eeoiySbx_xtFZTW // FILE_C-NOT: sil [transparent] [thunk] @$S4main5ThingVSkAAsADP9hashValueSivgTW // FILE_C-NOT: sil_witness_table hidden Thing: Hashable module main // FILE_C: sil_witness_table hidden Thing: Equatable module main // FILE_C-NOT: sil_witness_table hidden Thing: Hashable module main struct Thing { var value: Int }
apache-2.0
c4540bec4c51b78045780090f3420c46
89.80303
252
0.761055
3.007025
false
false
false
false
mdiep/Tentacle
Sources/Tentacle/User.swift
1
5650
// // User.swift // Tentacle // // Created by Matt Diephouse on 4/12/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation extension User { /// A request for issues assigned to the authenticated user. /// /// https://developer.github.com/v3/issues/#list-issues static public var assignedIssues: Request<[Issue]> { return Request(method: .get, path: "/issues") } /// A request for the authenticated user's profile. /// /// https://developer.github.com/v3/users/#get-the-authenticated-user static public var profile: Request<UserProfile> { return Request(method: .get, path: "/user") } /// A request for the authenticated user's public repositories. /// /// https://developer.github.com/v3/repos/#list-all-public-repositories static public var publicRepositories: Request<[RepositoryInfo]> { return Request(method: .get, path: "/repositories") } /// A request for the authenticated user's repositories. /// /// https://developer.github.com/v3/repos/#list-your-repositories static public var repositories: Request<[RepositoryInfo]> { return Request(method: .get, path: "/user/repos") } } extension User { /// A request for the user's profile. /// /// https://developer.github.com/v3/users/#get-a-single-user public var profile: Request<UserProfile> { return Request(method: .get, path: "/users/\(login)") } /// A request for the user's repositories. /// /// https://developer.github.com/v3/repos/#list-user-repositories public var repositories: Request<[RepositoryInfo]> { return Request(method: .get, path: "/users/\(login)/repos") } } /// A user on GitHub or GitHub Enterprise. public struct User: CustomStringConvertible, ResourceType { /// The user's login/username. public let login: String public init(_ login: String) { self.login = login } public var description: String { return login } } /// Information about a user on GitHub. public struct UserInfo: CustomStringConvertible, ResourceType, Identifiable { public enum UserType: String, Decodable { case user = "User" case organization = "Organization" } /// The unique ID of the user. public let id: ID<UserInfo> /// The user this information is about. public let user: User /// The URL of the user's GitHub page. public let url: URL /// The URL of the user's avatar. public let avatarURL: URL /// The type of user if it's a regular one or an organization public let type: UserType public var description: String { return user.description } private enum CodingKeys: String, CodingKey { case id case user = "login" case url = "html_url" case avatarURL = "avatar_url" case type } public init(id: ID<UserInfo>, user: User, url: URL, avatarURL: URL, type: UserType) { self.id = id self.user = user self.url = url self.avatarURL = avatarURL self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(ID.self, forKey: .id) self.user = try User(from: decoder) self.url = try container.decode(URL.self, forKey: .url) self.avatarURL = try container.decode(URL.self, forKey: .avatarURL) self.type = try container.decode(UserType.self, forKey: .type) } } /// Extended information about a user on GitHub. public struct UserProfile: ResourceType { /// The user that this information refers to. public let user: UserInfo /// The date that the user joined GitHub. public let joinedDate: Date /// The user's name if they've set one. public let name: String? /// The user's public email address if they've set one. public let email: String? /// The URL of the user's website if they've set one /// (the type here is a String because Github lets you use /// anything and doesn't validate that you've entered a valid URL) public let websiteURL: String? /// The user's company if they've set one. public let company: String? public var description: String { return user.description } public init(user: UserInfo, joinedDate: Date, name: String?, email: String?, websiteURL: String?, company: String?) { self.user = user self.joinedDate = joinedDate self.name = name self.email = email self.websiteURL = websiteURL self.company = company } public init(from decoder: Decoder) throws { self.user = try UserInfo(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.joinedDate = try container.decode(Date.self, forKey: .joinedDate) self.name = try container.decodeIfPresent(String.self, forKey: .name) self.email = try container.decodeIfPresent(String.self, forKey: .email) self.websiteURL = try container.decodeIfPresent(String.self, forKey: .websiteURL) self.company = try container.decodeIfPresent(String.self, forKey: .company) } private enum CodingKeys: String, CodingKey { case user case joinedDate = "created_at" case name case email case websiteURL = "blog" case company } public func hash(into hasher: inout Hasher) { user.hash(into: &hasher) } }
mit
ceebf83195fe1cb1a7ea5ae5b6e79934
30.209945
121
0.637458
4.273071
false
false
false
false
mperovic/my41
my41/Classes/RomChip.swift
1
2106
// // RomChip.swift // my41 // // Created by Miroslav Perovic on 8/1/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation final class RomChip { var writable: Bool var words: [word] var actualBankGroup: byte var altPage: ModulePage? var HEPAX: UInt8 = 0 var WWRAMBOX: UInt8 = 0 var RAM: byte = 0 init(isWritable: Bool) { words = [word](repeating: 0x0, count: 0x1000) writable = isWritable actualBankGroup = 1 } convenience init(fromBIN bin: [byte], actualBankGroup bankGroup: byte) { self.init(isWritable: false) binToWords(bin) self.actualBankGroup = bankGroup } convenience init(fromFile path: String) { self.init(isWritable: false) loadFromFile(path) } convenience init() { self.init(isWritable: false) } func binToWords(_ bin: [byte]) { if bin.count == 0 { return } var ptr: Int = 0 // for var idx = 0; idx < 5120; idx += 5 { for idx in stride(from: 0, to: 5120, by: 5) { self.words[ptr] = word(((word(bin[idx+1]) & 0x03) << 8) | word(bin[idx])) ptr += 1 self.words[ptr] = word(((word(bin[idx+2]) & 0x0f) << 6) | ((word(bin[idx+1]) & 0xfc) >> 2)) ptr += 1 self.words[ptr] = word(((word(bin[idx+3]) & 0x3f) << 4) | ((word(bin[idx+2]) & 0xf0) >> 4)) ptr += 1 self.words[ptr] = word((word(bin[idx+4]) << 2) | ((word(bin[idx+3]) & 0xc0) >> 6)) ptr += 1 } } func loadFromFile(_ path: String) { let data: Data? do { data = try Data(contentsOf: URL(fileURLWithPath: path), options: [.mappedIfSafe]) // var range = NSRange(location: 0, length: 2) var location = 0 for idx in 0..<0x1000 { var i16be: UInt16 = 0 var i16: UInt16 = 0 let buffer = UnsafeMutableBufferPointer(start: &i16be, count: 2) let _ = data?.copyBytes(to: buffer, from: location..<location+2) // data?.getBytes(&i16be, range: range) location += 2 i16 = UInt16(bigEndian: i16be) words[idx] = i16 } } catch _ { data = nil } } subscript(addr: Int) -> UInt16 { get { return words[addr] } set { if writable { words[addr] = newValue } } } }
bsd-3-clause
b517c4518f0f38202a7adec740d46f65
21.404255
94
0.603514
2.7
false
false
false
false
BirdBrainTechnologies/Hummingbird-iOS-Support
BirdBlox/BirdBlox/FrontendCallbackCenter.swift
1
7759
// // FrontendCallbackCenter.swift // BirdBlox // // Created by Jeremy Huang on 2017-06-20. // Copyright © 2017年 Birdbrain Technologies LLC. All rights reserved. // import Foundation import WebKit /* A central location for all the javascript callbacks. */ class FrontendCallbackCenter { private static let singleton: FrontendCallbackCenter = FrontendCallbackCenter() private let wvLock = NSCondition() public static var shared: FrontendCallbackCenter { return singleton } public static func safeString(from: String) -> String { return from.addingPercentEncoding(withAllowedCharacters: CharacterSet()) ?? "" } public static func jsonString(from: Any) -> String? { do { let data = try JSONSerialization.data(withJSONObject: from, options: [.prettyPrinted]) return String(data: data, encoding: .utf8) } catch { return nil } } var webView: WKWebView? = nil //MARK: Internal Method private func runJS(function: String, parameters: [String]) -> Bool { guard let wv = self.webView else { return false } let parametersStr = "(" + parameters.map({"'\($0)'"}).joined(separator: ", ") + ")" let js = function + parametersStr // self.wvLock.lock() //This might get run from the main thread. Might will crash if main.sync is called from //the main thread. DispatchQueue.main.async { wv.evaluateJavaScript(js, completionHandler: { ret, error in if let error = error { NSLog("Error running '\(js)': \(error)") return } //print("Ran '\(js)', got \(String(describing: ret))") #if DEBUG //print("Ran '\(js)', got \(String(describing: ret))") #endif }) } // self.wvLock.unlock() return true } //MARK: Dialog Responses private func boolToJSString(_ b: Bool) -> String { return b ? "true" : "" //empty string evaluates to false in Javascript } public func dialogPromptResponded(cancelled: Bool, response: String?) -> Bool { let safeResponse = FrontendCallbackCenter.safeString(from: response ?? "") let function = "CallbackManager.dialog.promptResponded" let parameters = [boolToJSString(cancelled), safeResponse] return self.runJS(function: function, parameters: parameters) } func choiceResponded(cancelled: Bool, firstSelected: Bool) -> Bool { let function = "CallbackManager.dialog.choiceResponded" let parameters = [boolToJSString(cancelled), boolToJSString(firstSelected)] return self.runJS(function: function, parameters: parameters) } //MARK: Robot Related public func robotUpdateStatus(id: String, connected: Bool) -> Bool { let safeResponse = FrontendCallbackCenter.safeString(from: id) let function = "CallbackManager.robot.updateStatus" let parameters = [safeResponse, boolToJSString(connected)] return self.runJS(function: function, parameters: parameters) } public func robotUpdateBattery(id: String, batteryStatus: Int) -> Bool { let safeResponse = FrontendCallbackCenter.safeString(from: id) let function = "CallbackManager.robot.updateBatteryStatus" let parameters = [safeResponse, String(batteryStatus)] return self.runJS(function: function, parameters: parameters) } public func robotCalibrationComplete(id: String, success: Bool) -> Bool { let function = "CallbackManager.robot.compassCalibrationResult" let parameters = [id, String(success)] return self.runJS(function: function, parameters: parameters) } //TODO: Make this for every type of robot public func robotFirmwareIncompatible(robotType: BBTRobotType, id: String, firmware: String) -> Bool { let safeID = FrontendCallbackCenter.safeString(from: id) let safeFirmware = FrontendCallbackCenter.safeString(from: firmware) let function = "CallbackManager.robot.disconnectIncompatible" let parameters = [safeID, safeFirmware, robotType.minimumFirmware] let safeMin = FrontendCallbackCenter.safeString(from: robotType.minimumFirmware) print("Firmware incompatible: \(id), \(firmware), \(safeMin), \(parameters)") return self.runJS(function: function, parameters: parameters) } public func robotDisconnected(name: String) -> Bool { let function = "CallbackManager.robot.connectionFailure" let parameters = [name] return self.runJS(function: function, parameters: parameters) } public func robotFirmwareStatus(id: String, status: String) -> Bool { let safeID = FrontendCallbackCenter.safeString(from: id) let safeSatus = FrontendCallbackCenter.safeString(from: status) let function = "CallbackManager.robot.updateFirmwareStatus" let parameters = [safeID, safeSatus] return self.runJS(function: function, parameters: parameters) } public func scanHasStopped() -> Bool { //let safeType = FrontendCallbackCenter.safeString(from: typeStr) NSLog("Scan has stopped. Notifying frontend.") let function = "CallbackManager.robot.stopDiscover" let parameters: [String] = [] return self.runJS(function: function, parameters: parameters) } public func updateDiscoveredRobotList(robotList: [[String: String]]) -> Bool { //let safeType = FrontendCallbackCenter.safeString(from: typeStr) guard let jsonList = FrontendCallbackCenter.jsonString(from: robotList) else { return false } let safeList = FrontendCallbackCenter.safeString(from: jsonList) let function = "CallbackManager.robot.discovered" let parameters = [safeList] return self.runJS(function: function, parameters: parameters) } //MARK: Updating UI func documentSetName(name: String) -> Bool { let safeName = FrontendCallbackCenter.safeString(from: name) let function = "CallbackManager.data.setName" let parameters = [safeName] return self.runJS(function: function, parameters: parameters) } func markLoadingDocument() -> Bool { let function = "CallbackManager.data.markLoading" let parameters: [String] = [] return self.runJS(function: function, parameters: parameters) } func reloadOpenDialog() -> Bool { let function = "OpenDialog.currentDialog.reloadDialog" let parameters: [String] = [] return self.runJS(function: function, parameters: parameters) } func recordingEnded() -> Bool { let function = "CallbackManager.sounds.recordingEnded" let parameters: Array<String> = [] return self.runJS(function: function, parameters: parameters) } //MARK: misc., utility func echo(getRequestString: String) -> Bool { let function = "CallbackManager.echo" let parameters = [FrontendCallbackCenter.safeString(from: getRequestString)] return self.runJS(function: function, parameters: parameters) } func sendFauxHTTPResponse(id: String, status: Int, obody: String?) -> Bool { let body = obody ?? "" let function = "CallbackManager.httpResponse" let parameters = [id, status.description, FrontendCallbackCenter.safeString(from: body)] return self.runJS(function: function, parameters: parameters) } //When the app is sent to the background, we need to stop any running code func stopExecution() -> Bool { return self.runJS(function: "CodeManager.stop", parameters: []) } func setLanguage(_ lang: String) -> Bool { let function = "CallbackManager.tablet.getLanguage" let parameters = [lang] return self.runJS(function: function, parameters: parameters) } func setFilePreference(_ fileName: String) -> Bool { let function = "CallbackManager.setFilePreference" let parameters = [fileName] print("setting file \(parameters)") return self.runJS(function: function, parameters: parameters) } }
mit
41a29da625e442e55037cafe922fa708
31.588235
106
0.704874
3.955125
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Views/CarouselCollectionView/CarouselCollectionViewFlowLayout.swift
1
1111
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit class CarouselCollectionViewFlowLayout: UICollectionViewFlowLayout { override init() { super.init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** This method sets up various properties of the carousel collectionview */ override func prepareLayout() { if let collectionView = self.collectionView { collectionView.pagingEnabled = true self.scrollDirection = .Horizontal self.minimumLineSpacing = 0 let viewSize = collectionView.bounds.size setItemSize(viewSize) } } /** This method sets the item size for each cell of the carousel collectionview. - parameter viewSize: <#viewSize description#> */ private func setItemSize(viewSize: CGSize){ let itemSize = CGSize(width: viewSize.width - minimumLineSpacing, height: viewSize.height) self.itemSize = itemSize } }
epl-1.0
08b10d4c9a679d246bff9f7e9b9526f8
25.428571
98
0.63964
5.441176
false
false
false
false
zhao765882596/XImagePickerController
XImagePickerController/Classes/Bundle_XMImagePicker.swift
1
1345
// // File.swift // channel_sp // // Created by ming on 2017/10/17. // Copyright © 2017年 TiandaoJiran. All rights reserved. // import Foundation extension Bundle { private static var imagePickerBundle: Bundle? private static var localizedBundle: Bundle? static var xm_imagePickerBundle: Bundle { if imagePickerBundle == nil { let frameworkBundle = Bundle.init(for: XMImagePickerController.classForCoder()) imagePickerBundle = Bundle.init(path: frameworkBundle.path(forResource: "XImagePickerController", ofType: "bundle") ?? "") } return imagePickerBundle ?? Bundle.main } class func xm_localizedString(key: String) -> String { return Bundle.xm_localizedString(key: key, value: "") } class func xm_localizedString(key: String, value: String) -> String { if localizedBundle == nil { var language = Locale.preferredLanguages.first if language?.range(of: "zh-Hans") != nil { language = "zh-Hans" } else { language = "en" } localizedBundle = Bundle.init(path: xm_imagePickerBundle.path(forResource: language, ofType: "lproj") ?? "") } return localizedBundle?.localizedString(forKey: key, value: value, table: nil) ?? key } }
mit
c3b686ffe42f616d0a23bae69b8585ed
35.27027
134
0.623696
4.357143
false
false
false
false
nsgeek/ELRouter
ELRouter/RouteSpec.swift
1
1791
// // RouteSpec.swift // ELRouter // // Created by Brandon Sneed on 4/19/16. // Copyright © 2016 theholygrail.io. All rights reserved. // import Foundation public protocol RouteEnum { var spec: RouteSpec { get } } /** Use a RouteSpec to document and define your routes. Example: struct WMListItemSpec: AssociatedData { let blah: Int } enum WishListRoutes: Int, { case AddToList case DeleteFromList var spec: RouteSpec { switch self { case .AddToList: return (name: "AddToList", exampleURL: "scheme://item/<variable>/addToList") case .DeleteFromList: return (name: "DeleteFromList", exampleURL: "scheme://item/<variable>/deleteFromList") } } } */ public typealias RouteSpec = (name: String, type: RoutingType, example: String?) /** */ public func Variable(value: String) -> RouteEnum { class VariableRoute: RouteEnum { var value: String var spec: RouteSpec { return (name: value, type: .Variable, example: nil) } init(_ rawValue: String) { value = rawValue } } let variable = VariableRoute(value) return variable } internal struct Redirection: RouteEnum { var name: String var spec: RouteSpec { // type and exampleURL are irrelevant, name is the only important piece here. return (name: name, type: .Other, example: nil) } init(name value: String) { name = value } } internal func routeEnumsFromComponents(components: [String]) -> [RouteEnum] { var result = [RouteEnum]() components.forEach { (component) in result.append(Redirection(name: component)) } return result }
mit
8eae50531eaebc00d8bdfbe83e2e5e69
21.658228
120
0.605587
4.143519
false
false
false
false
alessiobrozzi/firefox-ios
ClientTests/UIPasteboardExtensionsTests.swift
10
1726
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import MobileCoreServices import UIKit import XCTest class UIPasteboardExtensionsTests: XCTestCase { fileprivate var pasteboard: UIPasteboard! override func setUp() { super.setUp() pasteboard = UIPasteboard.withUniqueName() } override func tearDown() { super.tearDown() UIPasteboard.remove(withName: pasteboard.name) } func testAddPNGImage() { let path = Bundle(for: self.classForCoder).path(forResource: "image", ofType: "png")! let data = try! Data(contentsOf: URL(fileURLWithPath: path)) let url = URL(string: "http://foo.bar")! pasteboard.addImageWithData(data, forURL: url) verifyPasteboard(expectedURL: url, expectedImageTypeKey: kUTTypePNG) } func testAddGIFImage() { let path = Bundle(for: self.classForCoder).path(forResource: "image", ofType: "gif")! let data = try! Data(contentsOf: URL(fileURLWithPath: path)) let url = URL(string: "http://foo.bar")! pasteboard.addImageWithData(data, forURL: url) verifyPasteboard(expectedURL: url, expectedImageTypeKey: kUTTypeGIF) } fileprivate func verifyPasteboard(expectedURL: URL, expectedImageTypeKey: CFString) { XCTAssertEqual(pasteboard.items.count, 1) XCTAssertEqual(pasteboard.items[0].count, 2) XCTAssertEqual(pasteboard.items[0][kUTTypeURL as String] as? URL, expectedURL) XCTAssertNotNil(pasteboard.items[0][expectedImageTypeKey as String]) } }
mpl-2.0
1a6773a2cf3c5d9f4a32fbc8b20d219d
35.723404
93
0.690035
4.380711
false
true
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Persistence/Migrations/DatabaseMigration+Result.swift
2
2544
// // DatabaseMigration+Result.swift // SmartReceipts // // Created by Bogdan Evsenev on 30/03/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import Foundation import MessageUI private let FAILED_MIGRATION_COUNT_KEY = "db.migration.failed.count" private let FAILS_TO_REPORT = 3 extension DatabaseMigrator { func processFailedMigration(databasePath: String) { Logger.error("Database Migration Failed!") let failsCount = UserDefaults.standard.integer(forKey: FAILED_MIGRATION_COUNT_KEY) + 1 UserDefaults.standard.set(failsCount, forKey: FAILED_MIGRATION_COUNT_KEY) guard failsCount >= FAILS_TO_REPORT else { exit(0); } let window = UIWindow(frame: UIScreen.main.bounds) (UIApplication.shared.delegate as? AppDelegate)?.window = window window.rootViewController = UIViewController() let imageView = UIImageView(image: #imageLiteral(resourceName: "launch_image")) imageView.contentMode = .scaleAspectFill imageView.frame = CGRect(origin: .zero, size: UIScreen.main.bounds.size) window.rootViewController?.view.addSubview(imageView) window.makeKeyAndVisible() let title = LocalizedString("generic_error_alert_title") let message = LocalizedString("migration_failed_alert_message") let style: UIAlertController.Style = .alert let actionSheet = UIAlertController(title: title, message: message, preferredStyle: style) let report = UIAlertAction(title: LocalizedString("migration_failed_alert_send_button"), style: .default, handler: { [weak self] _ in let backup = DataExport(workDirectory: FileManager.documentsPath).execute() let data = try! Data(contentsOf: backup.asFileURL) let attachment = FeedbackAttachment(data: data, mimeType: "application/zip", fileName: SmartReceiptsExportName) let subject = "Database Migration Failed - Report" self?.feedbackComposer.present(on: window.rootViewController!, subject: subject, attachments: [attachment]) }) let cancel = UIAlertAction(title: LocalizedString("DIALOG_CANCEL"), style: .cancel, handler: nil) actionSheet.addAction(report) actionSheet.addAction(cancel) window.rootViewController?.present(actionSheet, animated: true) } func processSuccessMigration() { UserDefaults.standard.set(0, forKey: FAILED_MIGRATION_COUNT_KEY) } }
agpl-3.0
b33155d9bd07efb7a0dd4b771123aeab
42.101695
141
0.684624
4.700555
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/EVEMemberTracking.swift
1
2523
// // EVEMemberTracking.swift // EVEAPI // // Created by Artem Shimanski on 30.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit public class EVEMemberTrackingItem: EVEObject { public var characterID: Int64 = 0 public var name: String = "" public var startDateTime: Date = Date.distantPast public var baseID: Int = 0 public var base: String = "" public var title: String = "" public var logonDateTime: Date = Date.distantPast public var logoffDateTime: Date = Date.distantPast public var locationID: Int64 = 0 public var location: String = "" public var shipTypeID: Int = 0 public var shipType: String = "" public var roles: Int64 = 0 public var grantableRoles: Int64 = 0 public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "characterID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "name":EVESchemeElementType.String(elementName:nil, transformer:nil), "startDateTime":EVESchemeElementType.Date(elementName:nil, transformer:nil), "baseID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "base":EVESchemeElementType.String(elementName:nil, transformer:nil), "title":EVESchemeElementType.String(elementName:nil, transformer:nil), "logonDateTime":EVESchemeElementType.Date(elementName:nil, transformer:nil), "logoffDateTime":EVESchemeElementType.Date(elementName:nil, transformer:nil), "locationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "location":EVESchemeElementType.String(elementName:nil, transformer:nil), "shipTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "shipType":EVESchemeElementType.String(elementName:nil, transformer:nil), "roles":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "grantableRoles":EVESchemeElementType.Int64(elementName:nil, transformer:nil), ] } } public class EVEMemberTracking: EVEResult { public var members: [EVEMemberTrackingItem] = [] public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "members":EVESchemeElementType.Rowset(elementName: nil, type: EVEMemberTrackingItem.self, transformer: nil), ] } }
mit
b5590a5a7dae8b8e78a2b8b30d21d798
34.027778
111
0.760508
3.792481
false
false
false
false
Pocketbrain/nativeadslib-ios
PocketMediaNativeAds/Adunits/NativeAdTableViewCellRegular.swift
1
2761
// // NativeAdCell.swift // PocketMediaNativeAds // // Created by Pocket Media on 29/02/16. // Copyright © 2016 Pocket Media. All rights reserved. // import UIKit /** Standard AdUnit for TableView **/ open class NativeAdTableViewCellRegular: UITableViewCell, NativeViewCell { @IBOutlet weak var speakerPhone: UIImageView? @IBOutlet weak var adImage: UIImageView? @IBOutlet weak var adTitle: UILabel? @IBOutlet weak var adDescription: UILabel? @IBOutlet weak var installButton: UIButton? /// The ad shown in this cell. fileprivate(set) open var ad: NativeAd? /** Called to define what ad should be shown. */ open func render(_ nativeAd: NativeAd, completion handler: @escaping ((Bool) -> Swift.Void)) { self.ad = nativeAd if let button = installButton { setupInstallButton(button) } if let image = adImage { setupAdImage(image) } if let ad_description = adDescription { ad_description.text = ad!.campaignDescription } if let title = adTitle { title.text = ad!.campaignName } self.selectionStyle = UITableViewCellSelectionStyle.none } internal func setupAdImage(_ image: UIImageView) { image.nativeSetImageFromURL(ad!.campaignImage) image.layer.cornerRadius = image.frame.width / 10 image.layer.masksToBounds = true } internal func setupInstallButton(_ button: UIButton) { button.layer.borderColor = self.tintColor.cgColor button.layer.borderWidth = 1 button.layer.masksToBounds = true button.titleLabel?.baselineAdjustment = .alignCenters button.titleLabel?.textAlignment = .center button.titleLabel?.minimumScaleFactor = 0.1 let color = UIColor( red: 17.0 / 255.0, green: 147.0 / 255.0, blue: 67.0 / 255.0, alpha: 1) button.setTitleColor(color, for: UIControlState()) button.layer.borderColor = color.cgColor button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) button.titleLabel?.minimumScaleFactor = 0.50 button.titleLabel?.adjustsFontSizeToFitWidth = true if let image = adImage { button.layer.cornerRadius = image.frame.width / 20 } button.setTitle(ad!.callToActionText, for: .normal) } /** Called when the user presses on the call to action button */ @IBAction func install(_ sender: AnyObject) { if let viewController = UIApplication.shared.delegate?.window??.rootViewController { self.ad?.openAdUrl(FullscreenBrowser(parentViewController: viewController)) } } }
mit
ac14a5a6a424727d493fe14ee380662b
30.363636
98
0.641667
4.592346
false
false
false
false
LucianoPolit/RepositoryKit
Source/Bonus/NetworkingSession.swift
1
5494
// // NetworkingSession.swift // // Copyright (c) 2016-2017 Luciano Polit <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import PromiseKit // MARK: - Main /// A networking session that makes requests to a server (which url is specified). open class NetworkingSession: Networking { // MARK: - Properties /// The url of the server. open var url: String /// A `Dictionary` with the HTTP request headers. open var requestHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ] // MARK: - Initializers /// Initializes and returns a newly allocated object with the specified url. public init(url: String) { self.url = url self.initConfiguration() } // MARK: - Request /** Creates a promise with the response of a request for the specified method, url, parameters and headers. - Parameter method: The HTTP method. - Parameter path: The path of the URL. - Parameter parameters: The parameters (nil by default). - Parameter headers: The HTTP headers (nil by default). - Returns: A promise of `Any`. */ open func request(method: HTTPMethod, path: String, parameters: [String: Any]? = nil, headers: [String: String]? = nil) -> Promise<Any> { return requestWithData(method, "\(url)/\(path)", parameters: parameters, headers: headers) .then { request in Promise { success, failure in URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Swift.Error?) in guard error == nil else { failure(Error.other(error!)) return } guard let data = data, let response = response as? HTTPURLResponse else { failure(Error.badResponse) return } switch response.statusCode { case 200...299: break default: failure(Error.server(statusCode: response.statusCode)) } do { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) success(json) } catch { failure(Error.parsing) } }.resume() } } } } // MARK: - Util extension NetworkingSession { fileprivate func initConfiguration() { URLSession.shared.configuration.urlCache = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil) } fileprivate func requestWithData(_ method: HTTPMethod, _ urlString: String, parameters: [String: Any]?, headers: [String: String]?) -> Promise<URLRequest> { return Promise { success, failure in guard let url = URL(string: urlString) else { failure(Error.badRequest) return } var request = URLRequest(url: url) request.httpMethod = method.rawValue if headers != nil { for (key, value) in headers! { requestHeaders[key] = value } } for (key, value) in requestHeaders { request.addValue(value, forHTTPHeaderField: key) } guard let params = parameters else { success(request) return } do { let body = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions()) request.httpBody = body } catch { failure(Error.parsing) } success(request as URLRequest) } } }
mit
bd9334f3518a0967a4c4618a33af2b5c
34.908497
128
0.535311
5.494
false
false
false
false
swifty-iOS/MBPickerView
Sample/ViewController.swift
1
3747
// // ViewController.swift // Sample // // Created by Manish Bhande on 14/05/17. // Copyright © 2017 Manish Bhande. All rights reserved. // import UIKit struct AppName { var title: String = "" var image: UIImage? static func defaultApps() -> [AppName] { return [AppName(title: "Amazon", image: #imageLiteral(resourceName: "Amazon")), AppName(title: "Android", image: #imageLiteral(resourceName: "Android")), AppName(title: "Blackberry", image: #imageLiteral(resourceName: "Blackberry")), AppName(title: "Chrome", image: #imageLiteral(resourceName: "Chrome")), AppName(title: "Facebook", image: #imageLiteral(resourceName: "Facebook")), AppName(title: "Google Drive", image: #imageLiteral(resourceName: "GoogleDrive")), AppName(title: "Messenger", image: #imageLiteral(resourceName: "Messenger")), AppName(title: "Twitter", image: #imageLiteral(resourceName: "Twitter")), AppName(title: "Whats app", image: #imageLiteral(resourceName: "Whatsapp")), AppName(title: "Youtube", image: #imageLiteral(resourceName: "Youtube"))] } } class ViewController: UIViewController { @IBOutlet weak var label: UILabel! @IBOutlet weak var pagePickerView: MBPickerView! @IBOutlet weak var pageSlider: UISlider! @IBOutlet weak var pageScaleSlider: UISlider! @IBOutlet weak var labelPageScale: UILabel! let apps = AppName.defaultApps() override func viewDidLoad() { super.viewDidLoad() pagePickerView.selectItem(2, animation: false) pagePickerView.showAllItem = UIDevice.current.userInterfaceIdiom == .pad pagePickerView.delegate = self pagePickerView.dataSource = self pagePickerView.allowSelectionWhileScrolling = false // pagePickerView.selectItem(2, animation: true) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderViewChanged(_ sender: UISlider) { if pagePickerView.currentItem != Int(sender.value) { pagePickerView.selectItem(Int(sender.value), animation: true) } } @IBAction func pageScaleChange(_ sender: UISlider) { pagePickerView.itemPadingScale = CGFloat(sender.value) labelPageScale.text = "Select page scale: \(sender.value)" } } extension ViewController: MBPickerViewDelegate, MBPickerViewDataSource { func pickerViewNumberOfItems(_ pickerView: MBPickerView) -> Int { pageSlider.maximumValue = max(0, Float(apps.count-1)) pageScaleSlider.maximumValue = max(0, Float(apps.count-1)) pageScaleSlider.value = Float(pagePickerView.itemPadingScale) labelPageScale.text = "Select page scale: \(pageScaleSlider.value)" return apps.count } func pickerView(_ pickerView: MBPickerView, viewAtItem item: Int) -> UIView { if let view = PickerCell.loadFromNib() { view.imageView.image = apps[item].image view.labelTitle.text = apps[item].title view.alpha = pickerView.currentItem == item ? 1 : 0.3 view.backgroundColor = .clear return view } return UIView() } func pickerView(_ pickerView: MBPickerView, titleAtItem item: Int) -> String { return "Page \(item+1)" } func pickerView(_ pickerView: MBPickerView, didSelectItem item: Int) { print("Select item \(item+1) = \(Date())") label.text = "Selected item: \(item+1)" pageSlider.value = Float(item) } }
mit
a4fa6b5a4aadeff46a53073adc3e8e6e
36.46
90
0.655099
4.438389
false
false
false
false
maranathApp/GojiiFramework
GojiiFrameWork/UIViewControllerExtensions.swift
1
3518
// // CGFloatExtensions.swift // GojiiFrameWork // // Created by Stency Mboumba on 01/06/2017. // Copyright © 2017 Stency Mboumba. All rights reserved. // import UIKit /* --------------------------------------------------------------------------- */ // MARK: - Extensions UIViewController /* --------------------------------------------------------------------------- */ public extension UIViewController { /* --------------------------------------------------------------------------- */ // MARK: - UIViewController → Initilized ( init ) /* --------------------------------------------------------------------------- */ /** Init with view - parameter view: UIView - returns: UIViewController */ public convenience init(view:UIView) { self.init() view.frame = self.view.frame self.view = view } /* --------------------------------------------------------------------------- */ // MARK: - UIViewController → TabBar / Navigation bar /* --------------------------------------------------------------------------- */ /// Tab bar height public var tabBarHeight: CGFloat { get { if let me = self as? UINavigationController { return me.visibleViewController!.tabBarHeight } if let tab = self.tabBarController { return tab.tabBar.frame.size.height } return 0 } } /// Navigation bar public var navBar: UINavigationBar? { get { return navigationController?.navigationBar } } /// Navigation Bar Height public var navigationBarHeight: CGFloat { get { if let me = self as? UINavigationController { return me.visibleViewController!.navigationBarHeight } if let nav = self.navigationController { return nav.navigationBar.height } return 0 } } /// Navigation bar color public var navigationBarColor: UIColor? { get { if let me = self as? UINavigationController { return me.visibleViewController!.navigationBarColor } return navigationController?.navigationBar.tintColor } set(value) { navigationController?.navigationBar.barTintColor = value } } /* --------------------------------------------------------------------------- */ // MARK: - UIViewController → Notification /* --------------------------------------------------------------------------- */ /** Add Notification Observer - parameter name: String <br> **"com.app.labelViewButton"** - parameter selector: Selector */ public func addNotificationObserver(name: String, selector: Selector) { NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(name), object: nil) } /** Remove Notification Observer - parameter name: String */ public func removeNotificationObserver(name: String) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: name), object: nil) } /** Remove All Observer */ public func removeNotificationObserver() { NotificationCenter.default.removeObserver(self) } }
mit
897958627f42d71a197eba4b7b99068f
31.211009
118
0.469097
6.383636
false
false
false
false
spritekitbook/spritekitbook-swift
Bonus/SpaceRunner/SpaceRunner/GameFonts.swift
1
2602
// // GameFonts.swift // SpaceRunner // // Created by Jeremy Novak on 9/8/16. // Copyright © 2016 Spritekit Book. All rights reserved. // import SpriteKit class GameFonts { static let sharedInstance = GameFonts() // MARK: - Public Enum enum LabelType { case label, bonus, message } // MARK: - Private class constants private let labelSize:CGFloat = 16.0 private let bonusSize:CGFloat = 36.0 private let messageSize:CGFloat = 24.0 // MARK: - Private class variables private var label = SKLabelNode() // MARK: - Init init() { setup() } // MARK: - Setup private func setup() { label = SKLabelNode(fontNamed: kFont) label.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center } // MARK: - Label creation func createLabel(string: String, type: LabelType) -> SKLabelNode { let copiedLabel = label.copy() as! SKLabelNode switch type { case .label: copiedLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left copiedLabel.fontColor = Colors.colorFromRGB(rgbvalue: Colors.score) copiedLabel.fontSize = labelSize copiedLabel.text = string case .bonus: copiedLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center copiedLabel.fontColor = Colors.colorFromRGB(rgbvalue: Colors.bonus) copiedLabel.fontSize = bonusSize copiedLabel.text = string case .message: copiedLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center copiedLabel.fontColor = Colors.colorFromRGB(rgbvalue: Colors.border) copiedLabel.fontSize = messageSize copiedLabel.text = string } return copiedLabel } // MARK: - Actions func animate(label: SKLabelNode) -> SKAction { let action = SKAction.run({ label.run(SKAction.fadeIn(withDuration: 0.1), completion: { label.run(SKAction.scale(to: 1.25, duration: 0.1), completion: { label.run(SKAction.moveTo(y: label.position.y + label.frame.size.height * 2, duration: 0.1), completion: { label.run(SKAction.fadeOut(withDuration: 0.1), completion: { label.removeFromParent() }) }) }) }) }) return action } }
apache-2.0
886d6f040cd52b0c64a5184c23675c3b
28.896552
126
0.578624
5.011561
false
false
false
false
jaiversin/AppsCatalog
AppsCatalog/Modules/AppList/AppListWireframe.swift
1
1749
// // AppListWireframe.swift // AppsCatalog // // Created by Jhon López on 5/23/16. // Copyright © 2016 jaiversin. All rights reserved. // import Foundation import UIKit class AppListWireframe: BaseWireframe, UIViewControllerTransitioningDelegate { var appListPresenter:AppListPresenter? var currentViewController: UIViewController? func presentAppListFromController(viewController: UIViewController){ let appListViewController = self.listViewControllerFromStoryboard() appListViewController.transitioningDelegate = self appListViewController.appListPresenter = appListPresenter appListPresenter?.appListView = appListViewController viewController.presentViewController(appListViewController, animated: true) { } currentViewController = viewController } func dismissAppListController(){ currentViewController?.dismissViewControllerAnimated(true, completion: { }) } // MARK: Funciones utilitarias func listViewControllerFromStoryboard() -> AppListViewController { let viewController = viewControllerFromStoryboardWithIdentifier("AppsList") as! AppListViewController return viewController } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AppListPresentationTransition() } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AppListDismissTransition() } }
mit
ed99ce0e935925673bd439c29fdc8b8e
33.96
217
0.736691
6.797665
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift
12
2061
// // ConnectableObservable.swift // Rx // // Created by Krunoslav Zaher on 3/1/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Connection<S: SubjectType> : Disposable { // state weak var parent: ConnectableObservable<S>? var subscription : Disposable? init(parent: ConnectableObservable<S>, subscription: Disposable) { self.parent = parent self.subscription = subscription } func dispose() { guard let parent = self.parent else { return } parent.lock.performLocked { guard let oldSubscription = self.subscription else { return } self.subscription = nil if let parent = self.parent { parent.connection = nil } self.parent = nil oldSubscription.dispose() } } } public class ConnectableObservable<S: SubjectType> : Observable<S.E>, ConnectableObservableType { typealias ConnectionType = Connection<S> let subject: S let source: Observable<S.SubjectObserverType.E> let lock = NSRecursiveLock() // state var connection: ConnectionType? public init(source: Observable<S.SubjectObserverType.E>, subject: S) { self.source = AsObservable(source: source) self.subject = subject self.connection = nil } public func connect() -> Disposable { return self.lock.calculateLocked { if let connection = self.connection { return connection } let disposable = self.source.subscribeSafe(self.subject.asObserver()) let connection = Connection(parent: self, subscription: disposable) self.connection = connection return connection } } public override func subscribe<O : ObserverType where O.E == S.E>(observer: O) -> Disposable { return subject.subscribeSafe(observer) } }
mit
7d3a087e1e58689859a99fd12cf0123b
26.864865
98
0.595827
5.126866
false
false
false
false
mitsuaki1229/BeaconDetection
BeaconDetection/Setting/SettingViewModel.swift
1
2500
// // SettingViewModel.swift // BeaconDetection // // Created by Mitsuaki Ihara on 2017/07/30. // Copyright © 2017年 Mitsuaki Ihara. All rights reserved. // import RxDataSources struct SettinglistData { var title: String } struct SectionSettingListData { var header: String var items: [Item] } extension SectionSettingListData: SectionModelType { typealias Item = SettinglistData init(original: SectionSettingListData, items: [Item]) { self = original self.items = items } } enum SettinglistType: Int { case readme = 0 case license = 1 case version = 2 case clearTips = 3 } class SettingViewModel: NSObject { let dataSource = RxTableViewSectionedReloadDataSource<SectionSettingListData>(configureCell: {_, tableView, indexPath, _ in let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) return cell }) var sections: [SectionSettingListData] { let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return [ SectionSettingListData(header: "", items: [ SettinglistData(title: "README"), SettinglistData(title: "LICENSE"), SettinglistData(title: "Version:" + version), SettinglistData(title: "Clear Checked Tips") ]) ] } override init() { super.init() dataSource.configureCell = {_, tv, ip, item in let cell = tv.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell") cell.textLabel?.text = item.title switch SettinglistType(rawValue: ip.row)! { case .readme, .license: cell.selectionStyle = .default cell.accessoryType = .disclosureIndicator case .clearTips: cell.selectionStyle = .default cell.accessoryType = .none case .version: cell.selectionStyle = .none cell.accessoryType = .none } return cell } dataSource.titleForHeaderInSection = {ds, index in ds.sectionModels[index].header } } func clearCheckedTips() { UserDefaults().set(0, forKey: Const.kCheckedTipsUserDefaultKey) } }
mit
9e3b9b59da263189f36bf76b2a8963c7
26.744444
127
0.589908
5.044444
false
false
false
false
rwbutler/TypographyKit
TypographyKit/Classes/NSLineBreakMode.swift
1
655
// // NSLineBreakMode.swift // TypographyKit // // Created by Ross Butler on 21/01/2020. // import Foundation import UIKit extension NSLineBreakMode { init?(string: String) { switch string { case "char-wrap": self = .byCharWrapping case "clip": self = .byClipping case "truncate-head": self = .byTruncatingHead case "truncate-middle": self = .byTruncatingMiddle case "truncate-tail": self = .byTruncatingTail case "word-wrap": self = .byWordWrapping default: return nil } } }
mit
d1677c37918cfbeca95f46198bde3066
19.46875
41
0.535878
4.781022
false
false
false
false
ichu501/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/CommandBuffer.swift
2
1737
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation /** A Sink of raw data, which will result in command/s occuring when a full command is encountered. */ protocol CommandBuffer { var performer: CommandPerformer { get } var reporter: EventReporter { get } func append(_ data: Data) -> [CommandResult] } /** A CommandBuffer that will dispatch a command when a newline is encountered. */ class LineBuffer : CommandBuffer { internal let performer: CommandPerformer internal let reporter: EventReporter fileprivate var buffer: String = "" init (performer: CommandPerformer, reporter: EventReporter) { self.performer = performer self.reporter = reporter } func append(_ data: Data) -> [CommandResult] { let string = String(data: data, encoding: String.Encoding.utf8)! self.buffer.append(string) return self.runBuffer() } fileprivate func runBuffer() -> [CommandResult] { let buffer = self.buffer let lines = buffer .components(separatedBy: CharacterSet.newlines) .filter { line in line != "" } if (lines.isEmpty) { return [] } self.buffer = "" var results: [CommandResult] = [] DispatchQueue.main.sync { for line in lines { results.append(self.lineAvailable(line)) } } return results } fileprivate func lineAvailable(_ line: String) -> CommandResult { return self.performer.perform(line, reporter: self.reporter) } }
bsd-3-clause
f34ecbe57616f265f9fbd668e6f1cd5e
26.140625
96
0.684514
4.185542
false
false
false
false
Matzo/Kamishibai
Kamishibai/Classes/KamishibaiScene.swift
1
2334
// // KamishibaiScene.swift // Pods // // Created by Keisuke Matsuo on 2017/08/12. // // import Foundation public typealias KamishibaiSceneBlock = ((KamishibaiScene) -> Void) public class KamishibaiScene: NSObject { // MARK: Properties public weak var kamishibai: Kamishibai? public var identifier: KamishibaiSceneIdentifierType? public var transition: KamishibaiTransitioningType? public var sceneBlock: KamishibaiSceneBlock var fulfillGestures: [UIGestureRecognizer] = [] var isFinished: Bool = false var tapInRect: CGRect? // MARK: Initialization public init(id: KamishibaiSceneIdentifierType? = nil, transition: KamishibaiTransitioningType? = nil, scene: @escaping KamishibaiSceneBlock) { self.identifier = id self.transition = transition self.sceneBlock = scene } // MARK: Public Methods public func fulfill() { kamishibai?.fulfill(scene: self) disposeGestures() } public func fulfillWhenTap(view: UIView, inRect: CGRect? = nil) { // addTapGesture to view let tap = UITapGestureRecognizer(target: self, action: #selector(KamishibaiScene.didTapFulfill(gesture:))) view.addGestureRecognizer(tap) self.fulfillGestures.append(tap) tapInRect = inRect } public func fulfillWhenTapFocus() { guard let kamishibai = kamishibai else { return } guard let focus = kamishibai.focus.focusView.focus else { return } fulfillWhenTap(view: kamishibai.focus.view, inRect: focus.frame) } // MARK: Private Methods func disposeGestures() { fulfillGestures.forEach { (gesture) in gesture.view?.removeGestureRecognizer(gesture) } fulfillGestures.removeAll() } @objc func didTapFulfill(gesture: UITapGestureRecognizer) { if let inRect = tapInRect, let view = gesture.view { let point = gesture.location(in: view) if inRect.contains(point) { fulfill() } } else { fulfill() } } } public func == (l: KamishibaiScene, r: KamishibaiScene) -> Bool { if l === r { return true } guard let lId = l.identifier, let rId = r.identifier else { return false } return lId == rId }
mit
b1b1f8b6305aba01b9cd75e9d27f6b6d
29.311688
114
0.641817
4.658683
false
false
false
false
ali-zahedi/AZViewer
AZViewer/AZLabelIcon.swift
1
1799
// // AZLabelIcon.swift // AZViewer // // Created by Ali Zahedi on 2/14/1396 AP. // Copyright © 1396 AP Ali Zahedi. All rights reserved. // import Foundation public class AZLabelIcon: AZLabel { // MARK: IBInspectable @IBInspectable public var leftIcon: UIImage? { didSet { updateView() } } @IBInspectable var leftPadding: CGFloat = AZStyle.shared.sectionInputLeftPadding @IBInspectable var color: UIColor = AZStyle.shared.sectionInputIconColor { didSet { updateView() } } // MARK: Public // MARK: Private fileprivate var leftImageView: AZImageView = AZImageView() // MARK: Init override public init(frame: CGRect) { super.init(frame: frame) self.defaultInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.defaultInit() } // MARK: Function internal override func defaultInit(){ super.defaultInit() // add view for v in [leftImageView] as [UIView]{ v.translatesAutoresizingMaskIntoConstraints = false self.addSubview(v) } // prepare left image self.prepareLeftImageView() } // update view fileprivate func updateView() { self.leftImageView.image = self.leftIcon self.leftImageView.tintColor = self.color } } // prepare extension AZLabelIcon{ fileprivate func prepareLeftImageView(){ self.leftImageView.contentMode = .scaleAspectFit _ = self.leftImageView.aZConstraints.parent(parent: self).centerY().left(constant: self.leftPadding).width(constant: 20).height(to: self.leftImageView, toAttribute: .width) } }
apache-2.0
aaaf94c995b4672d2c4a26ddec319acb
23.972222
180
0.618465
4.586735
false
false
false
false
transparentmask/CheckIn
CheckIn/CIMainListViewController.swift
1
8924
// // CIMainListViewController.swift // CheckIn // // Created by Martin Yin on 10/05/2017. // Copyright © 2017 Martin Yin. All rights reserved. // import UIKit //class CIAppInfoCell: UITableViewCell { // // @IBOutlet var imageView: UIImageView? //} class CIMainListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView? = nil @IBOutlet var editButton: UIBarButtonItem? = nil @IBOutlet var startButton: UIBarButtonItem? = nil @IBOutlet var settingsButton: UIBarButtonItem? = nil @IBOutlet var addNewButton: UIButton? = nil var inCheckinLoop: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. addNewButton?.isHidden = true addNewButton?.alpha = 0 NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } override func viewWillAppear(_ animated: Bool) { tableView?.reloadData() startButton?.isEnabled = !CILocalApps.shared.isAllOpened() super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func applicationDidBecomeActive(_ notification: NSNotification) { tableView?.reloadData() if inCheckinLoop { DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute: { self.openApp({ result in if !result { self.navigationItem.rightBarButtonItem?.isEnabled = true self.navigationItem.leftBarButtonItem?.isEnabled = true self.inCheckinLoop = false if CILocalApps.shared.isAllOpened() { self.startButton?.isEnabled = false let alert = UIAlertController(title: "今日签到完毕", message: "记得明天再来哦!", preferredStyle: .alert) let doneAction = UIAlertAction(title: "知道了", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) }) alert.addAction(doneAction) self.navigationController?.present(alert, animated: true, completion: nil) } else { self.startButton?.isEnabled = true self.showOpenError(CILocalApps.shared.uncheckinApp()) } } }) }) } } override func setEditing(_ editing: Bool, animated: Bool) { tableView?.setEditing(editing, animated: true) addNewButton?.isHidden = false UIView.animate(withDuration: 0.3, animations: { self.addNewButton?.alpha = editing ? 1 : 0 }) { result in self.addNewButton?.isHidden = !editing } if editing { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelEdit(_:))) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(finishEdit(_:))) } else { navigationItem.leftBarButtonItem = editButton navigationItem.rightBarButtonItem = startButton } super.setEditing(editing, animated: animated) } @IBAction func doModifyList(_ sender: Any) { self.setEditing(true, animated: true) } @IBAction func doStartCheckIn(_ sender: Any) { openApp { result in if result { self.navigationItem.rightBarButtonItem?.isEnabled = false self.navigationItem.leftBarButtonItem?.isEnabled = false self.inCheckinLoop = true } else { self.showOpenError(CILocalApps.shared.uncheckinApp()) } } } func openApp(_ completion: ((Bool) -> Swift.Void)? = nil) { if let app = CILocalApps.shared.uncheckinApp() { app.open(completion) } else if let completion = completion { completion(false) } } func showOpenError(_ appInfo: CIAppInfo? = nil) { let alert = UIAlertController(title: "出错啦", message: "可能是未知错误", preferredStyle: .alert) if let app = appInfo { alert.message = "\(app.name!) 无法打开" } let doneAction = UIAlertAction(title: "知道了", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) }) alert.addAction(doneAction) self.navigationController?.present(alert, animated: true, completion: nil) } func cancelEdit(_ sender: Any) { self.setEditing(false, animated: true) CILocalApps.shared.loadList() tableView?.reloadData() } func finishEdit(_ sender: Any) { self.setEditing(false, animated: true) CILocalApps.shared.saveList() tableView?.reloadData() } @IBAction func doAddNewApp(_ sender: Any) { performSegue(withIdentifier: "ShowAddApp", sender: nil) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowAddApp" { } } // MARK: - Table View func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return CILocalApps.shared.allApps.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CIAppInfoCell", for: indexPath) let app = CILocalApps.shared.allApps[indexPath.row] if let iconURL = app.iconURL, let url = URL(string: iconURL) { cell.imageView?.sd_setImage(with: url, placeholderImage: UIImage(named: "defaultIcon")) cell.imageView?.layer.cornerRadius = 4 } cell.textLabel?.text = app.name cell.accessoryType = app.alreadyOpen ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.detailButton return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let app = CILocalApps.shared.allApps[indexPath.row] app.open { result in if !result { self.showOpenError(app) } } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let app = CILocalApps.shared.allApps[indexPath.row] let alert = UIAlertController(title: app.name, message: "\(app.id!)\n\(app.url!)", preferredStyle: .alert) let doneAction = UIAlertAction(title: "Done", style: .default, handler: { action in alert.dismiss(animated: true, completion: nil) }) alert.addAction(doneAction) self.navigationController?.present(alert, animated: true, completion: nil) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { CILocalApps.shared.allApps.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) if !self.isEditing { CILocalApps.shared.saveList() } } } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let app = CILocalApps.shared.allApps.remove(at: sourceIndexPath.row) CILocalApps.shared.allApps.insert(app, at: destinationIndexPath.row) } }
apache-2.0
99eb5a11ae6a48fc555f587025f7fbb9
35.751037
174
0.601332
5.131518
false
false
false
false
ahoppen/swift
test/Parse/enum_element_pattern_swift4.swift
49
2552
// RUN: %target-typecheck-verify-swift -swift-version 4 // https://bugs.swift.org/browse/SR-3452 // See test/Compatibility/enum_element_pattern.swift for Swift3 behavior. // As for FIXME cases: see https://bugs.swift.org/browse/SR-3466 enum E { case A, B, C, D static func testE(e: E) { switch e { case A<UndefinedTy>(): // expected-error {{cannot specialize a non-generic definition}} // expected-note@-1 {{while parsing this '<' as a type parameter bracket}} break case B<Int>(): // expected-error {{cannot specialize a non-generic definition}} expected-note {{while parsing this '<' as a type parameter bracket}} break default: break; } } } func testE(e: E) { switch e { case E.A<UndefinedTy>(): // expected-error {{cannot specialize a non-generic definition}} // expected-note@-1 {{while parsing this '<' as a type parameter bracket}} break case E.B<Int>(): // expected-error {{cannot specialize a non-generic definition}} expected-note {{while parsing this '<' as a type parameter bracket}} break case .C(): // expected-error {{pattern with associated values does not match enum case 'C'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{10-12=}} break case .D(let payload): // expected-error{{pattern with associated values does not match enum case 'D'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{10-23=}} let _: () = payload break default: break } guard case .C() = e, // expected-error {{pattern with associated values does not match enum case 'C'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-14=}} case .D(let payload) = e // expected-error {{pattern with associated values does not match enum case 'D'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-25=}} else { return } } extension E : Error {} func canThrow() throws { throw E.A } do { try canThrow() } catch E.A() { // expected-error {{pattern with associated values does not match enum case 'A'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-14=}} // .. } catch E.B(let payload) { // expected-error {{pattern with associated values does not match enum case 'B'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-25=}} let _: () = payload }
apache-2.0
b32f9c92b23d2160a3ee5324696b343c
40.16129
152
0.635972
4.012579
false
false
false
false
Paladinfeng/Weibo-Swift
Weibo/Weibo/Classes/Tools/Network/HMNetworkTools.swift
1
3435
// // HMNetworkTools.swift // Swift网络访问工具类 // // Created by itheima on 15/12/6. // Copyright © 2015年 itheima. All rights reserved. // import UIKit import AFNetworking typealias PFNetCallBack = (response: AnyObject?, error: NSError?)->() enum HMRequestMethod: String { case GET = "GET" case POST = "POST" } class HMNetworkTools: AFHTTPSessionManager { static let shareTools: HMNetworkTools = { let tools = HMNetworkTools() // 在 Swift 里面, 会把 NSSet 转成 Set tools.responseSerializer.acceptableContentTypes?.insert("text/plain") return tools }() /// 发送请求 /// /// - parameter method: 请求方式 /// - parameter urlString: 请求地址 /// - parameter params: 请求参数 /// - parameter callback: 请求成功之后的回调 func request(method: HMRequestMethod, urlString: String, params: AnyObject?, callback: PFNetCallBack){ // 在 Swift 中,是不能向当前类(AFHTTPSessionManager)发送 dataTaskWithHTTPMethod // 因为 dataTaskWithHTTPMethod 这个方法是 AFN 写到 .m 文件里面 // 那么对应在 Swift 里面就相当于是 private 修饰的方法 // 定义请求成功之后的闭包 let succCallback = { (dataTask: NSURLSessionDataTask, response: AnyObject) -> Void in callback(response: response, error: nil) } // 定义请求失败的闭包 let failureCallBack = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in callback(response: nil, error: error) } // 根据不同的请求类型,调用不同的请求方法 if method == .GET { self.GET(urlString, parameters: params, success: succCallback, failure: failureCallBack) }else{ self.POST(urlString, parameters: params, success: succCallback, failure: failureCallBack) } } } // MARK: - 授权页网络请求 extension HMNetworkTools { func getAccessToken(code code:String, callBack: PFNetCallBack) { let baseURL = "https://api.weibo.com/oauth2/access_token" let params = ["client_id":WB_APPKEY, "client_secret":WB_APPSECRET, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_REDIRECT_URI] request(HMRequestMethod.POST, urlString: baseURL, params: params, callback: callBack) } func getUserInfo(uid uid:String, accessToken: String, callBack: PFNetCallBack) { let baseURL = "https://api.weibo.com/2/users/show.json" let params: [String: AnyObject]? = [ "access_token": accessToken, "uid": uid ] request(.GET, urlString: baseURL, params: params, callback: callBack) } } // MARK: - 首页数据网络请求 extension HMNetworkTools { func loadHomeData(maxid maxid: Int64 = 0, sinceid: Int64 = 0, callBack: PFNetCallBack){ let baseURL = "https://api.weibo.com/2/statuses/friends_timeline.json" let params: [String: AnyObject]? = [ "access_token": PFUserViewModel.shareViewModel.accessToken!, "max_id": "\(maxid)", "since_id": "\(sinceid)" ] request(.GET, urlString: baseURL, params: params, callback: callBack) } }
mit
7c16f2cafc5b8a9649358fc0c2994ebf
28.867925
154
0.606128
4.165789
false
false
false
false
kylebshr/Linchi
Linchi/HTTP-Definitions/HTTPParser.swift
1
1966
// // HTTPParser.swift // Linchi // // TODO: document this internal func parseRequest(message: HTTPMessage) -> HTTPRequest? { let statusTokens = message.startLine.split(" ") print(statusTokens) guard statusTokens.count == 3 else { return nil } guard let method = HTTPMethod.fromString(statusTokens.first!) else { return nil } guard statusTokens.last!.uppercaseString == "HTTP/1.1" else { return nil } let path = statusTokens[1] var requestParameters : [String: String] = [:] if method == .GET { if path.contains("?"), let query = path.split("?").last { requestParameters = extractParameters(query) } } if method == .POST, let contentType = message.headers["content-type"] { if contentType.lowercaseString == "application/x-www-form-urlencoded" { requestParameters = extractParameters(message.body) } } return HTTPRequest( method : method, url : path, headers : message.headers, body : message.body, methodParameters : requestParameters, urlParameters : [:] ) } /** Given a string of type "application/x-www-form-urlencoded", this function extracts the keys and values of the parameters and puts them in a dictionary. __Example__ input: `"show=friends&layout=big/"` output: `["show": "friends", "layout": "big"]` */ internal func extractParameters(body: String) -> [String : String] { let splitted = body.split("&") var results : [String : String] = [:] for component in splitted { let tokens = component.split("=") guard tokens.count >= 2 else { continue } let t1 = tokens[0].newByReplacingPlusesBySpaces().newByRemovingPercentEncoding() let t2 = tokens[1].newByReplacingPlusesBySpaces().newByRemovingPercentEncoding() results[t1] = t2 } return results }
mit
09fd85dbf294de1e1973dd05e19f899b
27.911765
91
0.616989
4.292576
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/NSCalendar.swift
1
97101
// 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 // import CoreFoundation #if canImport(ObjectiveC) // automatic CF_OPTIONS(…) OptionSet hoisting depends on the objc_fixed_enum attribute internal let kCFCalendarUnitEra = CFCalendarUnit.era internal let kCFCalendarUnitYear = CFCalendarUnit.year internal let kCFCalendarUnitMonth = CFCalendarUnit.month internal let kCFCalendarUnitDay = CFCalendarUnit.day internal let kCFCalendarUnitHour = CFCalendarUnit.hour internal let kCFCalendarUnitMinute = CFCalendarUnit.minute internal let kCFCalendarUnitSecond = CFCalendarUnit.second internal let kCFCalendarUnitWeekday = CFCalendarUnit.weekday internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit.weekdayOrdinal internal let kCFCalendarUnitQuarter = CFCalendarUnit.quarter internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit.weekOfMonth internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit.weekOfYear internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit.yearForWeekOfYear internal let kCFCalendarUnitNanosecond = CFCalendarUnit(rawValue: CFOptionFlags(CoreFoundation.kCFCalendarUnitNanosecond)) internal func _CFCalendarUnitRawValue(_ unit: CFCalendarUnit) -> CFOptionFlags { return unit.rawValue } internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.noStyle internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.shortStyle internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.mediumStyle internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.longStyle internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.fullStyle #else internal let kCFCalendarUnitEra = CFCalendarUnit(CoreFoundation.kCFCalendarUnitEra) internal let kCFCalendarUnitYear = CFCalendarUnit(CoreFoundation.kCFCalendarUnitYear) internal let kCFCalendarUnitMonth = CFCalendarUnit(CoreFoundation.kCFCalendarUnitMonth) internal let kCFCalendarUnitDay = CFCalendarUnit(CoreFoundation.kCFCalendarUnitDay) internal let kCFCalendarUnitHour = CFCalendarUnit(CoreFoundation.kCFCalendarUnitHour) internal let kCFCalendarUnitMinute = CFCalendarUnit(CoreFoundation.kCFCalendarUnitMinute) internal let kCFCalendarUnitSecond = CFCalendarUnit(CoreFoundation.kCFCalendarUnitSecond) internal let kCFCalendarUnitWeekday = CFCalendarUnit(CoreFoundation.kCFCalendarUnitWeekday) internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit(CoreFoundation.kCFCalendarUnitWeekdayOrdinal) internal let kCFCalendarUnitQuarter = CFCalendarUnit(CoreFoundation.kCFCalendarUnitQuarter) internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit(CoreFoundation.kCFCalendarUnitWeekOfMonth) internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit(CoreFoundation.kCFCalendarUnitWeekOfYear) internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit(CoreFoundation.kCFCalendarUnitYearForWeekOfYear) internal let kCFCalendarUnitNanosecond = CFCalendarUnit(CoreFoundation.kCFCalendarUnitNanosecond) internal func _CFCalendarUnitRawValue(_ unit: CFCalendarUnit) -> CFOptionFlags { return unit } #endif extension NSCalendar { public struct Identifier : RawRepresentable, Equatable, Hashable, Comparable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public static let gregorian = NSCalendar.Identifier("gregorian") public static let buddhist = NSCalendar.Identifier("buddhist") public static let chinese = NSCalendar.Identifier("chinese") public static let coptic = NSCalendar.Identifier("coptic") public static let ethiopicAmeteMihret = NSCalendar.Identifier("ethiopic") public static let ethiopicAmeteAlem = NSCalendar.Identifier("ethiopic-amete-alem") public static let hebrew = NSCalendar.Identifier("hebrew") public static let ISO8601 = NSCalendar.Identifier("iso8601") public static let indian = NSCalendar.Identifier("indian") public static let islamic = NSCalendar.Identifier("islamic") public static let islamicCivil = NSCalendar.Identifier("islamic-civil") public static let japanese = NSCalendar.Identifier("japanese") public static let persian = NSCalendar.Identifier("persian") public static let republicOfChina = NSCalendar.Identifier("roc") public static let islamicTabular = NSCalendar.Identifier("islamic-tbla") public static let islamicUmmAlQura = NSCalendar.Identifier("islamic-umalqura") } public struct Unit: OptionSet { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let era = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitEra)) public static let year = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitYear)) public static let month = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitMonth)) public static let day = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitDay)) public static let hour = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitHour)) public static let minute = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitMinute)) public static let second = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitSecond)) public static let weekday = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekday)) public static let weekdayOrdinal = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekdayOrdinal)) public static let quarter = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitQuarter)) public static let weekOfMonth = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekOfMonth)) public static let weekOfYear = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekOfYear)) public static let yearForWeekOfYear = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitYearForWeekOfYear)) public static let nanosecond = Unit(rawValue: UInt(1 << 15)) public static let calendar = Unit(rawValue: UInt(1 << 20)) public static let timeZone = Unit(rawValue: UInt(1 << 21)) internal var _cfValue: CFCalendarUnit { #if os(macOS) || os(iOS) return CFCalendarUnit(rawValue: self.rawValue) #else return CFCalendarUnit(self.rawValue) #endif } } public struct Options : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let wrapComponents = Options(rawValue: 1 << 0) public static let matchStrictly = Options(rawValue: 1 << 1) public static let searchBackwards = Options(rawValue: 1 << 2) public static let matchPreviousTimePreservingSmallerUnits = Options(rawValue: 1 << 8) public static let matchNextTimePreservingSmallerUnits = Options(rawValue: 1 << 9) public static let matchNextTime = Options(rawValue: 1 << 10) public static let matchFirst = Options(rawValue: 1 << 12) public static let matchLast = Options(rawValue: 1 << 13) } } extension NSCalendar.Identifier { public static func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool { return lhs.rawValue < rhs.rawValue } } open class NSCalendar : NSObject, NSCopying, NSSecureCoding { typealias CFType = CFCalendar private var _base = _CFInfo(typeID: CFCalendarGetTypeID()) private var _identifier: UnsafeMutableRawPointer? = nil private var _locale: UnsafeMutableRawPointer? = nil private var _tz: UnsafeMutableRawPointer? = nil private var _firstWeekday: CFIndex = 0 private var _minDaysInFirstWeek: CFIndex = 0 private var _gregorianStart: UnsafeMutableRawPointer? = nil private var _cal: UnsafeMutableRawPointer? = nil private var _userSet_firstWeekday: Bool = false private var _userSet_minDaysInFirstWeek: Bool = false private var _userSet_gregorianStart: Bool = false internal var _cfObject: CFType { return unsafeBitCast(self, to: CFCalendar.self) } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let calendarIdentifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else { return nil } self.init(identifier: NSCalendar.Identifier.init(rawValue: calendarIdentifier._swiftObject)) if aDecoder.containsValue(forKey: "NS.timezone") { if let timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone") { self.timeZone = timeZone._swiftObject } } if aDecoder.containsValue(forKey: "NS.locale") { if let locale = aDecoder.decodeObject(of: NSLocale.self, forKey: "NS.locale") { self.locale = locale._swiftObject } } self.firstWeekday = aDecoder.decodeInteger(forKey: "NS.firstwkdy") self.minimumDaysInFirstWeek = aDecoder.decodeInteger(forKey: "NS.mindays") if aDecoder.containsValue(forKey: "NS.gstartdate") { if let startDate = aDecoder.decodeObject(of: NSDate.self, forKey: "NS.gstartdate") { self.gregorianStartDate = startDate._swiftObject } } } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.calendarIdentifier.rawValue._bridgeToObjectiveC(), forKey: "NS.identifier") aCoder.encode(self.timeZone._nsObject, forKey: "NS.timezone") aCoder.encode(self.locale?._bridgeToObjectiveC(), forKey: "NS.locale") aCoder.encode(self.firstWeekday, forKey: "NS.firstwkdy") aCoder.encode(self.minimumDaysInFirstWeek, forKey: "NS.mindays") aCoder.encode(self.gregorianStartDate?._nsObject, forKey: "NS.gstartdate") } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { let copy = NSCalendar(identifier: calendarIdentifier)! copy.locale = locale copy.timeZone = timeZone copy.firstWeekday = firstWeekday copy.minimumDaysInFirstWeek = minimumDaysInFirstWeek copy.gregorianStartDate = gregorianStartDate return copy } open class var current: Calendar { return Calendar.current } open class var autoupdatingCurrent: Calendar { // swift-corelibs-foundation does not yet support autoupdating, but we can return the current calendar (which will not change). return Calendar.autoupdatingCurrent } public /*not inherited*/ init?(identifier calendarIdentifierConstant: Identifier) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, calendarIdentifierConstant.rawValue._cfObject) { return nil } } public init?(calendarIdentifier ident: Identifier) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, ident.rawValue._cfObject) { return nil } } internal override init() { super.init() } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { if let value = value, self === value as AnyObject { return true } if let calendar = __SwiftValue.fetch(value as AnyObject) as? NSCalendar { return calendar.calendarIdentifier == calendarIdentifier && calendar.timeZone == timeZone && calendar.locale == locale && calendar.firstWeekday == firstWeekday && calendar.minimumDaysInFirstWeek == minimumDaysInFirstWeek && calendar.gregorianStartDate == gregorianStartDate } return false } open override var description: String { return CFCopyDescription(_cfObject)._swiftObject } deinit { _CFDeinit(self) } open var calendarIdentifier: Identifier { get { return Identifier(rawValue: CFCalendarGetIdentifier(_cfObject)._swiftObject) } } /*@NSCopying*/ open var locale: Locale? { get { return CFCalendarCopyLocale(_cfObject)._swiftObject } set { CFCalendarSetLocale(_cfObject, newValue?._cfObject) } } /*@NSCopying*/ open var timeZone: TimeZone { get { return CFCalendarCopyTimeZone(_cfObject)._swiftObject } set { CFCalendarSetTimeZone(_cfObject, newValue._cfObject) } } open var firstWeekday: Int { get { return CFCalendarGetFirstWeekday(_cfObject) } set { CFCalendarSetFirstWeekday(_cfObject, CFIndex(newValue)) } } open var minimumDaysInFirstWeek: Int { get { return CFCalendarGetMinimumDaysInFirstWeek(_cfObject) } set { CFCalendarSetMinimumDaysInFirstWeek(_cfObject, CFIndex(newValue)) } } internal var gregorianStartDate: Date? { get { return CFCalendarCopyGregorianStartDate(_cfObject)?._swiftObject } set { let date = newValue as NSDate? CFCalendarSetGregorianStartDate(_cfObject, date?._cfObject) } } // Methods to return component name strings localized to the calendar's locale private func _symbols(_ key: CFString) -> [String] { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, _cfObject) let result = (CFDateFormatterCopyProperty(dateFormatter, key) as! NSArray)._swiftObject return result.map { return ($0 as! NSString)._swiftObject } } private func _symbol(_ key: CFString) -> String { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._bridgeToObjectiveC()._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, self._cfObject) return (CFDateFormatterCopyProperty(dateFormatter, key) as! NSString)._swiftObject } open var eraSymbols: [String] { return _symbols(kCFDateFormatterEraSymbolsKey) } open var longEraSymbols: [String] { return _symbols(kCFDateFormatterLongEraSymbolsKey) } open var monthSymbols: [String] { return _symbols(kCFDateFormatterMonthSymbolsKey) } open var shortMonthSymbols: [String] { return _symbols(kCFDateFormatterShortMonthSymbolsKey) } open var veryShortMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortMonthSymbolsKey) } open var standaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterStandaloneMonthSymbolsKey) } open var shortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneMonthSymbolsKey) } open var veryShortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneMonthSymbolsKey) } open var weekdaySymbols: [String] { return _symbols(kCFDateFormatterWeekdaySymbolsKey) } open var shortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortWeekdaySymbolsKey) } open var veryShortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortWeekdaySymbolsKey) } open var standaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterStandaloneWeekdaySymbolsKey) } open var shortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneWeekdaySymbolsKey) } open var veryShortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneWeekdaySymbolsKey) } open var quarterSymbols: [String] { return _symbols(kCFDateFormatterQuarterSymbolsKey) } open var shortQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortQuarterSymbolsKey) } open var standaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterStandaloneQuarterSymbolsKey) } open var shortStandaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneQuarterSymbolsKey) } open var amSymbol: String { return _symbol(kCFDateFormatterAMSymbolKey) } open var pmSymbol: String { return _symbol(kCFDateFormatterPMSymbolKey) } // Calendrical calculations open func minimumRange(of unit: Unit) -> NSRange { let r = CFCalendarGetMinimumRangeOfUnit(self._cfObject, unit._cfValue) if (r.location == kCFNotFound) { return NSRange(location: NSNotFound, length: NSNotFound) } return NSRange(location: r.location, length: r.length) } open func maximumRange(of unit: Unit) -> NSRange { let r = CFCalendarGetMaximumRangeOfUnit(_cfObject, unit._cfValue) if r.location == kCFNotFound { return NSRange(location: NSNotFound, length: NSNotFound) } return NSRange(location: r.location, length: r.length) } open func range(of smaller: Unit, in larger: Unit, for date: Date) -> NSRange { let r = CFCalendarGetRangeOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate) if r.location == kCFNotFound { return NSRange(location: NSNotFound, length: NSNotFound) } return NSRange(location: r.location, length: r.length) } open func ordinality(of smaller: Unit, in larger: Unit, for date: Date) -> Int { return Int(CFCalendarGetOrdinalityOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate)) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func rangeOfUnit(_ unit: Unit, startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func range(of unit: Unit, for date: Date) -> DateInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointer(to: &start) { startp in withUnsafeMutablePointer(to: &ti) { tip in return CFCalendarGetTimeRangeOfUnit(_cfObject, unit._cfValue, date.timeIntervalSinceReferenceDate, startp, tip) } } if res { return DateInterval(start: Date(timeIntervalSinceReferenceDate: start), duration: ti) } return nil } private func _convert(_ comp: Int?, type: String, vector: inout [Int32], compDesc: inout [Int8]) { if let component = comp { vector.append(Int32(component)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(_ comp: Bool?, type: String, vector: inout [Int32], compDesc: inout [Int8]) { if let component = comp { vector.append(Int32(component ? 0 : 1)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(_ comps: DateComponents) -> (Array<Int32>, Array<Int8>) { var vector = [Int32]() var compDesc = [Int8]() _convert(comps.era, type: "G", vector: &vector, compDesc: &compDesc) _convert(comps.year, type: "y", vector: &vector, compDesc: &compDesc) _convert(comps.quarter, type: "Q", vector: &vector, compDesc: &compDesc) if comps.weekOfYear != NSDateComponentUndefined { _convert(comps.weekOfYear, type: "w", vector: &vector, compDesc: &compDesc) } else { // _convert(comps.week, type: "^", vector: &vector, compDesc: &compDesc) } _convert(comps.month, type: "M", vector: &vector, compDesc: &compDesc) _convert(comps.weekOfMonth, type: "W", vector: &vector, compDesc: &compDesc) _convert(comps.yearForWeekOfYear, type: "Y", vector: &vector, compDesc: &compDesc) _convert(comps.weekday, type: "E", vector: &vector, compDesc: &compDesc) _convert(comps.weekdayOrdinal, type: "F", vector: &vector, compDesc: &compDesc) _convert(comps.isLeapMonth, type: "l", vector: &vector, compDesc: &compDesc) _convert(comps.day, type: "d", vector: &vector, compDesc: &compDesc) _convert(comps.hour, type: "H", vector: &vector, compDesc: &compDesc) _convert(comps.minute, type: "m", vector: &vector, compDesc: &compDesc) _convert(comps.second, type: "s", vector: &vector, compDesc: &compDesc) _convert(comps.nanosecond, type: "#", vector: &vector, compDesc: &compDesc) compDesc.append(0) return (vector, compDesc) } open func date(from comps: DateComponents) -> Date? { var (vector, compDesc) = _convert(comps) let oldTz = self.timeZone self.timeZone = comps.timeZone ?? timeZone var at: CFAbsoluteTime = 0.0 let res: Bool = withUnsafeMutablePointer(to: &at) { t in return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in return _CFCalendarComposeAbsoluteTimeV(_cfObject, t, compDesc, vectorBuffer.baseAddress!, Int32(vectorBuffer.count)) } } self.timeZone = oldTz if res { return Date(timeIntervalSinceReferenceDate: at) } else { return nil } } private func _setup(_ unitFlags: Unit, field: Unit, type: String, compDesc: inout [Int8]) { if unitFlags.contains(field) { compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _setup(_ unitFlags: Unit, addIsLeapMonth: Bool = true) -> [Int8] { var compDesc = [Int8]() _setup(unitFlags, field: .era, type: "G", compDesc: &compDesc) _setup(unitFlags, field: .year, type: "y", compDesc: &compDesc) _setup(unitFlags, field: .quarter, type: "Q", compDesc: &compDesc) _setup(unitFlags, field: .weekOfYear, type: "w", compDesc: &compDesc) _setup(unitFlags, field: .month, type: "M", compDesc: &compDesc) if addIsLeapMonth { _setup(unitFlags, field: .month, type: "l", compDesc: &compDesc) } _setup(unitFlags, field: .weekOfMonth, type: "W", compDesc: &compDesc) _setup(unitFlags, field: .yearForWeekOfYear, type: "Y", compDesc: &compDesc) _setup(unitFlags, field: .weekday, type: "E", compDesc: &compDesc) _setup(unitFlags, field: .weekdayOrdinal, type: "F", compDesc: &compDesc) _setup(unitFlags, field: .day, type: "d", compDesc: &compDesc) _setup(unitFlags, field: .hour, type: "H", compDesc: &compDesc) _setup(unitFlags, field: .minute, type: "m", compDesc: &compDesc) _setup(unitFlags, field: .second, type: "s", compDesc: &compDesc) _setup(unitFlags, field: .nanosecond, type: "#", compDesc: &compDesc) compDesc.append(0) return compDesc } private func _setComp(_ unitFlags: Unit, field: Unit, vector: [Int32], compIndex: inout Int, setter: (Int32) -> Void) { if unitFlags.contains(field) { setter(vector[compIndex]) compIndex += 1 } } private func _components(_ unitFlags: Unit, vector: [Int32], addIsLeapMonth: Bool = true) -> DateComponents { var compIdx = 0 var comps = DateComponents() _setComp(unitFlags, field: .era, vector: vector, compIndex: &compIdx) { comps.era = Int($0) } _setComp(unitFlags, field: .year, vector: vector, compIndex: &compIdx) { comps.year = Int($0) } _setComp(unitFlags, field: .quarter, vector: vector, compIndex: &compIdx) { comps.quarter = Int($0) } _setComp(unitFlags, field: .weekOfYear, vector: vector, compIndex: &compIdx) { comps.weekOfYear = Int($0) } _setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.month = Int($0) } if addIsLeapMonth { _setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.isLeapMonth = $0 != 0 } } _setComp(unitFlags, field: .weekOfMonth, vector: vector, compIndex: &compIdx) { comps.weekOfMonth = Int($0) } _setComp(unitFlags, field: .yearForWeekOfYear, vector: vector, compIndex: &compIdx) { comps.yearForWeekOfYear = Int($0) } _setComp(unitFlags, field: .weekday, vector: vector, compIndex: &compIdx) { comps.weekday = Int($0) } _setComp(unitFlags, field: .weekdayOrdinal, vector: vector, compIndex: &compIdx) { comps.weekdayOrdinal = Int($0) } _setComp(unitFlags, field: .day, vector: vector, compIndex: &compIdx) { comps.day = Int($0) } _setComp(unitFlags, field: .hour, vector: vector, compIndex: &compIdx) { comps.hour = Int($0) } _setComp(unitFlags, field: .minute, vector: vector, compIndex: &compIdx) { comps.minute = Int($0) } _setComp(unitFlags, field: .second, vector: vector, compIndex: &compIdx) { comps.second = Int($0) } _setComp(unitFlags, field: .nanosecond, vector: vector, compIndex: &compIdx) { comps.nanosecond = Int($0) } if unitFlags.contains(.calendar) { comps.calendar = self._swiftObject } if unitFlags.contains(.timeZone) { comps.timeZone = timeZone } return comps } /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil open func components(_ unitFlags: Unit, from date: Date) -> DateComponents { let compDesc = _setup(unitFlags) // _CFCalendarDecomposeAbsoluteTimeV requires a bit of a funky vector layout; which does not express well in swift; this is the closest I can come up with to the required format // int32_t ints[20]; // int32_t *vector[20] = {&ints[0], &ints[1], &ints[2], &ints[3], &ints[4], &ints[5], &ints[6], &ints[7], &ints[8], &ints[9], &ints[10], &ints[11], &ints[12], &ints[13], &ints[14], &ints[15], &ints[16], &ints[17], &ints[18], &ints[19]}; var ints = [Int32](repeating: 0, count: 20) let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in intArrayBuffer.baseAddress!.advanced(by: idx) } return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarDecomposeAbsoluteTimeV(_cfObject, date.timeIntervalSinceReferenceDate, compDesc, vecBuffer.baseAddress!, Int32(compDesc.count - 1)) } } if res { return _components(unitFlags, vector: ints) } fatalError() } open func date(byAdding comps: DateComponents, to date: Date, options opts: Options = []) -> Date? { var (vector, compDesc) = _convert(comps) var at: CFAbsoluteTime = date.timeIntervalSinceReferenceDate let res: Bool = withUnsafeMutablePointer(to: &at) { t in let count = Int32(vector.count) return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in return _CFCalendarAddComponentsV(_cfObject, t, CFOptionFlags(opts.rawValue), compDesc, vectorBuffer.baseAddress!, count) } } if res { return Date(timeIntervalSinceReferenceDate: at) } return nil } open func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents { let validUnitFlags: NSCalendar.Unit = [ .era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekOfYear, .weekOfMonth, .yearForWeekOfYear, .weekday, .weekdayOrdinal ] let invalidUnitFlags: NSCalendar.Unit = [ .quarter, .timeZone, .calendar] // Mask off the unsupported fields let newUnitFlags = Unit(rawValue: unitFlags.rawValue & validUnitFlags.rawValue) let compDesc = _setup(newUnitFlags, addIsLeapMonth: false) var ints = [Int32](repeating: 0, count: 20) let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in return intArrayBuffer.baseAddress!.advanced(by: idx) } let count = Int32(vector.count) return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, count) } } if res { let emptyUnitFlags = Unit(rawValue: unitFlags.rawValue & invalidUnitFlags.rawValue) var components = _components(newUnitFlags, vector: ints, addIsLeapMonth: false) // quarter always gets set to zero if requested in the output if emptyUnitFlags.contains(.quarter) { components.quarter = 0 } // isLeapMonth is always set components.isLeapMonth = false return components } fatalError() } /* This API is a convenience for getting era, year, month, and day of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.era, .year, .month, .day], from: date) eraValuePointer?.pointee = comps.era ?? NSDateComponentUndefined yearValuePointer?.pointee = comps.year ?? NSDateComponentUndefined monthValuePointer?.pointee = comps.month ?? NSDateComponentUndefined dayValuePointer?.pointee = comps.day ?? NSDateComponentUndefined } /* This API is a convenience for getting era, year for week-of-year calculations, week of year, and weekday of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.era, .yearForWeekOfYear, .weekOfYear, .weekday], from: date) eraValuePointer?.pointee = comps.era ?? NSDateComponentUndefined yearValuePointer?.pointee = comps.yearForWeekOfYear ?? NSDateComponentUndefined weekValuePointer?.pointee = comps.weekOfYear ?? NSDateComponentUndefined weekdayValuePointer?.pointee = comps.weekday ?? NSDateComponentUndefined } /* This API is a convenience for getting hour, minute, second, and nanoseconds of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.hour, .minute, .second, .nanosecond], from: date) hourValuePointer?.pointee = comps.hour ?? NSDateComponentUndefined minuteValuePointer?.pointee = comps.minute ?? NSDateComponentUndefined secondValuePointer?.pointee = comps.second ?? NSDateComponentUndefined nanosecondValuePointer?.pointee = comps.nanosecond ?? NSDateComponentUndefined } /* Get just one component's value. */ open func component(_ unit: Unit, from date: Date) -> Int { let comps = components(unit, from: date) if let res = comps.value(for: Calendar._fromCalendarUnit(unit)) { return res } else { return NSDateComponentUndefined } } /* Create a date with given components. Current era is assumed. */ open func date(era eraValue: Int, year yearValue: Int, month monthValue: Int, day dayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? { var comps = DateComponents() comps.era = eraValue comps.year = yearValue comps.month = monthValue comps.day = dayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return date(from: comps) } /* Create a date with given components. Current era is assumed. */ open func date(era eraValue: Int, yearForWeekOfYear yearValue: Int, weekOfYear weekValue: Int, weekday weekdayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? { var comps = DateComponents() comps.era = eraValue comps.yearForWeekOfYear = yearValue comps.weekOfYear = weekValue comps.weekday = weekdayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return date(from: comps) } /* This API returns the first moment date of a given date. Pass in [NSDate date], for example, if you want the start of "today". If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist. */ open func startOfDay(for date: Date) -> Date { return range(of: .day, for: date)!.start } /* This API returns all the date components of a date, as if in a given time zone (instead of the receiving calendar's time zone). The time zone overrides the time zone of the NSCalendar for the purposes of this calculation. Note: if you want "date information in a given time zone" in order to display it, you should use NSDateFormatter to format the date. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil open func components(in timezone: TimeZone, from date: Date) -> DateComponents { let oldTz = self.timeZone self.timeZone = timezone let comps = components([.era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .calendar, .timeZone], from: date) self.timeZone = oldTz return comps } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units, otherwise either less than or greater than. */ open func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: Unit) -> ComparisonResult { switch (unit) { case .calendar: return .orderedSame case .timeZone: return .orderedSame case .day: fallthrough case .hour: let range = self.range(of: unit, for: date1) let ats = range!.start.timeIntervalSinceReferenceDate let at2 = date2.timeIntervalSinceReferenceDate if ats <= at2 && at2 < ats + range!.duration { return .orderedSame } if at2 < ats { return .orderedDescending } return .orderedAscending case .minute: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(int1 / 60.0) int2 = floor(int2 / 60.0) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending case .second: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending case .nanosecond: var int1 = 0.0 var int2 = 0.0 let frac1 = modf(date1.timeIntervalSinceReferenceDate, &int1) let frac2 = modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(frac1 * 1000000000.0) int2 = floor(frac2 * 1000000000.0) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending default: break } let calendarUnits1: [Unit] = [.era, .year, .month, .day] let calendarUnits2: [Unit] = [.era, .year, .month, .weekdayOrdinal, .day] let calendarUnits3: [Unit] = [.era, .year, .month, .weekOfMonth, .weekday] let calendarUnits4: [Unit] = [.era, .yearForWeekOfYear, .weekOfYear, .weekday] var units: [Unit] if unit == .yearForWeekOfYear || unit == .weekOfYear { units = calendarUnits4 } else if unit == .weekdayOrdinal { units = calendarUnits2 } else if unit == .weekday || unit == .weekOfMonth { units = calendarUnits3 } else { units = calendarUnits1 } // TODO: verify that the return value here is never going to be nil; it seems like it may - thusly making the return value here optional which would result in sadness and regret let reducedUnits = units.reduce(Unit()) { $0.union($1) } let comp1 = components(reducedUnits, from: date1) let comp2 = components(reducedUnits, from: date2) for testedUnit in units { let value1 = comp1.value(for: Calendar._fromCalendarUnit(testedUnit)) let value2 = comp2.value(for: Calendar._fromCalendarUnit(testedUnit)) if value1! > value2! { return .orderedDescending } else if value1! < value2! { return .orderedAscending } if testedUnit == .month && calendarIdentifier == .chinese { if let leap1 = comp1.isLeapMonth { if let leap2 = comp2.isLeapMonth { if !leap1 && leap2 { return .orderedAscending } else if leap1 && !leap2 { return .orderedDescending } } } } if testedUnit == unit { return .orderedSame } } return .orderedSame } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units. */ open func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: Unit) -> Bool { return compare(date1, to: date2, toUnitGranularity: unit) == .orderedSame } /* This API compares the Days of the given dates, reporting them equal if they are in the same Day. */ open func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool { return compare(date1, to: date2, toUnitGranularity: .day) == .orderedSame } /* This API reports if the date is within "today". */ open func isDateInToday(_ date: Date) -> Bool { return compare(date, to: Date(), toUnitGranularity: .day) == .orderedSame } /* This API reports if the date is within "yesterday". */ open func isDateInYesterday(_ date: Date) -> Bool { if let interval = range(of: .day, for: Date()) { let inYesterday = interval.start - 60.0 return compare(date, to: inYesterday, toUnitGranularity: .day) == .orderedSame } else { return false } } /* This API reports if the date is within "tomorrow". */ open func isDateInTomorrow(_ date: Date) -> Bool { if let interval = range(of: .day, for: Date()) { let inTomorrow = interval.end + 60.0 return compare(date, to: inTomorrow, toUnitGranularity: .day) == .orderedSame } else { return false } } /* This API reports if the date is within a weekend period, as defined by the calendar and calendar's locale. */ open func isDateInWeekend(_ date: Date) -> Bool { return _CFCalendarIsDateInWeekend(_cfObject, date._cfObject) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func rangeOfWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, containingDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// Find the range of the weekend around the given date, returned via two by-reference parameters. /// Returns nil if the given date is not in a weekend. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func range(ofWeekendContaining date: Date) -> DateInterval? { if let next = nextWeekendAfter(date, options: []) { if let prev = nextWeekendAfter(next.start, options: .searchBackwards) { if prev.start <= date && date < prev.end /* exclude the end since it's the start of the next day */ { return prev } } } return nil } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func nextWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, options: Options, afterDate date: NSDate) -> Bool /// Returns the range of the next weekend, via two by-reference parameters, which starts strictly after the given date. /// The .SearchBackwards option can be used to find the previous weekend range strictly before the date. /// Returns nil if there are no such things as weekend in the calendar and its locale. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func nextWeekendAfter(_ date: Date, options: Options) -> DateInterval? { var range = _CFCalendarWeekendRange() let res = withUnsafeMutablePointer(to: &range) { rangep in return _CFCalendarGetNextWeekend(_cfObject, rangep) } if res { var comp = DateComponents() comp.weekday = range.start if let nextStart = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) { let start = startOfDay(for: nextStart + range.onsetTime) comp.weekday = range.end if let nextEnd = nextDate(after: start, matching: comp, options: .matchNextTime) { var end = nextEnd if range.ceaseTime > 0 { end = end + range.ceaseTime } else { if let dayEnd = self.range(of: .day, for: end) { end = startOfDay(for: dayEnd.end) } else { return nil } } return DateInterval(start: start, end: end) } } } return nil } /* This API returns the difference between two dates specified as date components. For units which are not specified in each NSDateComponents, but required to specify an absolute date, the base value of the unit is assumed. For example, for an NSDateComponents with just a Year and a Month specified, a Day of 1, and an Hour, Minute, Second, and Nanosecond of 0 are assumed. Calendrical calculations with unspecified Year or Year value prior to the start of a calendar are not advised. For each date components object, if its time zone property is set, that time zone is used for it; if the calendar property is set, that is used rather than the receiving calendar, and if both the calendar and time zone are set, the time zone property value overrides the time zone of the calendar property. No options are currently defined; pass 0. */ open func components(_ unitFlags: Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: Options = []) -> DateComponents { var startDate: Date? var toDate: Date? if let startCalendar = startingDateComp.calendar { startDate = startCalendar.date(from: startingDateComp) } else { startDate = date(from: startingDateComp) } if let toCalendar = resultDateComp.calendar { toDate = toCalendar.date(from: resultDateComp) } else { toDate = date(from: resultDateComp) } if let start = startDate { if let end = toDate { return components(unitFlags, from: start, to: end, options: options) } } fatalError() } /* This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date. The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented. */ open func date(byAdding unit: Unit, value: Int, to date: Date, options: Options = []) -> Date? { var comps = DateComponents() comps.setValue(value, for: Calendar._fromCalendarUnit(unit)) return self.date(byAdding: comps, to: date, options: options) } /* This method computes the dates which match (or most closely match) a given set of components, and calls the block once for each of them, until the enumeration is stopped. There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result. If the NSCalendarSearchBackwards option is used, this method finds the previous match before the given date. The intent is that the same matches as for a forwards search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards). If the NSCalendarMatchStrictly option is used, the algorithm travels as far forward or backward as necessary looking for a match, but there are ultimately implementation-defined limits in how far distant the search will go. If the NSCalendarMatchStrictly option is not specified, the algorithm searches up to the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument. If you want to find the next Feb 29 in the Gregorian calendar, for example, you have to specify the NSCalendarMatchStrictly option to guarantee finding it. If an exact match is not possible, and requested with the NSCalendarMatchStrictly option, nil is passed to the block and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.) If the NSCalendarMatchStrictly option is NOT used, exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified, or an illegal argument exception will be thrown. If the NSCalendarMatchPreviousTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the previous existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 1:37am, if that exists). If the NSCalendarMatchNextTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 3:37am, if that exists). If the NSCalendarMatchNextTime option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing time which exists (e.g., no 2:37am results in 3:00am, if that exists). If the NSCalendarMatchFirst option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the first occurrence. If the NSCalendarMatchLast option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the last occurrence. If neither the NSCalendarMatchFirst or NSCalendarMatchLast option is specified, the default behavior is to act as if NSCalendarMatchFirst was specified. There is no option to return middle occurrences of more than two occurrences of a matching time, if such exist. Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the NSDateComponents matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers). The enumeration is stopped by setting *stop = YES in the block and return. It is not necessary to set *stop to NO to keep the enumeration going. */ open func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { if !verifyCalendarOptions(opts) { return } withoutActuallyEscaping(block) { (nonescapingBlock) in _CFCalendarEnumerateDates(_cfObject, start._cfObject, comps._createCFDateComponents(), CFOptionFlags(opts.rawValue)) { (cfDate, exact, stop) in var ourStop: ObjCBool = false nonescapingBlock(cfDate._swiftObject, exact, &ourStop) if ourStop.boolValue { stop.pointee = true } } } } private func verifyCalendarOptions(_ options: NSCalendar.Options) -> Bool { var optionsAreValid = true let matchStrictly = options.contains(.matchStrictly) let matchPrevious = options.contains(.matchPreviousTimePreservingSmallerUnits) let matchNextKeepSmaller = options.contains(.matchNextTimePreservingSmallerUnits) let matchNext = options.contains(.matchNextTime) let matchFirst = options.contains(.matchFirst) let matchLast = options.contains(.matchLast) if matchStrictly && (matchPrevious || matchNextKeepSmaller || matchNext) { // We can't throw here because we've never thrown on this case before, even though it is technically an invalid case. The next best thing is to return. optionsAreValid = false } if !matchStrictly { if (matchPrevious && matchNext) || (matchPrevious && matchNextKeepSmaller) || (matchNext && matchNextKeepSmaller) || (!matchPrevious && !matchNext && !matchNextKeepSmaller) { fatalError("Exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified.") } } if (matchFirst && matchLast) { fatalError("Only one option from the set {NSCalendarMatchFirst, NSCalendarMatchLast} can be specified.") } return optionsAreValid } /* This method computes the next date which matches (or most closely matches) a given set of components. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matching comps: DateComponents, options: Options = []) -> Date? { var result: Date? enumerateDates(startingAfter: date, matching: comps, options: options) { date, exactMatch, stop in result = date stop.pointee = true } return result } /* This API returns a new NSDate object representing the date found which matches a specific component value. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matching unit: Unit, value: Int, options: Options = []) -> Date? { var comps = DateComponents() comps.setValue(value, for: Calendar._fromCalendarUnit(unit)) return nextDate(after:date, matching: comps, options: options) } /* This API returns a new NSDate object representing the date found which matches the given hour, minute, and second values. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: Options = []) -> Date? { var comps = DateComponents() comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue return nextDate(after: date, matching: comps, options: options) } /* This API returns a new NSDate object representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the unit already has that value, this may result in a date which is the same as the given date. Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well. If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other units to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year. The specific behaviors here are as yet unspecified; for example, if I change the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? A likely rule is that the algorithm will try to produce a result which is in the next-larger unit to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For forwards or backwards behavior, one can use the -nextDateAfterDate:matchingUnit:value:options: method above. */ open func date(bySettingUnit unit: Unit, value v: Int, of date: Date, options opts: Options = []) -> Date? { let currentValue = component(unit, from: date) if currentValue == v { return date } var targetComp = DateComponents() targetComp.setValue(v, for: Calendar._fromCalendarUnit(unit)) var result: Date? enumerateDates(startingAfter: date, matching: targetComp, options: .matchNextTime) { date, match, stop in result = date stop.pointee = true } return result } /* This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time. If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course. */ open func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: Options = []) -> Date? { if let range = range(of: .day, for: date) { var comps = DateComponents() comps.hour = h comps.minute = m comps.second = s var options: Options = .matchNextTime options.formUnion(opts.contains(.matchLast) ? .matchLast : .matchFirst) if opts.contains(.matchStrictly) { options.formUnion(.matchStrictly) } if let result = nextDate(after: range.start - 0.5, matching: comps, options: options) { if result.compare(range.start) == .orderedAscending { return nextDate(after: range.start, matching: comps, options: options) } return result } } return nil } /* This API returns YES if the date has all the matched components. Otherwise, it returns NO. It is useful to test the return value of the -nextDateAfterDate:matchingUnit:value:options:, to find out if the components were obeyed or if the method had to fudge the result value due to missing time. */ open func date(_ date: Date, matchesComponents components: DateComponents) -> Bool { let units: [Unit] = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond] var unitFlags: Unit = [] for unit in units { if components.value(for: Calendar._fromCalendarUnit(unit)) != NSDateComponentUndefined { unitFlags.formUnion(unit) } } if unitFlags == [] { if components.isLeapMonth != nil { let comp = self.components(.month, from: date) if let leap = comp.isLeapMonth { return leap } return false } } let comp = self.components(unitFlags, from: date) var compareComp = comp var tempComp = components tempComp.isLeapMonth = comp.isLeapMonth if let nanosecond = comp.value(for: .nanosecond) { if labs(numericCast(nanosecond - tempComp.value(for: .nanosecond)!)) > 500 { return false } else { compareComp.nanosecond = 0 tempComp.nanosecond = 0 } return tempComp == compareComp } return false } } /// MARK: Current calendar. internal class _NSCopyOnWriteCalendar: NSCalendar { private let lock = NSLock() private var needsLocking_isMutated: Bool private var needsLocking_backingCalendar: NSCalendar override var _cfObject: CFCalendar { copyBackingCalendarIfNeededWithMutation { _ in } return self.backingCalendar._cfObject } var backingCalendar: NSCalendar { lock.lock() let it = needsLocking_backingCalendar lock.unlock() return it } init(backingCalendar: NSCalendar) { self.needsLocking_isMutated = false self.needsLocking_backingCalendar = backingCalendar super.init() } public convenience required init?(coder aDecoder: NSCoder) { fatalError() // Encoding } override var classForCoder: AnyClass { return NSCalendar.self } override func encode(with aCoder: NSCoder) { backingCalendar.encode(with: aCoder) } override func copy(with zone: NSZone? = nil) -> Any { return backingCalendar.copy(with: zone) } // -- Mutating the current calendar private func copyBackingCalendarIfNeededWithMutation(_ block: (NSCalendar) -> Void) { lock.lock() if !needsLocking_isMutated { needsLocking_isMutated = true needsLocking_backingCalendar = needsLocking_backingCalendar.copy() as! NSCalendar } block(needsLocking_backingCalendar) lock.unlock() } override var firstWeekday: Int { get { return backingCalendar.firstWeekday } set { copyBackingCalendarIfNeededWithMutation { $0.firstWeekday = newValue } } } override var locale: Locale? { get { return backingCalendar.locale } set { copyBackingCalendarIfNeededWithMutation { $0.locale = newValue } } } override var timeZone: TimeZone { get { return backingCalendar.timeZone } set { copyBackingCalendarIfNeededWithMutation { $0.timeZone = newValue } } } override var minimumDaysInFirstWeek: Int { get { return backingCalendar.minimumDaysInFirstWeek } set { copyBackingCalendarIfNeededWithMutation { $0.minimumDaysInFirstWeek = newValue } } } override var gregorianStartDate: Date? { get { return backingCalendar.gregorianStartDate } set { copyBackingCalendarIfNeededWithMutation { $0.gregorianStartDate = newValue } } } override func isEqual(_ value: Any?) -> Bool { return backingCalendar.isEqual(value) } override var hash: Int { return backingCalendar.hashValue } // Delegation: override var calendarIdentifier: NSCalendar.Identifier { return backingCalendar.calendarIdentifier } override func minimumRange(of unit: NSCalendar.Unit) -> NSRange { return backingCalendar.minimumRange(of: unit) } override func maximumRange(of unit: NSCalendar.Unit) -> NSRange { return backingCalendar.maximumRange(of: unit) } override func range(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> NSRange { return backingCalendar.range(of: smaller, in: larger, for: date) } override func ordinality(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> Int { return backingCalendar.ordinality(of: smaller, in: larger, for: date) } override func range(of unit: NSCalendar.Unit, for date: Date) -> DateInterval? { return backingCalendar.range(of: unit, for: date) } override func date(from comps: DateComponents) -> Date? { return backingCalendar.date(from: comps) } override func component(_ unit: NSCalendar.Unit, from date: Date) -> Int { return backingCalendar.component(unit, from: date) } override func date(byAdding comps: DateComponents, to date: Date, options opts: NSCalendar.Options = []) -> Date? { return backingCalendar.date(byAdding: comps, to: date, options: opts) } override func components(_ unitFlags: NSCalendar.Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: NSCalendar.Options = []) -> DateComponents { return backingCalendar.components(unitFlags, from: startingDateComp, to: resultDateComp, options: options) } override func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents { return backingCalendar.components(unitFlags, from: startingDate, to: resultDate, options: opts) } override func nextWeekendAfter(_ date: Date, options: NSCalendar.Options) -> DateInterval? { return backingCalendar.nextWeekendAfter(date, options: options) } override func isDateInWeekend(_ date: Date) -> Bool { return backingCalendar.isDateInWeekend(date) } override func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Void) { return backingCalendar.enumerateDates(startingAfter: start, matching: comps, options: opts, using: block) } } // This notification is posted through [NSNotificationCenter defaultCenter] // when the system day changes. Register with "nil" as the object of this // notification. If the computer/device is asleep when the day changed, // this will be posted on wakeup. You'll get just one of these if the // machine has been asleep for several days. The definition of "Day" is // relative to the current calendar ([NSCalendar currentCalendar]) of the // process and its locale and time zone. There are no guarantees that this // notification is received by observers in a "timely" manner, same as // with distributed notifications. extension NSNotification.Name { public static let NSCalendarDayChanged = NSNotification.Name(rawValue: "NSCalendarDayChangedNotification") } // This is a just used as an extensible struct, basically; // note that there are two uses: one for specifying a date // via components (some components may be missing, making the // specific date ambiguous), and the other for specifying a // set of component quantities (like, 3 months and 5 hours). // Undefined fields have (or fields can be set to) the value // NSDateComponentUndefined. // NSDateComponents is not responsible for answering questions // about a date beyond the information it has been initialized // with; for example, if you initialize one with May 6, 2004, // and then ask for the weekday, you'll get Undefined, not Thurs. // A NSDateComponents is meaningless in itself, because you need // to know what calendar it is interpreted against, and you need // to know whether the values are absolute values of the units, // or quantities of the units. // When you create a new one of these, all values begin Undefined. public var NSDateComponentUndefined: Int = Int.max open class NSDateComponents : NSObject, NSCopying, NSSecureCoding { internal var _calendar: Calendar? internal var _timeZone: TimeZone? internal var _values = [Int](repeating: NSDateComponentUndefined, count: 19) public override init() { super.init() } open override var hash: Int { var hasher = Hasher() var mask = 0 // The list of fields fed to the hasher here must be exactly // the same as the ones compared in isEqual(_:) (modulo // ordering). // // Given that NSDateComponents instances usually only have a // few fields present, it makes sense to only hash those, as // an optimization. We keep track of the fields hashed in the // mask value, which we also feed to the hasher to make sure // any two unequal values produce different hash encodings. // // FIXME: Why not just feed _values, calendar & timeZone to // the hasher? if let calendar = calendar { hasher.combine(calendar) mask |= 1 << 0 } if let timeZone = timeZone { hasher.combine(timeZone) mask |= 1 << 1 } if era != NSDateComponentUndefined { hasher.combine(era) mask |= 1 << 2 } if year != NSDateComponentUndefined { hasher.combine(year) mask |= 1 << 3 } if quarter != NSDateComponentUndefined { hasher.combine(quarter) mask |= 1 << 4 } if month != NSDateComponentUndefined { hasher.combine(month) mask |= 1 << 5 } if day != NSDateComponentUndefined { hasher.combine(day) mask |= 1 << 6 } if hour != NSDateComponentUndefined { hasher.combine(hour) mask |= 1 << 7 } if minute != NSDateComponentUndefined { hasher.combine(minute) mask |= 1 << 8 } if second != NSDateComponentUndefined { hasher.combine(second) mask |= 1 << 9 } if nanosecond != NSDateComponentUndefined { hasher.combine(nanosecond) mask |= 1 << 10 } if weekOfYear != NSDateComponentUndefined { hasher.combine(weekOfYear) mask |= 1 << 11 } if weekOfMonth != NSDateComponentUndefined { hasher.combine(weekOfMonth) mask |= 1 << 12 } if yearForWeekOfYear != NSDateComponentUndefined { hasher.combine(yearForWeekOfYear) mask |= 1 << 13 } if weekday != NSDateComponentUndefined { hasher.combine(weekday) mask |= 1 << 14 } if weekdayOrdinal != NSDateComponentUndefined { hasher.combine(weekdayOrdinal) mask |= 1 << 15 } hasher.combine(isLeapMonth) hasher.combine(mask) return hasher.finalize() } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSDateComponents else { return false } // FIXME: Why not just compare _values, calendar & timeZone? return self === other || (era == other.era && year == other.year && quarter == other.quarter && month == other.month && day == other.day && hour == other.hour && minute == other.minute && second == other.second && nanosecond == other.nanosecond && weekOfYear == other.weekOfYear && weekOfMonth == other.weekOfMonth && yearForWeekOfYear == other.yearForWeekOfYear && weekday == other.weekday && weekdayOrdinal == other.weekdayOrdinal && isLeapMonth == other.isLeapMonth && calendar == other.calendar && timeZone == other.timeZone) } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } self.init() self.era = aDecoder.decodeInteger(forKey: "NS.era") self.year = aDecoder.decodeInteger(forKey: "NS.year") self.quarter = aDecoder.decodeInteger(forKey: "NS.quarter") self.month = aDecoder.decodeInteger(forKey: "NS.month") self.day = aDecoder.decodeInteger(forKey: "NS.day") self.hour = aDecoder.decodeInteger(forKey: "NS.hour") self.minute = aDecoder.decodeInteger(forKey: "NS.minute") self.second = aDecoder.decodeInteger(forKey: "NS.second") self.nanosecond = aDecoder.decodeInteger(forKey: "NS.nanosec") self.weekOfYear = aDecoder.decodeInteger(forKey: "NS.weekOfYear") self.weekOfMonth = aDecoder.decodeInteger(forKey: "NS.weekOfMonth") self.yearForWeekOfYear = aDecoder.decodeInteger(forKey: "NS.yearForWOY") self.weekday = aDecoder.decodeInteger(forKey: "NS.weekday") self.weekdayOrdinal = aDecoder.decodeInteger(forKey: "NS.weekdayOrdinal") self.isLeapMonth = aDecoder.decodeBool(forKey: "NS.isLeapMonth") self.calendar = aDecoder.decodeObject(of: NSCalendar.self, forKey: "NS.calendar")?._swiftObject self.timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone")?._swiftObject } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.era, forKey: "NS.era") aCoder.encode(self.year, forKey: "NS.year") aCoder.encode(self.quarter, forKey: "NS.quarter") aCoder.encode(self.month, forKey: "NS.month") aCoder.encode(self.day, forKey: "NS.day") aCoder.encode(self.hour, forKey: "NS.hour") aCoder.encode(self.minute, forKey: "NS.minute") aCoder.encode(self.second, forKey: "NS.second") aCoder.encode(self.nanosecond, forKey: "NS.nanosec") aCoder.encode(self.weekOfYear, forKey: "NS.weekOfYear") aCoder.encode(self.weekOfMonth, forKey: "NS.weekOfMonth") aCoder.encode(self.yearForWeekOfYear, forKey: "NS.yearForWOY") aCoder.encode(self.weekday, forKey: "NS.weekday") aCoder.encode(self.weekdayOrdinal, forKey: "NS.weekdayOrdinal") aCoder.encode(self.isLeapMonth, forKey: "NS.isLeapMonth") aCoder.encode(self.calendar?._nsObject, forKey: "NS.calendar") aCoder.encode(self.timeZone?._nsObject, forKey: "NS.timezone") } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { let newObj = NSDateComponents() newObj.calendar = calendar newObj.timeZone = timeZone newObj.era = era newObj.year = year newObj.month = month newObj.day = day newObj.hour = hour newObj.minute = minute newObj.second = second newObj.nanosecond = nanosecond newObj.weekOfYear = weekOfYear newObj.weekOfMonth = weekOfMonth newObj.yearForWeekOfYear = yearForWeekOfYear newObj.weekday = weekday newObj.weekdayOrdinal = weekdayOrdinal newObj.quarter = quarter if leapMonthSet { newObj.isLeapMonth = isLeapMonth } return newObj } /*@NSCopying*/ open var calendar: Calendar? { get { return _calendar } set { if let val = newValue { _calendar = val } else { _calendar = nil } } } /*@NSCopying*/ open var timeZone: TimeZone? open var era: Int { get { return _values[0] } set { _values[0] = newValue } } open var year: Int { get { return _values[1] } set { _values[1] = newValue } } open var month: Int { get { return _values[2] } set { _values[2] = newValue } } open var day: Int { get { return _values[3] } set { _values[3] = newValue } } open var hour: Int { get { return _values[4] } set { _values[4] = newValue } } open var minute: Int { get { return _values[5] } set { _values[5] = newValue } } open var second: Int { get { return _values[6] } set { _values[6] = newValue } } open var weekday: Int { get { return _values[8] } set { _values[8] = newValue } } open var weekdayOrdinal: Int { get { return _values[9] } set { _values[9] = newValue } } open var quarter: Int { get { return _values[10] } set { _values[10] = newValue } } open var nanosecond: Int { get { return _values[11] } set { _values[11] = newValue } } open var weekOfYear: Int { get { return _values[12] } set { _values[12] = newValue } } open var weekOfMonth: Int { get { return _values[13] } set { _values[13] = newValue } } open var yearForWeekOfYear: Int { get { return _values[14] } set { _values[14] = newValue } } open var isLeapMonth: Bool { get { return _values[15] == 1 } set { _values[15] = newValue ? 1 : 0 } } internal var leapMonthSet: Bool { return _values[15] != NSDateComponentUndefined } /*@NSCopying*/ open var date: Date? { if let tz = timeZone { calendar?.timeZone = tz } return calendar?.date(from: self._swiftObject) } /* This API allows one to set a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth properties cannot be set by this method. */ open func setValue(_ value: Int, forComponent unit: NSCalendar.Unit) { switch unit { case .era: era = value case .year: year = value case .month: month = value case .day: day = value case .hour: hour = value case .minute: minute = value case .second: second = value case .nanosecond: nanosecond = value case .weekday: weekday = value case .weekdayOrdinal: weekdayOrdinal = value case .quarter: quarter = value case .weekOfMonth: weekOfMonth = value case .weekOfYear: weekOfYear = value case .yearForWeekOfYear: yearForWeekOfYear = value case .calendar: print(".Calendar cannot be set via \(#function)") case .timeZone: print(".TimeZone cannot be set via \(#function)") default: break } } /* This API allows one to get the value of a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth property values cannot be gotten by this method. */ open func value(forComponent unit: NSCalendar.Unit) -> Int { switch unit { case .era: return era case .year: return year case .month: return month case .day: return day case .hour: return hour case .minute: return minute case .second: return second case .nanosecond: return nanosecond case .weekday: return weekday case .weekdayOrdinal: return weekdayOrdinal case .quarter: return quarter case .weekOfMonth: return weekOfMonth case .weekOfYear: return weekOfYear case .yearForWeekOfYear: return yearForWeekOfYear default: break } return NSDateComponentUndefined } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. The calendar property must be set, or NO is returned. */ open var isValidDate: Bool { if let cal = calendar { return isValidDate(in: cal) } return false } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. */ open func isValidDate(in calendar: Calendar) -> Bool { var cal = calendar if let tz = timeZone { cal.timeZone = tz } let ns = nanosecond if ns != NSDateComponentUndefined && 1000 * 1000 * 1000 <= ns { return false } if ns != NSDateComponentUndefined && 0 < ns { nanosecond = 0 } let d = calendar.date(from: self._swiftObject) if ns != NSDateComponentUndefined && 0 < ns { nanosecond = ns } if let date = d { let all: NSCalendar.Unit = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear] let comps = calendar._bridgeToObjectiveC().components(all, from: date) var val = era if val != NSDateComponentUndefined { if comps.era != val { return false } } val = year if val != NSDateComponentUndefined { if comps.year != val { return false } } val = month if val != NSDateComponentUndefined { if comps.month != val { return false } } if leapMonthSet { if comps.isLeapMonth != isLeapMonth { return false } } val = day if val != NSDateComponentUndefined { if comps.day != val { return false } } val = hour if val != NSDateComponentUndefined { if comps.hour != val { return false } } val = minute if val != NSDateComponentUndefined { if comps.minute != val { return false } } val = second if val != NSDateComponentUndefined { if comps.second != val { return false } } val = weekday if val != NSDateComponentUndefined { if comps.weekday != val { return false } } val = weekdayOrdinal if val != NSDateComponentUndefined { if comps.weekdayOrdinal != val { return false } } val = quarter if val != NSDateComponentUndefined { if comps.quarter != val { return false } } val = weekOfMonth if val != NSDateComponentUndefined { if comps.weekOfMonth != val { return false } } val = weekOfYear if val != NSDateComponentUndefined { if comps.weekOfYear != val { return false } } val = yearForWeekOfYear if val != NSDateComponentUndefined { if comps.yearForWeekOfYear != val { return false } } return true } return false } } extension NSDateComponents : _SwiftBridgeable { typealias SwiftType = DateComponents var _swiftObject: SwiftType { return DateComponents(reference: self) } } extension DateComponents : _NSBridgeable { typealias NSType = NSDateComponents var _nsObject: NSType { return _bridgeToObjectiveC() } } extension NSCalendar: _SwiftBridgeable, _CFBridgeable { typealias SwiftType = Calendar var _swiftObject: SwiftType { return Calendar(reference: self) } } extension Calendar: _NSBridgeable, _CFBridgeable { typealias NSType = NSCalendar typealias CFType = CFCalendar var _nsObject: NSCalendar { return _bridgeToObjectiveC() } var _cfObject: CFCalendar { return _nsObject._cfObject } } extension CFCalendar : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSCalendar internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Calendar { return _nsObject._swiftObject } } extension NSCalendar : _StructTypeBridgeable { public typealias _StructType = Calendar public func _bridgeToSwift() -> Calendar { return Calendar._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateComponents : _StructTypeBridgeable { public typealias _StructType = DateComponents public func _bridgeToSwift() -> DateComponents { return DateComponents._unconditionallyBridgeFromObjectiveC(self) } } fileprivate extension NSDateComponents { func _createCFDateComponents() -> CFDateComponents { let components = CFDateComponentsCreate(kCFAllocatorSystemDefault)! CFDateComponentsSetValue(components, kCFCalendarUnitEra, era) CFDateComponentsSetValue(components, kCFCalendarUnitYear, year) CFDateComponentsSetValue(components, kCFCalendarUnitMonth, month) CFDateComponentsSetValue(components, kCFCalendarUnitDay, day) CFDateComponentsSetValue(components, kCFCalendarUnitHour, hour) CFDateComponentsSetValue(components, kCFCalendarUnitMinute, minute) CFDateComponentsSetValue(components, kCFCalendarUnitSecond, second) CFDateComponentsSetValue(components, kCFCalendarUnitWeekday, weekday) CFDateComponentsSetValue(components, kCFCalendarUnitWeekdayOrdinal, weekdayOrdinal) CFDateComponentsSetValue(components, kCFCalendarUnitQuarter, quarter) CFDateComponentsSetValue(components, kCFCalendarUnitWeekOfMonth, weekOfMonth) CFDateComponentsSetValue(components, kCFCalendarUnitWeekOfYear, weekOfYear) CFDateComponentsSetValue(components, kCFCalendarUnitYearForWeekOfYear, yearForWeekOfYear) CFDateComponentsSetValue(components, kCFCalendarUnitNanosecond, nanosecond) return components } } fileprivate extension DateComponents { func _createCFDateComponents() -> CFDateComponents { return _nsObject._createCFDateComponents() } } // CF Bridging: internal func _CFSwiftCalendarGetCalendarIdentifier(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef> { // It is tempting to just: // return Unmanaged.passUnretained(unsafeBitCast(calendar, to: NSCalendar.self).calendarIdentifier.rawValue._cfObject) // The problem is that Swift will then release the ._cfObject from under us. It needs to be retained, but Swift objects do not necessarily have a way to retain that CFObject to be alive for the caller because, outside of ObjC, there is no autorelease pool to save us from this. This is a problem with the fact that we're bridging a Get function; Copy functions of course just return +1 and live happily. // So, the solution here is to canonicalize to one of the CFString constants, which are immortal. If someone is using a nonstandard calendar identifier, well, this will currently explode :( TODO. let result: CFString switch unsafeBitCast(calendar, to: NSCalendar.self).calendarIdentifier { case .gregorian: result = kCFCalendarIdentifierGregorian case .buddhist: result = kCFCalendarIdentifierBuddhist case .chinese: result = kCFCalendarIdentifierChinese case .coptic: result = kCFCalendarIdentifierCoptic case .ethiopicAmeteMihret: result = kCFCalendarIdentifierEthiopicAmeteMihret case .ethiopicAmeteAlem: result = kCFCalendarIdentifierEthiopicAmeteAlem case .hebrew: result = kCFCalendarIdentifierHebrew case .ISO8601: result = kCFCalendarIdentifierISO8601 case .indian: result = kCFCalendarIdentifierIndian case .islamic: result = kCFCalendarIdentifierIslamic case .islamicCivil: result = kCFCalendarIdentifierIslamicCivil case .japanese: result = kCFCalendarIdentifierJapanese case .persian: result = kCFCalendarIdentifierPersian case .republicOfChina: result = kCFCalendarIdentifierRepublicOfChina case .islamicTabular: result = kCFCalendarIdentifierIslamicTabular case .islamicUmmAlQura: result = kCFCalendarIdentifierIslamicUmmAlQura default: fatalError("Calendars returning a non-system calendar identifier in Swift Foundation are not supported.") } return Unmanaged.passUnretained(result) } internal func _CFSwiftCalendarCopyLocale(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef>? { if let locale = unsafeBitCast(calendar, to: NSCalendar.self).locale { return Unmanaged.passRetained(locale._cfObject) } else { return nil } } internal func _CFSwiftCalendarSetLocale(_ calendar: CFTypeRef, _ locale: CFTypeRef?) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) if let locale = locale { calendar.locale = unsafeBitCast(locale, to: NSLocale.self)._swiftObject } else { calendar.locale = nil } } internal func _CFSwiftCalendarCopyTimeZone(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef> { return Unmanaged.passRetained(unsafeBitCast(calendar, to: NSCalendar.self).timeZone._cfObject) } internal func _CFSwiftCalendarSetTimeZone(_ calendar: CFTypeRef, _ timeZone: CFTypeRef) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) calendar.timeZone = unsafeBitCast(timeZone, to: NSTimeZone.self)._swiftObject } internal func _CFSwiftCalendarGetFirstWeekday(_ calendar: CFTypeRef) -> CFIndex { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) return calendar.firstWeekday } internal func _CFSwiftCalendarSetFirstWeekday(_ calendar: CFTypeRef, _ firstWeekday: CFIndex) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) calendar.firstWeekday = firstWeekday } internal func _CFSwiftCalendarGetMinimumDaysInFirstWeek(_ calendar: CFTypeRef) -> CFIndex { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) return calendar.minimumDaysInFirstWeek } internal func _CFSwiftCalendarSetMinimumDaysInFirstWeek(_ calendar: CFTypeRef, _ minimumDaysInFirstWeek: CFIndex) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) calendar.minimumDaysInFirstWeek = minimumDaysInFirstWeek } internal func _CFSwiftCalendarCopyGregorianStartDate(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef>? { if let date = unsafeBitCast(calendar, to: NSCalendar.self).gregorianStartDate { return Unmanaged.passRetained(date._cfObject) } else { return nil } } internal func _CFSwiftCalendarSetGregorianStartDate(_ calendar: CFTypeRef, _ date: CFTypeRef?) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) if let date = date { calendar.gregorianStartDate = unsafeBitCast(date, to: NSDate.self)._swiftObject } else { calendar.gregorianStartDate = nil } }
apache-2.0
b5343728652b0e805f48f47e60335902
43.479615
880
0.645547
5.041747
false
false
false
false
velvetroom/columbus
Source/View/Store/VStoreStatusReadyListCellMessage.swift
1
1585
import UIKit final class VStoreStatusReadyListCellMessage:VStoreStatusReadyListCellAvailable { private weak var label:UILabel! override init(frame:CGRect) { super.init(frame:frame) isUserInteractionEnabled = false let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = NSTextAlignment.center label.backgroundColor = UIColor.clear label.font = UIFont.regular(size:VStoreStatusReadyListCellMessage.Constants.labelFontSize) label.textColor = UIColor(white:0, alpha:0.4) self.label = label addSubview(label) NSLayoutConstraint.bottomToBottom( view:label, toView:self) NSLayoutConstraint.height( view:label, constant:VStoreStatusReadyListCellMessage.Constants.labelHeight) NSLayoutConstraint.equalsHorizontal( view:label, toView:self) } required init?(coder:NSCoder) { return nil } override func config( controller:CStore, model:MStorePerkProtocol) { super.config( controller:controller, model:model) guard let status:MStorePerkStatusAvailableMessageProtocol = model.status as? MStorePerkStatusAvailableMessageProtocol else { return } label.text = status.message } }
mit
66f7abdde03da75092b3a144a01eecbc
26.327586
123
0.613249
5.640569
false
false
false
false
julienbodet/wikipedia-ios
FeaturedArticleWidget/FeaturedArticleWidget.swift
1
5871
import UIKit import NotificationCenter import WMF class FeaturedArticleWidget: UIViewController, NCWidgetProviding { let collapsedArticleView = ArticleRightAlignedImageCollectionViewCell() let expandedArticleView = ArticleFullWidthImageCollectionViewCell() var isExpanded = true var currentArticleKey: String? override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false let tapGR = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) view.addGestureRecognizer(tapGR) collapsedArticleView.saveButton.addTarget(self, action: #selector(saveButtonPressed), for: .touchUpInside) collapsedArticleView.frame = view.bounds view.addSubview(collapsedArticleView) expandedArticleView.saveButton.addTarget(self, action: #selector(saveButtonPressed), for: .touchUpInside) expandedArticleView.frame = view.bounds view.addSubview(expandedArticleView) extensionContext?.widgetLargestAvailableDisplayMode = .expanded } var isEmptyViewHidden = true { didSet { collapsedArticleView.isHidden = !isEmptyViewHidden expandedArticleView.isHidden = !isEmptyViewHidden } } var dataStore: MWKDataStore? { return SessionSingleton.sharedInstance()?.dataStore } var article: WMFArticle? { guard let featuredContentGroup = dataStore?.viewContext.newestGroup(of: .featuredArticle), let articleURL = featuredContentGroup.contentPreview as? URL else { return nil } return dataStore?.fetchArticle(with: articleURL) } func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { defer { updateView() } guard let article = self.article, let articleKey = article.key else { isEmptyViewHidden = false completionHandler(.failed) return } guard articleKey != currentArticleKey else { completionHandler(.noData) return } currentArticleKey = articleKey isEmptyViewHidden = true let theme:Theme = .widget collapsedArticleView.configure(article: article, displayType: .relatedPages, index: 0, shouldShowSeparators: false, theme: theme, layoutOnly: false) collapsedArticleView.titleTextStyle = .body collapsedArticleView.updateFonts(with: traitCollection) collapsedArticleView.tintColor = theme.colors.link collapsedArticleView.saveButton.saveButtonState = article.savedDate == nil ? .longSave : .longSaved expandedArticleView.configure(article: article, displayType: .pageWithPreview, index: 0, theme: theme, layoutOnly: false) expandedArticleView.tintColor = theme.colors.link expandedArticleView.saveButton.saveButtonState = article.savedDate == nil ? .longSave : .longSaved completionHandler(.newData) } func updateViewAlpha(isExpanded: Bool) { expandedArticleView.alpha = isExpanded ? 1 : 0 collapsedArticleView.alpha = isExpanded ? 0 : 1 } @objc func updateView() { guard viewIfLoaded != nil else { return } var maximumSize = CGSize(width: view.bounds.size.width, height: UIViewNoIntrinsicMetric) if let context = extensionContext { isExpanded = context.widgetActiveDisplayMode == .expanded maximumSize = context.widgetMaximumSize(for: context.widgetActiveDisplayMode) } updateViewAlpha(isExpanded: isExpanded) updateViewWithMaximumSize(maximumSize, isExpanded: isExpanded) } func updateViewWithMaximumSize(_ maximumSize: CGSize, isExpanded: Bool) { let sizeThatFits: CGSize if isExpanded { sizeThatFits = expandedArticleView.sizeThatFits(CGSize(width: maximumSize.width, height:UIViewNoIntrinsicMetric), apply: true) expandedArticleView.frame = CGRect(origin: .zero, size:sizeThatFits) } else { collapsedArticleView.imageViewDimension = maximumSize.height - 30 //hax sizeThatFits = collapsedArticleView.sizeThatFits(CGSize(width: maximumSize.width, height:UIViewNoIntrinsicMetric), apply: true) collapsedArticleView.frame = CGRect(origin: .zero, size:sizeThatFits) } preferredContentSize = CGSize(width: maximumSize.width, height: sizeThatFits.height) } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { debounceViewUpdate() } func debounceViewUpdate() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateView), object: nil) perform(#selector(updateView), with: nil, afterDelay: 0.1) } @objc func saveButtonPressed() { guard let article = self.article, let articleKey = article.key else { return } let isSaved = dataStore?.savedPageList.toggleSavedPage(forKey: articleKey) ?? false expandedArticleView.saveButton.saveButtonState = isSaved ? .longSaved : .longSave collapsedArticleView.saveButton.saveButtonState = isSaved ? .longSaved : .longSave } @objc func handleTapGesture(_ tapGR: UITapGestureRecognizer) { guard tapGR.state == .recognized else { return } guard let article = self.article, let articleURL = article.url else { return } let URL = articleURL as NSURL? let URLToOpen = URL?.wmf_wikipediaScheme ?? NSUserActivity.wmf_baseURLForActivity(of: .explore) self.extensionContext?.open(URLToOpen) } }
mit
f08fe4e6e11c3c2d9804a8059d8a8495
38.668919
156
0.677397
5.346995
false
false
false
false
darrylwest/saguaro-data-model
SaguaroDataModel/SADateTimeCalculator.swift
1
9864
// // SADateTimeCalculator.swift // SaguaroDataModel // // Created by darryl west on 7/23/15. // Copyright © 2015 darryl west. All rights reserved. // import Foundation import SaguaroJSON public protocol SADateTimeCalculatorType { var ISO8601DateTimeFormat:String { get } var calendar:Calendar { get } var isoFormatter:DateFormatter { get } var today:Date { get } func stripTime(_ date:Date) -> Date func formatISO8601Date(_ date:Date) -> String func getDateFormatter(_ dateFormat:String) -> DateFormatter func datePlusDays(_ date:Date, days:Int) -> Date func datePlusMonths(_ date:Date, months:Int) -> Date func calcMonthsFromDates(_ fromDate:Date, toDate:Date) -> Int func calcDaysFromDates(_ fromDate:Date, toDate:Date) -> Int func calcMinutesFromDates(_ fromDate:Date, toDate:Date) -> Int func createMutableDateRange() -> SAMutableDateRange func firstDayOfMonth(_ fromDate:Date?) -> Date func firstDayOfNextMonth(_ fromDate:Date?) -> Date func sortDates(_ reference:Date, compareTo:Date, order:ComparisonResult?) -> Bool func monthNamesBetweenDates(_ fromDate:Date, toDate:Date, dateFormat:String?) -> [String] func monthNamesBetweenDates(_ dateRange:SADateRangeModel, dateFormat:String?) -> [String] } /// this makes nsdate not suck so much... public extension Date { /// return true if the supplied date is before the reference public func isBeforeDate(_ date:Date) -> Bool { return self.compare( date ) == ComparisonResult.orderedAscending } /// return true if the supplied date is after the reference public func isAfterDate(_ date:Date) -> Bool { return self.compare( date ) == ComparisonResult.orderedDescending } /// return true if the two dates match (OrderedSame) public func equals(_ date:Date) -> Bool { return self.compare( date ) == ComparisonResult.orderedSame } /// return a new date by adding the number of days to the reference public func plusDays(_ days:Int) -> Date { let dayInterval = TimeInterval( days * 24 * 60 * 60 ) return Date(timeInterval: dayInterval, since: self) } /// return a new date by adding the number of minutes to the reference public func plusMinutes(_ minutes:Int) -> Date { let minuteInterval = TimeInterval( minutes * 60 ) return Date( timeInterval: minuteInterval, since: self ) } /// return a new date by adding the hours to reference public func plusHours(_ hours: Int) -> Date { let hourInterval = TimeInterval( hours * 60 * 60 ) return Date( timeInterval: hourInterval, since: self ) } /// return the standard JSON date string compatible with javascript / node and safe for over-the-wire public func toJSONString() -> String { return JSON.jnparser.stringFromDate( self ) } } /// some date helper methods; all date format time zones are zulu public struct SADateTimeCalculator: SADateTimeCalculatorType { public let dateFormats = [ "MMMM", "MMM", "dd-MMM-yyyy", "dd MMM yyyy","yyyy-MM-dd", "HH:mm:ss" ] public let ISO8601DateTimeFormat = JSON.DateFormatString public let calendar: Calendar public let isoFormatter = DateFormatter() public fileprivate(set) var formatters = [String:DateFormatter]() /// the current date with time stripped public var today:Date { return stripTime( Date() ) } /// strip the time from the given date public func stripTime(_ date:Date) -> Date { let comps = (calendar as NSCalendar).components([ .year, .month, .day ], from: date) return calendar.date( from: comps )! } /// format the date to an ISO8601 date/time string public func formatISO8601Date(_ date:Date) -> String { return isoFormatter.string( from: date ) } /// parse the ISO8601 date/time string and return a date or nil if the parse fails public func dateFromISO8601String(_ dateString:String) -> Date? { return isoFormatter.date( from: dateString ) } /// parse a json date string and return the date or nil public func dateFromJSONDateString(_ jsonDateString:String) -> Date? { return JSON.jnparser.dateFromString( jsonDateString ) } /// calculate and return the new date by adding the days public func datePlusDays(_ date:Date, days:Int) -> Date { if days == 0 { return date } var comps = DateComponents() comps.day = days return (calendar as NSCalendar).date(byAdding: comps, to: date, options: [ ])! } /// calculate and return the new date by adding the number of months public func datePlusMonths(_ date:Date, months: Int) -> Date { if months == 0 { return date } var comps = DateComponents() comps.month = months return (calendar as NSCalendar).date(byAdding: comps, to: date, options: [ ])! } /// calculate the number of months between the two dates rounded public func calcMonthsFromDates(_ fromDate:Date, toDate:Date) -> Int { let comps = (calendar as NSCalendar).components([ NSCalendar.Unit.month ], from: fromDate, to: toDate, options: [ ]) return comps.month! } /// calculate and return the number of days between the two dates public func calcDaysFromDates(_ fromDate:Date, toDate:Date) -> Int { let comps = (calendar as NSCalendar).components([ NSCalendar.Unit.day ], from: fromDate, to: toDate, options: [ ]) return comps.day! } /// calculate and return the number of minutes between the two dates public func calcMinutesFromDates(_ fromDate:Date, toDate:Date) -> Int { let comps = (calendar as NSCalendar).components([ NSCalendar.Unit.minute ], from: fromDate, to: toDate, options: [ ]) return comps.minute! } /// create a mutable date range with calculator public func createMutableDateRange() -> SAMutableDateRange { return SAMutableDateRange( dateTimeCalculator: self ) } /// calculate and return the first day of the supplied month public func firstDayOfMonth(_ fromDate:Date? = Date()) -> Date { let date = fromDate! var comps = (calendar as NSCalendar).components([ .year, .month, .day ], from: date ) comps.day = 1 return calendar.date( from: comps )! } /// calculate and return the date of the first day of the month public func firstDayOfNextMonth(_ fromDate:Date? = Date()) -> Date { var date = fromDate! var comps = (calendar as NSCalendar).components([ .year, .month, .day ], from: date ) comps.day = 1 date = calendar.date( from: comps )! // reset to enable adding... comps.day = 0 comps.year = 0 comps.month = 1 return (calendar as NSCalendar).date(byAdding: comps, to: date, options: [ ])! } /// return all components from the date public func componentsFromDate(_ date:Date) -> DateComponents { return (calendar as NSCalendar).components( NSCalendar.Unit(rawValue: UInt.max), from: date) } /// return true if the reference is before compareTo date; public func sortDates(_ reference:Date, compareTo:Date, order:ComparisonResult? = ComparisonResult.orderedAscending) -> Bool { return reference.compare( compareTo ) == order! } /// return an array of month names optionally formatted as MMMM public func monthNamesBetweenDates(_ fromDate:Date, toDate:Date, dateFormat:String? = "MMMM") -> [String] { var names = [String]() let formatter = getDateFormatter( dateFormat! ) var dt = self.firstDayOfMonth( fromDate ) let lastDate = self.firstDayOfMonth( toDate ) while dt.isBeforeDate( lastDate ) { names.append( formatter.string( from: dt )) dt = datePlusMonths(dt, months: 1) } names.append( formatter.string( from: dt )) return names } /// return the month names public func monthNamesBetweenDates(_ dateRange: SADateRangeModel, dateFormat:String? = "MMMM") -> [String] { return monthNamesBetweenDates(dateRange.startDate as Date, toDate: dateRange.endDate as Date, dateFormat: dateFormat) } /// return the formatter from cache, or create new and return public func getDateFormatter(_ dateFormat:String) -> DateFormatter { if let fmt = formatters[ dateFormat ] { // insure that this is the correct format and hasn't been externally modified fmt.dateFormat = dateFormat return fmt } else { let fmt = DateFormatter() fmt.dateFormat = dateFormat return fmt } } public init() { isoFormatter.dateFormat = ISO8601DateTimeFormat // No non-failable initializer is available, but it shouldn't ever return nil // However, rather than force unwrapping, it's probably better to give another timezone // than making the app crash let timeZone = TimeZone(secondsFromGMT: 0) ?? TimeZone.current isoFormatter.timeZone = timeZone var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.timeZone = timeZone self.calendar = calendar for df in dateFormats { let fmt = DateFormatter() fmt.dateFormat = df fmt.timeZone = TimeZone(secondsFromGMT: 0) formatters[ df ] = fmt } } /// return a shared instance; in most cases it's more efficient to use the shared instance public static let sharedInstance:SADateTimeCalculator = SADateTimeCalculator() }
mit
87364b3eb8ad0499677aaacd9bedf8a7
36.789272
130
0.648991
4.617509
false
false
false
false
alessioborraccino/reviews
reviews/Networking/ReviewAPI.swift
1
3544
// // ReviewAPI.swift // reviews // // Created by Alessio Borraccino on 14/05/16. // Copyright © 2016 Alessio Borraccino. All rights reserved. // import Alamofire import ObjectMapper import ReactiveCocoa import Result enum ReviewAPIError : ErrorType { case ParsingFailed case NetworkFailed case APIError(message: String) } protocol ReviewAPIType { func reviews(count count: Int, pageNumber: Int) -> SignalProducer<[Review],ReviewAPIError> func addReview(review: Review) -> SignalProducer<Int,ReviewAPIError> } class ReviewAPI : ReviewAPIType { //MARK : Constants private let host : String = "https://www.getyourguide.com" private let city : String = "berlin-l17" private let tour : String = "tempelhof-2-hour-airport-history-tour-berlin-airlift-more-t23776" // MARK: Dependencies /** Used to get maximum Review ID to give back. Would not be needed in a production environment */ private let reviewEntityManager : ReviewEntityManagerType init(reviewEntityManager: ReviewEntityManagerType = ReviewEntityManager()) { self.reviewEntityManager = reviewEntityManager } // MARK: Public Methods func reviews(count count: Int, pageNumber: Int) -> SignalProducer<[Review],ReviewAPIError> { return SignalProducer { observer, disposable in let request = ReviewAPIRequestBuilder.SearchReviews( city: self.city, tour: self.tour, count: count, page: pageNumber).URLRequest(host: self.host) Alamofire.request(request).validate().responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) in if let _ = response.result.error { observer.sendFailed(.NetworkFailed) } else if let success = Mapper<ReviewSuccessResponse>().map(response.result.value), reviews = success.reviews { observer.sendNext(reviews) } else if let error = Mapper<ReviewErrorResponse>().map(response.result.value), message = error.message { observer.sendFailed(.APIError(message: message)) } else { observer.sendFailed(.ParsingFailed) } observer.sendCompleted() }) } } func addReview(review: Review) -> SignalProducer<Int,ReviewAPIError> { return SignalProducer { [unowned self] observer, disposable in let _ = ReviewAPIRequestBuilder.AddReview( city: self.city, tour: self.tour, author: review.author, title: review.title, message: review.message, rating: review.rating, date: NSDate(), travelerType: review.travelerType ).URLRequest(host: self.host) //Should send request to backend, which will return the id for the review //Request should be for example: //https://www.getyourguide.com/berlin-l17/tempelhof-2-hour-airport-history-tour-berlin-airlift-more-t23776/addreview.json?author=alessio&title=super&message=super&rating=5&type=solo&date_of_review=date //Response would be as a json for example: // { // "review_id" : 456 // } let id = self.reviewEntityManager.maxReviewID() + 1 //Should be managed by backend observer.sendNext(id) observer.sendCompleted() } } }
mit
6a51853c8389234a324b699cf7452733
34.089109
213
0.623483
4.553985
false
false
false
false
google/JacquardSDKiOS
Tests/TagConnectionTests/TagPairingStateMachineTests.swift
1
16424
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Combine import CoreBluetooth import XCTest @testable import JacquardSDK final class TagPairingStateMachineTests: XCTestCase { struct CatchLogger: Logger { func log(level: LogLevel, file: String, line: Int, function: String, message: () -> String) { let _ = message() if level == .assertion { expectation.fulfill() } } var expectation: XCTestExpectation } override func setUp() { super.setUp() let logger = PrintLogger( logLevels: [.debug, .info, .warning, .error, .assertion, .preconditionFailure], includeSourceDetails: true ) setGlobalJacquardSDKLogger(logger) } override func tearDown() { // Other tests may run in the same process. Ensure that any fake logger fulfillment doesn't // cause any assertions later. JacquardSDK.setGlobalJacquardSDKLogger(JacquardSDK.createDefaultLogger()) super.tearDown() } var observations = [Cancellable]() let uuid = UUID(uuidString: "BD415750-8EF1-43EE-8A7F-7EF1E365C35E")! let deviceName = "Fake Device" func testVerifyDidConnect() { let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let service = CBMutableService(type: JacquardServices.v2Service, primary: true) let commandUUID = CBUUID(string: "D2F2EABB-D165-445C-B0E1-2D6B642EC57B") let commandCharacteristic = CBMutableCharacteristic( type: commandUUID, properties: [.write], value: nil, permissions: .writeable ) let responseUUID = CBUUID(string: "D2F2B8D0-D165-445C-B0E1-2D6B642EC57B") let responseCharacteristic = CBMutableCharacteristic( type: responseUUID, properties: [.notify], value: nil, permissions: .readable ) let notifyUUID = CBUUID(string: "D2F2B8D1-D165-445C-B0E1-2D6B642EC57B") let notifyCharacteristic = CBMutableCharacteristic( type: notifyUUID, properties: [.notify], value: nil, permissions: .readable ) let rawDataUUID = CBUUID(string: "D2F2B8D2-D165-445C-B0E1-2D6B642EC57B") let rawDataCharacteristic = CBMutableCharacteristic( type: rawDataUUID, properties: [.notify], value: nil, permissions: .readable ) service.characteristics = [ commandCharacteristic, responseCharacteristic, notifyCharacteristic, rawDataCharacteristic, ] peripheral.services = [service] let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let bluetoothConnectedExpectation = expectation(description: "BluetoothConnectedExpectation") let servicesDiscoveredExpectation = expectation(description: "ServicesDiscoveredExpectation") let awaitingNotificationUpdatesExpectation = expectation( description: "AwaitingNotificationUpdatesExpectation" ) awaitingNotificationUpdatesExpectation.expectedFulfillmentCount = 3 let tagPairedExpectation = expectation(description: "TagPairedExpectation") let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .bluetoothConnected: bluetoothConnectedExpectation.fulfill() case .servicesDiscovered: servicesDiscoveredExpectation.fulfill() case .awaitingNotificationUpdates: // This state called 2 times (for each characteristics). awaitingNotificationUpdatesExpectation.fulfill() case .tagPaired(_, _): tagPairedExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didConnect(peripheral: peripheral) wait( for: [ disconnectedStateExpectation, bluetoothConnectedExpectation, servicesDiscoveredExpectation, awaitingNotificationUpdatesExpectation, tagPairedExpectation, ], timeout: 1.0, enforceOrder: true ) } func testVerifyDidFailToConnect() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let failToConnectExpectation = expectation(description: "FailToConnectExpectation") let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .error(let error): XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) XCTAssert(state.isTerminal) failToConnectExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didFailToConnect( peripheral: peripheral, error: TagConnectionError.unknownCoreBluetoothError ) wait( for: [disconnectedStateExpectation, failToConnectExpectation], timeout: 1.0, enforceOrder: true ) } func testVerifyNoServicesFound() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let bluetoothConnectedExpectation = expectation(description: "BluetoothConnectedExpectation") let noServiceFoundExpectation = expectation(description: "NoServiceFoundExpectation") let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .bluetoothConnected: bluetoothConnectedExpectation.fulfill() case .error(let error): XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) noServiceFoundExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didConnect(peripheral: peripheral) wait( for: [ disconnectedStateExpectation, bluetoothConnectedExpectation, noServiceFoundExpectation, ], timeout: 1.0, enforceOrder: true ) } func testVerifyNoCharacteristicsFound() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let bluetoothConnectedExpectation = expectation(description: "BluetoothConnectedExpectation") let servicesDiscoveredExpectation = expectation(description: "ServicesDiscoveredExpectation") let noCharacteristicFoundExpectation = expectation( description: "NoCharacteristicFoundExpectation" ) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let service = CBMutableService(type: JacquardServices.v2Service, primary: true) peripheral.services = [service] let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .bluetoothConnected: bluetoothConnectedExpectation.fulfill() case .servicesDiscovered: servicesDiscoveredExpectation.fulfill() case .error(let error): XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) noCharacteristicFoundExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didConnect(peripheral: peripheral) wait( for: [ disconnectedStateExpectation, bluetoothConnectedExpectation, servicesDiscoveredExpectation, noCharacteristicFoundExpectation, ], timeout: 1.0, enforceOrder: true) } func testVerifyAnotherPeripheralDidConnect() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let anotherPeripheralConnectExpectation = expectation( description: "AnotherPeripheralConnectExpectation" ) let assetExpectation = expectation(description: "assetExpectation") jqLogger = CatchLogger(expectation: assetExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .error(let error): XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) anotherPeripheralConnectExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) let anotherFakePeripheral = FakePeripheralImplementation( identifier: UUID(uuidString: "BD415750-8EF1-43EE-8A7F-7EF1E365C35F")!, name: "Another device" ) pairingStateMachine.didConnect(peripheral: anotherFakePeripheral) wait( for: [disconnectedStateExpectation, assetExpectation, anotherPeripheralConnectExpectation], timeout: 1.0, enforceOrder: true ) } func testVerifyAnotherServiceDiscover() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let bluetoothConnectedExpectation = expectation(description: "BluetoothConnectedExpectation") let anotherServicesDiscoveredExpectation = expectation( description: "AnotherServicesDiscoveredExpectation" ) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let anotherService = CBMutableService( type: CBUUID(string: "D2F2BF0D-D165-445C-B0E1-2D6B642EC57C"), primary: true ) peripheral.services = [anotherService] let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .bluetoothConnected: bluetoothConnectedExpectation.fulfill() case .error(let error): XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) anotherServicesDiscoveredExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didConnect(peripheral: peripheral) wait( for: [ disconnectedStateExpectation, bluetoothConnectedExpectation, anotherServicesDiscoveredExpectation, ], timeout: 1.0, enforceOrder: true ) } func testVerifyAnotherCharacteristicDiscover() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let bluetoothConnectedExpectation = expectation(description: "BluetoothConnectedExpectation") let servicesDiscoveredExpectation = expectation(description: "ServicesDiscoveredExpectation") let anotherCharacteristicFoundExpectation = expectation( description: "anotherCharacteristicFoundExpectation" ) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let service = CBMutableService(type: JacquardServices.v2Service, primary: true) let unknownUUID = CBUUID(string: "D2F2B8D2-D165-445C-B0E1-2D6B642EC57B") let unknownCharacteristic = CBMutableCharacteristic( type: unknownUUID, properties: [.notify], value: nil, permissions: .readable ) service.characteristics = [unknownCharacteristic] peripheral.services = [service] let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .bluetoothConnected: bluetoothConnectedExpectation.fulfill() case .servicesDiscovered: servicesDiscoveredExpectation.fulfill() case .error(let error): XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) anotherCharacteristicFoundExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didConnect(peripheral: peripheral) wait( for: [ disconnectedStateExpectation, bluetoothConnectedExpectation, servicesDiscoveredExpectation, anotherCharacteristicFoundExpectation, ], timeout: 1.0, enforceOrder: true ) } func testVerifyNotifyStateError() { let disconnectedStateExpectation = expectation(description: "DisconnectedStateExpectation") let bluetoothConnectedExpectation = expectation(description: "BluetoothConnectedExpectation") let servicesDiscoveredExpectation = expectation(description: "ServicesDiscoveredExpectation") let awaitingNotificationUpdatesExpectation = expectation( description: "AwaitingNotificationUpdatesExpectation" ) let notifyStateErrorExpectation = expectation(description: "NotifyStateErrorExpectation") notifyStateErrorExpectation.expectedFulfillmentCount = 3 let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let service = CBMutableService(type: JacquardServices.v2Service, primary: true) let commandUUID = CBUUID(string: "D2F2EABB-D165-445C-B0E1-2D6B642EC57B") let commandCharacteristic = CBMutableCharacteristic( type: commandUUID, properties: [.write], value: nil, permissions: .writeable ) let responseUUID = CBUUID(string: "D2F2B8D0-D165-445C-B0E1-2D6B642EC57B") let responseCharacteristic = CBMutableCharacteristic( type: responseUUID, properties: [.notify], value: nil, permissions: .readable ) let notifyUUID = CBUUID(string: "D2F2B8D1-D165-445C-B0E1-2D6B642EC57B") let notifyCharacteristic = CBMutableCharacteristic( type: notifyUUID, properties: [.notify], value: nil, permissions: .readable ) let rawDataUUID = CBUUID(string: "D2F2B8D2-D165-445C-B0E1-2D6B642EC57B") let rawDataCharacteristic = CBMutableCharacteristic( type: rawDataUUID, properties: [.notify], value: nil, permissions: .readable ) service.characteristics = [ commandCharacteristic, responseCharacteristic, notifyCharacteristic, rawDataCharacteristic, ] peripheral.services = [service] peripheral.notifyStateError = TagConnectionError.internalError let pairingStateMachine = TagPairingStateMachine(peripheral: peripheral) pairingStateMachine.statePublisher.sink { state in switch state { case .disconnected: disconnectedStateExpectation.fulfill() case .bluetoothConnected: bluetoothConnectedExpectation.fulfill() case .servicesDiscovered: servicesDiscoveredExpectation.fulfill() case .awaitingNotificationUpdates: awaitingNotificationUpdatesExpectation.fulfill() case .error(let error): // Notify updates is called 2 times for response & notify characteristic. So error comes 2 // times. XCTAssertNotNil(error) XCTAssert(error is TagConnectionError) notifyStateErrorExpectation.fulfill() default: XCTFail("Failed with state \(state)") } }.addTo(&observations) pairingStateMachine.didConnect(peripheral: peripheral) wait( for: [ disconnectedStateExpectation, bluetoothConnectedExpectation, servicesDiscoveredExpectation, awaitingNotificationUpdatesExpectation, notifyStateErrorExpectation, ], timeout: 1.0, enforceOrder: true ) } }
apache-2.0
0a38e04d85b16bcfc1878b6be3faa444
34.32043
98
0.72802
4.960435
false
false
false
false
khizkhiz/swift
stdlib/public/SDK/AppKit/NSError.swift
1
2993
extension NSCocoaError { public static var textReadInapplicableDocumentTypeError: NSCocoaError { return NSCocoaError(rawValue: 65806) } public static var textWriteInapplicableDocumentTypeError: NSCocoaError { return NSCocoaError(rawValue: 66062) } public static var serviceApplicationNotFoundError: NSCocoaError { return NSCocoaError(rawValue: 66560) } public static var serviceApplicationLaunchFailedError: NSCocoaError { return NSCocoaError(rawValue: 66561) } public static var serviceRequestTimedOutError: NSCocoaError { return NSCocoaError(rawValue: 66562) } public static var serviceInvalidPasteboardDataError: NSCocoaError { return NSCocoaError(rawValue: 66563) } public static var serviceMalformedServiceDictionaryError: NSCocoaError { return NSCocoaError(rawValue: 66564) } public static var serviceMiscellaneousError: NSCocoaError { return NSCocoaError(rawValue: 66800) } public static var sharingServiceNotConfiguredError: NSCocoaError { return NSCocoaError(rawValue: 67072) } public var isServiceError: Bool { return rawValue >= 66560 && rawValue <= 66817 } public var isSharingServiceError: Bool { return rawValue >= 67072 && rawValue <= 67327 } public var isTextReadWriteError: Bool { return rawValue >= 65792 && rawValue <= 66303 } } extension NSCocoaError { @swift3_migration(renamed="textReadInapplicableDocumentTypeError") public static var TextReadInapplicableDocumentTypeError: NSCocoaError { return NSCocoaError(rawValue: 65806) } @swift3_migration(renamed="textWriteInapplicableDocumentTypeError") public static var TextWriteInapplicableDocumentTypeError: NSCocoaError { return NSCocoaError(rawValue: 66062) } @swift3_migration(renamed="serviceApplicationNotFoundError") public static var ServiceApplicationNotFoundError: NSCocoaError { return NSCocoaError(rawValue: 66560) } @swift3_migration(renamed="serviceApplicationLaunchFailedError") public static var ServiceApplicationLaunchFailedError: NSCocoaError { return NSCocoaError(rawValue: 66561) } @swift3_migration(renamed="serviceRequestTimedOutError") public static var ServiceRequestTimedOutError: NSCocoaError { return NSCocoaError(rawValue: 66562) } @swift3_migration(renamed="serviceInvalidPasteboardDataError") public static var ServiceInvalidPasteboardDataError: NSCocoaError { return NSCocoaError(rawValue: 66563) } @swift3_migration(renamed="serviceMalformedServiceDictionaryError") public static var ServiceMalformedServiceDictionaryError: NSCocoaError { return NSCocoaError(rawValue: 66564) } @swift3_migration(renamed="serviceMiscellaneousError") public static var ServiceMiscellaneousError: NSCocoaError { return NSCocoaError(rawValue: 66800) } @swift3_migration(renamed="sharingServiceNotConfiguredError") public static var SharingServiceNotConfiguredError: NSCocoaError { return NSCocoaError(rawValue: 67072) } }
apache-2.0
e3414d2761503d0f606b8e91431574d6
36.4125
74
0.789175
5.64717
false
false
false
false
kunsy/DYZB
DYZB/DYZB/Classes/Home/Controller/RecommandViewController.swift
1
4301
// // RecommandViewController.swift // DYZB // // Created by Anyuting on 2017/8/8. // Copyright © 2017年 Anyuting. All rights reserved. // import UIKit private let kViewH : CGFloat = 30 private let kCycleViewH : CGFloat = kScreenW * 3 / 8 private let kGameViewH : CGFloat = 90 //private let kGameViewID = "kGameViewID" class RecommandViewController: BaseAnchorViewController { //懒加载属性 fileprivate lazy var recommandVM : RecommandViewModel = RecommandViewModel() fileprivate lazy var cycleView : RecommandCycleView = { let cycleView = RecommandCycleView.recommandCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() fileprivate lazy var gameView : RecommandGameView = { let gameView = RecommandGameView.recommandGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() /*系统回调函数 override func viewDidLoad() { super.viewDidLoad() //view.backgroundColor = UIColor.purple //设置UI界面 setupUI() //发送网络请求 loadData() //闭包里面提示不好用: //collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID) //collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) //collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] //UINib(nibName: "CollectionHeaderView", bundle: nil) //collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) }*/ } //设置UI界面 extension RecommandViewController { override func setupUI(){ //view.addSubview(collectionView) //添加滚动广告图 collectionView.addSubview(cycleView) //添加推荐游戏滚动及 collectionView.addSubview(gameView) //设置superview的内边距 collectionView.contentInset = UIEdgeInsets(top: kGameViewH + kGameViewH + kViewH, left: 0, bottom: 0, right: 0) //把UICollectionView加入控制器中 super.setupUI() } } //发送网络请求数据 extension RecommandViewController { override func loadData() { //给父类baseVM赋予值 baseVM = recommandVM //请求推荐数据 recommandVM.requestData { self.collectionView.reloadData() //传递data到GameView var groups = self.recommandVM.anchorGroups //remove first two data groups.removeFirst() groups.removeFirst() //添加最后的更多 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" groups.append(moreGroup) self.gameView.groups = groups self.loadDataFinished() } //请求广告数据 recommandVM.requestCycleData { self.cycleView.cycleModels = self.recommandVM.cycleModels } } } //区别颜值数据xib extension RecommandViewController : UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell prettyCell.anchor = recommandVM.anchorGroups[indexPath.section].anchors[indexPath.item] return prettyCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } }
mit
06d39f882d02971a94b94b2177ced043
33.888889
188
0.671975
5.392338
false
false
false
false
CodeEagle/SSPageViewController
MyPlayground.playground/Contents.swift
1
1369
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var _map = [Int: String]() _map[0] = "item0" _map[1] = "item1" _map[2] = "item2" _map[3] = "item3" _map[4] = "item4" _map[5] = "item5" let _loopDisplay = true typealias Back = (value: String?, target: Int?, targetNext: Int?, targetPreviousId:Int?) func itemAfter(_ id: Int, after: Bool = false) -> Back { if id < 0 { return (nil, nil, nil, nil) } let count = _map.count var nextId: Int? = nil var previousId: Int? = nil if count == 1 { return (_map[0], 0, nil, nil) } var now: Int? if after { if id >= count - 1 { if _loopDisplay { now = 0 } } else { now = id + 1 } } else { if id == 0 { if _loopDisplay { now = count - 1 } } else { now = id - 1 } } guard let nowId = now else { return (nil, now, nextId, previousId) } let value = _map[nowId] if count == 1 { return (value, now, nextId, previousId) } if nowId >= count - 1 { if _loopDisplay { nextId = 0 } } else { nextId = nowId + 1 } if nowId == 0 { if _loopDisplay { previousId = count - 1 } } else { previousId = nowId - 1 } return (value, nowId, nextId, previousId) } let one = itemAfter(0) let two = itemAfter(1) let three = itemAfter(2) let four = itemAfter(3) let five = itemAfter(4) let zero = itemAfter(5)
mit
74a5db5c9f65ded0f60dc953c46d45b1
27.520833
88
0.577794
3.002193
false
false
false
false
google/taqo-paco
taqo_client/plugins/email/macos/Classes/TaqoEmailPlugin.swift
1
2116
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Cocoa import FlutterMacOS import os private let channelName : String = "taqo_email_plugin" private let sendEmailMethod : String = "send_email" private let toArg : String = "to" private let subjArg : String = "subject" private let gmailTemplate = "https://mail.google.com/mail/?view=cm&fs=1&to=%@&su=%@" private func log(_ msg: String, _ args: CVarArg...) { if #available(macOS 10.12, *) { os_log("TaqoEmailPlugin %s", msg, args) } } public class TaqoEmailPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger) let instance = TaqoEmailPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch(call.method) { case sendEmailMethod: guard let args = call.arguments as? [String: String] else { result("Failed") return } guard let to = args[toArg], let subj = args[subjArg] else { log("'to' and 'subject' args must be provided") result("Failed") return } if let subjEncode = subj.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { if let url = URL(string: String(format: gmailTemplate, to, subjEncode)) { NSWorkspace.shared.open(url) } } result("Success") default: result(FlutterMethodNotImplemented) } } }
apache-2.0
8849ca78a1553aab48342b56d23a7cf9
33.688525
95
0.69518
4.06142
false
false
false
false
thomasmeagher/TimeMachine
TimeMachine/ViewControllers/PostsViewController.swift
2
11183
// // PostsViewController.swift // HuntTimehop // // Created by thomas on 11/7/15. // Copyright © 2015 thomas. All rights reserved. // import UIKit class PostsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var tabBar: UITabBar! let apiController = ApiController() var techCategory = Category(name: "Tech", color: .blue(), originDate: NSDate.stringToDate(year: 2013, month: 11, day: 24)) var gamesCategory = Category(name: "Games", color: .purple(), originDate: NSDate.stringToDate(year: 2015, month: 5, day: 6)) var booksCategory = Category(name: "Books", color: .orange(), originDate: NSDate.stringToDate(year: 2015, month: 6, day: 25)) var podcastsCategory = Category(name: "Podcasts", color: .green(), originDate: NSDate.stringToDate(year: 2015, month: 9, day: 18)) var activeCategory: Category! var reloadImageView = UIImageView() var reloadButton = UIButton() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self activeCategory = techCategory authenticateAndGetPosts() navigationItem.title = activeCategory.name navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.grayD()] navigationController!.navigationBar.barTintColor = .white() navigationController!.navigationBar.tintColor = .red() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) let techTabBarItem = UITabBarItem(title: "Tech", image: UIImage(named: "tech"), selectedImage: UIImage(named: "tech")) let gamesTabBarItem = UITabBarItem(title: "Games", image: UIImage(named: "games"), selectedImage: UIImage(named: "games")) let booksTabBarItem = UITabBarItem(title: "Books", image: UIImage(named: "books"), selectedImage: UIImage(named: "books")) let podcastsTabBarItem = UITabBarItem(title: "Podcasts", image: UIImage(named: "podcasts"), selectedImage: UIImage(named: "podcasts")) tabBar.items = [techTabBarItem, gamesTabBarItem, booksTabBarItem, podcastsTabBarItem] tabBar.selectedItem = techTabBarItem tabBar.tintColor = .red() tabBar.backgroundColor = .white() tabBar.delegate = self tableView.backgroundColor = .grayL() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 80.0 tableView.tableFooterView = UIView() let kittyImage = UIImage(named: "kitty") reloadImageView = UIImageView(frame: CGRect(x: screenRect.width/2 - 25, y: screenRect.height/2 - 65, width: 50, height: 46)) reloadImageView.image = kittyImage reloadImageView.hidden = true view.addSubview(reloadImageView) reloadButton = UIButton(frame: CGRect(x: screenRect.width/2 - 70, y: screenRect.height/2, width: 140, height: 36)) reloadButton.setTitle("Reload Posts", forState: .Normal) reloadButton.titleLabel!.font = UIFont.boldSystemFontOfSize(16) reloadButton.tintColor = .white() reloadButton.backgroundColor = .red() reloadButton.layer.cornerRadius = reloadButton.frame.height/2 reloadButton.addTarget(self, action: "reloadButtonPressed:", forControlEvents: .TouchUpInside) reloadButton.hidden = true view.addSubview(reloadButton) } @IBAction func filterButtonTapped(sender: UIBarButtonItem) { performSegueWithIdentifier("showFilterVC", sender: self) } @IBAction func aboutButtonTapped(sender: UIBarButtonItem) { performSegueWithIdentifier("showAboutVC", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showPostDetailsVC" { let detailsVC = segue.destinationViewController as! PostDetailsViewController let indexPath = tableView.indexPathForSelectedRow let product = activeCategory.products[indexPath!.row] detailsVC.product = product detailsVC.filterDate = activeCategory.filterDate detailsVC.color = activeCategory.color } else if segue.identifier == "popoverFilterVC" { let filterVC = segue.destinationViewController as! FilterViewController filterVC.postsVC = self filterVC.modalPresentationStyle = .Popover filterVC.popoverPresentationController!.delegate = self } } internal func authenticateAndGetPosts() { activityIndicator.hidesWhenStopped = true activityIndicator.startAnimating() tableView.hidden = true reloadImageView.hidden = true reloadButton.hidden = true let filterDate = activeCategory.filterDate let lowercaseCategoryName = activeCategory.name.lowercaseString if Token.hasTokenExpired() { apiController.getClientOnlyAuthenticationToken { success, error in if let error = error { self.displayReloadButtonWithError(error) } else { self.apiController.getPostsForCategoryAndDate(lowercaseCategoryName, date: filterDate) { objects, error in if let products = objects as [Product]! { self.activeCategory.products = products self.displayPostsInTableView() } else { self.showAlertWithHeaderTextAndMessage("Oops :(", message: "\(error!.localizedDescription)", actionMessage: "Okay") } } } } } else { self.apiController.getPostsForCategoryAndDate(lowercaseCategoryName, date: filterDate) { objects, error in if let products = objects as [Product]! { self.activeCategory.products = products self.displayPostsInTableView() } else { self.displayReloadButtonWithError(error) } } } } private func displayPostsInTableView() { dispatch_async(dispatch_get_main_queue()) { let filterDate = self.activeCategory.filterDate if self.activeCategory.products.count == 0 { self.showAlertWithHeaderTextAndMessage("Hey", message: "There aren't any posts on \(NSDate.toPrettyString(date: filterDate)).", actionMessage: "Okay") } if filterDate == NSDate.stringToDate(year: 2013, month: 11, day: 24) { self.showAlertWithHeaderTextAndMessage("Hey :)", message: "You made it back to Product Hunt's first day!", actionMessage: "Okay") } self.tableView.reloadData() self.tableView.scrollToRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: .Top, animated: false) self.activityIndicator.stopAnimating() self.tableView.hidden = false } } private func displayReloadButtonWithError(error: NSError?) { dispatch_async(dispatch_get_main_queue()) { if let error = error { self.showAlertWithHeaderTextAndMessage("Oops :(", message: "\(error.localizedDescription)", actionMessage: "Okay") } self.activityIndicator.stopAnimating() self.reloadImageView.hidden = false self.reloadButton.hidden = false } } func reloadButtonPressed(sender: UIButton!) { authenticateAndGetPosts() } private func showAlertWithHeaderTextAndMessage(header: String, message: String, actionMessage: String) { let alert = UIAlertController(title: header, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: actionMessage, style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { if motion == .MotionShake { activeCategory.filterDate = NSDate.getRandomDateWithOrigin(activeCategory.originDate) authenticateAndGetPosts() } } } extension PostsViewController: UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == activeCategory.products.count { let buttonCell = tableView.dequeueReusableCellWithIdentifier("ButtonTableViewCell") as! ButtonTableViewCell buttonCell.buttonLabel.textColor = .red() return buttonCell } else { let cell = tableView.dequeueReusableCellWithIdentifier("ProductTableViewCell") as! ProductTableViewCell let product = activeCategory.products[indexPath.row] cell.votesLabel.text = "\(product.votes)" cell.nameLabel.text = product.name cell.taglineLabel.text = product.tagline cell.commentsLabel.text = "\(product.comments)" cell.makerImageView.hidden = product.makerInside ? false : true return cell } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return activeCategory.products.count + 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return NSDate.toPrettyString(date: activeCategory.filterDate) } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.contentView.backgroundColor = .grayL() header.textLabel!.textColor = .gray() header.textLabel!.textAlignment = .Center header.textLabel!.font = UIFont.boldSystemFontOfSize(14) } } // MARK: - UITableViewDelegate extension PostsViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.activeCategory.products.count { activeCategory.filterDate = NSDate.getRandomDateWithOrigin(activeCategory.originDate) authenticateAndGetPosts() } else { performSegueWithIdentifier("showPostDetailsVC", sender: self) let cell = tableView.dequeueReusableCellWithIdentifier("ProductTableViewCell") as! ProductTableViewCell cell.selectionStyle = .None } tableView.deselectRowAtIndexPath(indexPath, animated: true) } } extension PostsViewController: UITabBarDelegate { func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { switch item.title! { case "Books": activeCategory = booksCategory case "Games": activeCategory = gamesCategory case "Podcasts": activeCategory = podcastsCategory default: activeCategory = techCategory } navigationItem.title = activeCategory.name activeCategory.filterDate = activeCategory.filterDate.isLessThan(activeCategory.originDate) ? activeCategory.originDate : activeCategory.filterDate if activeCategory.products.isEmpty { authenticateAndGetPosts() } else { tableView.reloadData() self.tableView.scrollToRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: .Top, animated: false) } } } extension PostsViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } }
mit
306343a61b40554a7dd607c0ed5ce374
38.793594
151
0.720265
4.885103
false
false
false
false
gregbarbosa/HomeSpark
HomeSpark/PaperSwitch/RAMPaperSwitch.swift
1
5305
// RAMPaperSwitch.swift // // Copyright (c) 26/11/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class RAMPaperSwitch: UISwitch { @IBInspectable var duration: Double = 0.35 var animationDidStartClosure = {(onAnimation: Bool) -> Void in } var animationDidStopClosure = {(onAnimation: Bool, finished: Bool) -> Void in } private var shape: CAShapeLayer! = CAShapeLayer() private var radius: CGFloat = 0.0 override func setOn(on: Bool, animated: Bool) { let changed:Bool = on != self.on super.setOn(on, animated: animated) if changed { if animated { switchChanged() } else { showShapeIfNeed() } } } override func layoutSubviews() { let x:CGFloat = max(frame.midX, superview!.frame.size.width - frame.midX); let y:CGFloat = max(frame.midY, superview!.frame.size.height - frame.midY); radius = sqrt(x*x + y*y); shape.frame = CGRectMake(frame.midX - radius, frame.midY - radius, radius * 2, radius * 2) shape.anchorPoint = CGPointMake(0.5, 0.5); shape.path = UIBezierPath(ovalInRect: CGRectMake(0, 0, radius * 2, radius * 2)).CGPath } override func awakeFromNib() { var shapeColor:UIColor = (onTintColor != nil) ? onTintColor : UIColor.greenColor() layer.borderWidth = 0.5 layer.borderColor = UIColor.whiteColor().CGColor; layer.cornerRadius = frame.size.height / 2; shape.fillColor = shapeColor.CGColor shape.masksToBounds = true superview?.layer.insertSublayer(shape, atIndex: 0) superview?.layer.masksToBounds = true showShapeIfNeed() addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged) } private func showShapeIfNeed() { shape.transform = on ? CATransform3DMakeScale(1.0, 1.0, 1.0) : CATransform3DMakeScale(0.0001, 0.0001, 0.0001) } internal func switchChanged(){ if on { CATransaction.begin() shape.removeAnimationForKey("scaleDown") var scaleAnimation:CABasicAnimation = animateKeyPath("transform", fromValue: NSValue(CATransform3D: CATransform3DMakeScale(0.0001, 0.0001, 0.0001)), toValue:NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), timing:kCAMediaTimingFunctionEaseIn); shape.addAnimation(scaleAnimation, forKey: "scaleUp") CATransaction.commit(); } else { CATransaction.begin() shape.removeAnimationForKey("scaleUp") var scaleAnimation:CABasicAnimation = animateKeyPath("transform", fromValue: NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), toValue:NSValue(CATransform3D: CATransform3DMakeScale(0.0001, 0.0001, 0.0001)), timing:kCAMediaTimingFunctionEaseOut); shape.addAnimation(scaleAnimation, forKey: "scaleDown") CATransaction.commit(); } } private func animateKeyPath(keyPath: String, fromValue from: AnyObject, toValue to: AnyObject, timing timingFunction: String) -> CABasicAnimation { let animation:CABasicAnimation = CABasicAnimation(keyPath: keyPath) animation.fromValue = from animation.toValue = to animation.repeatCount = 1 animation.timingFunction = CAMediaTimingFunction(name: timingFunction) animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.duration = duration; animation.delegate = self return animation; } //CAAnimation delegate override func animationDidStart(anim: CAAnimation!){ animationDidStartClosure(on) } override func animationDidStop(anim: CAAnimation!, finished flag: Bool){ animationDidStopClosure(on, flag) } }
mit
247eb5f2bc1595f92b0a8ff7d10f318f
35.335616
151
0.635061
4.953315
false
false
false
false
xivol/MCS-V3-Mobile
examples/uiKit/UIKitCatalog.playground/Pages/UITableView.xcplaygroundpage/Contents.swift
1
4385
//: # UITableView //: Displays hierarchical lists of information and supports selection and editing of the information. //: //: [Table View API Reference](https://developer.apple.com/reference/uikit/uitableview) import UIKit import PlaygroundSupport class Model: NSObject, UITableViewDataSource { let cellReuseIdentifier = "Cell" var data = [[String]]() var titles = [String]() func numberOfSections(in tableView: UITableView) -> Int { return data.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data[section].count } // MARK: Cells func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Create new cell let cell = UITableViewCell(style: .value1, reuseIdentifier: cellReuseIdentifier) // or REUSE existing cell that is out of sight //let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) // add Accessories cell.accessoryType = .none // Populate cell let components = (data[indexPath.section][indexPath.row]).components(separatedBy: " ") cell.imageView?.image = components[0].image if components.count > 2 { cell.textLabel?.text = components[2] cell.detailTextLabel?.text = components[1] } else { cell.textLabel?.text = components[1] } return cell } // MARK: Section Headers and Footers func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard section < titles.count else { return nil } return titles[section] } //: MARK: Editing func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { data[indexPath.section].remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) } else { data[indexPath.section].insert("🍍 Fancy Pineapples", at: indexPath.row + 1) tableView.insertRows(at: [IndexPath(row: indexPath.row + 1, section: indexPath.section)], with: .automatic) } tableView.setEditing(false, animated: true) } } class Controller: NSObject, UITableViewDelegate { let label: UILabel! init(with label: UILabel) { self.label = label } // MARK: Row Selection func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let dataSource = tableView.dataSource as? Model else { print("Wrong data source!") PlaygroundPage.current.finishExecution() } label.text = dataSource.data[indexPath.section][indexPath.row] } // MARK: Editing func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Remove" } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { switch indexPath.section { case 0: return .insert default: return .delete } } } //: ### Initialize Table View let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 250, height: 500), style: .grouped) tableView.bounces = false //: ### Initialize Data let dataSource = Model() dataSource.titles.append("Fruits") dataSource.data.append(["🍎 Delicious Apples", "🍊 Oranges", "🍌 Bananas"]) dataSource.titles.append("Vegetables") dataSource.data.append(["🥔 Potatoes", "🍅 Tomatoes", "🥕 Crunchy Carrots"]) //: Register reusable cell class tableView.register(UITableViewCell.self, forCellReuseIdentifier: dataSource.cellReuseIdentifier) tableView.dataSource = dataSource //: ### Initialize Controller let displayLabel = UILabel(frame: CGRect(x: 0, y: 400, width: 250, height: 100)) tableView.addSubview(displayLabel) displayLabel.textAlignment = .center let delegate = Controller(with: displayLabel) tableView.delegate = delegate PlaygroundPage.current.liveView = tableView tableView.setEditing(true, animated: true) //: [Previous](@previous) | [Table of Contents](TableOfContents) | [Next](@next)
mit
eb88c8ca344a6b4bbbe1d7967ff6c284
35.366667
127
0.665903
4.822099
false
false
false
false
rymcol/PerfectPress
Sources/IndexHandler.swift
2
2089
// // IndexHandler.swift // PerfectPress // // Created by Ryan Collins on 6/9/16. // Copyright (C) 2016 Ryan M. Collins. // //===----------------------------------------------------------------------===// // // This source file is part of the PerfectPress open source blog project // //===----------------------------------------------------------------------===// // #if os(Linux) import Glibc #else import Darwin #endif struct IndexHandler { func loadPageContent() -> String { var post = "No matching post was found" let randomContent = ContentGenerator().generate() if let firstPost = randomContent["Test Post 1"] { post = firstPost as! String } let imageNumber = Int(arc4random_uniform(25) + 1) var finalContent = "<section id=\"content\"><div class=\"container\"><div class=\"row\"><div class=\"banner center-block\"><div><img src=\"/img/[email protected]\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-1.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-2.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-3.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-4.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-5.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div></div></div><div class=\"row\"><div class=\"col-xs-12\"><h1>" finalContent += "Test Post 1" finalContent += "</h1><img src=\"" finalContent += "/img/random/random-\(imageNumber).jpg\" alt=\"Random Image \(imageNumber)\" class=\"alignleft feature-image img-responsive\" />" finalContent += "<div class=\"content\">\(post)</div>" finalContent += "</div></div</div></section>" return finalContent } }
apache-2.0
13c9f9c9dc36586d14d8cbdca9d1584b
47.581395
917
0.585448
4.144841
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Game/GameQuestionPlayRoomViewController.swift
1
20195
// // GameQuestionPlayRoomViewController.swift // Whereami // // Created by lens on 16/3/25. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import Social import SVProgressHUD class GameQuestionPlayRoomViewController: UIViewController { var questionHeadView:GameQuestionHeadView? = nil var answerBottomView:GameAnswerBottomView? = nil var evaluateBottomView:GameEvaluateBottomView? = nil var bottomScrollView:UIScrollView? = nil var rightBarButtonItem:UIButton? = nil var timer:NSTimer? = nil var battleModel:BattleModel? = nil //战斗信息 var questionModel:QuestionModel? = nil //题目信息 var isClassic:Bool? = nil //是否经典 var hasNextQuestion:Bool? = nil //是否有下一题 var answerTime:Int = 30 //答题剩余时间 var lastQuestionModel:QuestionModel? = nil //上一题题目信息 override func viewDidLoad() { super.viewDidLoad() self.setConfig() if battleModel == nil{ self.battleModel = GameParameterManager.sharedInstance.battleModel } self.questionModel = self.battleModel?.questions self.getGameModel() self.setUI() self.addTimer() } func getGameModel(){ let gameMode = GameParameterManager.sharedInstance.gameMode if gameMode != nil{ let gameModel = gameMode!["gameModel"] as! Int if gameModel == 1 { self.isClassic = true } else{ self.isClassic = false } } } func setUI(){ self.view.backgroundColor = UIColor.getGameColor() self.navigationItem.hidesBackButton = false self.navigationItem.hidesBackButton = true self.setTitleAndRightBarButtonItemType(rightBarButtonItemType.time.rawValue) self.bottomScrollView = UIScrollView() self.bottomScrollView?.scrollEnabled = false self.bottomScrollView?.pagingEnabled = true self.bottomScrollView?.showsHorizontalScrollIndicator = false self.view.addSubview(self.bottomScrollView!) self.questionHeadView = GameQuestionHeadView() self.questionHeadView?.backgroundColor = UIColor.clearColor() self.questionHeadView?.QuestionTitle?.text = questionModel?.content // self.questionHeadView?.callBack = {() -> Void in // // } let picUrl = questionModel?.pictureUrl if picUrl != nil { self.getPictureContent(picUrl!) } else{ self.getPictureContent("") } self.view.addSubview(self.questionHeadView!) let answerArray = (self.questionModel?.answers)! as [AnswerModel] self.answerBottomView = GameAnswerBottomView() self.answerBottomView?.callBack = {(button) -> Void in self.answerButtonClick(button) } self.answerBottomView?.backgroundColor = UIColor.clearColor() self.answerBottomView?.answerBtn1?.setTitle(answerArray[0].content, forState: .Normal) self.answerBottomView?.answerBtn2?.setTitle(answerArray[1].content, forState: .Normal) self.answerBottomView?.answerBtn3?.setTitle(answerArray[2].content, forState: .Normal) self.answerBottomView?.answerBtn4?.setTitle(answerArray[3].content, forState: .Normal) self.bottomScrollView!.addSubview(self.answerBottomView!) self.evaluateBottomView = GameEvaluateBottomView() self.evaluateBottomView?.creatorAvatar?.image = UIImage(named: "temp4") self.evaluateBottomView?.callBack = {(button) -> Void in self.evaluateButtonClick(button) } self.bottomScrollView?.addSubview(self.evaluateBottomView!) self.questionHeadView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 0) self.questionHeadView?.autoPinEdgeToSuperviewEdge(.Left, withInset: 0) self.questionHeadView?.autoPinEdgeToSuperviewEdge(.Right, withInset: 0) self.questionHeadView?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.bottomScrollView!) self.questionHeadView?.autoMatchDimension(.Height, toDimension: .Height, ofView: self.bottomScrollView!) // self.questionHeadView?.autoSetDimension(.Height, toSize: screenH * 0.6) self.bottomScrollView?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 0) self.bottomScrollView?.autoPinEdgeToSuperviewEdge(.Left, withInset: 0) self.bottomScrollView?.autoPinEdgeToSuperviewEdge(.Right, withInset: 0) self.answerBottomView?.autoPinEdgeToSuperviewEdge(.Left, withInset: 0) self.answerBottomView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 0) self.answerBottomView?.autoPinEdge(.Right, toEdge: .Left, ofView: self.evaluateBottomView!) self.answerBottomView?.autoSetDimension(.Width, toSize: LScreenW) self.answerBottomView?.autoMatchDimension(.Height, toDimension: .Height, ofView: self.questionHeadView!) // self.answerBottomView?.autoSetDimension(.Height, toSize: screenH * 0.4) self.evaluateBottomView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 0) self.evaluateBottomView?.autoPinEdgeToSuperviewEdge(.Right, withInset: 0) self.evaluateBottomView?.autoSetDimension(.Width, toSize: LScreenW) self.evaluateBottomView?.autoMatchDimension(.Height, toDimension: .Height, ofView: self.questionHeadView!) // self.evaluateBottomView?.autoSetDimension(.Height, toSize: screenH * 0.4) } func addTimer() { self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.answerTimeChange), userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes) } func answerTimeChange(){ self.answerTime -= 1 rightBarButtonItem?.setTitle("\(answerTime as Int)", forState: .Normal) if self.answerTime <= 0{ let button = UIButton() button.tag = GameAnswerButtonType.wrong.rawValue self.answerButtonClick(button) } } func getPictureContent(pictureUrl:String){ let url = pictureUrl.toUrl() self.questionHeadView?.QuestionPicture?.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } func collectPhoto(){ var dict = [String: AnyObject]() dict["picId"] = questionModel?.pictureUrl dict["accountId"] = UserModel.getCurrentUser()?.id SocketManager.sharedInstance.sendMsg("collectPhoto", data: dict, onProto: "collectPhotoed") { (code, objs) in if code == statusCode.Normal.rawValue{ SVProgressHUD.showSuccessWithStatus("success") } } } func answerButtonClick(button:UIButton){ let tag = button.tag var answerArray = (self.questionModel?.answers)! as [AnswerModel] let count = answerArray.count var rightArray = [AnyObject]() var wrongArray = [AnyObject]() var wrongIndex = 0 var rightIndex = 0 for i in 0...count-1 { let isRight = answerArray[i].result if isRight == 0 { let dic = ["answer":answerArray[i],"tag":i+1] wrongArray.append(dic) wrongIndex = Int(arc4random()%2) } else{ rightArray.append(answerArray[i]) rightIndex = i+1 } } switch tag { case GameAnswerButtonType.bomb.rawValue: for i in 0...wrongArray.count-1{ let dic = wrongArray[i] if i != wrongIndex { let wrongButton = self.answerBottomView?.viewWithTag(dic["tag"] as! Int) as! UIButton wrongButton.backgroundColor = UIColor.redColor() wrongButton.enabled = false } } case GameAnswerButtonType.chance.rawValue: self.answerTime += 15 rightBarButtonItem?.setTitle("\(answerTime as Int)", forState: .Normal) case GameAnswerButtonType.skip.rawValue: let rightButton = self.answerBottomView?.viewWithTag(rightIndex) as! UIButton self.answerProblem(rightButton) default: self.answerProblem(button) } button.enabled = false } func answerProblem(button:UIButton){ let tag = button.tag var costtime = 30-answerTime if costtime<0 { costtime = 0 } var dict = [String:AnyObject]() dict["accountId"] = UserModel.getCurrentUser()?.id dict["battleId"] = self.battleModel?.battleId dict["problemId"] = self.battleModel?.questions?.id dict["costtime"] = costtime dict["answerId"] = "" self.lastQuestionModel = self.battleModel?.questions var answerArray = (self.questionModel?.answers)! as [AnswerModel] if tag != 100 { let isRight = answerArray[tag-1].result if isRight == 0 { button.backgroundColor = UIColor(red: 244/255.0, green: 106/255.0, blue: 110/255.0, alpha: 1) let count = self.answerBottomView!.answerButtonArray!.count for i in 0...count-1 { let item = self.answerBottomView?.answerButtonArray![i] let btn = item as! UIButton if answerArray[i].result == 1 { btn.backgroundColor = UIColor(red: 148/255.0, green: 235/255.0, blue: 65/255.0, alpha: 1) } btn.enabled = false } } else{ button.backgroundColor = UIColor.greenColor() for item in (self.answerBottomView?.answerButtonArray)!{ let btn = item as! UIButton btn.enabled = false } } dict["answerId"] = answerArray[tag-1].id } self.timer?.invalidate() self.timer = nil SocketManager.sharedInstance.sendMsg("answerProblem", data: dict, onProto: "answerProblemed") { (code, objs) in if code == statusCode.Complete.rawValue || code == statusCode.Overtime.rawValue { self.runInMainQueue({ let alertController = UIAlertController(title: "", message: NSLocalizedString("endGame",tableName:"Localizable", comment: ""), preferredStyle: .Alert) let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (confirmAction) in self.hasNextQuestion = false self.setTitleAndRightBarButtonItemType(rightBarButtonItemType.share.rawValue) self.bottomScrollView?.contentOffset = CGPoint(x: LScreenW,y: 0) }) alertController.addAction(confirmAction) self.presentViewController(alertController, animated: true, completion: nil) }) } if code == statusCode.Normal.rawValue { print("===============\(objs)") self.runInMainQueue({ self.setTitleAndRightBarButtonItemType(rightBarButtonItemType.share.rawValue) self.bottomScrollView?.contentOffset = CGPoint(x: LScreenW,y: 0) }) if objs[0]["problemId"] as! String != "" { self.hasNextQuestion = true self.evaluateBottomView?.continueButton?.enabled = false var dict = [String: AnyObject]() dict["battleId"] = objs[0]["battleId"] dict["questionId"] = objs[0]["problemId"] SocketManager.sharedInstance.sendMsg("queryProblemById", data: dict, onProto: "queryProblemByIded") { (code, objs) in if code == statusCode.Normal.rawValue { self.evaluateBottomView?.continueButton?.enabled = true let battleModel = BattleModel.getModelFromDictionary(objs[0] as! NSDictionary) self.battleModel = battleModel self.questionModel = self.battleModel?.questions answerArray = (self.questionModel?.answers)! as [AnswerModel] self.runInMainQueue({ let count = self.answerBottomView!.answerButtonArray!.count for i in 0..<count { let item = self.answerBottomView?.answerButtonArray![i] let btn = item as! UIButton btn.backgroundColor = UIColor.whiteColor() btn.enabled = true btn.setTitle(answerArray[i].content, forState: .Normal) } }) } } } else{ self.hasNextQuestion = false } } } } func evaluateButtonClick(button:UIButton){ switch button.tag { case GameEvaluateButtonType.Continue.rawValue: if hasNextQuestion == true { self.evaluateBottomView?.boringButton?.enabled = true self.evaluateBottomView?.interestingButton?.enabled = true self.questionHeadView?.QuestionTitle?.text = self.questionModel?.content let picUrl = questionModel?.pictureUrl if picUrl != nil { self.getPictureContent(picUrl!) } else{ self.getPictureContent("") } self.bottomScrollView?.contentOffset = CGPoint(x: 0,y: 0) self.answerTime = 30 self.setTitleAndRightBarButtonItemType(rightBarButtonItemType.time.rawValue) self.addTimer() } else{ self.dismissViewControllerAnimated(true, completion: nil) self.navigationController?.popToRootViewControllerAnimated(true) } case GameEvaluateButtonType.Collect.rawValue: self.collectPhoto() case GameEvaluateButtonType.Boring.rawValue: self.evaluateBottomView?.boringButton?.enabled = false self.evaluateBottomView?.interestingButton?.enabled = false var dict = [String: AnyObject]() if self.lastQuestionModel != nil { dict["problemId"] = self.lastQuestionModel?.id } SocketManager.sharedInstance.sendMsg("boring", data: dict) case GameEvaluateButtonType.Fun.rawValue: self.evaluateBottomView?.boringButton?.enabled = false self.evaluateBottomView?.interestingButton?.enabled = false var dict = [String: AnyObject]() if self.lastQuestionModel != nil { dict["problemId"] = self.lastQuestionModel?.id } SocketManager.sharedInstance.sendMsg("interesting", data: dict) default: let reportVC = GameReportViewController() if self.lastQuestionModel != nil { reportVC.problemId = self.lastQuestionModel?.id } self.navigationController?.pushViewController(reportVC, animated: true) } } func share(){ guard SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) else{ let alertController = UIAlertController(title: "tips", message: "请在设置中添加facebook账号", preferredStyle: .Alert) let setAction = UIAlertAction(title: "设置", style: .Default, handler: { (action) in LApplication().openURL(NSURL(string: "prefs:root=FACEBOOK")!) }) let cancelAction = UIAlertAction(title: "稍后", style: .Cancel, handler: { (action) in self.presentActivityVC() }) alertController.addAction(setAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) return } self.presentActivityVC() } func presentActivityVC(){ // let text = "说点什么吧..." // let image = UIImage(named: "personal_back") let url = NSURL(string: "http://www.baidu.com") // let activityItems = [text,image!,url!] as [AnyObject] let activityVC = UIActivityViewController(activityItems: [url!], applicationActivities: nil) activityVC.excludedActivityTypes = [UIActivityTypeAirDrop] self.presentViewController(activityVC, animated: true, completion: nil) } func consumeItem(code:String){ let currentUser = UserModel.getCurrentUser()?.id var dict = [String: AnyObject]() dict["accountId"] = currentUser dict["code"] = code dict["itemNum"] = -1 var arr = LUserDefaults().objectForKey("gainItems") as? [AnyObject] if arr == nil { arr = [AnyObject]() } var json:NSData? = nil do { json = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted) arr!.append(json!) LUserDefaults().setObject(arr, forKey: "gainItems") }catch{ } SocketManager.sharedInstance.sendMsg("gainItems", data: dict, onProto: "gainItemsed") { (code, objs) in if code == statusCode.Normal.rawValue { for (index, value) in arr!.enumerate() { if value.isEqual(json!) { arr?.removeAtIndex(index) LUserDefaults().setObject(arr, forKey: "gainItems") break } } }else{ } } let item = CoreDataManager.sharedInstance.fetchItemByIdAndCode(currentUser!, code: code) guard item != nil else { return } item?.itemNum = (item?.itemNum)! - 1 CoreDataManager.sharedInstance.increaseOrUpdateAccItem(item!) } func setTitleAndRightBarButtonItemType(type:Int) { if type == rightBarButtonItemType.time.rawValue { self.title = "\((questionModel?.classificationName)! as String)" self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] rightBarButtonItem = UIButton() rightBarButtonItem?.enabled = false rightBarButtonItem?.setTitle("\(answerTime as Int)", forState: .Normal) rightBarButtonItem?.layer.bounds = CGRect(x: 0,y: 0,width: 30,height: 30) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButtonItem!) } else{ self.title = "\((self.questionModel?.classificationName)! as String)" self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] let shareBarButton = UIBarButtonItem.init(image: UIImage(named: "share"), style: .Done, target: self, action: #selector(self.share)) self.navigationItem.rightBarButtonItem = shareBarButton } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
34e352683b2afee36b51ace4b23b2db5
42.777778
170
0.588982
5.230088
false
false
false
false
freak4pc/netfox
netfox/iOS/NFXDetailsController_iOS.swift
1
14008
// // NFXDetailsController.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // #if os(iOS) import Foundation import UIKit import MessageUI fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class NFXDetailsController_iOS: NFXDetailsController, MFMailComposeViewControllerDelegate { var infoButton: UIButton = UIButton() var requestButton: UIButton = UIButton() var responseButton: UIButton = UIButton() private var copyAlert: UIAlertController? var infoView: UIScrollView = UIScrollView() var requestView: UIScrollView = UIScrollView() var responseView: UIScrollView = UIScrollView() private lazy var headerButtons: [UIButton] = { return [self.infoButton, self.requestButton, self.responseButton] }() private lazy var infoViews: [UIScrollView] = { return [self.infoView, self.requestView, self.responseView] }() internal var sharedContent: String? override func viewDidLoad() { super.viewDidLoad() self.title = "Details" self.view.layer.masksToBounds = true self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(NFXDetailsController_iOS.actionButtonPressed(_:))) // Header buttons self.infoButton = createHeaderButton("Info", x: 0, selector: #selector(NFXDetailsController_iOS.infoButtonPressed)) self.requestButton = createHeaderButton("Request", x: self.infoButton.frame.maxX, selector: #selector(NFXDetailsController_iOS.requestButtonPressed)) self.responseButton = createHeaderButton("Response", x: self.requestButton.frame.maxX, selector: #selector(NFXDetailsController_iOS.responseButtonPressed)) self.headerButtons.forEach { self.view.addSubview($0) } // Info views self.infoView = createDetailsView(getInfoStringFromObject(self.selectedModel), forView: .info) self.requestView = createDetailsView(getRequestStringFromObject(self.selectedModel), forView: .request) self.responseView = createDetailsView(getResponseStringFromObject(self.selectedModel), forView: .response) self.infoViews.forEach { self.view.addSubview($0) } // Swipe gestures let lswgr = UISwipeGestureRecognizer(target: self, action: #selector(NFXDetailsController_iOS.handleSwipe(_:))) lswgr.direction = UISwipeGestureRecognizerDirection.left self.view.addGestureRecognizer(lswgr) let rswgr = UISwipeGestureRecognizer(target: self, action: #selector(NFXDetailsController_iOS.handleSwipe(_:))) rswgr.direction = UISwipeGestureRecognizerDirection.right self.view.addGestureRecognizer(rswgr) infoButtonPressed() } func createHeaderButton(_ title: String, x: CGFloat, selector: Selector) -> UIButton { var tempButton: UIButton tempButton = UIButton() tempButton.frame = CGRect(x: x, y: 0, width: self.view.frame.width / 3, height: 44) tempButton.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] tempButton.backgroundColor = UIColor.NFXDarkStarkWhiteColor() tempButton.setTitle(title, for: UIControlState()) tempButton.setTitleColor(UIColor.init(netHex: 0x6d6d6d), for: UIControlState()) tempButton.setTitleColor(UIColor.init(netHex: 0xf3f3f4), for: .selected) tempButton.titleLabel?.font = UIFont.NFXFont(size: 15) tempButton.addTarget(self, action: selector, for: .touchUpInside) return tempButton } @objc fileprivate func copyLabel(lpgr: UILongPressGestureRecognizer) { guard let text = (lpgr.view as? UILabel)?.text, copyAlert == nil else { return } UIPasteboard.general.string = text let alert = UIAlertController(title: "Text Copied!", message: nil, preferredStyle: .alert) copyAlert = alert self.present(alert, animated: true) { [weak self] in guard let `self` = self else { return } Timer.scheduledTimer(timeInterval: 0.45, target: self, selector: #selector(NFXDetailsController_iOS.dismissCopyAlert), userInfo: nil, repeats: false) } } @objc fileprivate func dismissCopyAlert() { copyAlert?.dismiss(animated: true) { [weak self] in self?.copyAlert = nil } } func createDetailsView(_ content: NSAttributedString, forView: EDetailsView) -> UIScrollView { var scrollView: UIScrollView scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 44, width: self.view.frame.width, height: self.view.frame.height - 44) scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.autoresizesSubviews = true scrollView.backgroundColor = UIColor.clear var textLabel: UILabel textLabel = UILabel() textLabel.frame = CGRect(x: 20, y: 20, width: scrollView.frame.width - 40, height: scrollView.frame.height - 20); textLabel.font = UIFont.NFXFont(size: 13) textLabel.textColor = UIColor.NFXGray44Color() textLabel.numberOfLines = 0 textLabel.attributedText = content textLabel.sizeToFit() textLabel.isUserInteractionEnabled = true scrollView.addSubview(textLabel) let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(NFXDetailsController_iOS.copyLabel)) textLabel.addGestureRecognizer(lpgr) var moreButton: UIButton moreButton = UIButton.init(frame: CGRect(x: 20, y: textLabel.frame.maxY + 10, width: scrollView.frame.width - 40, height: 40)) moreButton.backgroundColor = UIColor.NFXGray44Color() if ((forView == EDetailsView.request) && (self.selectedModel.requestBodyLength > 1024)) { moreButton.setTitle("Show request body", for: UIControlState()) moreButton.addTarget(self, action: #selector(NFXDetailsController_iOS.requestBodyButtonPressed), for: .touchUpInside) scrollView.addSubview(moreButton) scrollView.contentSize = CGSize(width: textLabel.frame.width, height: moreButton.frame.maxY + 16) } else if ((forView == EDetailsView.response) && (self.selectedModel.responseBodyLength > 1024)) { moreButton.setTitle("Show response body", for: UIControlState()) moreButton.addTarget(self, action: #selector(NFXDetailsController_iOS.responseBodyButtonPressed), for: .touchUpInside) scrollView.addSubview(moreButton) scrollView.contentSize = CGSize(width: textLabel.frame.width, height: moreButton.frame.maxY + 16) } else { scrollView.contentSize = CGSize(width: textLabel.frame.width, height: textLabel.frame.maxY + 16) } return scrollView } @objc func actionButtonPressed(_ sender: UIBarButtonItem) { let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) actionSheetController.addAction(cancelAction) let simpleLog: UIAlertAction = UIAlertAction(title: "Simple log", style: .default) { [unowned self] action -> Void in self.shareLog(full: false) } actionSheetController.addAction(simpleLog) let fullLogAction: UIAlertAction = UIAlertAction(title: "Full log", style: .default) { [unowned self] action -> Void in self.shareLog(full: true) } actionSheetController.addAction(fullLogAction) if let reqCurl = self.selectedModel.requestCurl { let curlAction: UIAlertAction = UIAlertAction(title: "Export request as curl", style: .default) { [unowned self] action -> Void in let activityViewController = UIActivityViewController(activityItems: [reqCurl], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) } actionSheetController.addAction(curlAction) } actionSheetController.view.tintColor = UIColor.NFXOrangeColor() self.present(actionSheetController, animated: true, completion: nil) } @objc func infoButtonPressed() { buttonPressed(self.infoButton) } @objc func requestButtonPressed() { buttonPressed(self.requestButton) } @objc func responseButtonPressed() { buttonPressed(self.responseButton) } @objc func handleSwipe(_ gesture: UISwipeGestureRecognizer) { guard let currentButtonIdx = headerButtons.index(where: { $0.isSelected }) else { return } let numButtons = headerButtons.count switch gesture.direction { case UISwipeGestureRecognizerDirection.left: let nextIdx = currentButtonIdx + 1 buttonPressed(headerButtons[nextIdx > numButtons - 1 ? 0 : nextIdx]) case UISwipeGestureRecognizerDirection.right: let previousIdx = currentButtonIdx - 1 buttonPressed(headerButtons[previousIdx < 0 ? numButtons - 1 : previousIdx]) default: break } } func buttonPressed(_ sender: UIButton) { guard let selectedButtonIdx = self.headerButtons.index(of: sender) else { return } let infoViews = [self.infoView, self.requestView, self.responseView] UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: { [unowned self] in self.headerButtons.indices.forEach { let button = self.headerButtons[$0] let view = infoViews[$0] button.isSelected = button == sender view.frame = CGRect(x: CGFloat(-selectedButtonIdx + $0) * view.frame.size.width, y: view.frame.origin.y, width: view.frame.size.width, height: view.frame.size.height) } }, completion: nil) } @objc func responseBodyButtonPressed() { bodyButtonPressed().bodyType = NFXBodyType.response } @objc func requestBodyButtonPressed() { bodyButtonPressed().bodyType = NFXBodyType.request } func bodyButtonPressed() -> NFXGenericBodyDetailsController { var bodyDetailsController: NFXGenericBodyDetailsController if self.selectedModel.shortType as String == HTTPModelShortType.IMAGE.rawValue { bodyDetailsController = NFXImageBodyDetailsController() } else { bodyDetailsController = NFXRawBodyDetailsController() } bodyDetailsController.selectedModel(self.selectedModel) self.navigationController?.pushViewController(bodyDetailsController, animated: true) return bodyDetailsController } func shareLog(full: Bool) { var tempString = String() tempString += "** INFO **\n" tempString += "\(getInfoStringFromObject(self.selectedModel).string)\n\n" tempString += "** REQUEST **\n" tempString += "\(getRequestStringFromObject(self.selectedModel).string)\n\n" tempString += "** RESPONSE **\n" tempString += "\(getResponseStringFromObject(self.selectedModel).string)\n\n" tempString += "logged via netfox - [https://github.com/kasketis/netfox]\n" if full { let requestFilePath = self.selectedModel.getRequestBodyFilepath() if let requestFileData = try? String(contentsOf: URL(fileURLWithPath: requestFilePath as String), encoding: .utf8) { tempString += requestFileData } let responseFilePath = self.selectedModel.getResponseBodyFilepath() if let responseFileData = try? String(contentsOf: URL(fileURLWithPath: responseFilePath as String), encoding: .utf8) { tempString += responseFileData } } displayShareSheet(shareContent: tempString) } func displayShareSheet(shareContent: String) { self.sharedContent = shareContent let activityViewController = UIActivityViewController(activityItems: [self], applicationActivities: nil) present(activityViewController, animated: true, completion: nil) } } extension NFXDetailsController_iOS: UIActivityItemSource { func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { return "placeholder" } func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? { return sharedContent } func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivityType?) -> String { return "netfox log - \(self.selectedModel.requestURL!)" } } #endif
mit
0d546685f555e2350f31b17e9d7740a2
40.6875
177
0.648247
5.084211
false
false
false
false
kharrison/CodeExamples
AllVisible/AllVisible/MasterViewController.swift
1
3153
// // MasterViewController.swift // AllVisible // // Created by Keith Harrison http://useyourloaf.com // Copyright (c) 2016-2018 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import UIKit final class MasterViewController: UIViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let navController = segue.destination as? UINavigationController, let viewController = navController.topViewController as? DetailViewController else { fatalError("Expected DetailViewController") } viewController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem viewController.navigationItem.leftItemsSupplementBackButton = true viewController.detailItem = Date() } } extension MasterViewController: UISplitViewControllerDelegate { func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { // Returning true prevents the default of showing // the secondary view controller. guard let navigationController = secondaryViewController as? UINavigationController, let detailViewController = navigationController.topViewController as? DetailViewController else { // Fallback to the default return false } // Once we have something to show in the detail // view return false to show the secondary in a // collapsed split view return detailViewController.detailItem == nil } }
bsd-3-clause
62f9e7127b7e0dab088316aaa0240afe
47.507692
191
0.747859
5.455017
false
false
false
false
StupidTortoise/personal
iOS/Swift/ModalViewSample/ModalViewSample/ViewController.swift
1
1428
// // ViewController.swift // ModalViewSample // // Created by tortoise on 7/11/15. // Copyright (c) 2015 703. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var username: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("registerCompletion:"), name: "RegisterCompletionNotification", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func registerClick(sender: UIButton) { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let registerViewController = mainStoryboard.instantiateViewControllerWithIdentifier("registerViewController") as? UIViewController registerViewController!.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal self.presentViewController(registerViewController!, animated: true, completion: {println("Present Modal View")}) } func registerCompletion(notification: NSNotification) { let data = notification.userInfo if let username = data?["username"] as? String { self.username.text = username } } }
gpl-2.0
b22806e15ab08e175e3bae2ab8d2d9b5
32.209302
158
0.69958
5.388679
false
false
false
false
skonmeme/Reservation
Reservation/AddressViewController.swift
1
6732
// // AddressViewController.swift // Reservation // // Created by Sung Gon Yi on 27/12/2016. // Copyright © 2016 skon. All rights reserved. // import UIKit import MapKit import Contacts protocol LocationSearchTableViewControllerDelegate { func locationSearchDidSelected(_ locationSearchTableViewController: LocationSearchTableViewController, placemark: MKPlacemark) } extension CLPlacemark { var pseudoAddress: String? { get { return (self.addressDictionary?[AnyHashable("FormattedAddressLines")] as? [String])?.joined(separator: ", ") ?? "" } } } class AddressViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, LocationSearchTableViewControllerDelegate { var delegate: AddressViewControllerDelegate? var address = String() var locationManager = CLLocationManager() var searchController = UISearchController() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.requestLocation() // Cancel self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "<", style: .plain, target: self, action: #selector(AddressViewController.cancelSearch)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(AddressViewController.selectSearch)) // Search bar if let storyboard = storyboard { let locationSearchTableViewController = storyboard.instantiateViewController(withIdentifier: "LocationSearchTableView") as! LocationSearchTableViewController locationSearchTableViewController.mapView = self.mapView locationSearchTableViewController.delegate = self self.searchController = UISearchController(searchResultsController: locationSearchTableViewController) self.searchController.searchResultsUpdater = locationSearchTableViewController } self.searchController.searchBar.sizeToFit() self.searchController.searchBar.placeholder = "Search for places" self.searchController.hidesNavigationBarDuringPresentation = false self.searchController.dimsBackgroundDuringPresentation = true self.navigationItem.titleView = self.searchController.searchBar self.definesPresentationContext = true // LocationSearchTableViewDelegate } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func cancelSearch(_ sender: Any) { self.dismiss(animated: true) } @IBAction func selectSearch(_ sender: Any) { if let address = self.searchController.searchBar.text { self.delegate?.addressSearched(self, address: address) } self.dismiss(animated: true) } // Location Manager Delegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { self.locationManager.requestLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { self.mapView.setRegion(MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)), animated: true) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("error:: (error)") } func locationSearchDidSelected(_ locationSearchTableViewController: LocationSearchTableViewController, placemark: MKPlacemark) { self.mapView.removeAnnotations(self.mapView.annotations) let annotation = MKPointAnnotation() annotation.coordinate = placemark.coordinate annotation.title = placemark.name annotation.subtitle = placemark.pseudoAddress self.mapView.addAnnotation(annotation) self.mapView.setRegion(MKCoordinateRegion(center: placemark.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)), animated: true) self.searchController.searchBar.text = placemark.pseudoAddress } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pointed") annotationView.isDraggable = true annotationView.isEnabled = true annotationView.canShowCallout = true annotationView.animatesDrop = true annotationView.tag = 3000 return annotationView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { guard let annotation = view.annotation else { return } if newState == .ending { CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude), completionHandler: { (placemarks, error) in guard let placemarks = placemarks else { print("Reverse geocoder failed with error: " + (error?.localizedDescription ?? "")) return } if placemarks.count > 0 { let placemark = placemarks[0] self.searchController.searchBar.text = placemark.pseudoAddress let annotationView = self.mapView.viewWithTag(3000) as! MKAnnotationView if let annotation = annotationView.annotation as? MKPointAnnotation { annotation.title = placemark.name annotation.subtitle = placemark.pseudoAddress } } }) } } }
mit
4a1b1de335d584f490a707a77d8afced
41.601266
176
0.683702
6.031362
false
false
false
false
february29/Learning
swift/Fch_Contact/Fch_Contact/BTools/BExtension/UIDevice+BBase.swift
1
920
// // UIDevice+BBase.swift // Fch_Contact // // Created by bai on 2017/12/1. // Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved. // import Foundation extension UIDevice { static func isIPhoneX() -> Bool { // BIsIPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) // UIScreen.main.currentMode?.size = CGSize(width: 1125, height: 2436); if UIScreen.main.bounds.height == 812 { return true } return false } static func versionGreatThanOrEqual(version:String) -> Bool{ let result = self.current.systemVersion.compare(version); if result == .orderedAscending{ return false; }else{ return true; } } }
mit
c6fce468420aa5cda123f486a458be20
24.514286
174
0.592385
4.232227
false
false
false
false
dduan/swift
test/SILGen/collection_downcast.swift
1
11831
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | FileCheck %s // REQUIRES: objc_interop import Foundation class BridgedObjC : NSObject { } func == (x: BridgedObjC, y: BridgedObjC) -> Bool { return true } struct BridgedSwift : Hashable, _ObjectiveCBridgeable { static func _isBridgedToObjectiveC() -> Bool { return true } var hashValue: Int { return 0 } func _bridgeToObjectiveC() -> BridgedObjC { return BridgedObjC() } static func _forceBridgeFromObjectiveC( x: BridgedObjC, result: inout BridgedSwift? ) { } static func _conditionallyBridgeFromObjectiveC( x: BridgedObjC, result: inout BridgedSwift? ) -> Bool { return true } } func == (x: BridgedSwift, y: BridgedSwift) -> Bool { return true } // CHECK-LABEL: sil hidden @_TF19collection_downcast17testArrayDowncast // CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<AnyObject>): func testArrayDowncast(array: [AnyObject]) -> [BridgedObjC] { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs15_arrayForceCast // CHECK: apply [[DOWNCAST_FN]]<AnyObject, BridgedObjC>([[ARRAY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Array<τ_0_1> return array as! [BridgedObjC] } // CHECK-LABEL: sil hidden @_TF19collection_downcast27testArrayDowncastFromObject // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): func testArrayDowncastFromObject(obj: AnyObject) -> [BridgedObjC] { // CHECK: unconditional_checked_cast_addr take_always AnyObject in [[OBJECT_ALLOC:%[0-9]+]] : $*AnyObject to Array<BridgedObjC> in [[VALUE_ALLOC:%[0-9]+]] : $*Array<BridgedObjC> return obj as! [BridgedObjC] } // CHECK-LABEL: sil hidden @_TF19collection_downcast28testArrayDowncastFromNSArray // CHECK: bb0([[NSARRAY_OBJ:%[0-9]+]] : $NSArray): func testArrayDowncastFromNSArray(obj: NSArray) -> [BridgedObjC] { // CHECK: unconditional_checked_cast_addr take_always NSArray in [[OBJECT_ALLOC:%[0-9]+]] : $*NSArray to Array<BridgedObjC> in [[VALUE_ALLOC:%[0-9]+]] : $*Array<BridgedObjC> return obj as! [BridgedObjC] } // CHECK-LABEL: sil hidden @_TF19collection_downcast28testArrayDowncastConditional // CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<AnyObject>): func testArrayDowncastConditional(array: [AnyObject]) -> [BridgedObjC]? { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs21_arrayConditionalCast // CHECK-NEXT: apply [[DOWNCAST_FN]]<AnyObject, BridgedObjC>([[ARRAY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> return array as? [BridgedObjC] } // CHECK-LABEL: sil hidden @_TF19collection_downcast12testArrayIsa // CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<AnyObject>) func testArrayIsa(array: [AnyObject]) -> Bool { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs21_arrayConditionalCast // CHECK-NEXT: apply [[DOWNCAST_FN]]<AnyObject, BridgedObjC>([[ARRAY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> return array is [BridgedObjC] ? true : false } // CHECK-LABEL: sil hidden @_TF19collection_downcast24testArrayDowncastBridged // CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<AnyObject>): func testArrayDowncastBridged(array: [AnyObject]) -> [BridgedSwift] { // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TFs15_arrayForceCast // CHECK-NEXT: apply [[BRIDGE_FN]]<AnyObject, BridgedSwift>([[ARRAY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Array<τ_0_1> return array as! [BridgedSwift] } // CHECK-LABEL: sil hidden @_TF19collection_downcast35testArrayDowncastBridgedConditional // CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<AnyObject>): func testArrayDowncastBridgedConditional(array: [AnyObject]) -> [BridgedSwift]?{ // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TFs21_arrayConditionalCast // CHECK-NEXT: apply [[BRIDGE_FN]]<AnyObject, BridgedSwift>([[ARRAY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> return array as? [BridgedSwift] } // CHECK-LABEL: sil hidden @_TF19collection_downcast19testArrayIsaBridged // CHECK: bb0([[ARRAY:%[0-9]+]] : $Array<AnyObject>) func testArrayIsaBridged(array: [AnyObject]) -> Bool { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs21_arrayConditionalCast // CHECK: apply [[DOWNCAST_FN]]<AnyObject, BridgedSwift>([[ARRAY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> return array is [BridgedSwift] ? true : false } // CHECK-LABEL: sil hidden @_TF19collection_downcast32testDictionaryDowncastFromObject // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): func testDictionaryDowncastFromObject(obj: AnyObject) -> Dictionary<BridgedObjC, BridgedObjC> { // CHECK: unconditional_checked_cast_addr take_always AnyObject in [[OBJECT_ALLOC:%[0-9]+]] : $*AnyObject to Dictionary<BridgedObjC, BridgedObjC> in [[VALUE_ALLOC:%[0-9]+]] : $*Dictionary<BridgedObjC, BridgedObjC> return obj as! Dictionary<BridgedObjC, BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast22testDictionaryDowncast // CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<NSObject, AnyObject>) func testDictionaryDowncast(dict: Dictionary<NSObject, AnyObject>) -> Dictionary<BridgedObjC, BridgedObjC> { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs19_dictionaryDownCast // CHECK-NEXT: apply [[DOWNCAST_FN]]<NSObject, AnyObject, BridgedObjC, BridgedObjC>([[DICT]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> return dict as! Dictionary<BridgedObjC, BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast33testDictionaryDowncastConditional // CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<NSObject, AnyObject>) func testDictionaryDowncastConditional(dict: Dictionary<NSObject, AnyObject>) -> Dictionary<BridgedObjC, BridgedObjC>? { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs30_dictionaryDownCastConditional // CHECK-NEXT: apply [[DOWNCAST_FN]]<NSObject, AnyObject, BridgedObjC, BridgedObjC>([[DICT]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> return dict as? Dictionary<BridgedObjC, BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast41testDictionaryDowncastBridgedVConditional // CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<NSObject, AnyObject>) func testDictionaryDowncastBridgedVConditional(dict: Dictionary<NSObject, AnyObject>) -> Dictionary<BridgedObjC, BridgedSwift>? { // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TFs42_dictionaryBridgeFromObjectiveCConditional // CHECK-NEXT: apply [[BRIDGE_FN]]<NSObject, AnyObject, BridgedObjC, BridgedSwift>([[DICT]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>>{{.*}} // user: %6 return dict as? Dictionary<BridgedObjC, BridgedSwift> } // CHECK-LABEL: sil hidden @_TF19collection_downcast41testDictionaryDowncastBridgedKConditional // CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<NSObject, AnyObject>) func testDictionaryDowncastBridgedKConditional(dict: Dictionary<NSObject, AnyObject>) -> Dictionary<BridgedSwift, BridgedObjC>? { // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TFs42_dictionaryBridgeFromObjectiveCConditional // CHECK-NEXT: apply [[BRIDGE_FN]]<NSObject, AnyObject, BridgedSwift, BridgedObjC>([[DICT]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> return dict as? Dictionary<BridgedSwift, BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast31testDictionaryDowncastBridgedKV // CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<NSObject, AnyObject>) func testDictionaryDowncastBridgedKV(dict: Dictionary<NSObject, AnyObject>) -> Dictionary<BridgedSwift, BridgedSwift> { // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TFs31_dictionaryBridgeFromObjectiveC // CHECK-NEXT: apply [[BRIDGE_FN]]<NSObject, AnyObject, BridgedSwift, BridgedSwift>([[DICT]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> return dict as! Dictionary<BridgedSwift, BridgedSwift> } // CHECK-LABEL: sil hidden @_TF19collection_downcast42testDictionaryDowncastBridgedKVConditional // CHECK: bb0([[DICT:%[0-9]+]] : $Dictionary<NSObject, AnyObject>) func testDictionaryDowncastBridgedKVConditional(dict: Dictionary<NSObject, AnyObject>) -> Dictionary<BridgedSwift, BridgedSwift>? { // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TFs42_dictionaryBridgeFromObjectiveCConditional // CHECK-NEXT: apply [[BRIDGE_FN]]<NSObject, AnyObject, BridgedSwift, BridgedSwift>([[DICT]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> return dict as? Dictionary<BridgedSwift, BridgedSwift> } // CHECK-LABEL: sil hidden @_TF19collection_downcast25testSetDowncastFromObject // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): func testSetDowncastFromObject(obj: AnyObject) -> Set<BridgedObjC> { // CHECK: unconditional_checked_cast_addr take_always AnyObject in [[OBJECT_ALLOC:%[0-9]+]] : $*AnyObject to Set<BridgedObjC> in [[VALUE_ALLOC:%[0-9]+]] : $*Set<BridgedObjC> return obj as! Set<BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast15testSetDowncast // CHECK: bb0([[SET:%[0-9]+]] : $Set<NSObject>) func testSetDowncast(dict: Set<NSObject>) -> Set<BridgedObjC> { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs12_setDownCast // CHECK-NEXT: apply [[DOWNCAST_FN]]<NSObject, BridgedObjC>([[SET]]) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@owned Set<τ_0_0>) -> @owned Set<τ_0_1> return dict as! Set<BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast26testSetDowncastConditional // CHECK: bb0([[SET:%[0-9]+]] : $Set<NSObject>) func testSetDowncastConditional(dict: Set<NSObject>) -> Set<BridgedObjC>? { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs23_setDownCastConditional // CHECK-NEXT: apply [[DOWNCAST_FN]]<NSObject, BridgedObjC>([[SET]]) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@owned Set<τ_0_0>) -> @owned Optional<Set<τ_0_1>> return dict as? Set<BridgedObjC> } // CHECK-LABEL: sil hidden @_TF19collection_downcast22testSetDowncastBridged // CHECK: bb0([[SET:%[0-9]+]] : $Set<NSObject>) func testSetDowncastBridged(dict: Set<NSObject>) -> Set<BridgedSwift> { // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs24_setBridgeFromObjectiveC // CHECK-NEXT: apply [[DOWNCAST_FN]]<NSObject, BridgedSwift>([[SET]]) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@owned Set<τ_0_0>) -> @owned Set<τ_0_1> return dict as! Set<BridgedSwift> } // CHECK-LABEL: sil hidden @_TF19collection_downcast33testSetDowncastBridgedConditional // CHECK: bb0([[SET:%[0-9]+]] : $Set<NSObject>) func testSetDowncastBridgedConditional(dict: Set<NSObject>) -> Set<BridgedSwift>? { return dict as? Set<BridgedSwift> // CHECK: [[DOWNCAST_FN:%[0-9]+]] = function_ref @_TFs35_setBridgeFromObjectiveCConditional // CHECK: apply [[DOWNCAST_FN]]<NSObject, BridgedSwift>([[SET]]) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Hashable, τ_0_1 : Hashable> (@owned Set<τ_0_0>) -> @owned Optional<Set<τ_0_1>> }
apache-2.0
950dd689b4173f61f4985774b80884e3
56.748768
282
0.69257
3.426776
false
true
false
false
hrscy/TodayNews
News/News/Classes/Video/View/VideoDetailUserView.swift
1
2734
// // VideoDetailUserView.swift // News // // Created by 杨蒙 on 2018/1/19. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import IBAnimatable import Kingfisher class VideoDetailUserView: UIView, NibLoadable { var userInfo = NewsUserInfo() { didSet { avatarImageView.kf.setImage(with: URL(string: userInfo.avatar_url)!) vImageView.isHidden = !userInfo.user_verified nameLabel.text = userInfo.name followerCountLabel.text = userInfo.fansCount + "粉丝" concernButton.isSelected = userInfo.follow concernButton.theme_backgroundColor = userInfo.follow ? "colors.userDetailFollowingConcernBtnBgColor" : "colors.globalRedColor" concernButton.borderColor = userInfo.follow ? .grayColor232() : .globalRedColor() concernButton.borderWidth = userInfo.follow ? 1 : 0 } } /// 覆盖按钮 @IBOutlet weak var coverButton: UIButton! /// 头像 @IBOutlet weak var avatarImageView: UIImageView! /// v @IBOutlet weak var vImageView: UIImageView! /// 用户名 @IBOutlet weak var nameLabel: UILabel! /// 粉丝数量 @IBOutlet weak var followerCountLabel: UILabel! /// 关注按钮点击 @IBOutlet weak var concernButton: AnimatableButton! override func awakeFromNib() { super.awakeFromNib() theme_backgroundColor = "colors.cellBackgroundColor" nameLabel.theme_textColor = "colors.black" followerCountLabel.theme_textColor = "colors.black" concernButton.theme_setTitleColor("colors.userDetailConcernButtonTextColor", forState: .normal) concernButton.theme_setTitleColor("colors.userDetailConcernButtonSelectedTextColor", forState: .selected) } /// 关注按钮点击 @IBAction func concernButtonClicked(_ sender: AnimatableButton) { if sender.isSelected { // 已经关注,点击则取消关注 // 已关注用户,取消关注 NetworkTool.loadRelationUnfollow(userId: userInfo.user_id, completionHandler: { (_) in sender.isSelected = !sender.isSelected sender.theme_backgroundColor = "colors.globalRedColor" }) } else { // 未关注,点击则关注这个用户 // 点击关注按钮,关注用户 NetworkTool.loadRelationFollow(userId: userInfo.user_id, completionHandler: { (_) in sender.isSelected = !sender.isSelected sender.theme_backgroundColor = "colors.userDetailFollowingConcernBtnBgColor" sender.borderColor = .grayColor232() sender.borderWidth = 1 }) } } }
mit
4de09888cfe1340ebed6e68c94270f1e
36.955882
139
0.65091
4.600713
false
false
false
false