repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
timgrohmann/vertretungsplan_ios
Vertretungsplan/ChangedLesson.swift
1
1686
// // ChangedLesson.swift // Vertretungsplan // // Created by Tim Grohmann on 15.08.16. // Copyright © 2016 Tim Grohmann. All rights reserved. // import Foundation import UIKit import CoreData class ChangedLesson: Equatable{ var subject: String = "" var origSubject: String? var teacher: String = "" var origTeacher: String? var room: String = "" var course: String = "" var info: String = "" var day: Int? var hour: Int? var identifier: String{ return subject+teacher+room+course+info+String(describing: day)+String(describing: hour) } init(subject: String, teacher: String, room: String, course: String, info: String, day: Int, hour: Int) { self.subject = subject self.teacher = teacher self.room = room self.course = course self.info = info self.day = day self.hour = hour } init(){} func applies(_ lesson: Lesson, user: User)->Bool{ if (course.lowercased() == lesson.course.lowercased()){ return true } if let oTeacher = self.origTeacher, let oSubject = self.origSubject { //print("asserting:",oTeacher.lowercased(),"==",lesson.teacher.lowercased()) return (oTeacher.lowercased() == lesson.teacher.lowercased()) && (oSubject.lowercased() == lesson.subject.lowercased()) } /*if klasse?.klassen.count == 1 && klasse?.klassen[0] == myKlasse{ return true }*/ return false } } func ==(lhs: ChangedLesson, rhs: ChangedLesson) -> Bool{ return lhs.identifier == rhs.identifier }
apache-2.0
89bb6ab63e8887fb5faccc8f03c981a5
25.746032
131
0.586944
4.099757
false
false
false
false
jbennett/Bugology
Bugology/MockPresentationContext.swift
1
1207
// // MockPresentationContext.swift // Bugology // // Created by Jonathan Bennett on 2016-01-20. // Copyright © 2016 Jonathan Bennett. All rights reserved. // import UIKit // swiftlint:disable variable_name_min_length public class MockPresentationContext: PresentationContext { func adsfa() { // let a = UIViewController() } var shownViewControllers = [UIViewController]() public func showViewController(vc: UIViewController, sender: AnyObject?) { shownViewControllers.append(vc) } var shownDetailViewControllers = [UIViewController]() public func showDetailViewController(vc: UIViewController, sender: AnyObject?) { shownDetailViewControllers.append(vc) } typealias VCCallback = (() -> Void) var presentedViewControllers = [UIViewController]() var presentedViewControllerCallbacks = [VCCallback?]() public func presentViewController(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) { presentedViewControllers.append(viewControllerToPresent) presentedViewControllerCallbacks.append(completion) } var styles = [Service?]() public func setStyleForService(service: Service?) { styles.append(service) } }
mit
b052c159fa19efbe462342085693cad8
27.714286
123
0.749585
4.882591
false
false
false
false
IngmarStein/swift
test/attr/attr_noescape.swift
4
18654
// RUN: %target-parse-verify-swift @noescape var fn : () -> Int = { 4 } // expected-error {{@noescape may only be used on 'parameter' declarations}} {{1-11=}} func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{29-39=}} func doesEscape(_ fn : @escaping () -> Int) {} func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-warning{{@noescape is the default and is deprecated}} {{47-57=}} func takesNoEscapeClosure(_ fn : () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-3{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-4{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} takesNoEscapeClosure { 4 } // ok _ = fn() // ok var x = fn // expected-error {{non-escaping parameter 'fn' may only be called}} // This is ok, because the closure itself is noescape. takesNoEscapeClosure { fn() } // This is not ok, because it escapes the 'fn' closure. doesEscape { fn() } // expected-error {{closure use of non-escaping parameter 'fn' may allow it to escape}} // This is not ok, because it escapes the 'fn' closure. func nested_function() { _ = fn() // expected-error {{declaration closing over non-escaping parameter 'fn' may allow it to escape}} } takesNoEscapeClosure(fn) // ok doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} takesGenericClosure(4, fn) // ok takesGenericClosure(4) { fn() } // ok. } class SomeClass { final var x = 42 func test() { // This should require "self." doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} // Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't // require "self." qualification of member references. takesNoEscapeClosure { x } } @discardableResult func foo() -> Int { foo() func plain() { foo() } let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} func multi() -> Int { foo(); return 0 } let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} takesNoEscapeClosure { foo(); return 0 } // okay func outer() { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } } let outer2: () -> Void = { func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}} let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} } doesEscape { func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}} let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} return 0 } takesNoEscapeClosure { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // okay return 0 } struct Outer { @discardableResult func bar() -> Int { bar() func plain() { bar() } let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} takesNoEscapeClosure { bar() } // okay doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} takesNoEscapeClosure { bar(); return 0 } // okay return 0 } } func structOuter() { struct Inner { @discardableResult func bar() -> Int { bar() // no-warning func plain() { bar() } let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}} func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}} doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} takesNoEscapeClosure { bar() } // okay doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} takesNoEscapeClosure { bar(); return 0 } // okay return 0 } } } return 0 } } // Implicit conversions (in this case to @convention(block)) are ok. @_silgen_name("whatever") func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{31-41=}} takeNoEscapeAsObjCBlock(fn) } // Autoclosure implies noescape, but produce nice diagnostics so people know // why noescape problems happen. func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping because it was declared @autoclosure}} doesEscape { a() } // expected-error {{closure use of non-escaping parameter 'a' may allow it to escape}} } // <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both func redundant(_ fn : @noescape // expected-error @+1 {{@noescape is implied by @autoclosure and should not be redundantly specified}} @autoclosure () -> Int) { // expected-warning@-2{{@noescape is the default and is deprecated}} {{23-33=}} } protocol P1 { associatedtype Element } protocol P2 : P1 { associatedtype Element } func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {} func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {} struct S : P2 { typealias Element = Int func each(_ transform: @noescape (Int) -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{26-36=}} overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, (Int) -> (), Int)'}} transform, 1) // expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, @escaping (O.Element) -> (), T), (P, @escaping (P.Element) -> (), T)}} } } // rdar://19763676 - False positive in @noescape analysis triggered by parameter label func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}} func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}} r19763676Callee({ _ in g(1) }) } // <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-warning {{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}} func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} calleeWithDefaultParameters(g) } // <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape class NoEscapeImmediatelyApplied { func f() { // Shouldn't require "self.", the closure is obviously @noescape. _ = { return ivar }() } final var ivar = 42 } // Reduced example from XCTest overlay, involves a TupleShuffleExpr public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { } public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { XCTAssertTrue(expression, message, file: file, line: line); } /// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{41-50=}} return { f in x.flatMap(f) } } func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{42-51=}} return { (f : @noescape (A) -> [B]) in // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}} x.flatMap(f) } } func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 } func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-warning{{@noescape is the default and is deprecated}} {{43-52=}} return { f in // expected-note{{parameter 'f' is implicitly non-escaping}} bad(f) // expected-error {{passing non-escaping parameter 'f' to function expecting an @escaping closure}} } } // SR-824 - @noescape for Type Aliased Closures // // Old syntax -- @noescape is the default, and is redundant typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} // Explicit @escaping is not allowed here typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}} // No @escaping -- it's implicit from context typealias CompletionHandler = (_ success: Bool) -> () var escape : CompletionHandlerNE var escapeOther : CompletionHandler func doThing1(_ completion: (_ success: Bool) -> ()) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing2(_ completion: CompletionHandlerNE) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing3(_ completion: CompletionHandler) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing4(_ completion: @escaping CompletionHandler) { escapeOther = completion } // <rdar://problem/19997680> @noescape doesn't work on parameters of function type func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U { // expected-warning@-1{{@noescape is the default and is deprecated}} {{23-33=}} // expected-warning@-2{{@noescape is the default and is deprecated}} {{46-56=}} // expected-warning@-3{{@noescape is the default and is deprecated}} {{57-66=}} return g(f) } // <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code enum r19997577Type { case Unit case Function(() -> r19997577Type, () -> r19997577Type) case Sum(() -> r19997577Type, () -> r19997577Type) func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-warning{{@noescape is the default and is deprecated}} {{53-63=}} let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}} switch self { case .Unit: return combine(initial, self) case let .Function(t1, t2): return binary(t1(), t2()) case let .Sum(t1, t2): return binary(t1(), t2()) } } } // type attribute and decl attribute func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} {{16-25=}} {{29-29=@noescape }} func noescapeT(f: @noescape () -> Bool) {} // expected-warning{{@noescape is the default and is deprecated}} {{19-29=}} func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{19-31=}} {{35-35=@autoclosure }} func autoclosureT(f: @autoclosure () -> Bool) {} // ok func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}} func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{29-41=}} {{45-45=@autoclosure }} // expected-warning@-1{{@noescape is the default and is deprecated}} {{45-55=}}
apache-2.0
60ae67d1ada48bcc88c3c788e9875675
53.703812
214
0.659376
4.028072
false
false
false
false
h-n-y/BigNerdRanch-SwiftProgramming
chapter-25/GoldChallenge.playground/Contents.swift
1
915
/* GOLD CHALLENGE The method indexOf(_:) is made available in an extension on `CollectionType` that requires the `CollectionType`s `Element`s to conform to the `Equatable` protocol. `Array<Person>` ( the type of *people*, below ) conforms to `CollectionType`, but `Person` must also conform to `Equatable` in order to access the indexOf(_:) method. Here, I've made two `Person` types considered equal if their name and age types are themselves equal. */ import Cocoa class Person: Equatable { let name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } func ==(lhs: Person, rhs: Person) -> Bool { return ( lhs.name == rhs.name ) && ( lhs.age == rhs.age ) } let p1 = Person(name: "John", age: 26) let p2 = Person(name: "Jane", age: 22) var people: [Person] = [p1, p2] let p1Index = people.indexOf(p1)
mit
62e68e6c979a753b7e39e4f914726ee1
25.941176
95
0.642623
3.519231
false
false
false
false
swift-lang/swift-k
tests/language-behaviour/mappers/075-array-mapper.swift
2
364
type messagefile; (messagefile t) write() { app { echo @filename(t) stdout=@filename(t); } } string fns[]=["075-array-mapper.first.out", "075-array-mapper.second.out", "075-array-mapper.third.out"]; messagefile outfile[] <array_mapper; files=fns>; outfile[0] = write(); outfile[1] = write(); outfile[2] = write();
apache-2.0
97aff3f6dec6515109c64e8b25a70e28
19.222222
48
0.590659
3.192982
false
false
true
false
LoganHollins/SuperStudent
SuperStudent/AddEventViewController.swift
1
2130
// // AddEventViewController.swift // SuperStudent // // Created by Logan Hollins on 2015-11-28. // Copyright © 2015 Logan Hollins. All rights reserved. // import UIKit import Alamofire class AddEventViewController: UIViewController { var eventObject = Event() @IBOutlet weak var descriptionField: UITextView! @IBOutlet weak var titleField: UITextField! @IBOutlet weak var endTimeField: UIDatePicker! @IBOutlet weak var startTimeField: UIDatePicker! @IBOutlet weak var dateField: UIDatePicker! @IBOutlet weak var locationField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.descriptionField.layer.borderWidth = 1 self.descriptionField.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor self.descriptionField.layer.cornerRadius = 5 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func createEvent(sender: AnyObject) { let dFormatter = NSDateFormatter() dFormatter.dateFormat = "yyyy-MM-dd" let tFormatter = NSDateFormatter() tFormatter.dateFormat = "hh:mm a" let currentDate = NSDate() let parameters : [String : AnyObject] = [ "title": titleField.text!, "date": dFormatter.stringFromDate(dateField.date), "location": locationField.text!, "startTime": tFormatter.stringFromDate(startTimeField.date), "endTime": tFormatter.stringFromDate(startTimeField.date), "description": descriptionField.text! ] Alamofire.request(.POST, "https://api.mongolab.com/api/1/databases/rhythmictracks/collections/Events?apiKey=L4HrujTTG-XOamCKvRJp5RwYMpoJ6xCZ", parameters: parameters, encoding: .JSON) StudentInfo.EventCreated = true navigationController?.popViewControllerAnimated(true) } }
gpl-2.0
7047fd55cb82fe99ddf7f2f646a00ed3
33.33871
191
0.658055
4.66886
false
false
false
false
Chantalisima/Spirometry-app
EspiroGame/ResultViewController.swift
1
6616
// // ResultViewController.swift // BLEgame4 // // Created by Chantal de Leste on 25/3/17. // Copyright © 2017 Universidad de Sevilla. All rights reserved. // import Foundation import UIKit import CoreData import MessageUI struct cellData { var name: String! var value: Float! } class ResultViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate { var FVC: Float = 0.0 var FEV1: Float = 0.0 var PEF: Float = 0.0 var ratio: Float = 0.0 var names = ["FVC","FEV1","ratio"] var results: [Float] = [] var arrayRPM1: [Int] = [] var arrayRPM2: [Int] = [] var arrayRPM3: [Int] = [] var arrayVol: [Float] = [] var arrayFlow: [Float] = [] var computeResult = ComputeResults() @IBOutlet weak var tableView: UITableView! @IBOutlet weak var lineChart: LineChart! @IBAction func saveDataButton(_ sender: Any) { saveData(fvc: FVC, fev1: FEV1, ratio: ratio) } @IBAction func sendEmailButton(_ sender: Any) { let mailComposeViewController = configureMailController() if MFMailComposeViewController.canSendMail(){ self.present(mailComposeViewController, animated: true, completion: nil) }else{ showMailError() } } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self compute() setLineChart(xdata: arrayVol, ydata: arrayFlow) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)?.first as! CustomTableViewCell cell.name.text = names[indexPath.row] // cell.nameLabel.text = names[indexPath.row] cell.value.text = String(results[indexPath.row]) return cell } func compute(){ var ev = computeResult.evaluatefvc(first: arrayRPM1, second: arrayRPM2, third: arrayRPM3) let flow1 = computeResult.convertToFlow(rpms: ev[0]) print("flujo:\(flow1)") let flow2 = computeResult.convertToFlow(rpms: ev[1]) let volumen1 = computeResult.convertToVolume(flow: flow1) print("volumen:\(volumen1)") //let volumen2 = computeResult.convertToVolume(flow: flow2) /*let volumes:[[Float]] = [volumen1,volumen2,volumen3] let maxvolumesfev1 = computeResult.evaluatefev1(volumes: volumes)*/ FVC = computeResult.computeFVC(volumes: volumen1) results.append(FVC) FEV1 = computeResult.computeFEV1(volume: volumen1) results.append(FEV1) ratio = computeResult.computeRatio(fvc: FVC, fev: FEV1) results.append(ratio) arrayVol = volumen1 arrayFlow = flow1 } func setLineChart(xdata: [Float], ydata:[Float]) { var charData: [CGPoint] = [] let length = xdata.count-1 print("length of xdata: \(xdata.count)") print("length of ydata: \(ydata.count)") for index in 0..<length { charData.append(CGPoint(x: Double(xdata[index]), y: Double(ydata[index]))) } print(charData as Any) lineChart.xMax = 6 lineChart.xMin = 0 lineChart.deltaX = 1 lineChart.yMax = 8 lineChart.yMin = 0 lineChart.deltaY = 1 lineChart.plot(charData) } func saveData(fvc: Float,fev1: Float,ratio: Float){ let appDelegate = (UIApplication.shared.delegate) as! AppDelegate let context = appDelegate.persistentContainer.viewContext let newTest = NSEntityDescription.insertNewObject(forEntityName: "Test", into: context) let date = Date() let calendar = Calendar.current let year = calendar.component(.year, from: date) let month = calendar.component(.month, from: date) let week = calendar.component(.weekday, from: date) let day = calendar.component(.day, from: date) let hour = calendar.component(.hour, from: date) let minute = calendar.component(.minute, from: date) newTest.setValue(fvc, forKey: "fvc") newTest.setValue(fev1, forKey: "fev1") newTest.setValue(ratio, forKey: "ratio") newTest.setValue(date, forKey: "date") newTest.setValue(year, forKey: "year") newTest.setValue(month, forKey: "month") newTest.setValue(week, forKey: "week") newTest.setValue(day, forKey: "day") newTest.setValue(hour, forKey: "hour") newTest.setValue(minute, forKey: "minute") //appDelegate.saveContext() do{ try newTest.managedObjectContext?.save() }catch{ print("error") } } func configureMailController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setCcRecipients(["[email protected]"]) mailComposerVC.setSubject("Chart flow/volumen") mailComposerVC.setMessageBody("Hello, I attach to this email my results from today:", isHTML: false) //Create the UIImage UIGraphicsBeginImageContext(view.frame.size) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() //Save it to the camera roll //UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) let imageData = UIImageJPEGRepresentation(image!, 1.0) mailComposerVC.addAttachmentData(imageData!, mimeType: "image/jpeg", fileName: "My Image") return mailComposerVC } func showMailError() { let sendMailErrorAlert = UIAlertController(title: "Could not send email", message: "Your device could not send email", preferredStyle: .alert) let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil) sendMailErrorAlert.addAction(dismiss) self.present(sendMailErrorAlert, animated: true, completion: nil) } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
apache-2.0
0330d9d011faf1006124b51642da2309
33.453125
150
0.634014
4.546392
false
true
false
false
cuappdev/eatery
Eatery/Onboarding/Controllers/OnboardingViewController.swift
1
5372
// // OnboardingViewController.swift // Eatery // // Created by Reade Plunkett on 11/11/19. // Copyright © 2019 CUAppDev. All rights reserved. // import UIKit protocol OnboardingViewControllerDelegate { func onboardingViewControllerDidTapNext(_ viewController: OnboardingViewController) } class OnboardingViewController: UIViewController { private let stackView = UIStackView() private var stackViewBottomConstraint: NSLayoutConstraint? private var skipButtonTopContraint: NSLayoutConstraint? private let titleLabel = UILabel() private let subtitleLabel = UILabel() private let onboardingTitle: String private let onboardingSubtitle: String private let skipButton = UIButton() let contentView = UIView() var delegate: OnboardingViewControllerDelegate? init(title: String, subtitle: String) { self.onboardingTitle = title self.onboardingSubtitle = subtitle super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .eateryBlue setUpStackView() setUpTitleLabel() setUpSubtitleLabel() setUpContentView() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil) } private func setUpStackView() { stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .center stackView.spacing = 40 view.addSubview(stackView) stackView.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(32) make.centerY.equalToSuperview().priority(.high) } stackViewBottomConstraint = view.bottomAnchor.constraint(equalTo: stackView.bottomAnchor) stackViewBottomConstraint?.isActive = false } private func setUpTitleLabel() { titleLabel.text = onboardingTitle titleLabel.textColor = .white titleLabel.textAlignment = .center titleLabel.font = .systemFont(ofSize: 36, weight: .bold) stackView.addArrangedSubview(titleLabel) } private func setUpSubtitleLabel() { subtitleLabel.text = onboardingSubtitle subtitleLabel.textColor = .white subtitleLabel.numberOfLines = 0 subtitleLabel.textAlignment = .center subtitleLabel.font = .systemFont(ofSize: 24, weight: .medium) stackView.addArrangedSubview(subtitleLabel) } private func setUpContentView() { stackView.addArrangedSubview(contentView) } func setUpSkipButton(target: Any?, action: Selector) { skipButton.setTitle("SKIP", for: .normal) skipButton.titleLabel?.font = .systemFont(ofSize: 18, weight: .bold) skipButton.titleLabel?.textColor = .white skipButton.addTarget(target, action: action, for: .touchUpInside) view.addSubview(skipButton) skipButton.snp.makeConstraints { make in make.topMargin.equalToSuperview().offset(32) make.rightMargin.equalToSuperview().offset(-32) } skipButtonTopContraint = view.topAnchor.constraint(equalTo: skipButton.topAnchor) skipButtonTopContraint?.isActive = false } } extension OnboardingViewController { @objc private func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo, let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } let actions: () -> Void = { self.stackViewBottomConstraint?.constant = keyboardFrame.height + 16 self.stackViewBottomConstraint?.isActive = true self.skipButtonTopContraint?.constant = keyboardFrame.height + 16 self.skipButtonTopContraint?.isActive = true self.view.layoutIfNeeded() } if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval { UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: actions) } else { actions() } } @objc private func keyboardWillHide(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } let actions: () -> Void = { self.stackViewBottomConstraint?.isActive = false self.skipButtonTopContraint?.isActive = false self.view.layoutIfNeeded() } if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval { UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: actions) } else { actions() } } }
mit
3eec7f317150479fb0d0bb5bfe340204
33.429487
105
0.639732
5.707758
false
false
false
false
zpz1237/NirZhihuDaily2.0
zhihuDaily 2.0/ThemeViewController.swift
2
12746
// // ThemeViewController.swift // zhihuDaily 2.0 // // Created by Nirvana on 10/15/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import SDWebImage class ThemeViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var navTitleLabel: UILabel! @IBOutlet weak var topConstant: NSLayoutConstraint! var id = "" var name = "" var firstDisplay = true var dragging = false var triggered = false var navImageView: UIImageView! var themeSubview: ParallaxHeaderView! var animator: ZFModalTransitionAnimator! var loadCircleView: PNCircleChart! var loadingView: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false //清空原数据 self.appCloud().themeContent = nil //拿到新数据 refreshData(nil) //创建leftBarButtonItem let leftButton = UIBarButtonItem(image: UIImage(named: "leftArrow"), style: .Plain, target: self.revealViewController(), action: "revealToggle:") leftButton.tintColor = UIColor.whiteColor() self.navigationItem.setLeftBarButtonItem(leftButton, animated: false) //为当前view添加手势识别 self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) //生成并配置HeaderImageView navImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, 64)) navImageView.contentMode = UIViewContentMode.ScaleAspectFill navImageView.clipsToBounds = true //将其添加到ParallaxView themeSubview = ParallaxHeaderView.parallaxThemeHeaderViewWithSubView(navImageView, forSize: CGSizeMake(self.view.frame.width, 64), andImage: navImageView.image) as! ParallaxHeaderView themeSubview.delegate = self //将ParallaxView设置为tableHeaderView,主View添加tableView self.tableView.tableHeaderView = themeSubview self.view.addSubview(tableView) //设置NavigationBar为透明 self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor()) self.navigationController?.navigationBar.shadowImage = UIImage() //初始化下拉加载loadCircleView let comp1 = self.navTitleLabel.frame.width/2 let comp2 = (self.navTitleLabel.text! as NSString).sizeWithAttributes(nil).width/2 let loadCircleViewXPosition = comp1 - comp2 - 35 loadCircleView = PNCircleChart(frame: CGRect(x: loadCircleViewXPosition, y: 3, width: 15, height: 15), total: 100, current: 0, clockwise: true, shadow: false, shadowColor: nil, displayCountingLabel: false, overrideLineWidth: 1) loadCircleView.backgroundColor = UIColor.clearColor() loadCircleView.strokeColor = UIColor.whiteColor() loadCircleView.strokeChart() loadCircleView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) self.navTitleLabel.addSubview(loadCircleView) //初始化下拉加载loadingView loadingView = UIActivityIndicatorView(frame: CGRect(x: loadCircleViewXPosition+2.5, y: 5.5, width: 10, height: 10)) self.navTitleLabel.addSubview(loadingView) //tableView基础设置 self.tableView.delegate = self self.tableView.dataSource = self self.tableView.separatorStyle = .None self.tableView.showsVerticalScrollIndicator = false } override func viewDidAppear(animated: Bool) { self.tableView.reloadData() if !firstDisplay { self.topConstant.constant = -44 } else { self.topConstant.constant = -64 firstDisplay = false } } func refreshData(completionHandler: (()->())?) { //更改标题 navTitleLabel.text = name //获取数据 Alamofire.request(.GET, "http://news-at.zhihu.com/api/4/theme/" + id).responseJSON { (_, _, dataResult) -> Void in guard dataResult.error == nil else { print("数据获取失败") return } let data = JSON(dataResult.value!) //取得Story let storyData = data["stories"] //暂时注入themeStory var themeStory: [ContentStoryModel] = [] for i in 0 ..< storyData.count { //判断是否含图 if storyData[i]["images"] != nil { themeStory.append(ContentStoryModel(images: [storyData[i]["images"][0].string!], id: String(storyData[i]["id"]), title: storyData[i]["title"].string!)) } else { //若不含图 themeStory.append(ContentStoryModel(images: [""], id: String(storyData[i]["id"]), title: storyData[i]["title"].string!)) } } //取得avatars let avatarsData = data["editors"] //暂时注入editorsAvatars var editorsAvatars: [String] = [] for i in 0 ..< avatarsData.count { editorsAvatars.append(avatarsData[i]["avatar"].string!) } //更新图片 self.navImageView.sd_setImageWithURL(NSURL(string: data["background"].string!), completed: { (image, _, _, _) -> Void in self.themeSubview.blurViewImage = image self.themeSubview.refreshBlurViewForNewImage() }) //注入themeContent self.appCloud().themeContent = ThemeContentModel(stories: themeStory, background: data["background"].string!, editorsAvatars: editorsAvatars) //刷新数据 self.tableView.reloadData() if let completionHandler = completionHandler { completionHandler() } } } //设置StatusBar颜色 override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } //获取总代理 func appCloud() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } } extension ThemeViewController: UITableViewDelegate, UITableViewDataSource, ParallaxHeaderViewDelegate { //实现Parallax效果 func scrollViewDidScroll(scrollView: UIScrollView) { let header = self.tableView.tableHeaderView as! ParallaxHeaderView header.layoutThemeHeaderViewForScrollViewOffset(scrollView.contentOffset) let offsetY = scrollView.contentOffset.y if offsetY <= 0 { let ratio = -offsetY*2 if ratio <= 100 { if triggered == false && loadCircleView.hidden == true { loadCircleView.hidden = false } loadCircleView.updateChartByCurrent(ratio) } else { if loadCircleView.current != 100 { loadCircleView.updateChartByCurrent(100) } //第一次检测到松手 if !dragging && !triggered { loadCircleView.hidden = true loadingView.startAnimating() refreshData({ () -> () in self.loadingView.stopAnimating() }) triggered = true } } if triggered == true && offsetY == 0 { triggered = false } } else { if loadCircleView.hidden != true { loadCircleView.hidden = true } } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { dragging = false } func scrollViewWillBeginDragging(scrollView: UIScrollView) { dragging = true } //设置滑动极限 func lockDirection() { self.tableView.contentOffset.y = -95 } //处理UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //如果还未获取到数据 if appCloud().themeContent == nil { return 0 } //如含有数据 return appCloud().themeContent!.stories.count + 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //取得已读新闻数组以供配置 let readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String] if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("themeEditorTableViewCell") as! ThemeEditorTableViewCell for (index, editorsAvatar) in appCloud().themeContent!.editorsAvatars.enumerate() { let avatar = UIImageView(frame: CGRectMake(62 + CGFloat(37 * index), 12.5, 20, 20)) avatar.contentMode = .ScaleAspectFill avatar.layer.cornerRadius = 10 avatar.clipsToBounds = true avatar.sd_setImageWithURL(NSURL(string: editorsAvatar)) cell.contentView.addSubview(avatar) } return cell } //取到Story数据 let tempContentStoryItem = appCloud().themeContent!.stories[indexPath.row - 1] //保证图片一定存在,选择合适的Cell类型 guard tempContentStoryItem.images[0] != "" else { let cell = tableView.dequeueReusableCellWithIdentifier("themeTextTableViewCell") as! ThemeTextTableViewCell //验证是否已被点击过 if let _ = readNewsIdArray.indexOf(tempContentStoryItem.id) { cell.themeTextLabel.textColor = UIColor.lightGrayColor() } else { cell.themeTextLabel.textColor = UIColor.blackColor() } cell.themeTextLabel.text = tempContentStoryItem.title return cell } //处理图片存在的情况 let cell = tableView.dequeueReusableCellWithIdentifier("themeContentTableViewCell") as! ThemeContentTableViewCell //验证是否已被点击过 if let _ = readNewsIdArray.indexOf(tempContentStoryItem.id) { cell.themeContentLabel.textColor = UIColor.lightGrayColor() } else { cell.themeContentLabel.textColor = UIColor.blackColor() } cell.themeContentLabel.text = tempContentStoryItem.title cell.themeContentImageView.sd_setImageWithURL(NSURL(string: tempContentStoryItem.images[0])) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return 45 } return 92 } //处理UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { return } //拿到webViewController let webViewController = self.storyboard?.instantiateViewControllerWithIdentifier("webViewController") as! WebViewController webViewController.newsId = appCloud().themeContent!.stories[self.tableView.indexPathForSelectedRow!.row - 1].id webViewController.index = indexPath.row - 1 webViewController.isThemeStory = true //取得已读新闻数组以供修改 var readNewsIdArray = NSUserDefaults.standardUserDefaults().objectForKey(Keys.readNewsId) as! [String] //记录已被选中的id readNewsIdArray.append(webViewController.newsId) NSUserDefaults.standardUserDefaults().setObject(readNewsIdArray, forKey: Keys.readNewsId) //对animator进行初始化 animator = ZFModalTransitionAnimator(modalViewController: webViewController) self.animator.dragable = true self.animator.bounces = false self.animator.behindViewAlpha = 0.7 self.animator.behindViewScale = 0.9 self.animator.transitionDuration = 0.7 self.animator.direction = ZFModalTransitonDirection.Right //设置webViewController webViewController.transitioningDelegate = self.animator //实施转场 self.presentViewController(webViewController, animated: true) { () -> Void in } } }
mit
2cf36f926049a87aa9459aa1ecbe4abb
38.028662
235
0.619665
5.417772
false
false
false
false
ps2/rileylink_ios
MinimedKit/Messages/PowerOnCarelinkMessageBody.swift
1
782
// // PowerOnCarelinkMessageBody.swift // Naterade // // Created by Nathan Racklyeft on 12/26/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation public struct PowerOnCarelinkMessageBody: MessageBody { public static var length: Int = 65 public var txData: Data let duration: TimeInterval public init(duration: TimeInterval) { self.duration = duration let numArgs = 2 let on = 1 let durationMinutes: Int = Int(ceil(duration / 60.0)) self.txData = Data(hexadecimalString: String(format: "%02x%02x%02x", numArgs, on, durationMinutes))!.paddedTo(length: PowerOnCarelinkMessageBody.length) } public var description: String { return "PowerOn(duration:\(duration))" } }
mit
6ad7e78071ff363a4e2a34e287f77d4a
25.931034
160
0.681178
4.067708
false
false
false
false
benlangmuir/swift
test/Interop/SwiftToCxx/structs/swift-struct-in-cxx.swift
2
4450
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Structs -clang-header-expose-public-decls -emit-clang-header-path %t/structs.h // RUN: %FileCheck %s < %t/structs.h // RUN: %check-interop-cxx-header-in-clang(%t/structs.h -Wno-unused-private-field -Wno-unused-function) // CHECK: namespace Structs { // CHECK: namespace _impl { // CHECK: namespace Structs { // CHECK: namespace _impl { // CHECK-EMPTY: // CHECK-NEXT: class _impl_StructWithIntField; // CHECK-EMPTY: // CHECK-NEXT: // Type metadata accessor for StructWithIntField // CHECK-NEXT: SWIFT_EXTERN swift::_impl::MetadataResponseTy $s7Structs18StructWithIntFieldVMa(swift::_impl::MetadataRequestTy) SWIFT_NOEXCEPT SWIFT_CALL; // CHECK-EMPTY: // CHECK-EMPTY: // CHECK-NEXT: } // CHECK: class StructWithIntField final { // CHECK-NEXT: public: // CHECK-NEXT: inline ~StructWithIntField() { // CHECK: } // CHECK-NEXT: inline StructWithIntField(const StructWithIntField &other) { // CHECK: } // CHECK-NEXT: inline StructWithIntField(StructWithIntField &&) = default; // CHECK-NEXT: private: // CHECK-NEXT: inline StructWithIntField() {} // CHECK-NEXT: static inline StructWithIntField _make() { return StructWithIntField(); } // CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage; } // CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage; } // CHECK-EMPTY: // CHECK-NEXT: alignas(8) char _storage[8]; // CHECK-NEXT: friend class _impl::_impl_StructWithIntField; // CHECK-NEXT: }; // CHECK: namespace _impl { // CHECK-EMPTY: // CHECK-NEXT: class _impl_StructWithIntField { // CHECK-NEXT: public: // CHECK-NEXT: static inline char * _Nonnull getOpaquePointer(StructWithIntField &object) { return object._getOpaquePointer(); } // CHECK-NEXT: static inline const char * _Nonnull getOpaquePointer(const StructWithIntField &object) { return object._getOpaquePointer(); } // CHECK-NEXT: template<class T> // CHECK-NEXT: static inline StructWithIntField returnNewValue(T callable) { // CHECK-NEXT: auto result = StructWithIntField::_make(); // CHECK-NEXT: callable(result._getOpaquePointer()); // CHECK-NEXT: return result; // CHECK-NEXT: } // CHECK-NEXT: static inline void initializeWithTake(char * _Nonnull destStorage, char * _Nonnull srcStorage) { // CHECK-NEXT: auto metadata = _impl::$s7Structs18StructWithIntFieldVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: vwTable->initializeWithTake(destStorage, srcStorage, metadata._0); // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-EMPTY: // CHECK-NEXT: } // CHECK-EMPTY: // CHECK-NEXT: } // end namespace // CHECK-EMPTY: // CHECK-NEXT: namespace swift { // CHECK-NEXT: #pragma clang diagnostic push // CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions" // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<Structs::StructWithIntField> = true; // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<Structs::StructWithIntField> // CHECK-NEXT: inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return Structs::_impl::$s7Structs18StructWithIntFieldVMa(0)._0; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-NEXT: namespace _impl{ // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isValueType<Structs::StructWithIntField> = true; // CHECK-NEXT: template<> // CHECK-NEXT: struct implClassFor<Structs::StructWithIntField> { using type = Structs::_impl::_impl_StructWithIntField; }; // CHECK-NEXT: } // namespace // CHECK-NEXT: #pragma clang diagnostic pop // CHECK-NEXT: } // namespace swift // CHECK-EMPTY: // CHECK-NEXT: namespace Structs { public struct StructWithIntField { let field: Int64 } // Special name gets renamed in C++. // CHECK: class register_ final { // CHECK: alignas(8) char _storage[16]; // CHECK-NEXT: friend class // CHECK-NEXT: }; public struct register { let field1: Int64 let field2: Int64 } // CHECK: } // namespace Structs
apache-2.0
266ef4d9280753cfac34c9637808e09e
42.203883
231
0.71191
3.696013
false
false
false
false
codepgq/LearningSwift
ListenKeyboard/ListenKeyboard/ViewController.swift
1
4231
// // ViewController.swift // ListenKeyboard // // Created by ios on 16/9/24. // Copyright © 2016年 ios. All rights reserved. // import UIKit class ViewController: UIViewController,UITextViewDelegate { @IBOutlet weak var toolBarConstraints: NSLayoutConstraint! @IBOutlet weak var toobar: UIToolbar! @IBOutlet weak var textView: UITextView! @IBOutlet weak var textCount: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() /* UIKeyboardWillHideNotification 将要隐藏 UIKeyboardWillShowNotification 将要显示 UIKeyboardDidChangeFrameNotification 已经修改frame UIKeyboardWillChangeFrameNotification 将要修改frame UIKeyboardDidHideNotification 已经隐藏 UIKeyboardDidShowNotification 已经显示 */ /* UIKeyboardFrameBeginUserInfoKey Rect UIKeyboardFrameEndUserInfoKey Rect UIKeyboardAnimationDurationUserInfoKey 动画时长 UIKeyboardAnimationCurveUserInfoKey 动画Options UIKeyboardIsLocalUserInfoKey NSNumber of BOOL */ /** 监听键盘将要出现通知 */ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification , object: nil) /** 监听键盘将要隐藏通知 */ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification , object: nil) /** 设置textView的背景颜色 - parameter white: 白色 0表示黑色 1表示白色 - parameter alpha: 透明度 */ textView.backgroundColor = UIColor(white: 0, alpha: 0.3) /** 代理 */ textView.delegate = self } /** 点击取消 - parameter sender: 取消 */ @IBAction func cancel(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } /** 点击其他的地方取消键盘编辑 - parameter touches: - parameter event: */ override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { view.endEditing(true) } /** 键盘将要显示 - parameter note: 通知 */ @objc private func keyboardWillShow(note:NSNotification){ //获取信息 let userInfo = note.userInfo //得到rect let endRect = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() //得到动画时长 let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue //开始动画 UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16)), animations: { self.toolBarConstraints.constant = endRect.height self.toobar.layoutIfNeeded() }, completion: nil) } /** 键盘将要隐藏 - parameter note: 通知 */ @objc private func keyboardWillHide(note:NSNotification){ let userInfo = note.userInfo let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue UIView.animateWithDuration(duration, delay: 0, options: [], animations: { self.toolBarConstraints.constant = 0 self.toobar.layoutIfNeeded() }, completion: nil) } } //*********************** textView代理 ***************** extension ViewController{ func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{ let text = textView.text as NSString if text.length >= 140 { textView.text = text.substringToIndex(140) } textCount.title = "\(140 - text.length)" //如果这里返回false,textView就不能编辑啦! return true } }
apache-2.0
05e04e15aea83a8160a5d6bb54ac574c
31.377049
200
0.623038
5.547753
false
false
false
false
tannernelson/hamburger-menu
Pod/Classes/DefaultMenuView.swift
1
2171
// // DefaultMenu.swift // Pods // // Created by Tanner Nelson on 1/16/16. // // import Foundation @available(iOS 9 , *) class DefaultMenuView: MenuView { override init(rootView: UIView, controller: MenuController) { super.init(rootView: rootView, controller: controller) self.backgroundColor = UIColor.whiteColor() let stackView = UIStackView() stackView.axis = .Vertical self.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false //align to edges of super view self.addConstraint( NSLayoutConstraint(item: stackView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 20) ) self.addConstraint( NSLayoutConstraint(item: stackView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0) ) self.addConstraint( NSLayoutConstraint(item: stackView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0) ) if let items = controller.tabBar.items { for (index, item) in items.enumerate() { let button = UIButton() button.contentHorizontalAlignment = .Left button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 0) button.setTitleColor(controller.view.tintColor, forState: .Normal) button.setTitle(item.title, forState: .Normal) button.tag = index button.addTarget(self, action: Selector("buttonTap:"), forControlEvents: .TouchUpInside) stackView.addArrangedSubview(button) } } } func buttonTap(sender: UIButton) { self.switchToTab(sender.tag, andClose: true) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
043b8b90befa46a270097bf48f25c035
31.41791
146
0.588669
4.922902
false
false
false
false
paulomendes/nextel-challange
nextel-challange/Source/DataProvider/MoviesConnector.swift
1
5084
import Alamofire import Gloss import UIKit protocol MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) } enum MoviesConnectorError { case errorInSaveLocalFile case internetError } class MoviesConnector : MoviesConnectorProtocol { let moviesPersistence: Persistence static let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() init(moviesPersistence: Persistence) { self.moviesPersistence = moviesPersistence } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let params = ["api_key" : DataProvider.apiKey, "query" : query] let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire .request(DataProvider.searchMoviePath, parameters: params) .validate() .responseString (queue: utilityQueue) { response in switch response.result { case .success: DispatchQueue.main.async { success(response.data!) } case .failure: DispatchQueue.main.async { failure(.internetError) } } } } func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let ago = Calendar.current.date(byAdding: .month, value: -1, to: Date())! let agoString = MoviesConnector.formatter.string(from: ago) let nowString = MoviesConnector.formatter.string(from: Date()) let params = ["api_key" : DataProvider.apiKey, "primary_release_date.gte" : agoString, "primary_release_date.lte" : nowString, "vote_average.gte" : "5"] let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire .request(DataProvider.discoverMoviePath, parameters: params) .validate() .responseString(queue: utilityQueue) { response in switch response.result { case .success: if self.moviesPersistence.saveFile(stringJson: response.result.value!, file: .nowPlayingMovies) { DispatchQueue.main.async { success(response.data!) } } else { DispatchQueue.main.async { failure(.errorInSaveLocalFile) } } case .failure: DispatchQueue.main.async { failure(.internetError) } } } } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let add = Calendar.current.date(byAdding: .month, value: 1, to: Date())! let add2 = Calendar.current.date(byAdding: .day, value: 1, to: Date())! let futureString = MoviesConnector.formatter.string(from: add) let nowString = MoviesConnector.formatter.string(from: add2) let params = ["api_key" : DataProvider.apiKey, "primary_release_date.gte" : nowString, "primary_release_date.lte" : futureString, "vote_average.gte" : "5"] let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire .request(DataProvider.discoverMoviePath, parameters: params) .validate() .responseString(queue: utilityQueue) { response in switch response.result { case .success: if self.moviesPersistence.saveFile(stringJson: response.result.value!, file: .upcomingMovies) { DispatchQueue.main.async { success(response.data!) } } else { DispatchQueue.main.async { failure(.errorInSaveLocalFile) } } case .failure: DispatchQueue.main.async { failure(.internetError) } } } } }
mit
8fbf67f9a7e1640be942ba3246ef4d6e
37.225564
117
0.516916
5.496216
false
false
false
false
piwik/piwik-sdk-ios
MatomoTracker/Application.swift
1
2297
#if SWIFT_PACKAGE import Foundation #endif public struct Application { /// Creates an returns a new application object representing the current application public static func makeCurrentApplication() -> Application { let displayName = bundleDisplayNameForCurrentApplication() let name = bundleNameForCurrentApplication() let identifier = bundleIdentifierForCurrentApplication() let version = bundleVersionForCurrentApplication() let shortVersion = bundleShortVersionForCurrentApplication() return Application(bundleDisplayName: displayName, bundleName: name, bundleIdentifier: identifier, bundleVersion: version, bundleShortVersion: shortVersion) } /// The name of your app as displayed on the homescreen i.e. "My App" public let bundleDisplayName: String? /// The bundle name of your app i.e. "my-app" public let bundleName: String? /// The bundle identifier of your app i.e. "com.my-company.my-app" public let bundleIdentifier: String? /// The bundle version a.k.a. build number as String i.e. "149" public let bundleVersion: String? /// The app version as String i.e. "1.0.1" public let bundleShortVersion: String? } extension Application { /// Returns the name of the app as displayed on the homescreen private static func bundleDisplayNameForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String } /// Returns the bundle name of the app private static func bundleNameForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleName"] as? String } /// Returns the bundle identifier private static func bundleIdentifierForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String } /// Returns the bundle version private static func bundleVersionForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleVersion"] as? String } /// Returns the app version private static func bundleShortVersionForCurrentApplication() -> String? { return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } }
mit
edfce1c761a261893a790c65d300a069
39.298246
164
0.710492
5.469048
false
false
false
false
pabloroca/NewsApp
NewsApp/Controllers/ViewControllers/DetailViewController.swift
1
1921
// // DetailViewController.swift // NewsApp // // Created by Pablo Roca Rozas on 28/03/2017. // Copyright © 2017 PR2Studio. All rights reserved. // import UIKit class DetailViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var detailDescriptionLabel: UILabel! //UI @IBOutlet weak var viewWeb: UIWebView! @IBOutlet weak var viewActivity: UIActivityIndicatorView! //UI var link: String = "" func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let label = self.detailDescriptionLabel { label.text = detail.description } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() if !link.isEmpty { viewWeb.delegate = self viewWeb.loadRequest(NSURLRequest(url: NSURL(string: link)! as URL) as URLRequest) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var detailItem: NSDate? { didSet { // Update the view. self.configureView() } } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { self.viewActivity.isHidden = false self.viewActivity.startAnimating() return true } func webViewDidFinishLoad(_ webView: UIWebView) { self.viewActivity.stopAnimating() self.viewActivity.isHidden = true } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.viewActivity.stopAnimating() self.viewActivity.isHidden = true } }
mit
3b22ca52b27e91ed389932b0ea778a92
26.042254
130
0.628646
5.175202
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Axis/ChartAxisModel.swift
3
6047
// // ChartAxisModel.swift // SwiftCharts // // Created by ischuetz on 22/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public enum ChartAxisPadding { case label /// Add padding corresponding to half of leading / trailing label sizes case none case fixed(CGFloat) /// Set a fixed padding value case maxLabelFixed(CGFloat) /// Use max of padding value corresponding to .Label and a fixed value case labelPlus(CGFloat) /// Use .Label padding + a fixed value } public func ==(a: ChartAxisPadding, b: ChartAxisPadding) -> Bool { switch (a, b) { case (.label, .label): return true case (.fixed(let a), .fixed(let b)) where a == b: return true case (.maxLabelFixed(let a), .maxLabelFixed(let b)) where a == b: return true case (.labelPlus(let a), .labelPlus(let b)) where a == b: return true case (.none, .none): return true default: return false } } /// This class models the contents of a chart axis open class ChartAxisModel { let firstModelValue: Double let lastModelValue: Double let axisValuesGenerator: ChartAxisValuesGenerator let labelsGenerator: ChartAxisLabelsGenerator /// The color used to draw the axis lines let lineColor: UIColor /// The axis title lables let axisTitleLabels: [ChartAxisLabel] let labelsConflictSolver: ChartAxisLabelsConflictSolver? let leadingPadding: ChartAxisPadding let trailingPadding: ChartAxisPadding let labelSpaceReservationMode: AxisLabelsSpaceReservationMode let clipContents: Bool public convenience init(axisValues: [ChartAxisValue], lineColor: UIColor = UIColor.black, axisTitleLabel: ChartAxisLabel, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { self.init(axisValues: axisValues, lineColor: lineColor, axisTitleLabels: [axisTitleLabel], labelsConflictSolver: labelsConflictSolver, leadingPadding: leadingPadding, trailingPadding: trailingPadding, labelSpaceReservationMode: labelSpaceReservationMode, clipContents: clipContents) } /// Convenience initializer to pass a fixed axis value array. The array is mapped to axis values and label generators. public convenience init(axisValues: [ChartAxisValue], lineColor: UIColor = UIColor.black, axisTitleLabels: [ChartAxisLabel] = [], labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { precondition(!axisValues.isEmpty, "Axis cannot be empty") var scalars: [Double] = [] var dict = [Double: [ChartAxisLabel]]() for axisValue in axisValues { scalars.append(axisValue.scalar) dict[axisValue.scalar] = axisValue.labels } let (firstModelValue, lastModelValue) = (axisValues.first!.scalar, axisValues.last!.scalar) let fixedArrayGenerator = ChartAxisValuesGeneratorFixed(values: scalars) let fixedLabelGenerator = ChartAxisLabelsGeneratorFixed(dict: dict) self.init(lineColor: lineColor, firstModelValue: firstModelValue, lastModelValue: lastModelValue, axisTitleLabels: axisTitleLabels, axisValuesGenerator: fixedArrayGenerator, labelsGenerator: fixedLabelGenerator, labelsConflictSolver: labelsConflictSolver, leadingPadding: leadingPadding, trailingPadding: trailingPadding, labelSpaceReservationMode: labelSpaceReservationMode, clipContents: clipContents) } public convenience init(lineColor: UIColor = UIColor.black, firstModelValue: Double, lastModelValue: Double, axisTitleLabel: ChartAxisLabel, axisValuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { self.init(lineColor: lineColor, firstModelValue: firstModelValue, lastModelValue: lastModelValue, axisTitleLabels: [axisTitleLabel], axisValuesGenerator: axisValuesGenerator, labelsGenerator: labelsGenerator, labelsConflictSolver: labelsConflictSolver, leadingPadding: leadingPadding, trailingPadding: trailingPadding, labelSpaceReservationMode: labelSpaceReservationMode, clipContents: clipContents) } public init(lineColor: UIColor = UIColor.black, firstModelValue: Double, lastModelValue: Double, axisTitleLabels: [ChartAxisLabel] = [], axisValuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, leadingPadding: ChartAxisPadding = .none, trailingPadding: ChartAxisPadding = .none, labelSpaceReservationMode: AxisLabelsSpaceReservationMode = .minPresentedSize, clipContents: Bool = false) { self.lineColor = lineColor self.firstModelValue = firstModelValue self.lastModelValue = lastModelValue self.axisTitleLabels = axisTitleLabels self.axisValuesGenerator = axisValuesGenerator self.labelsGenerator = labelsGenerator self.labelsConflictSolver = labelsConflictSolver self.leadingPadding = leadingPadding self.trailingPadding = trailingPadding self.labelSpaceReservationMode = labelSpaceReservationMode self.clipContents = clipContents } } extension ChartAxisModel: CustomDebugStringConvertible { public var debugDescription: String { return [ "firstModelValue": firstModelValue, "lastModelValue": lastModelValue, "axisTitleLabels": axisTitleLabels, ] .debugDescription } }
apache-2.0
b08fda91367aeeedac2c12dbbb791718
56.590476
488
0.755747
6.13286
false
false
false
false
digitalcatnip/Pace-SSS-iOS
SSSFreshmanApp/SSSFreshmanApp/RootGroup/RootVC.swift
1
3132
// // RootVC.swift // SSS Freshman App // // Created by James McCarthy on 8/15/16. // Copyright © 2016 Digital Catnip. All rights reserved. // import UIKit class RootVC: UIViewController { override func viewDidAppear(animated: Bool) { registerScreen("StartScreen") } override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } func displayAlert(title: String, body: String) { let alertController = UIAlertController(title: title, message: body, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } func displayPrompt(title: String, body: String, action: ((UIAlertAction)->(Void))?) { let alertController = UIAlertController(title: title, message: body, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) let proceedAction = UIAlertAction(title: "OK", style: .Default, handler: action) alertController.addAction(proceedAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } func goToBlackboard(action: UIAlertAction) { let url = NSURL(string: "itms-apps://itunes.apple.com/us/app/blackboard-mobile-learn/id376413870") if UIApplication.sharedApplication().canOpenURL(url!) { UIApplication.sharedApplication().openURL(url!) } else { displayAlert("Failed", body: "Cannot open iTunes for Blackboard Mobile Learn") } } func goToOutlook(action: UIAlertAction) { let url = NSURL(string: "https://itunes.apple.com/us/app/microsoft-outlook-email-calendar/id951937596") if UIApplication.sharedApplication().canOpenURL(url!) { UIApplication.sharedApplication().openURL(url!) } else { displayAlert("Failed", body: "Cannot open MS Outlook or iTunes for MS Outlook.") } } @IBAction func blackBoardPressed() { registerButtonAction("StartScreen", action: "Go To App", label: "Blackboard") displayPrompt("BlackBoard", body: "Go to App Store to open / download Blackboard?", action: goToBlackboard) } @IBAction func msOutlookPressed() { registerButtonAction("StartScreen", action: "Go To App", label: "Outlook") let url = NSURL(string: "ms-outlook://") if UIApplication.sharedApplication().canOpenURL(url!) { UIApplication.sharedApplication().openURL(url!) } else { displayPrompt("Outlook", body: "Go to App Store to download Outlook?", action: goToOutlook) } } }
mit
4337d40158cf0db9f2de462a0f02f025
40.746667
115
0.670712
4.673134
false
false
false
false
loganSims/wsdot-ios-app
wsdot/MountainPassesViewController.swift
1
6419
// // MountainPassesViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import Foundation import GoogleMobileAds class MountainPassesViewController: RefreshViewController, UITableViewDelegate, UITableViewDataSource, GADBannerViewDelegate { let cellIdentifier = "PassCell" let segueMountainPassDetailsViewController = "MountainPassDetailsViewController" var passItems = [MountainPassItem]() @IBOutlet weak var bannerView: DFPBannerView! let refreshControl = UIRefreshControl() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // refresh controller refreshControl.addTarget(self, action: #selector(MountainPassesViewController.refreshAction(_:)), for: .valueChanged) tableView.addSubview(refreshControl) showOverlay(self.view) self.passItems = MountainPassStore.getPasses() self.tableView.reloadData() refresh(false) tableView.rowHeight = UITableView.automaticDimension // Ad Banner bannerView.adUnitID = ApiKeys.getAdId() bannerView.adSize = getFullWidthAdaptiveAdSize() bannerView.rootViewController = self let request = DFPRequest() request.customTargeting = ["wsdotapp":"passes"] bannerView.load(request) bannerView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "PassReports") } func refresh(_ force: Bool){ DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in MountainPassStore.updatePasses(force, completion: { error in if (error == nil) { // Reload tableview on UI thread DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.passItems = MountainPassStore.getPasses() selfValue.tableView.reloadData() selfValue.refreshControl.endRefreshing() selfValue.hideOverlayView() UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: selfValue.tableView) } } } else { DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.refreshControl.endRefreshing() selfValue.hideOverlayView() AlertMessages.getConnectionAlert(backupURL: WsdotURLS.passes, message: WSDOTErrorStrings.passReports) } } } }) } } @objc func refreshAction(_ sender: UIRefreshControl) { refresh(true) } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return passItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! MountainPassCell let passItem = passItems[indexPath.row] cell.nameLabel.text = passItem.name cell.forecastLabel.text = "" if (passItem.weatherCondition != ""){ cell.forecastLabel.text = passItem.weatherCondition } if (passItem.forecast.count > 0){ if (cell.forecastLabel.text == "") { cell.forecastLabel.text = WeatherUtils.getForecastBriefDescription(passItem.forecast[0].forecastText) } cell.weatherImage.image = UIImage(named: WeatherUtils.getIconName(passItem.forecast[0].forecastText, title: passItem.forecast[0].day)) } else { cell.forecastLabel.text = "" cell.weatherImage.image = nil } if passItem.dateUpdated as Date == Date.init(timeIntervalSince1970: 0){ cell.updatedLabel.text = "Not Available" }else { cell.updatedLabel.text = TimeUtils.timeAgoSinceDate(date: passItem.dateUpdated, numericDates: true) } return cell } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Perform Segue performSegue(withIdentifier: segueMountainPassDetailsViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == segueMountainPassDetailsViewController { if let indexPath = tableView.indexPathForSelectedRow { let passItem = self.passItems[indexPath.row] as MountainPassItem let destinationViewController = segue.destination as! MountainPassTabBarViewController destinationViewController.passItem = passItem let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem } } } }
gpl-3.0
705e948e937f034bce673463f66915e8
37.90303
146
0.629537
5.567216
false
false
false
false
toymachiner62/myezteam-ios
Myezteam/TeamDao.swift
1
1373
// // TeamDao.swift // Myezteam // // Created by Caflisch, Thomas J. (Tom) on 11/24/15. // Copyright (c) 2015 Tom Caflisch. All rights reserved. // import Foundation struct TeamDao { // MARK: Functions /** Gets the team info from the team id */ static func getTeamInfo(id: Int, callback: (NSDictionary?, String?) -> Void) throws { let request = NSMutableURLRequest(URL: NSURL(string: Constants.makeUrl("/teams/\(id)"))!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let token = NSUserDefaults.standardUserDefaults().stringForKey("myezteamToken") request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if error != nil { callback(nil, error!.localizedDescription) } else { let teamInfo: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary callback(teamInfo, nil) } } task.resume() } }
mit
81e66e91ed4405f68619b5870fbc7155
32.487805
158
0.619811
4.702055
false
false
false
false
iAmNaz/FormValidationKit
FormValidationKit/ValidatorIterator.swift
1
783
// // ArrayIteratorNZ.swift // FormValidator // // Created by JMariano on 11/11/14. // Copyright (c) 2014 JMariano. All rights reserved. // import UIKit public class ValidatorIterator: NSObject, IteratorNZ { var mutableList: Array<Validator>? var position: Int required public init(listItems: Array<Validator>) { mutableList = listItems position = 0; } func next() -> Validator { let object = mutableList?[position] position++; return object!; } func hasNext() -> Bool { if (position >= mutableList?.count || mutableList?[position] == nil) { return false; } else { return true; } } public func reset() { position = 0 } }
mit
5472d7514b4ab71fd6292547a6fffbbd
20.162162
78
0.565773
4.35
false
false
false
false
deepak475121/JustForFun
justForFun/Archive/SecondCell.swift
1
998
// // SecondCell.swift // justForFun // // Created by Hari Crayond Digital Reach Pvt Ltd on 20/05/2017. // Copyright © 2017 Crayond Digital Reach Pvt Ltd. All rights reserved. // import UIKit class SecondCell: UITableViewCell { @IBOutlet weak var RegBt: UIButton! @IBOutlet weak var WhatTextView: UITextView! override func awakeFromNib() { super.awakeFromNib() // Initialization code let width = CGFloat(2.0) let border = CALayer() border.borderColor = UIColor.lightGray.cgColor border.frame = CGRect(x: 0, y: WhatTextView.frame.size.height - width, width: WhatTextView.frame.size.width, height: 1) border.borderWidth = width WhatTextView.layer.addSublayer(border) WhatTextView.layer.masksToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
f57b8eafd0837aad2e38b590c0e62cc5
28.323529
127
0.67001
4.242553
false
false
false
false
OscarSwanros/swift
test/IRGen/dynamic_self_metadata.swift
18
2000
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir -parse-as-library | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: Not a SIL test because we can't parse dynamic Self in SIL. // <rdar://problem/16931299> // CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }> @inline(never) func id<T>(_ t: T) -> T { return t } // CHECK-LABEL: define hidden swiftcc void @_T021dynamic_self_metadata2idxxlF class C { class func fromMetatype() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @_T021dynamic_self_metadata1CC12fromMetatypeACXDSgyFZ(%swift.type* swiftself) // CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8 // CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: store i64 0, i64* [[CAST1]], align 8 // CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8 // CHECK: ret i64 [[LOAD]] func fromInstance() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @_T021dynamic_self_metadata1CC12fromInstanceACXDSgyF(%T21dynamic_self_metadata1CC* swiftself) // CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8 // CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: store i64 0, i64* [[CAST1]], align 8 // CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8 // CHECK: ret i64 [[LOAD]] func dynamicSelfArgument() -> Self? { return id(nil) } // CHECK-LABEL: define hidden swiftcc i64 @_T021dynamic_self_metadata1CC0A12SelfArgumentACXDSgyF(%T21dynamic_self_metadata1CC* swiftself) // CHECK: [[CAST1:%.+]] = bitcast %T21dynamic_self_metadata1CC* %0 to [[METATYPE:%.+]] // CHECK: [[TYPE1:%.+]] = call %swift.type* @swift_getObjectType([[METATYPE]] [[CAST1]]) // CHECK: [[TYPE2:%.+]] = call %swift.type* @_T0SqMa(%swift.type* [[TYPE1]]) // CHECK: call swiftcc void @_T021dynamic_self_metadata2idxxlF({{.*}}, %swift.type* [[TYPE2]]) }
apache-2.0
743a114aa6ef924fc49e41d0f681ac0b
46.619048
139
0.63
3.236246
false
false
false
false
leonereveel/Moya
Source/Moya+Internal.swift
1
12726
import Foundation import Result /// Internal extension to keep the inner-workings outside the main Moya.swift file. internal extension MoyaProvider { // Yup, we're disabling these. The function is complicated, but breaking it apart requires a large effort. // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length /// Performs normal requests. func requestNormal(target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> Cancellable { let endpoint = self.endpoint(target) let stubBehavior = self.stubClosure(target) let cancellableToken = CancellableWrapper() if trackInflights { objc_sync_enter(self) var inflightCompletionBlocks = self.inflightRequests[endpoint] inflightCompletionBlocks?.append(completion) self.inflightRequests[endpoint] = inflightCompletionBlocks objc_sync_exit(self) if inflightCompletionBlocks != nil { return cancellableToken } else { objc_sync_enter(self) self.inflightRequests[endpoint] = [completion] objc_sync_exit(self) } } let performNetworking = { (requestResult: Result<NSURLRequest, Moya.Error>) in if cancellableToken.cancelled { self.cancelCompletion(completion, target: target) return } var request: NSURLRequest! switch requestResult { case .Success(let urlRequest): request = urlRequest case .Failure(let error): completion(result: .Failure(error)) return } switch stubBehavior { case .Never: let networkCompletion: Moya.Completion = { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach({ $0(result: result) }) objc_sync_enter(self) self.inflightRequests.removeValueForKey(endpoint) objc_sync_exit(self) } else { completion(result: result) } } switch target.task { case .Request: cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, progress: progress, completion: networkCompletion) case .Upload(.File(let file)): cancellableToken.innerCancellable = self.sendUploadFile(target, request: request, queue: queue, file: file, progress: progress, completion: networkCompletion) case .Upload(.Multipart(let multipartBody)): guard !multipartBody.isEmpty && target.method.supportsMultipart else { fatalError("\(target) is not a multipart upload target.") } cancellableToken.innerCancellable = self.sendUploadMultipart(target, request: request, queue: queue, multipartBody: multipartBody, progress: progress, completion: networkCompletion) case .Download(.Request(let destination)): cancellableToken.innerCancellable = self.sendDownloadRequest(target, request: request, queue: queue, destination: destination, progress: progress, completion: networkCompletion) } default: cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in if self.trackInflights { self.inflightRequests[endpoint]?.forEach({ $0(result: result) }) objc_sync_enter(self) self.inflightRequests.removeValueForKey(endpoint) objc_sync_exit(self) } else { completion(result: result) } }, endpoint: endpoint, stubBehavior: stubBehavior) } } requestClosure(endpoint, performNetworking) return cancellableToken } // swiftlint:enable cyclomatic_complexity // swiftlint:enable function_body_length func cancelCompletion(completion: Moya.Completion, target: Target) { let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) } completion(result: .Failure(error)) } /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) { return { if token.cancelled { self.cancelCompletion(completion, target: target) return } switch endpoint.sampleResponseClosure() { case .NetworkResponse(let statusCode, let data): let response = Moya.Response(statusCode: statusCode, data: data, response: nil) plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) } completion(result: .Success(response)) case .NetworkError(let error): let error = Moya.Error.Underlying(error) plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) } completion(result: .Failure(error)) } } } /// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`. final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) { let alamoRequest = manager.request(request) plugins.forEach { $0.willSendRequest(alamoRequest, target: target) } } } private extension MoyaProvider { private func sendUploadMultipart(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: Moya.Completion) -> CancellableWrapper { let cancellable = CancellableWrapper() let multipartFormData = { (form: RequestMultipartFormData) -> Void in for bodyPart in multipartBody { switch bodyPart.provider { case .Data(let data): self.append(data: data, bodyPart: bodyPart, to: form) case .File(let url): self.append(fileURL: url, bodyPart: bodyPart, to: form) case .Stream(let stream, let length): self.append(stream: stream, length: length, bodyPart: bodyPart, to: form) } } if let parameters = target.parameters { parameters .flatMap { (key, value) in multipartQueryComponents(key, value) } .forEach { (key, value) in if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { form.appendBodyPart(data: data, name: key) } } } } manager.upload(request, multipartFormData: multipartFormData) { (result: MultipartFormDataEncodingResult) in switch result { case .Success(let alamoRequest, _, _): if cancellable.cancelled { self.cancelCompletion(completion, target: target) return } cancellable.innerCancellable = self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) case .Failure(let error): completion(result: .Failure(Moya.Error.Underlying(error as NSError))) } } return cancellable } private func sendUploadFile(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, file: NSURL, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken { let alamoRequest = manager.upload(request, file: file) return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } private func sendDownloadRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, destination: DownloadDestination, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken { let alamoRequest = manager.download(request, destination: destination) return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } private func sendRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken { let alamoRequest = manager.request(request) return sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion) } private func sendAlamofireRequest(alamoRequest: Request, target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken { // Give plugins the chance to alter the outgoing request let plugins = self.plugins plugins.forEach { $0.willSendRequest(alamoRequest, target: target) } // Perform the actual request if let progress = progress { alamoRequest .progress { (bytesWritten, totalBytesWritten, totalBytesExpected) in let sendProgress: () -> () = { progress(progress: ProgressResponse(totalBytes: totalBytesWritten, bytesExpected: totalBytesExpected)) } if let queue = queue { dispatch_async(queue, sendProgress) } else { sendProgress() } } } alamoRequest .response(queue: queue) { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in let result = convertResponseToResult(response, data: data, error: error) // Inform all plugins about the response plugins.forEach { $0.didReceiveResponse(result, target: target) } completion(result: result) } alamoRequest.resume() return CancellableToken(request: alamoRequest) } } // MARK: - RequestMultipartFormData appending private extension MoyaProvider { private func append(data data: NSData, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { if let mimeType = bodyPart.mimeType { if let fileName = bodyPart.fileName { form.appendBodyPart(data: data, name: bodyPart.name, fileName: fileName, mimeType: mimeType) } else { form.appendBodyPart(data: data, name: bodyPart.name, mimeType: mimeType) } } else { form.appendBodyPart(data: data, name: bodyPart.name) } } private func append(fileURL url: NSURL, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { if let fileName = bodyPart.fileName, mimeType = bodyPart.mimeType { form.appendBodyPart(fileURL: url, name: bodyPart.name, fileName: fileName, mimeType: mimeType) } else { form.appendBodyPart(fileURL: url, name: bodyPart.name) } } private func append(stream stream: NSInputStream, length: UInt64, bodyPart: MultipartFormData, to form: RequestMultipartFormData) { form.appendBodyPart(stream: stream, length: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "") } } /// Encode parameters for multipart/form-data private func multipartQueryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += multipartQueryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += multipartQueryComponents("\(key)[]", value) } } else { components.append((key, "\(value)")) } return components }
mit
4e43fbec51216d2dd23428eb1597341c
46.842105
227
0.61614
5.468844
false
false
false
false
babumoshai-ankush/UITableView-Self-Sizing
TableViewSelfSizingDemo/ViewController.swift
1
3425
// // ViewController.swift // TableViewSelfSizingDemo // // Created by Ankush Chakraborty on 05/07/17. // Copyright © 2017 Ankush Chakraborty. All rights reserved. // import UIKit struct Data { var title: String? var description: String? init(title: String, description: String) { self.title = title self.description = description } } class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var tblView: UITableView! @IBOutlet weak var sliderFont: UISlider! @IBOutlet weak var lblFontSize: UILabel! var arrData: [Data]? var fontSize: Int = UIDevice.current.userInterfaceIdiom == .pad ? 22 : 15 //MARK: - View Controller Life Cycle - override func viewDidLoad() { super.viewDidLoad() tblView.estimatedRowHeight = 64.0 tblView.rowHeight = UITableViewAutomaticDimension sliderFont.value = Float(fontSize) lblFontSize.text = "\(lblFontSize.text!) \(fontSize)" arrData = loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - UITableViewDataSource Methods Implementation - func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (arrData?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! CustomTableViewCell let d = arrData?[indexPath.row] cell.lblTitle.text = d?.title cell.lblDescription.text = d?.description cell.lblTitle.font = UIFont(name: cell.lblTitle.font.fontName, size: CGFloat(fontSize)) cell.lblDescription.font = UIFont(name: cell.lblDescription.font.fontName, size: CGFloat(fontSize)) cell.contentView.backgroundColor = (indexPath.row % 2 == 0 ? UIColor.white : UIColor(red: 242.0/255.0, green: 244.0/255.0, blue: 244.0/255.0, alpha: 1.0)) return cell } //MARK: - Button Actions - @IBAction func sliderFontDidValueChange(_ sender: Any) { let slider = sender as! UISlider if fontSize != (Int(slider.value) / 1) { fontSize = Int(slider.value) / 1 lblFontSize.text = "Font Size \(fontSize)" let cells = self.tblView.visibleCells as! [CustomTableViewCell] for cell in cells { cell.lblTitle.font = UIFont(name: cell.lblTitle.font.fontName, size: CGFloat(fontSize)) cell.lblDescription.font = UIFont(name: cell.lblDescription.font.fontName, size: CGFloat(fontSize)) } tblView.reloadRows(at: tblView.indexPathsForVisibleRows!, with: .fade) } } //MARK: - Internal Methods - func loadData() -> [Data] { var aData = [Data]() let path = Bundle.main.path(forResource: "data", ofType: "plist") if let p = path { if let arr = NSArray(contentsOfFile: p) { for data in arr as! [Dictionary<String, String>] { aData.append(Data(title: data["title"]!, description: data["desc"]!)) } } } return aData } }
gpl-3.0
3a8f1675ff09ceb918d9d39e241a6b8a
34.666667
162
0.629089
4.547145
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/About/Credits/CreditsViewController.swift
1
1276
import UIKit class CreditsViewController: UIViewController, UIToolbarDelegate { @IBOutlet weak var infoView: UITextView! @IBOutlet weak var infoTextView: UITextView! @IBOutlet weak var titleLabel: UILabel! init() { super.init(nibName: "CreditsViewController", bundle: nil) title = L10n.Credits.title } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Theme.darkGrey let version = Bundle.main.versionName titleLabel.text = L10n.Credits.header(version) titleLabel.textColor = Theme.white infoTextView.text = L10n.Credits.copyright infoTextView.textColor = Theme.grey infoView.text = getAboutText() infoView.textColor = Theme.darkGrey infoView.isEditable = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Analytics.track("About") } func getAboutText() -> String { let thirdPartyTitle = L10n.Credits.Licenses.title let thirdPartyText = L10n.Credits.Licenses.subtitle return thirdPartyTitle + "\r\n\r\n" + thirdPartyText } }
gpl-3.0
e229169e60e23545074f62407a10bd9a
23.075472
66
0.661442
4.656934
false
false
false
false
thiagotmb/BEPiD-Challenges-2016
2016-02-15-TimerWatch/TimerWatch/desafio_3 WatchKit Extension/InterfaceController.swift
2
4174
// // InterfaceController.swift // desafio_3 WatchKit Extension // // Created by Dennis Merli Rodrigues on 2/15/16. // Copyright © 2016 Dennis Merli Rodrigues. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { //Outlets @IBOutlet var phraseLabel: WKInterfaceLabel! @IBOutlet var saveButton: WKInterfaceButton! @IBOutlet var passButton: WKInterfaceButton! @IBOutlet var phrasesTable: WKInterfaceTable! @IBOutlet var eventDate: WKInterfaceDate! @IBOutlet var eventTimer: WKInterfaceTimer! @IBOutlet var labelDate: WKInterfaceLabel! var currentEvent : Event! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() self.getPhrase() self.loadTable() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } //MARK: Table func loadTable() { self.phrasesTable.setNumberOfRows(CatchyPhrasesDAO.sharedInstance.getPhrasesArray().count, withRowType: "phTable") for (index, event) in CatchyPhrasesDAO.sharedInstance.getPhrasesArray().enumerate() { let row = self.phrasesTable.rowControllerAtIndex(index) as! PhrasesRowController row.rowLabel.setText(event.title) self.startATimer(event,label: row.rowLabel) } } //MARK: Acoes @IBAction func passAction() { self.getPhrase() } @IBAction func saveAction() { CatchyPhrasesDAO.sharedInstance.insertPhrase(self.currentEvent) { (status) -> Void in if(status){ //print("frase salva com sucesso!") self.passAction() self.loadTable() } } } //MARK: Carregar conteudo func getPhrase(){ if let value : NSInteger = NSInteger.random(Events.listOfEvents.count)(){ let eventTupla = Events.listOfEvents[value] self.currentEvent = Event(title: eventTupla.0, date: eventTupla.1) self.phraseLabel.setText(currentEvent.title) self.labelDate.setText(currentEvent.date) } } //MARK: Startar um timer func startATimer(event : Event, label: WKInterfaceLabel){ let dateFormat = NSDateFormatter() dateFormat.dateFormat = "HH:mm" dateFormat.timeZone = NSTimeZone(name: "America/Sao_Paulo") let date = dateFormat.dateFromString(event.date) let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian) let componentNow = calendar?.components([.Hour, .Minute], fromDate: NSDate()) let componentEvent = calendar?.components([.Hour, .Minute], fromDate: date!) let hourInterval = (componentEvent!.hour - componentNow!.hour)*60 let minuteInterval = (componentEvent!.minute - componentNow!.minute) let timerInverval = Double( (hourInterval + minuteInterval) * 60) self.performSelector("highlightCurrentEvent:", withObject: label, afterDelay: timerInverval) } //MARK: func highlightCurrentEvent(label : WKInterfaceLabel?){ // let event = timer.userInfo as! Event label?.setTextColor(UIColor.greenColor()) // if let index = CatchyPhrasesDAO.sharedInstance.getPhrasesArray().indexOf(event){ // print(index) // // let tableRow = phrasesTable.rowControllerAtIndex(index) as! PhrasesRowController // tableRow.rowLabel.setTextColor(UIColor.greenColor()) // } } }
mit
3346d1f588e221207efc49c2df6ffc84
29.459854
102
0.60556
5.076642
false
false
false
false
tkrajacic/SampleCodeStalker
SampleCodeStalker/MainWindow.swift
1
1024
// // MainWindow.swift // SampleCodeStalker // // Created by Thomas Krajacic on 23.1.2016. // Copyright © 2016 Thomas Krajacic. All rights reserved. // import Cocoa class MainWindow: NSWindow { override init(contentRect: NSRect, styleMask aStyle: NSWindowStyleMask, backing bufferingType: NSBackingStoreType, defer flag: Bool) { super.init(contentRect: contentRect, styleMask: aStyle, backing: bufferingType, defer: flag) self.commonInit() } // required init?(coder: NSCoder) { // super.init(coder: coder) // // self.commonInit() // } func commonInit() { self.titlebarAppearsTransparent = true self.titleVisibility = .hidden self.isMovable = true self.isMovableByWindowBackground = true self.isOpaque = false self.backgroundColor = NSColor.white } override var canBecomeKey: Bool { return true } override var canBecomeMain: Bool { return true } }
mit
9f80c71a6db89575ebc3020dabbcc2b2
23.95122
138
0.633431
4.467249
false
false
false
false
DevilWang/BlinkingLabel
Example/BlinkingLabel/ViewController.swift
1
1685
// // ViewController.swift // BlinkingLabel // // Created by DevilWang on 07/19/2017. // Copyright (c) 2017 DevilWang. All rights reserved. // import UIKit import BlinkingLabel class ViewController: UIViewController { var isBlinking = false; let blinkingLabel = BlinkingLabel(frame:CGRect(origin:CGPoint.init(x:10,y:20), size:CGSize.init(width:200,height:30))) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //setup the blinkingLabel blinkingLabel.text = "I blink" blinkingLabel.font = UIFont.systemFont(ofSize: 20.0) view.addSubview(blinkingLabel) blinkingLabel.startBlinking() isBlinking = true //create a UIButton to toggle the blinking let toggleButton = UIButton.init(frame: CGRect(origin:CGPoint.init(x: 10, y: 60), size:CGSize.init(width: 125, height: 30))) toggleButton.setTitle("Toggle Blinkiing", for: .normal) toggleButton.setTitleColor(UIColor.red, for: .normal) toggleButton.addTarget(self, action: #selector(ViewController.ToggleBlinking), for: .touchUpInside) view.addSubview(toggleButton) } func ToggleBlinking() { if isBlinking { blinkingLabel.stopBlinking() } else{ blinkingLabel.startBlinking() } isBlinking = !isBlinking } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3f0f45de114ecb0d0ee36dffea76152d
28.561404
122
0.624926
4.746479
false
false
false
false
lkzhao/ElasticTransition
Pods/MotionAnimation/MotionAnimation/NSObject+MotionAnimation.swift
1
4258
// // NSObject+MotionAnimation.swift // DynamicView // // Created by YiLun Zhao on 2016-01-17. // Copyright © 2016 lkzhao. All rights reserved. // import UIKit public extension NSObject{ fileprivate struct m_associatedKeys { static var m_propertyStates = "m_propertyStates_key" } // use NSMutableDictionary since swift dictionary requires a O(n) dynamic cast even when using as! fileprivate var m_propertyStates:NSMutableDictionary{ get { // never use `as?` in this case. it is very expensive let rtn = objc_getAssociatedObject(self, &m_associatedKeys.m_propertyStates) if rtn != nil{ return rtn as! NSMutableDictionary } self.m_propertyStates = NSMutableDictionary() return objc_getAssociatedObject(self, &m_associatedKeys.m_propertyStates) as! NSMutableDictionary } set { objc_setAssociatedObject( self, &m_associatedKeys.m_propertyStates, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } fileprivate func getPropertyState(_ key:String) -> MotionAnimationPropertyState{ if m_propertyStates[key] == nil { if let animatable = self as? MotionAnimationAnimatable, let (getter, setter) = animatable.defaultGetterAndSetterForKey(key){ m_propertyStates[key] = MotionAnimationPropertyState(getter: getter, setter: setter) } else { fatalError("\(key) is not animatable, you can define customAnimation property via m_defineCustomProperty or conform to MotionAnimationAnimatable") } } return m_propertyStates[key] as! MotionAnimationPropertyState } // define custom animatable property func m_setValues(_ values:[CGFloat], forCustomProperty key:String){ getPropertyState(key).setValues(values) } func m_defineCustomProperty<T:MotionAnimatableProperty>(_ key:String, initialValues:T, valueUpdateCallback:@escaping (T)->Void){ if m_propertyStates[key] != nil{ return } m_propertyStates[key] = MotionAnimationPropertyState(values: initialValues.CGFloatValues) let _ = getPropertyState(key).addValueUpdateCallback({ values in valueUpdateCallback(T.fromCGFloatValues(values)) }) } func m_defineCustomProperty(_ key:String, getter:@escaping CGFloatValueBlock, setter:@escaping CGFloatValueBlock){ if m_propertyStates[key] != nil{ return } m_propertyStates[key] = MotionAnimationPropertyState(getter: getter, setter: setter) } func m_removeAnimationForKey(_ key:String){ getPropertyState(key).stop() } // add callbacks func m_addValueUpdateCallback<T:MotionAnimatableProperty>(_ key:String, valueUpdateCallback:@escaping (T)->Void) -> MotionAnimationObserverKey{ return getPropertyState(key).addValueUpdateCallback({ values in valueUpdateCallback(T.fromCGFloatValues(values)) }) } func m_addVelocityUpdateCallback<T:MotionAnimatableProperty>(_ key:String, velocityUpdateCallback:@escaping (T)->Void) -> MotionAnimationObserverKey{ return getPropertyState(key).addVelocityUpdateCallback({ values in velocityUpdateCallback(T.fromCGFloatValues(values)) }) } func m_removeCallback(_ key:String, observerKey:MotionAnimationObserverKey){ let _ = getPropertyState(key).removeCallback(observerKey) } func m_isAnimating(_ key:String) -> Bool{ return getPropertyState(key).animation?.playing ?? false } func m_animate<T:MotionAnimatableProperty>( _ key:String, to:T, stiffness:CGFloat? = nil, damping:CGFloat? = nil, threshold:CGFloat? = nil, valueUpdate:((T) -> Void)? = nil, velocityUpdate:((T) -> Void)? = nil, completion:(() -> Void)? = nil) { let valueOb:MotionAnimationValueObserver? = valueUpdate == nil ? nil : { values in valueUpdate!(T.fromCGFloatValues(values)) } let velocityOb:MotionAnimationValueObserver? = velocityUpdate == nil ? nil : { values in velocityUpdate!(T.fromCGFloatValues(values)) } getPropertyState(key) .animate(to.CGFloatValues, stiffness: stiffness, damping: damping, threshold: threshold, valueUpdate:valueOb, velocityUpdate:velocityOb, completion: completion) } }
mit
1e72fe8cd41479a209e58141c8ecee76
36.672566
154
0.701198
4.657549
false
false
false
false
lrtitze/Swift-VectorBoolean
Swift VectorBoolean/CanvasView.swift
1
9584
// // CanvasView.swift // Swift VectorBoolean // // Created by Leslie Titze on 2015-07-12. // Copyright (c) 2015 Starside Softworks. All rights reserved. // import UIKit import VectorBoolean enum DisplayMode { case original case union case intersect case subtract case join } class PathItem { fileprivate var path: UIBezierPath fileprivate var color: UIColor init(path:UIBezierPath,color:UIColor) { self.path = path self.color = color } } class CanvasView: UIView { fileprivate var paths: [PathItem] = [] var boundsOfPaths: CGRect = CGRect.zero fileprivate var _unionPath: UIBezierPath? fileprivate var _intersectPath: UIBezierPath? fileprivate var _differencePath: UIBezierPath? fileprivate var _xorPath: UIBezierPath? var displayMode: DisplayMode = .original { didSet(previousMode) { if displayMode != previousMode { setNeedsDisplay() } } } var showPoints: Bool = false var showIntersections: Bool = true let vectorFillColor = UIColor(red: 0.4314, green:0.6784, blue:1.0000, alpha:1.0) let vectorStrokeColor = UIColor(red: 0.0392, green:0.3725, blue:1.0000, alpha:1.0) func clear() { paths = [] _unionPath = nil _intersectPath = nil _differencePath = nil _xorPath = nil } func addPath(_ path: UIBezierPath, withColor color: UIColor) { paths.append(PathItem(path: path, color: color)) // we clear these because they're no longer valid _unionPath = nil _intersectPath = nil _differencePath = nil _xorPath = nil } fileprivate var viewScale = 1.0 fileprivate var decorationLineWidth: CGFloat { return CGFloat(1.5 / viewScale) } func BoxFrame(_ point: CGPoint) -> CGRect { let visualWidth = CGFloat(9 / viewScale) let offset = visualWidth / 2 let left = point.x - offset //let right = point.x + offset //let top = point.y + offset let bottom = point.y - offset return CGRect(x: left, y: bottom, width: visualWidth, height: visualWidth) } override func draw(_ rect: CGRect) { // fill with white before going further let background = UIBezierPath(rect: rect) UIColor.white.setFill() background.fill() // When running my Xcode tests for geometry I want to // prevent the app shell from any geometry so I can // use breakpoints during test development. if paths.count == 0 { return } // calculate a useful scale and offset for drawing these paths // as large as possible in the middle of the display // expand size by 20 to provide a margin let expandedPathBounds = boundsOfPaths.insetBy(dx: -10, dy: -10) let pSz = expandedPathBounds.size let pOr = expandedPathBounds.origin let vSz = self.bounds.size let scaleX = vSz.width / pSz.width let scaleY = vSz.height / pSz.height let scale = min(scaleX, scaleY) viewScale = Double(scale) // obtain context let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState(); if scale == scaleX { let xTranslate = -(pOr.x * scale) let yTranslate = vSz.height - ((vSz.height-pSz.height*scale)/2.0) + (pOr.y*scale) ctx?.translateBy(x: xTranslate, y: yTranslate) ctx?.scaleBy(x: scale, y: -scale); } else { let xTranslate = ((vSz.width - pSz.width*scale)/2.0) - (pOr.x*scale) let yTranslate = vSz.height + (pOr.y * scale) ctx?.translateBy(x: xTranslate, y: yTranslate) ctx?.scaleBy(x: scale, y: -scale); } // Draw shapes now switch displayMode { case .original: drawOriginal() case .union: drawUnion() case .intersect: drawIntersect() case .subtract: drawSubtract() case .join: drawJoin() } // All done ctx?.restoreGState() } fileprivate func drawOriginal() { // Draw shapes now for pathItem in paths { pathItem.color.setFill() pathItem.path.fill() pathItem.path.lineWidth = decorationLineWidth //pathItem.path.stroke() // was not in original } // Draw on the end and control points if showPoints { for pathItem in paths { let bezier = LRTBezierPathWrapper(pathItem.path) for item in bezier.elements { var showMe : UIBezierPath? switch item { case let .move(v): showMe = UIBezierPath(rect: BoxFrame(v)) case let .line(v): // Convert lines to bezier curves as well. // Just set control point to be in the line formed by the end points showMe = UIBezierPath(rect: BoxFrame(v)) case .quadCurve(let to, let cp): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(cp)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() break case .cubicCurve(let to, let v1, let v2): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(v1)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() let cp2 = UIBezierPath(ovalIn: BoxFrame(v2)) cp2.lineWidth = decorationLineWidth / 2 cp2.stroke() case .close: break } UIColor.red.setStroke() showMe?.lineWidth = decorationLineWidth showMe?.stroke() } } } // If we have exactly two objects, show where they intersect if showIntersections && paths.count == 2 { let path1 = paths[0].path let path2 = paths[1].path // get both [FBBezierCurve] sets let curves1 = FBBezierCurve.bezierCurvesFromBezierPath(path1) let curves2 = FBBezierCurve.bezierCurvesFromBezierPath(path2) for curve1 in curves1 { for curve2 in curves2 { var unused: FBBezierIntersectRange? curve1.intersectionsWithBezierCurve(curve2, overlapRange: &unused) { (intersection: FBBezierIntersection) -> (setStop: Bool, stopValue:Bool) in if intersection.isTangent { UIColor.purple.setStroke() } else { UIColor.green.setStroke() } let inter = UIBezierPath(ovalIn: self.BoxFrame(intersection.location)) inter.lineWidth = self.decorationLineWidth inter.stroke() return (false, false) } } } } } func drawEndPointsForPath(_ path: UIBezierPath) { let bezier = LRTBezierPathWrapper(path) //var previousPoint = CGPointZero for item in bezier.elements { var showMe : UIBezierPath? switch item { case let .move(v): showMe = UIBezierPath(rect: BoxFrame(v)) case let .line(v): // Convert lines to bezier curves as well. // Just set control point to be in the line formed by the end points showMe = UIBezierPath(rect: BoxFrame(v)) case .quadCurve(let to, let cp): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(cp)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() break case .cubicCurve(let to, let v1, let v2): showMe = UIBezierPath(rect: BoxFrame(to)) UIColor.black.setStroke() let cp1 = UIBezierPath(ovalIn: BoxFrame(v1)) cp1.lineWidth = decorationLineWidth / 2 cp1.stroke() let cp2 = UIBezierPath(ovalIn: BoxFrame(v2)) cp2.lineWidth = decorationLineWidth / 2 cp2.stroke() case .close: break //previousPoint = CGPointZero } UIColor.red.setStroke() showMe?.lineWidth = decorationLineWidth showMe?.stroke() } } fileprivate func drawUnion() { if _unionPath == nil { if paths.count == 2 { _unionPath = paths[0].path.fb_union(paths[1].path) } } if let path = _unionPath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } fileprivate func drawIntersect() { if _intersectPath == nil { if paths.count == 2 { _intersectPath = paths[0].path.fb_intersect(paths[1].path) } } if let path = _intersectPath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } fileprivate func drawSubtract() { if _differencePath == nil { if paths.count == 2 { _differencePath = paths[0].path.fb_difference(paths[1].path) } } if let path = _differencePath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } fileprivate func drawJoin() { if _xorPath == nil { if paths.count == 2 { _xorPath = paths[0].path.fb_xor(paths[1].path) } } if let path = _xorPath { vectorFillColor.setFill() vectorStrokeColor.setStroke() path.fill() path.lineWidth = decorationLineWidth path.stroke() if showPoints { drawEndPointsForPath(path) } } } }
mit
5e875294e34ac40be4884605b082a2e4
25.043478
87
0.612166
4.305481
false
false
false
false
notbakaneko/JsonType
JsonType/JsonType.swift
1
5955
// // JsonType.swift // JsonType // // Created by bakaneko on 6/02/2015. // Copyright (c) 2015 bakaneko. All rights reserved. // import Foundation public enum JsonType { case DictionaryType(NSDictionary) case ArrayType(NSArray) case StringType(String) case NumberType(NSNumber) case BoolType(Bool) case NullType case InvalidType([String:AnyObject]) public init(_ rawValue: AnyObject) { switch rawValue { case let raw as NSNull: self = .NullType case let raw as NSString: self = .StringType(raw as! String) case let raw as String: self = .StringType(raw) case let raw as NSNumber: self = .NumberType(raw) case let raw as NSArray: self = .ArrayType(raw) case let raw as Bool: self = .BoolType(raw) case let raw as NSDictionary: self = .DictionaryType(raw) default: self = .InvalidType([:]) } } // MARK:- value overloads public func value() -> String? { switch self { case .StringType(let value): return value default: return nil } } public func value() -> NSURL? { switch self { case .StringType(let value): return NSURL(string: value) default: return nil } } public func value() -> Int? { switch self { case .NumberType(let value): return Int(value) case .StringType(let value): return value.toInt() case .BoolType(let value): return Int(value) default: return nil } } public func value() -> UInt? { switch self { case .NumberType(let value): return UInt(value) case .StringType(let value): if let int = value.toInt() { return UInt(int) } else { return nil } case .BoolType(let value): return UInt(value) default: return nil } } public func value() -> Bool? { switch self { case .BoolType(let value): return value case .NumberType(let value): return Bool(value) default: return nil } } public func value() -> Double? { switch self { case .NumberType(let value): return Double(value) case .StringType(let value): return ((value as NSString).doubleValue) // use strtod? default: return nil } } public func value() -> NSDictionary? { switch self { case .DictionaryType(let value): return value default: return nil } } public func value() -> NSArray? { switch self { case .ArrayType(let value): return value default: return nil } } // MARK:- non-operator format public static func jsonType(json: [String: AnyObject], _ key: String) -> JsonType? { let type = json[key].map { JsonType($0) } return type } } // MARK:- operators infix operator <- { associativity right precedence 90 } public func <-(inout left: Int, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Int?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: UInt, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: UInt?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Double, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Double?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: String, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: String?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Bool, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: Bool?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSDictionary, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSDictionary?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSArray, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } public func <-(inout left: NSArray?, right: AnyObject?) { let type = right.map { JsonType($0) } type?.value().map { left = $0 } } // MARK:- operators for direct assignment prefix operator <-? {} public prefix func <-?(right: AnyObject?) -> Int? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> UInt? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> Double? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> String? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> Bool? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> NSDictionary? { let type = right.map { JsonType($0) } return type?.value() } public prefix func <-?(right: AnyObject?) -> NSArray? { let type = right.map { JsonType($0) } return type?.value() }
mit
741b245a58f245338be0bcf028d8de50
23.916318
94
0.572628
3.889615
false
false
false
false
ruslanskorb/CoreStore
CoreStoreDemo/CoreStoreDemo/List and Object Observers Demo/Palette.swift
1
2343
// // Palette.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/05/05. // Copyright © 2018 John Rommel Estropia. All rights reserved. // import Foundation import UIKit import CoreData import CoreStore // MARK: - Palette final class Palette: CoreStoreObject { let hue = Value.Required<Int>("hue", initial: 0) let saturation = Value.Required<Float>("saturation", initial: 0) let brightness = Value.Required<Float>("brightness", initial: 0) let colorName = Value.Optional<String>( "colorName", isTransient: true, customGetter: Palette.getColorName ) static func randomHue() -> Int { return Int(arc4random_uniform(360)) } private static func getColorName(_ partialObject: PartialObject<Palette>) -> String? { if let colorName = partialObject.primitiveValue(for: { $0.colorName }) { return colorName } let colorName: String switch partialObject.value(for: { $0.hue }) % 360 { case 0 ..< 20: colorName = "Lower Reds" case 20 ..< 57: colorName = "Oranges and Browns" case 57 ..< 90: colorName = "Yellow-Greens" case 90 ..< 159: colorName = "Greens" case 159 ..< 197: colorName = "Blue-Greens" case 197 ..< 241: colorName = "Blues" case 241 ..< 297: colorName = "Violets" case 297 ..< 331: colorName = "Magentas" default: colorName = "Upper Reds" } partialObject.setPrimitiveValue(colorName, for: { $0.colorName }) return colorName } } extension Palette { var color: UIColor { return UIColor( hue: CGFloat(self.hue.value) / 360.0, saturation: CGFloat(self.saturation.value), brightness: CGFloat(self.brightness.value), alpha: 1.0 ) } var colorText: String { return "H: \(self.hue.value)˚, S: \(round(self.saturation.value * 100.0))%, B: \(round(self.brightness.value * 100.0))%" } } extension Palette { func setInitialValues(in transaction: BaseDataTransaction) { self.hue .= Palette.randomHue() self.saturation .= Float(1.0) self.brightness .= Float(arc4random_uniform(70) + 30) / 100.0 } }
mit
601b240cebb30331acefef08d18fb533
26.22093
128
0.587356
4.158082
false
false
false
false
aguptaadco/cordoba-plugin-iosrtc
src/PluginEnumerateDevices.swift
1
1808
import Foundation import AVFoundation /** * Doc: https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVCaptureDevice_Class/index.html */ class PluginEnumerateDevices { class func call(callback: (data: NSDictionary) -> Void) { NSLog("PluginEnumerateDevices#call()") let devices = AVCaptureDevice.devices() as! Array<AVCaptureDevice> let json: NSMutableDictionary = [ "devices": NSMutableDictionary() ] for device: AVCaptureDevice in devices { var facing: String let hasAudio = device.hasMediaType(AVMediaTypeAudio) let hasVideo = device.hasMediaType(AVMediaTypeVideo) switch device.position { case AVCaptureDevicePosition.Unspecified: facing = "unknown" case AVCaptureDevicePosition.Back: facing = "back" case AVCaptureDevicePosition.Front: facing = "front" } NSLog("- device [uniqueID:'%@', localizedName:'%@', facing:%@, audio:%@, video:%@, connected:%@]", String(device.uniqueID), String(device.localizedName), String(facing), String(hasAudio), String(hasVideo), String(device.connected)) if device.connected == false || (hasAudio == false && hasVideo == false) { continue } (json["devices"] as! NSMutableDictionary)[device.uniqueID] = [ "deviceId": device.uniqueID, "kind": hasAudio ? "audioinput" : "videoinput", "label": device.localizedName, "facing": facing ] } callback(data: json) } }
mit
f5cef3c7ce18727ca7af30c11271b40d
33.788462
117
0.55365
5.65
false
false
false
false
LesCoureurs/Courir
Courir/Courir/ScoreSpriteNode.swift
1
2517
// // ScoreSpriteNode.swift // Courir // // Created by Sebastian Quek on 8/4/16. // Copyright © 2016 NUS CS3217. All rights reserved. // import SpriteKit class ScoreSpriteNode: SKSpriteNode { // ============================================== // Static variables and methods // ============================================== static private var hasInitTextures = false static private var digits = [SKTexture]() static private let size = CGSize(width: 72, height: 72) static private let yCoordinate = -10 * unitsPerGameGridCell static private let minXCoordinate = 18 * unitsPerGameGridCell static private let xCoordinateIncrement = 2 * unitsPerGameGridCell static private func initTextures() { for i in 0..<digitsAtlas.textureNames.count { digits.append(digitsAtlas.textureNamed("\(i)")) } hasInitTextures = true } static private func generatePositionForNthDigit(n: Int) -> CGPoint { let x = ScoreSpriteNode.minXCoordinate + n * ScoreSpriteNode.xCoordinateIncrement let y = ScoreSpriteNode.yCoordinate return IsoViewConverter.calculateRenderPositionFor(x, y) } // ============================================== // Instance variables and methods // ============================================== init() { if !ScoreSpriteNode.hasInitTextures { ScoreSpriteNode.initTextures() } let texture = ScoreSpriteNode.digits.first! super.init(texture: nil, color: UIColor.clearColor(), size: texture.size()) position = IsoViewConverter.calculateRenderPositionFor(0, 0) anchorPoint = CGPointMake(0, 0) zPosition = 0 } func setScore(score: Int) { dispatch_async(dispatch_get_main_queue()) { self.removeAllChildren() for (i, digit) in score.digits.enumerate() { let node = SKSpriteNode(texture: ScoreSpriteNode.digits[digit]) node.anchorPoint = CGPointMake(0, 0) node.position = ScoreSpriteNode.generatePositionForNthDigit(i) node.size = ScoreSpriteNode.size self.addChild(node) } } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } extension Int { var digits: [Int] { return description.characters.map {Int(String($0)) ?? 0} } }
mit
850f7f16d602f76344ef1d859fa3026c
30.860759
89
0.565978
5.001988
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/TagsCategoriesStatsRecordValue+CoreDataClass.swift
2
3402
import Foundation import CoreData public enum TagsCategoriesType: Int16 { case tag case category case folder } public class TagsCategoriesStatsRecordValue: StatsRecordValue { public var linkURL: URL? { guard let url = urlString as String? else { return nil } return URL(string: url) } public override func validateForInsert() throws { try super.validateForInsert() guard let type = TagsCategoriesType(rawValue: type) else { throw StatsCoreDataValidationError.invalidEnumValue } if let children = children, children.count > 0 { guard type == .folder else { throw StatsCoreDataValidationError.invalidEnumValue } } } } fileprivate extension TagsCategoriesStatsRecordValue { convenience init?(context: NSManagedObjectContext, tagCategory: StatsTagAndCategory) { self.init(context: context) self.name = tagCategory.name self.urlString = tagCategory.url?.absoluteString self.viewsCount = Int64(tagCategory.viewsCount ?? 0) self.type = tagCategoryType(from: tagCategory.kind).rawValue let children = tagCategory.children.compactMap { TagsCategoriesStatsRecordValue(context: context, tagCategory: $0) } self.children = NSOrderedSet(array: children) } } extension StatsTagsAndCategoriesInsight: StatsRecordValueConvertible { func statsRecordValues(in context: NSManagedObjectContext) -> [StatsRecordValue] { return topTagsAndCategories.compactMap { return TagsCategoriesStatsRecordValue(context: context, tagCategory: $0) } } init?(statsRecordValues: [StatsRecordValue]) { guard let categories = statsRecordValues as? [TagsCategoriesStatsRecordValue] else { return nil } self = StatsTagsAndCategoriesInsight(topTagsAndCategories: categories.compactMap { StatsTagAndCategory(recordValue: $0) }) } static var recordType: StatsRecordType { return .tagsAndCategories } } fileprivate extension StatsTagAndCategory { init?(recordValue: TagsCategoriesStatsRecordValue) { guard let name = recordValue.name, let categoriesType = TagsCategoriesType(rawValue: recordValue.type), let children = recordValue.children?.array as? [TagsCategoriesStatsRecordValue] else { return nil } self = StatsTagAndCategory(name: name, kind: tagAndCategoryKind(from: categoriesType), url: recordValue.linkURL, viewsCount: Int(recordValue.viewsCount), children: children.compactMap { StatsTagAndCategory(recordValue: $0) }) } } fileprivate func tagAndCategoryKind(from localType: TagsCategoriesType) -> StatsTagAndCategory.Kind { switch localType { case .tag: return .tag case .category: return .category case .folder: return .folder } } fileprivate func tagCategoryType(from kind: StatsTagAndCategory.Kind) -> TagsCategoriesType { switch kind { case .category: return TagsCategoriesType.category case .folder: return TagsCategoriesType.folder case .tag: return TagsCategoriesType.tag } }
gpl-2.0
36edf16bbe66aa552ef8bcab9c737445
30.211009
130
0.658142
5.469453
false
false
false
false
buddax2/tmpNote
LauncherApplication/AppDelegate.swift
1
1751
// // AppDelegate.swift // LauncherApplication // // Created by BUDDAx2 on 9/25/17. // Copyright © 2017 BUDDAx2. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application NSLog("launched tmpNote launcher") let mainAppIdentifier = Bundle.main.bundleIdentifier!.replacingOccurrences(of: ".LauncherApplication", with: "") let runningApps = NSWorkspace.shared.runningApplications var alreadyRunning = false for app in runningApps { if app.bundleIdentifier == mainAppIdentifier { alreadyRunning = true break } } if alreadyRunning == false { DistributedNotificationCenter.default().addObserver(self, selector: #selector(terminate), name: Notification.Name(rawValue: "killme"), object: mainAppIdentifier) let path = Bundle.main.bundlePath as NSString var components = path.pathComponents components.removeLast() components.removeLast() components.removeLast() components.append("MacOS") components.append("tmpNote") let newPath = NSString.path(withComponents: components) NSWorkspace.shared.launchApplication(newPath) } else { terminate() } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } @objc func terminate() { NSApp.terminate(self) } }
mit
4a5df8b2bbff30333923b605b9c6e446
28.661017
173
0.623429
5.573248
false
false
false
false
mathcamp/Carlos
Tests/DispatchedCacheTests.swift
1
6694
import Foundation import Quick import Nimble import Carlos import PiedPiper var kCurrentQueue = 0 func getMutablePointer (object: AnyObject) -> UnsafeMutablePointer<Void> { return UnsafeMutablePointer<Void>(bitPattern: Int(ObjectIdentifier(object).uintValue)) } struct DispatchedShareExamplesContext { static let CacheToTest = "cache" static let InternalCache = "internalCache" static let QueueToUse = "queue" } class DispatchedSharedExamplesConfiguration: QuickConfiguration { override class func configure(configuration: Configuration) { sharedExamples("a dispatched cache") { (sharedExampleContext: SharedExampleContext) in var cache: BasicCache<String, Int>! var queue: dispatch_queue_t! var internalCache: CacheLevelFake<String, Int>! beforeEach { cache = sharedExampleContext()[DispatchedShareExamplesContext.CacheToTest] as? BasicCache<String, Int> internalCache = sharedExampleContext()[DispatchedShareExamplesContext.InternalCache] as? CacheLevelFake<String, Int> queue = sharedExampleContext()[DispatchedShareExamplesContext.QueueToUse] as? dispatch_queue_t } context("when calling get") { var fakeRequest: Promise<Int>! let key = "key_test" var successSentinel: Bool? var failureSentinel: Bool? var successValue: Int? beforeEach { successSentinel = nil failureSentinel = nil successValue = nil fakeRequest = Promise<Int>() internalCache.cacheRequestToReturn = fakeRequest.future cache.get(key).onSuccess({ value in successSentinel = true successValue = value }).onFailure({ _ in failureSentinel = true }) } it("should forward the call to the internal cache") { expect(internalCache.numberOfTimesCalledGet).toEventually(equal(1)) } it("should pass the right key") { expect(internalCache.didGetKey).toEventually(equal(key)) } it("should forward the calls on the right queue") { expect(internalCache.queueUsedForTheLastCall).toEventually(equal(getMutablePointer(queue))) } context("when the request succeeds") { let successValuePassed = 10 beforeEach { fakeRequest.succeed(successValuePassed) } it("should call the success closure") { expect(successSentinel).toEventuallyNot(beNil()) } it("should pass the right value") { expect(successValue).toEventually(equal(successValuePassed)) } } context("when the request fails") { beforeEach { fakeRequest.fail(TestError.SimpleError) } it("should call the failure closure") { expect(failureSentinel).toEventuallyNot(beNil()) } } } context("when calling set") { let key = "test_key" let value = 30 beforeEach { cache.set(value, forKey: key) } it("should forward it to the internal cache") { expect(internalCache.numberOfTimesCalledSet).toEventually(equal(1)) } it("should set the right key") { expect(internalCache.didSetKey).toEventually(equal(key)) } it("should set the right value") { expect(internalCache.didSetValue).toEventually(equal(value)) } it("should forward the calls on the right queue") { expect(internalCache.queueUsedForTheLastCall).toEventually(equal(getMutablePointer(queue))) } } context("when calling onMemoryWarning") { beforeEach { cache.onMemoryWarning() } it("should forward it to the internal cache") { expect(internalCache.numberOfTimesCalledOnMemoryWarning).toEventually(equal(1)) } it("should forward the calls on the right queue") { expect(internalCache.queueUsedForTheLastCall).toEventually(equal(getMutablePointer(queue))) } } context("when calling clear") { beforeEach { cache.clear() } it("should forward it to the internal cache") { expect(internalCache.numberOfTimesCalledClear).toEventually(equal(1)) } it("should forward the calls on the right queue") { expect(internalCache.queueUsedForTheLastCall).toEventually(equal(getMutablePointer(queue))) } } } } } func currentQueueSpecific() -> UnsafeMutablePointer<Void> { return dispatch_get_specific(&kCurrentQueue) } class DispatchedCacheTests: QuickSpec { var queue: dispatch_queue_t! override func spec() { var cache: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeSuite { self.queue = dispatch_queue_create("Test queue", DISPATCH_QUEUE_CONCURRENT) dispatch_queue_set_specific(self.queue, &kCurrentQueue, getMutablePointer(self.queue), nil) } describe("Dispatched cache obtained through the protocol extension") { beforeEach { cache = CacheLevelFake() composedCache = cache.dispatch(self.queue) } itBehavesLike("a dispatched cache") { [ DispatchedShareExamplesContext.CacheToTest: composedCache, DispatchedShareExamplesContext.InternalCache: cache, DispatchedShareExamplesContext.QueueToUse: self.queue ] } } describe("Dispatched cache obtained through the operator") { beforeEach { cache = CacheLevelFake() composedCache = cache ~>> self.queue } itBehavesLike("a dispatched cache") { [ DispatchedShareExamplesContext.CacheToTest: composedCache, DispatchedShareExamplesContext.InternalCache: cache, DispatchedShareExamplesContext.QueueToUse: self.queue ] } } xdescribe("Dispatched cache obtained through the operator on a fetch closure") { //FIX beforeEach { cache = CacheLevelFake() composedCache = cache.get ~>> self.queue } itBehavesLike("a dispatched cache") { [ DispatchedShareExamplesContext.CacheToTest: composedCache, DispatchedShareExamplesContext.InternalCache: cache, DispatchedShareExamplesContext.QueueToUse: self.queue ] } } } }
mit
675ff033833f186cc141a3efa9b1ba3c
30.729858
124
0.620556
5.518549
false
false
false
false
Eric217/-OnSale
打折啦/打折啦/ESTabBar.swift
1
16390
// // ESTabBar.swift // // Created by Vincent Li on 2017/2/8. // Copyright (c) 2013-2017 ESTabBarController (https://github.com/eggswift/ESTabBarController) // // 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 /// 对原生的UITabBarItemPositioning进行扩展,通过UITabBarItemPositioning设置时,系统会自动添加insets,这使得添加背景样式的需求变得不可能实现。ESTabBarItemPositioning完全支持原有的item Position 类型,除此之外还支持完全fill模式。 /// /// - automatic: UITabBarItemPositioning.automatic /// - fill: UITabBarItemPositioning.fill /// - centered: UITabBarItemPositioning.centered /// - fillExcludeSeparator: 完全fill模式,布局不覆盖tabBar顶部分割线 /// - fillIncludeSeparator: 完全fill模式,布局覆盖tabBar顶部分割线 public enum ESTabBarItemPositioning : Int { case automatic case fill case centered case fillExcludeSeparator case fillIncludeSeparator } /// 对UITabBarDelegate进行扩展,以支持UITabBarControllerDelegate的相关方法桥接 internal protocol ESTabBarDelegate: NSObjectProtocol { /// 当前item是否支持选中 /// /// - Parameters: /// - tabBar: tabBar /// - item: 当前item /// - Returns: Bool func tabBar(_ tabBar: UITabBar, shouldSelect item: UITabBarItem) -> Bool /// 当前item是否需要被劫持 /// /// - Parameters: /// - tabBar: tabBar /// - item: 当前item /// - Returns: Bool func tabBar(_ tabBar: UITabBar, shouldHijack item: UITabBarItem) -> Bool /// 当前item的点击被劫持 /// /// - Parameters: /// - tabBar: tabBar /// - item: 当前item /// - Returns: Void func tabBar(_ tabBar: UITabBar, didHijack item: UITabBarItem) } /// ESTabBar是高度自定义的UITabBar子类,通过添加UIControl的方式实现自定义tabBarItem的效果。目前支持tabBar的大部分属性的设置,例如delegate,items,selectedImge,itemPositioning,itemWidth,itemSpacing等,以后会更加细致的优化tabBar原有属性的设置效果。 open class ESTabBar: UITabBar { internal weak var customDelegate: ESTabBarDelegate? /// tabBar中items布局偏移量 public var itemEdgeInsets = UIEdgeInsets.zero /// 是否设置为自定义布局方式,默认为空。如果为空,则通过itemPositioning属性来设置。如果不为空则忽略itemPositioning,所以当tabBar的itemCustomPositioning属性不为空时,如果想改变布局规则,请设置此属性而非itemPositioning。 public var itemCustomPositioning: ESTabBarItemPositioning? { didSet { if let itemCustomPositioning = itemCustomPositioning { switch itemCustomPositioning { case .fill: itemPositioning = .fill case .automatic: itemPositioning = .automatic case .centered: itemPositioning = .centered default: break } } self.reload() } } /// tabBar自定义item的容器view internal var containers = [ESTabBarItemContainer]() /// 缓存当前tabBarController用来判断是否存在"More"Tab internal weak var tabBarController: UITabBarController? /// 自定义'More'按钮样式,继承自ESTabBarItemContentView open var moreContentView: ESTabBarItemContentView? = ESTabBarItemMoreContentView.init() { didSet { self.reload() } } open override var items: [UITabBarItem]? { didSet { self.reload() } } open var isEditing: Bool = false { didSet { if oldValue != isEditing { self.updateLayout() } } } open override func setItems(_ items: [UITabBarItem]?, animated: Bool) { super.setItems(items, animated: animated) self.reload() } open override func beginCustomizingItems(_ items: [UITabBarItem]) { ESTabBarController.printError("beginCustomizingItems(_:) is unsupported in ESTabBar.") super.beginCustomizingItems(items) } open override func endCustomizing(animated: Bool) -> Bool { ESTabBarController.printError("endCustomizing(_:) is unsupported in ESTabBar.") return super.endCustomizing(animated: animated) } open override func layoutSubviews() { super.layoutSubviews() self.updateLayout() } open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { var b = super.point(inside: point, with: event) if !b { for container in containers { if container.point(inside: CGPoint.init(x: point.x - container.frame.origin.x, y: point.y - container.frame.origin.y), with: event) { b = true } } } return b } } internal extension ESTabBar /* Layout */ { internal func updateLayout() { guard let tabBarItems = self.items else { ESTabBarController.printError("empty items") return } let tabBarButtons = subviews.filter { subview -> Bool in if let cls = NSClassFromString("UITabBarButton") { return subview.isKind(of: cls) } return false } .sorted { (subview1, subview2) -> Bool in return subview1.frame.origin.x < subview2.frame.origin.x } if isCustomizing { for (idx, _) in tabBarItems.enumerated() { tabBarButtons[idx].isHidden = false moreContentView?.isHidden = true } for (_, container) in containers.enumerated(){ container.isHidden = true } } else { for (idx, item) in tabBarItems.enumerated() { if let _ = item as? ESTabBarItem { tabBarButtons[idx].isHidden = true } else { tabBarButtons[idx].isHidden = false } if isMoreItem(idx), let _ = moreContentView { tabBarButtons[idx].isHidden = true } } for (_, container) in containers.enumerated(){ container.isHidden = false } } var layoutBaseSystem = true if let itemCustomPositioning = itemCustomPositioning { switch itemCustomPositioning { case .fill, .automatic, .centered: break case .fillIncludeSeparator, .fillExcludeSeparator: layoutBaseSystem = false } } if layoutBaseSystem { // System itemPositioning for (idx, container) in containers.enumerated(){ container.frame = tabBarButtons[idx].frame } } else { // Custom itemPositioning var x: CGFloat = itemEdgeInsets.left var y: CGFloat = itemEdgeInsets.top switch itemCustomPositioning! { case .fillExcludeSeparator: if y <= 0.0 { y += 1.0 } default: break } let width = bounds.size.width - itemEdgeInsets.left - itemEdgeInsets.right let height = bounds.size.height - y - itemEdgeInsets.bottom let eachWidth = itemWidth == 0.0 ? width / CGFloat(containers.count) : itemWidth let eachSpacing = itemSpacing == 0.0 ? 0.0 : itemSpacing for container in containers { container.frame = CGRect.init(x: x, y: y, width: eachWidth, height: height) x += eachWidth x += eachSpacing } } } } internal extension ESTabBar /* Actions */ { internal func isMoreItem(_ index: Int) -> Bool { return ESTabBarController.isShowingMore(tabBarController) && (index == (items?.count ?? 0) - 1) } internal func removeAll() { for container in containers { container.removeFromSuperview() } containers.removeAll() } internal func reload() { removeAll() guard let tabBarItems = self.items else { ESTabBarController.printError("empty items") return } for (idx, item) in tabBarItems.enumerated() { let container = ESTabBarItemContainer.init(self, tag: 1000 + idx) self.addSubview(container) self.containers.append(container) if let item = item as? ESTabBarItem, let contentView = item.contentView { container.addSubview(contentView) } if self.isMoreItem(idx), let moreContentView = moreContentView { container.addSubview(moreContentView) } } self.setNeedsLayout() } @objc internal func highlightAction(_ sender: AnyObject?) { guard let container = sender as? ESTabBarItemContainer else { return } let newIndex = max(0, container.tag - 1000) guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else { return } if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false { return } if let item = item as? ESTabBarItem { item.contentView?.highlight(animated: true, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.highlight(animated: true, completion: nil) } } @objc internal func dehighlightAction(_ sender: AnyObject?) { guard let container = sender as? ESTabBarItemContainer else { return } let newIndex = max(0, container.tag - 1000) guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else { return } if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false { return } if let item = item as? ESTabBarItem { item.contentView?.dehighlight(animated: true, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.dehighlight(animated: true, completion: nil) } } @objc internal func selectAction(_ sender: AnyObject?) { guard let container = sender as? ESTabBarItemContainer else { return } select(itemAtIndex: container.tag - 1000, animated: true) } @objc internal func select(itemAtIndex idx: Int, animated: Bool) { let newIndex = max(0, idx) let currentIndex = (selectedItem != nil) ? (items?.index(of: selectedItem!) ?? -1) : -1 guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else { return } if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false { return } if (customDelegate?.tabBar(self, shouldHijack: item) ?? false) == true { customDelegate?.tabBar(self, didHijack: item) if animated { if let item = item as? ESTabBarItem { item.contentView?.select(animated: animated, completion: { item.contentView?.deselect(animated: false, completion: nil) }) } else if self.isMoreItem(newIndex) { moreContentView?.select(animated: animated, completion: { self.moreContentView?.deselect(animated: animated, completion: nil) }) } } return } if currentIndex != newIndex { if currentIndex != -1 && currentIndex < items?.count ?? 0{ if let currentItem = items?[currentIndex] as? ESTabBarItem { currentItem.contentView?.deselect(animated: animated, completion: nil) } else if self.isMoreItem(currentIndex) { moreContentView?.deselect(animated: animated, completion: nil) } } if let item = item as? ESTabBarItem { item.contentView?.select(animated: animated, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.select(animated: animated, completion: nil) } delegate?.tabBar?(self, didSelect: item) } else if currentIndex == newIndex { if let item = item as? ESTabBarItem { item.contentView?.reselect(animated: animated, completion: nil) } else if self.isMoreItem(newIndex) { moreContentView?.reselect(animated: animated, completion: nil) } if let tabBarController = tabBarController { var navVC: UINavigationController? if let n = tabBarController.selectedViewController as? UINavigationController { navVC = n } else if let n = tabBarController.selectedViewController?.navigationController { navVC = n } if let navVC = navVC { if navVC.viewControllers.contains(tabBarController) { if navVC.viewControllers.count > 1 && navVC.viewControllers.last != tabBarController { navVC.popToViewController(tabBarController, animated: true); } } else { if navVC.viewControllers.count > 1 { navVC.popToRootViewController(animated: animated) } } } } } self.updateAccessibilityLabels() } internal func updateAccessibilityLabels() { guard let tabBarItems = self.items, tabBarItems.count == self.containers.count else { return } for (idx, item) in tabBarItems.enumerated() { let container = self.containers[idx] var accessibilityTitle = "" if let item = item as? ESTabBarItem { accessibilityTitle = item.title ?? "" } if self.isMoreItem(idx) { accessibilityTitle = NSLocalizedString("More_TabBarItem", bundle: Bundle(for:ESTabBarController.self), comment: "") } let formatString = NSLocalizedString(item == selectedItem ? "TabBarItem_Selected_AccessibilityLabel" : "TabBarItem_AccessibilityLabel", bundle: Bundle(for: ESTabBarController.self), comment: "") container.accessibilityLabel = String(format: formatString, accessibilityTitle, idx + 1, tabBarItems.count) } } }
apache-2.0
d690ecb93aeea0751610495da024b0f6
36.193396
180
0.575777
5.302623
false
false
false
false
lenssss/whereAmI
Whereami/Manager/SettingUpManager.swift
1
9814
// // SettingUpManager.swift // Whereami // // Created by WuQifei on 16/2/4. // Copyright © 2016年 WuQifei. All rights reserved. // import Foundation import UIKit import ReactiveCocoa import MagicalRecord import SVProgressHUD import SocketIOClientSwift public var KNotificationLogin: String { get{ return "KNotificationLogin"} } public var KNotificationGetRemind: String { get{ return "KNotificationGetRemind"} } public var KNotificationGetLevelupedremind: String { get{ return "KNotificationgetLevelupedremind"} } public var KNotificationGetDanupedremind: String { get{ return "KNotificationGetDanupedremind"} } enum statusCode:Int { case Normal = 200 //正常 case Complete = 100 // 完成 case Overtime = 300 //超时 case Unfinished = 400 //未完成 case Error = 500 //错误 } class SettingUpManager: NSObject { private static var instance:SettingUpManager? = nil private static var onceToken:dispatch_once_t = 0 class var sharedInstance: SettingUpManager { dispatch_once(&onceToken) { () -> Void in instance = SettingUpManager() } return instance! } func launch(application:UIApplication,launchOptions: [NSObject: AnyObject]?) { //注册coredata数据库 MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStoreNamed("whereami.sqlite") //注册通知 let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes:[.Alert,.Badge,.Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() //连接socket SocketManager.sharedInstance.connection { (ifConnected:Bool) -> Void in if ifConnected{ print("succeed") SocketManager.sharedInstance.getMsg("remindother", callBack: { (code, objs) in NSNotificationCenter.defaultCenter().postNotificationName(KNotificationGetRemind, object: code,userInfo: ["question":objs]) }) SocketManager.sharedInstance.getMsg("levelupedremind", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { NSNotificationCenter.defaultCenter().postNotificationName(KNotificationGetLevelupedremind, object: objs) } }) SocketManager.sharedInstance.getMsg("danupedremind", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { NSNotificationCenter.defaultCenter().postNotificationName(KNotificationGetDanupedremind, object: objs) } }) let sessionId = LUserDefaults().objectForKey("sessionId") as? String if sessionId != nil { let model = CoreDataManager.sharedInstance.fetchUser(sessionId!) if model != nil { var dict = [String:AnyObject]() dict["sessionId"] = model?.sessionId SocketManager.sharedInstance.sendMsg("autoLogin", data: dict, onProto: "logined", callBack: { (code, objs) -> Void in if code == statusCode.Normal.rawValue { let dic = objs[0] as! [String:AnyObject] let userData:[AnyObject] = dic["userData"] as! [AnyObject] let modelDic = userData[0] as! [String:AnyObject] let userModel = UserModel.getModelFromDictionary(modelDic) CoreDataManager.sharedInstance.increaseOrUpdateUser(userModel) let userDefaults = LUserDefaults() userDefaults.setObject(userModel.sessionId, forKey: "sessionId") userDefaults.synchronize() print("autoLogin succeed") self.getCountryOpendMsg() self.getAllKindsOfGame() self.getAccItems() self.gainItems() self.registAVClient(userModel) } else{ dispatch_async(dispatch_get_main_queue(), { () -> Void in SVProgressHUD.showErrorWithStatus("please login") self.change2ChooseLoginVC() }) } }) } } } } NSNotificationCenter.defaultCenter().rac_addObserverForName(KNotificationLogin, object: nil).subscribeNext { (notification) -> Void in let user = notification.object as! UserModel self.registAVClient(user) self.getCountryOpendMsg() self.getFreinds(user.id!) self.getAllKindsOfGame() self.getAccItems() self.gainItems() dispatch_async(dispatch_get_main_queue(), { () -> Void in LocationManager.sharedInstance.setupLocation() self.change2CustomTabbarVC() }) } LeanCloudManager.sharedInstance.setupApplication() } //注册聊天client func registAVClient(currentUsr:UserModel) { let clientId = currentUsr.id LeanCloudManager.sharedInstance.openSessionWithClientId(clientId!) { (succeed, error) in if !succeed { print("failed to register a client"); } } } //获取国家开放信息 func getCountryOpendMsg(){ var dict = [String:AnyObject]() dict["id"] = "" print("=================\(dict)") SocketManager.sharedInstance.sendMsg("getCountryOpendMsg", data: dict, onProto: "getCountryOpendMsged", callBack: { (code, objs) -> Void in if code == statusCode.Normal.rawValue { print("====================\(objs)") FileManager.sharedInstance.countryListWriteToFile(objs) } }) } //获取所有游戏类型 func getAllKindsOfGame(){ var dict = [String:AnyObject]() dict["id"] = UserModel.getCurrentUser()?.id SocketManager.sharedInstance.sendMsg("getAllKindsOfGame", data: dict, onProto: "getAllKindsOfGameed") { (code, objs) in if code == statusCode.Normal.rawValue { print("====================\(objs)") FileManager.sharedInstance.gameKindListWriteToFile(objs) } } } //获取所有好友 func getFreinds(id:String){ var dict = [String:AnyObject]() dict["accountId"] = id dict["nickname"] = "" SocketManager.sharedInstance.sendMsg("getFreinds", data: dict, onProto: "getFreindsed") { (code, objs) in if code == statusCode.Normal.rawValue { let accountList = FriendsModel.getModelFromObject(objs) for item in accountList { CoreDataManager.sharedInstance.increaseFriends(item) } } } } //获取个人道具数量 func getAccItems(){ var dict = [String: AnyObject]() dict["accountId"] = UserModel.getCurrentUser()?.id SocketManager.sharedInstance.sendMsg("queryAccItems", data: dict, onProto: "queryAccItemsed") { (code, objs) in if code == statusCode.Normal.rawValue{ let dic = objs[0] as? [String:AnyObject] guard let arr = dic!["items"] as? [AnyObject] else{ return } let items = AccItems.getModelFromArray(arr) for item in items! { CoreDataManager.sharedInstance.increaseOrUpdateAccItem(item) } } } } //获取道具列表 func gainItems(){ var arr = LUserDefaults().objectForKey("gainItems") as? [NSData] guard arr != nil && arr?.count != 0 else { return } for item in arr! { do { let json = item let dict = try NSJSONSerialization.JSONObjectWithData(json, options: .MutableContainers) as! [String:AnyObject] 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 } } self.getAccItems() } } }catch{ print("gainItems error") } } } //跳转登陆 func change2ChooseLoginVC(){ let currentWindow = (LApplication().delegate!.window)! currentWindow!.rootViewController = LoginNavViewController(rootViewController: ChooseLoginItemViewController()) } //跳转主页 func change2CustomTabbarVC(){ let currentWindow = (LApplication().delegate!.window)! currentWindow!.rootViewController = CustomTabBarViewController() } }
mit
8ce2a11a5a0ada249490ba968d1dc216
39.978814
147
0.539655
5.632499
false
false
false
false
zom/Zom-iOS
Zom/Zom/Classes/View Controllers/Onboarding/ZomCongratsViewController.swift
1
4730
// // ZomCongratsViewController.swift // Zom // // Created by N-Pex on 2017-01-24. // // import UIKit import ChatSecureCore import MobileCoreServices open class ZomCongratsViewController: UIViewController { @IBOutlet weak var avatarImageView:UIButton! open var account:OTRAccount? { didSet { guard let acct = account else { return; } self.viewHandler?.keyCollectionObserver.observe(acct.uniqueId, collection: OTRAccount.collection) } } private var avatarPicker:OTRAttachmentPicker? private var viewHandler:OTRYapViewHandler? open override func viewDidLoad() { super.viewDidLoad() if let connection = OTRDatabaseManager.sharedInstance().longLivedReadOnlyConnection { self.viewHandler = OTRYapViewHandler(databaseConnection: connection, databaseChangeNotificationName: DatabaseNotificationName.LongLivedTransactionChanges) if let accountKey = account?.uniqueId { self.viewHandler?.keyCollectionObserver.observe(accountKey, collection: OTRAccount.collection) } self.viewHandler?.delegate = self } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.avatarImageView.layer.cornerRadius = self.avatarImageView.frame.width/2; self.avatarImageView.isUserInteractionEnabled = true self.avatarImageView.clipsToBounds = true; } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.refreshAvatarImage(account: self.account) } func refreshAvatarImage(account:OTRAccount?) { if let account = self.account, let data = account.avatarData, data.count > 0 { self.avatarImageView.setImage(account.avatarImage(), for: .normal) } else { self.avatarImageView.setImage(UIImage(named: "onboarding_avatar", in: OTRAssets.resourcesBundle, compatibleWith: nil), for: .normal) } } @IBAction func avatarButtonPressed(_ sender: AnyObject) { let picker = OTRAttachmentPicker(parentViewController: self, delegate: self) self.avatarPicker = picker if let view = sender as? UIView { picker.showAlertController(fromSourceView: view, withCompletion: nil) } } /** Uses the global readOnlyDatabaseConnection to refetch the account object and refresh the avatar image view with that new object*/ fileprivate func refreshViews() { guard let key = self.account?.uniqueId else { self.refreshAvatarImage(account: nil) return } var account:OTRAccount? = nil OTRDatabaseManager.sharedInstance().longLivedReadOnlyConnection?.asyncRead({ (transaction) in account = OTRAccount.fetchObject(withUniqueID:key, transaction: transaction) }, completionQueue: DispatchQueue.main) { self.account = account self.refreshAvatarImage(account: self.account) } } } extension ZomCongratsViewController: OTRYapViewHandlerDelegateProtocol { public func didReceiveChanges(_ handler: OTRYapViewHandler, key: String, collection: String) { if key == self.account?.uniqueId { self.refreshViews() } } } extension ZomCongratsViewController:UIPopoverPresentationControllerDelegate { public func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { if popoverPresentationController.sourceView == nil { popoverPresentationController.sourceView = self.avatarImageView } } } extension ZomCongratsViewController:OTRAttachmentPickerDelegate { public func attachmentPicker(_ attachmentPicker: OTRAttachmentPicker, gotVideoURL videoURL: URL) { } public func attachmentPicker(_ attachmentPicker: OTRAttachmentPicker, gotPhoto photo: UIImage, withInfo info: [AnyHashable : Any]) { guard let account = self.account else { return } if (OTRProtocolManager.sharedInstance().protocol(for: account) != nil) { if let xmppManager = OTRProtocolManager.sharedInstance().protocol(for: account) as? XMPPManager { xmppManager.setAvatar(photo, completion: { (success) in //We updated the avatar }) } } } public func attachmentPicker(_ attachmentPicker: OTRAttachmentPicker, preferredMediaTypesFor source: UIImagePickerControllerSourceType) -> [String] { return [kUTTypeImage as String] } }
mpl-2.0
5acddd9cb5d4647ef0182b87b88fabe2
36.539683
166
0.671882
5.637664
false
false
false
false
openHPI/xikolo-ios
Common/Logger.swift
1
1864
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import os let logger = Logger(subsystem: "de.xikolo.common", category: "Common") public struct Logger { private let log: OSLog public init(subsystem: String, category: String) { self.log = OSLog(subsystem: subsystem, category: category) } private func log(type: OSLogType, file: String, _ message: String, _ args: [CVarArg]) { let expendedMessage = String(format: message, arguments: args) if let url = URL(string: file) { os_log("[%@] %@", log: self.log, type: type, url.lastPathComponent, expendedMessage) } else { os_log("%@", log: self.log, type: type, expendedMessage) } } public func info(_ message: String, file: String = #file, _ args: CVarArg...) { self.log(type: .info, file: file, message, args) } public func debug(_ message: String, file: String = #file, _ args: CVarArg...) { self.log(type: .debug, file: file, message, args) } public func warning(_ message: String, file: String = #file, _ args: CVarArg...) { self.log(type: .default, file: file, message, args) } public func error(_ message: String, file: String = #file, _ args: CVarArg..., error: Error? = nil) { var builtArgs = args var builtMessage: String = message if let error = error { let originalMessage = String(format: message, arguments: args) builtMessage = "%@ ===> Error found: %@" builtArgs = [originalMessage, String(reflecting: error)] } self.log(type: .error, file: file, builtMessage, builtArgs) } public func fault(_ message: String, file: String = #file, _ args: CVarArg...) { self.log(type: .fault, file: file, message, args) } }
gpl-3.0
e77fc6806e1ff5c2280e5f7b16b6d1c2
32.872727
105
0.600644
3.817623
false
false
false
false
josercc/ZHTableViewGroupSwift
Sources/SwiftTableViewGroup/UICollectionView/CollectionSection.swift
1
1083
// // CollectionSection.swift // // // Created by 张行 on 2019/7/17. // import UIKit.UICollectionViewCell public struct CollectionSection : DataNode { public var header:CollectionHeaderView? public var footer:CollectionFooterView? public var cells:[CollectionCell] = [CollectionCell]() public init(@CollectionSectionBuilder _ block:() -> DataNode) { if let group = block() as? CollectionViewRegiterGroup { self.header = group.header self.footer = group.footer self.cells = group.cells } } public func number() -> Int { var count = 0 for cell in cells { count += cell.number } return count } /// 1 2 3 public func cell(index:Int) -> (cell:CollectionCell, index:Int) { var count = 0 for cell in cells { let countIndex = count + cell.number if index < countIndex { return (cell, index - count) } count = countIndex } return (cells[0],0) } }
mit
157b6d0f3a7cb02d18bc253af66adb63
25.317073
69
0.563485
4.552743
false
false
false
false
psobot/hangover
Hangover/Channel.swift
1
16244
// // Channel.swift // Hangover // // Created by Peter Sobot on 5/26/15. // Copyright (c) 2015 Peter Sobot. All rights reserved. // import Foundation import Alamofire import JavaScriptCore protocol ChannelDelegate { func channelDidConnect(channel: Channel) func channelDidDisconnect(channel: Channel) func channelDidReconnect(channel: Channel) func channel(channel: Channel, didReceiveMessage: NSString) } class Channel : NSObject, NSURLSessionDataDelegate { static let ORIGIN_URL = "https://talkgadget.google.com" let CHANNEL_URL_PREFIX = "https://0.client-channel.google.com/client-channel" // Long-polling requests send heartbeats every 15 seconds, so if we miss two in // a row, consider the connection dead. let PUSH_TIMEOUT = 30 let MAX_READ_BYTES = 1024 * 1024 let CONNECT_TIMEOUT = 30 static let LEN_REGEX = "([0-9]+)\n" var isConnected = false var isSubscribed = false var onConnectCalled = false var pushParser = PushDataParser() var sidParam: String? = nil var gSessionIDParam: String? = nil static let MAX_RETRIES = 5 // maximum number of times to retry after a failure var retries = MAX_RETRIES // number of remaining retries var need_new_sid = true // whether a new SID is needed let manager: Alamofire.Manager var delegate: ChannelDelegate? init(manager: Alamofire.Manager) { self.manager = manager } func getCookieValue(key: String) -> String? { if let c = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies { if let match = (c.filter { ($0 as NSHTTPCookie).name == key && ($0 as NSHTTPCookie).domain == ".google.com" }).first { return match.value } } return nil } func listen() { // Listen for messages on the channel. if self.retries >= 0 { // After the first failed retry, back off exponentially longer after // each attempt. if self.retries + 1 < Channel.MAX_RETRIES { let backoff_seconds = UInt64(2 << (Channel.MAX_RETRIES - self.retries)) NSLog("Backing off for \(backoff_seconds) seconds") usleep(useconds_t(backoff_seconds * USEC_PER_SEC)) } // Request a new SID if we don't have one yet, or the previous one // became invalid. if self.need_new_sid { // TODO: error handling self.fetchChannelSID() return } // Clear any previous push data, since if there was an error it // could contain garbage. self.pushParser = PushDataParser() self.makeLongPollingRequest() } else { NSLog("Listen failed due to no retries left."); } // logger.error('Ran out of retries for long-polling request') } func makeLongPollingRequest() { // Open a long-polling request and receive push data. // // This method uses keep-alive to make re-opening the request faster, but // the remote server will set the "Connection: close" header once an hour. print("Opening long polling request.") // Make the request! let queryString = "VER=8&RID=rpc&t=1&CI=0&ctype=hangouts&TYPE=xmlhttp&gsessionid=\(gSessionIDParam!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)&SID=\(sidParam!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)" let url = "\(CHANNEL_URL_PREFIX)/channel/bind?\(queryString)" // TODO: Include timeout var request = NSMutableURLRequest(URL: NSURL(string: url)!) let sapisid = getCookieValue("SAPISID")! print("SAPISID param: \(sapisid)") for (k, v) in getAuthorizationHeaders(sapisid) { print("Setting header \(k) to \(v)") request.setValue(v, forHTTPHeaderField: k) } print("Making request to URL: \(url)") // let cfg = NSURLSessionConfiguration.defaultSessionConfiguration() // cfg.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() // let sessionCopy = NSURLSession(configuration: cfg, delegate: self, delegateQueue: nil) // sessionCopy.dataTaskWithRequest(request).resume() request.timeoutInterval = 30 manager.request(request).stream { (data: NSData) in self.onPushData(data) }.response { ( request: NSURLRequest, response: NSHTTPURLResponse?, responseObject: AnyObject?, error: NSError?) in print("long poll completed with status code: \(response?.statusCode)") if response?.statusCode >= 400 { NSLog("Request failed with: \(NSString(data: responseObject as! NSData, encoding: 4))") self.need_new_sid = true self.listen() } else if response?.statusCode == 200 { //self.onPushData(responseObject as! NSData) self.makeLongPollingRequest() } else { NSLog("Received unknown response code \(response?.statusCode)") NSLog(NSString(data: responseObject as! NSData, encoding: 4)! as String) } } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { print("GOT DATA \(NSString(data: data, encoding: NSUTF8StringEncoding))") } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { NSLog("Request failed: \(error)") // if let error = () { // NSLog("Long-polling request failed: \(error)") // retries -= 1 // if isConnected { // isConnected = false // } //self.on_disconnect.fire() // if isinstance(e, UnknownSIDError) { // need_new_sid = true // } // } else { // The connection closed successfully, so reset the number of // retries. // retries = Channel.MAX_RETRIES // } // If the request ended with an error, the client must account for // messages being dropped during this time. } func fetchChannelSID() { // Creates a new channel for receiving push data. NSLog("Requesting new gsessionid and SID...") // There's a separate API to get the gsessionid alone that Hangouts for // Chrome uses, but if we don't send a gsessionid with this request, it // will return a gsessionid as well as the SID. var params = ["VER": 8, "RID": 81187, "ctype": "hangouts"] let headers = getAuthorizationHeaders(getCookieValue("SAPISID")!) let url = "\(CHANNEL_URL_PREFIX)/channel/bind?VER=8&RID=81187&ctype=hangouts" var URLRequest = NSMutableURLRequest(URL: NSURL(string: url)!) URLRequest.HTTPMethod = "POST" for (k, v) in headers { URLRequest.addValue(v, forHTTPHeaderField: k) } let data = "count=0".dataUsingEncoding(NSUTF8StringEncoding)! isSubscribed = false manager.upload(URLRequest, data: data).response { ( request: NSURLRequest, response: NSHTTPURLResponse?, responseObject: AnyObject?, error: NSError?) in if let error = error { NSLog("Request failed: \(error)") } else { let responseValues = parseSIDResponse(responseObject as! NSData) print("Got SID response back: \(NSString(data: responseObject as! NSData, encoding: NSUTF8StringEncoding))") self.sidParam = responseValues.sid self.gSessionIDParam = responseValues.gSessionID NSLog("New SID: \(self.sidParam)") NSLog("New gsessionid: \(self.gSessionIDParam)") self.need_new_sid = false self.listen() } } } private func onPushData(data: NSData) { // Delay subscribing until first byte is received prevent "channel not // ready" errors that appear to be caused by a race condition on the // server. if !isSubscribed { subscribe { self.onPushData(data) } return } // This method is only called when the long-polling request was // successful, so use it to trigger connection events if necessary. if !isConnected { if onConnectCalled { isConnected = true delegate?.channelDidReconnect(self) } else { onConnectCalled = true isConnected = true delegate?.channelDidConnect(self) } } for submission in pushParser.getSubmissions(data) { delegate?.channel(self, didReceiveMessage: submission) } } private var isSubscribing = false private func subscribe(cb: (() -> Void)?) { // Subscribes the channel to receive relevant events. // Only needs to be called when a new channel (SID/gsessionid) is opened. if isSubscribing { return } print("Subscribing channel...") isSubscribing = true // Temporary workaround for #58 delay(1) { let timestamp = Int(NSDate().timeIntervalSince1970 * 1000) // Hangouts for Chrome splits this over 2 requests, but it's possible to // do everything in one. let data: Dictionary<String, AnyObject> = [ "count": "3", "ofs": "0", "req0_p": "{\"1\":{\"1\":{\"1\":{\"1\":3,\"2\":2}},\"2\":{\"1\":{\"1\":3,\"2\":2},\"2\":\"\",\"3\":\"JS\",\"4\":\"lcsclient\"},\"3\":\(timestamp),\"4\":0,\"5\":\"c1\"},\"2\":{}}", "req1_p": "{\"1\":{\"1\":{\"1\":{\"1\":3,\"2\":2}},\"2\":{\"1\":{\"1\":3,\"2\":2},\"2\":\"\",\"3\":\"JS\",\"4\":\"lcsclient\"},\"3\":\(timestamp),\"4\":\(timestamp),\"5\":\"c3\"},\"3\":{\"1\":{\"1\":\"babel\"}}}", "req2_p": "{\"1\":{\"1\":{\"1\":{\"1\":3,\"2\":2}},\"2\":{\"1\":{\"1\":3,\"2\":2},\"2\":\"\",\"3\":\"JS\",\"4\":\"lcsclient\"},\"3\":\(timestamp),\"4\":\(timestamp),\"5\":\"c4\"},\"3\":{\"1\":{\"1\":\"hangout_invite\"}}}", ] let postBody = data.urlEncodedQueryStringWithEncoding(NSUTF8StringEncoding) let queryString = (["VER": 8, "RID": 81188, "ctype": "hangouts", "gsessionid": self.gSessionIDParam!, "SID": self.sidParam!] as Dictionary<String, AnyObject>).urlEncodedQueryStringWithEncoding(NSUTF8StringEncoding) let url = "\(self.CHANNEL_URL_PREFIX)/channel/bind?\(queryString)" var request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "POST" request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! for (k, v) in getAuthorizationHeaders(self.getCookieValue("SAPISID")!) { request.setValue(v, forHTTPHeaderField: k) } print("Making request to URL: \(url)") self.manager.request(request).response { ( request: NSURLRequest, response: NSHTTPURLResponse?, responseObject: AnyObject?, error: NSError?) in print("Channel is now subscribed.") self.isSubscribed = true cb?() } } } } func parseSIDResponse(res: NSData) -> (sid: String, gSessionID: String) { // Parse response format for request for new channel SID. // // Example format (after parsing JS): // [ [0,["c","SID_HERE","",8]], // [1,[{"gsid":"GSESSIONID_HERE"}]]] if let firstSubmission = PushDataParser().getSubmissions(res).first { let ctx = JSContext() let val: JSValue = ctx.evaluateScript(firstSubmission) let sid = ((val.toArray()[0] as! NSArray)[1] as! NSArray)[1] as! String let gSessionID = (((val.toArray()[1] as! NSArray)[1] as! NSArray)[0] as! NSDictionary)["gsid"]! as! String return (sid, gSessionID) } return ("", "") } func getAuthorizationHeaders(sapisid_cookie: String) -> Dictionary<String, String> { // Return authorization headers for API request. // // It doesn't seem to matter what the url and time are as long as they are // consistent. let time_msec = Int(NSDate().timeIntervalSince1970 * 1000) let auth_string = "\(time_msec) \(sapisid_cookie) \(Channel.ORIGIN_URL)" let auth_hash = auth_string.SHA1() let sapisidhash = "SAPISIDHASH \(time_msec)_\(auth_hash)" return [ "Authorization": sapisidhash, "X-Origin": Channel.ORIGIN_URL, "X-Goog-Authuser": "0", ] } func bestEffortDecode(data: NSData) -> String? { // Decode data_bytes into a string using UTF-8. // // If data_bytes cannot be decoded, pop the last byte until it can be or // return an empty string. for var i = 0; i < data.length; i++ { if let s = NSString(data: data.subdataWithRange(NSMakeRange(0, data.length - i)), encoding: NSUTF8StringEncoding) { return s as String } } return nil } class PushDataParser { // Parse data from the long-polling endpoint. var buf = NSMutableData() func getSubmissions(newBytes: NSData) -> [String] { // Yield submissions generated from received data. // // Responses from the push endpoint consist of a sequence of submissions. // Each submission is prefixed with its length followed by a newline. // // The buffer may not be decodable as UTF-8 if there's a split multi-byte // character at the end. To handle this, do a "best effort" decode of the // buffer to decode as much of it as possible. // // The length is actually the length of the string as reported by // JavaScript. JavaScript's string length function returns the number of // code units in the string, represented in UTF-16. We can emulate this by // encoding everything in UTF-16 and multipling the reported length by 2. // // Note that when encoding a string in UTF-16, Python will prepend a // byte-order character, so we need to remove the first two bytes. buf.appendData(newBytes) var submissions = [String]() while buf.length > 0 { if let decoded = bestEffortDecode(buf) { let bufUTF16 = decoded.dataUsingEncoding(NSUTF16BigEndianStringEncoding)! let decodedUtf16LengthInChars = bufUTF16.length / 2 let lengths = Regex(Channel.LEN_REGEX).findall(decoded) if let length_str = lengths.first { let length_str_without_newline = length_str.substringToIndex(advance(length_str.endIndex, -1)) if let length = Int(length_str_without_newline) { if decodedUtf16LengthInChars - length_str.characters.count < length { break } let subData = bufUTF16.subdataWithRange(NSMakeRange(length_str.characters.count * 2, length * 2)) let submission = NSString(data: subData, encoding: NSUTF16BigEndianStringEncoding)! as String submissions.append(submission) let submissionAsUTF8 = submission.dataUsingEncoding(NSUTF8StringEncoding)! let removeRange = NSMakeRange(0, length_str.characters.count + submissionAsUTF8.length) buf.replaceBytesInRange(removeRange, withBytes: nil, length: 0) } else { break } } else { break } } } return submissions } }
mit
e52862f2a3300d3373edbada0958a828
39.916877
256
0.577752
4.665135
false
false
false
false
goblinr/omim
iphone/Maps/UI/Search/Filters/FilterCollectionHolderCell.swift
1
1045
@objc(MWMFilterCollectionHolderCell) final class FilterCollectionHolderCell: MWMTableViewCell { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet private weak var collectionViewHeight: NSLayoutConstraint! private weak var tableView: UITableView? override var frame: CGRect { didSet { if frame.size.height < 1 /* minimal correct height */ { frame.size.height = max(collectionViewHeight.constant, 1) tableView?.refresh() } } } private func layout() { collectionView.setNeedsLayout() collectionView.layoutIfNeeded() collectionViewHeight.constant = collectionView.contentSize.height } @objc func config(tableView: UITableView?) { self.tableView = tableView layout() collectionView.allowsMultipleSelection = true collectionView.reloadData() } override func awakeFromNib() { super.awakeFromNib() isSeparatorHidden = true backgroundColor = UIColor.clear } override func layoutSubviews() { super.layoutSubviews() layout() } }
apache-2.0
1b01f5e863273ae7ee0ae6e404669148
26.5
70
0.719617
5.277778
false
false
false
false
quadro5/swift3_L
swift_question.playground/Pages/Dictionary.xcplaygroundpage/Contents.swift
1
668
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) var dict1 = Dictionary<Int, Int>() // contain if dict1[3] != nil { print("dict1 has key 3") } else { print("dict1 has not key 3") } var dict2 = Dictionary<Int, Int?>() dict2[3] = nil dict2.count if dict2[3] != nil { print("dict2 has key 3") } else { print("dict2 has not key 3") } // add dict1[1] = 11 dict1[2] = 22 let hehe = dict1.updateValue(22, forKey: 10) print(hehe ?? -1) print(dict1[10] ?? -1) // remove // remove key let value = dict1.removeValue(forKey: 1) // remove all dict1.removeAll(keepingCapacity: true) dict1.removeAll()
unlicense
c5c5f7475965959adfe739302e0d2b43
11.603774
44
0.622754
2.794979
false
false
false
false
littlelightwang/firefox-ios
Providers/ProfilePrefs.swift
2
2806
/* 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 public protocol ProfilePrefs { func setObject(value: AnyObject?, forKey defaultName: String) func stringArrayForKey(defaultName: String) -> [AnyObject]? func arrayForKey(defaultName: String) -> [AnyObject]? func dictionaryForKey(defaultName: String) -> [NSObject : AnyObject]? func removeObjectForKey(defaultName: String) } public class MockProfilePrefs : ProfilePrefs { var things: NSMutableDictionary = NSMutableDictionary() public func setObject(value: AnyObject?, forKey defaultName: String) { things[defaultName] = value } public func stringArrayForKey(defaultName: String) -> [AnyObject]? { return self.arrayForKey(defaultName) } public func arrayForKey(defaultName: String) -> [AnyObject]? { let r: AnyObject? = things.objectForKey(defaultName) if (r == nil) { return nil } if let arr = r as? [AnyObject] { return arr } return nil } public func dictionaryForKey(defaultName: String) -> [NSObject : AnyObject]? { return things.objectForKey(defaultName) as? [NSObject: AnyObject] } public func removeObjectForKey(defaultName: String) { self.things[defaultName] = nil } } public class NSUserDefaultsProfilePrefs : ProfilePrefs { private let profile: Profile private let prefix: String private let userDefaults: NSUserDefaults init(profile: Profile) { self.profile = profile self.prefix = profile.localName() + "." self.userDefaults = NSUserDefaults(suiteName: SuiteName)! } // Preferences are qualified by the profile's local name. // Connecting a profile to a Firefox Account, or changing to another, won't alter this. private func qualifyKey(key: String) -> String { return self.prefix + key } public func setObject(value: AnyObject?, forKey defaultName: String) { userDefaults.setObject(value, forKey: qualifyKey(defaultName)) } public func stringArrayForKey(defaultName: String) -> [AnyObject]? { return userDefaults.stringArrayForKey(qualifyKey(defaultName)) } public func arrayForKey(defaultName: String) -> [AnyObject]? { return userDefaults.arrayForKey(qualifyKey(defaultName)) } public func dictionaryForKey(defaultName: String) -> [NSObject : AnyObject]? { return userDefaults.dictionaryForKey(qualifyKey(defaultName)) } public func removeObjectForKey(defaultName: String) { userDefaults.removeObjectForKey(qualifyKey(defaultName)); } }
mpl-2.0
ad8e97613e2e0bcff18d68337a1580a3
33.219512
91
0.686386
4.905594
false
false
false
false
Antidote-for-Tox/Antidote
Antidote/TabBarBadgeItem.swift
1
5362
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let ImageAndTextContainerYOffset = 2.0 static let ImageAndTextOffset = 3.0 static let BadgeTopOffset = -5.0 static let BadgeHorizontalOffset = 5.0 static let BadgeMinimumWidth = 22.0 static let BadgeHeight: CGFloat = 18.0 } class TabBarBadgeItem: TabBarAbstractItem { override var selected: Bool { didSet { let color = theme.colorForType(selected ? .TabItemActive : .TabItemInactive) textLabel.textColor = color imageView.tintColor = color } } var image: UIImage? { didSet { imageView.image = image?.withRenderingMode(.alwaysTemplate) } } var text: String? { didSet { textLabel.text = text } } var badgeText: String? { didSet { badgeTextWasUpdated() } } /// If there is any badge text, accessibilityValue will be set to <badgeText + badgeAccessibilityEnding> var badgeAccessibilityEnding: String? fileprivate let theme: Theme fileprivate var imageAndTextContainer: UIView! fileprivate var imageView: UIImageView! fileprivate var textLabel: UILabel! fileprivate var badgeContainer: UIView! fileprivate var badgeLabel: UILabel! fileprivate var button: UIButton! init(theme: Theme) { self.theme = theme super.init(frame: CGRect.zero) backgroundColor = .clear createViews() installConstraints() badgeTextWasUpdated() } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // Accessibility extension TabBarBadgeItem { override var accessibilityLabel: String? { get { return text } set {} } override var accessibilityValue: String? { get { guard var result = badgeText else { return nil } if let ending = badgeAccessibilityEnding { result += " " + ending } return result } set {} } } // Actions extension TabBarBadgeItem { @objc func buttonPressed() { didTapHandler?() } } private extension TabBarBadgeItem { func createViews() { imageAndTextContainer = UIView() imageAndTextContainer.backgroundColor = .clear addSubview(imageAndTextContainer) imageView = UIImageView() imageView.backgroundColor = .clear imageAndTextContainer.addSubview(imageView) textLabel = UILabel() textLabel.textColor = theme.colorForType(.NormalText) textLabel.textAlignment = .center textLabel.backgroundColor = .clear textLabel.font = UIFont.systemFont(ofSize: 10.0) imageAndTextContainer.addSubview(textLabel) badgeContainer = UIView() badgeContainer.backgroundColor = theme.colorForType(.TabBadgeBackground) badgeContainer.layer.masksToBounds = true badgeContainer.layer.cornerRadius = Constants.BadgeHeight / 2 addSubview(badgeContainer) badgeLabel = UILabel() badgeLabel.textColor = theme.colorForType(.TabBadgeText) badgeLabel.textAlignment = .center badgeLabel.backgroundColor = .clear badgeLabel.font = UIFont.antidoteFontWithSize(14.0, weight: .light) badgeContainer.addSubview(badgeLabel) button = UIButton() button.backgroundColor = .clear button.addTarget(self, action: #selector(TabBarBadgeItem.buttonPressed), for: .touchUpInside) addSubview(button) } func installConstraints() { imageAndTextContainer.snp.makeConstraints { $0.centerX.equalTo(self) $0.centerY.equalTo(self).offset(Constants.ImageAndTextContainerYOffset) } imageView.snp.makeConstraints { $0.top.equalTo(imageAndTextContainer) $0.centerX.equalTo(imageAndTextContainer) } textLabel.snp.makeConstraints { $0.top.equalTo(imageView.snp.bottom).offset(Constants.ImageAndTextOffset) $0.centerX.equalTo(imageAndTextContainer) $0.bottom.equalTo(imageAndTextContainer) } badgeContainer.snp.makeConstraints { $0.leading.equalTo(imageAndTextContainer.snp.leading) $0.top.equalTo(imageAndTextContainer.snp.top).offset(Constants.BadgeTopOffset) $0.width.greaterThanOrEqualTo(Constants.BadgeMinimumWidth) $0.height.equalTo(Constants.BadgeHeight) } badgeLabel.snp.makeConstraints { $0.leading.equalTo(badgeContainer).offset(Constants.BadgeHorizontalOffset) $0.trailing.equalTo(badgeContainer).offset(-Constants.BadgeHorizontalOffset) $0.centerY.equalTo(badgeContainer) } button.snp.makeConstraints { $0.edges.equalTo(self) } } func badgeTextWasUpdated() { badgeLabel.text = badgeText badgeContainer.isHidden = (badgeText == nil) || badgeText!.isEmpty } }
mpl-2.0
3624ad3de38c994f986e5a5a472a2cb6
28.141304
108
0.643976
5.101808
false
false
false
false
bizz84/SwiftyStoreKit
Sources/SwiftyStoreKit/SKProductDiscount+LocalizedPrice.swift
1
3060
// // SKProductDiscount+LocalizedPrice.swift // SwiftyStoreKit // // Created by Sam Spencer on 5/29/20. // Copyright © 2020 Sam Spencer. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import StoreKit @available(iOSApplicationExtension 11.2, iOS 11.2, OSX 10.13.2, tvOS 11.2, watchOS 4.2, macCatalyst 13.0, *) public extension SKProductDiscount { /// The formatted discount price of the product using the local currency. var localizedPrice: String? { return priceFormatter(locale: priceLocale).string(from: price) } private func priceFormatter(locale: Locale) -> NumberFormatter { let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .currency return formatter } /// The formatted, localized period / date for the product discount. /// - note: The subscription period for the discount is independent of the product's regular subscription period, and does not have to match in units or duration. var localizedSubscriptionPeriod: String { let dateComponents: DateComponents switch subscriptionPeriod.unit { case .day: dateComponents = DateComponents(day: subscriptionPeriod.numberOfUnits) case .week: dateComponents = DateComponents(weekOfMonth: subscriptionPeriod.numberOfUnits) case .month: dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits) case .year: dateComponents = DateComponents(year: subscriptionPeriod.numberOfUnits) @unknown default: print("WARNING: SwiftyStoreKit localizedSubscriptionPeriod does not handle all SKProduct.PeriodUnit cases.") // Default to month units in the unlikely event a different unit type is added to a future OS version dateComponents = DateComponents(month: subscriptionPeriod.numberOfUnits) } return DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: .full) ?? "" } }
mit
2dd9748ced4e1c147abafb3af6559e07
48.33871
166
0.730958
5.098333
false
false
false
false
FabrizioBrancati/SwiftyBot
Sources/Messenger/Activation/Activation.swift
1
3032
// // Activation.swift // SwiftyBot // // The MIT License (MIT) // // Copyright (c) 2016 - 2019 Fabrizio Brancati. // // 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 Vapor /// Actiovation struct. public struct Activation: Codable { /// Activation mode. public private(set) var mode: String /// Activation token. public private(set) var verifyToken: String /// Activation challenge. public private(set) var challenge: String /// Coding keys, used by Codable protocol. private enum CodingKeys: String, CodingKey { case mode = "hub.mode" case verifyToken = "hub.verify_token" case challenge = "hub.challenge" } } // MARK: - Activation Extension /// Activation extension. public extension Activation { /// Empty init method. /// Declared in an extension to not override default `init` function. /// /// - Parameter request: Activation request. /// - Throws: Decoding errors. init(for request: Request) throws { /// Try decoding the request query as `Activation`. self = try request.query.decode(Activation.self) /// Check for "hub.mode", "hub.verify_token" & "hub.challenge" query parameters. guard mode == "subscribe", verifyToken == messengerSecret else { throw Abort(.badRequest, reason: "Missing Facebook Messenger verification data.") } } } // MARK: - Activation Handling /// Activation extension. public extension Activation { /// Check if the activation is valid. /// /// - Returns: Returns the activation `HTTPResponse`. /// - Throws: Decoding errors. func check() throws -> HTTPResponse { /// Create a response with the challenge query parameter to verify the webhook. let body = HTTPBody(data: self.challenge.convertToData()) /// Send a 200 (OK) response. return HTTPResponse(status: .ok, headers: ["Content-Type": "text/plain"], body: body) } }
mit
7fe7eb87197b1765cff8d43787548931
36.432099
93
0.687335
4.439239
false
false
false
false
kirkvogen/masterdetail-j2objc-swift
masterdetail-ios/masterdetail-ios/MasterViewController.swift
1
5498
// // Copyright 2014-2015 Kirk C. Vogen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var listIds: [CInt] = [] let detailService: DetailService required init?(coder decoder: NSCoder) { detailService = FlatFileDetailService(storageService: LocalStorageService()) super.init(coder: decoder) } override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewWillAppear(animated: Bool) { if let view = self.tableView { view.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { let list = detailService.create() let listId = list.getId() listIds += [listId] _ = NSIndexPath(forRow: 0, inSection: 0) //self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) let storyboard = UIStoryboard(name: "Main", bundle: nil) let detailController = storyboard.instantiateViewControllerWithIdentifier("detailView") as! DetailViewController detailController.listId = listId self.navigationController?.pushViewController(detailController, animated: false) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { let indexPath = self.tableView.indexPathForSelectedRow let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController let listId = listIds[indexPath!.row] controller.listId = listId controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { listIds.removeAll(keepCapacity: true) let lists = detailService.findAll() let listSize = Int(lists.size()) for var i = 0; i < listSize; i++ { let list = lists.getWithInt(CInt(i)) as! DetailEntry listIds += [list.getId()] } return listIds.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let listId = listIds[indexPath.row] _ = detailService.findWithInt(listId) let viewModel = DetailViewModel(detailService: detailService, withNSString: " ") viewModel.init__WithInt(listId) cell.textLabel?.text = viewModel.getTitle() cell.detailTextLabel?.text = viewModel.getWords() return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let listId = listIds[indexPath.row] detailService.delete__WithInt(listId) listIds.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
apache-2.0
171d0128a0bcdd9dfe9a2177efbfa3a7
36.917241
157
0.671335
5.492507
false
false
false
false
practicalswift/swift
stdlib/public/core/SIMDVector.swift
2
30784
infix operator .== : ComparisonPrecedence infix operator .!= : ComparisonPrecedence infix operator .< : ComparisonPrecedence infix operator .<= : ComparisonPrecedence infix operator .> : ComparisonPrecedence infix operator .>= : ComparisonPrecedence // Not used in the stdlib, but declared here so the declarations are always // visible. infix operator .& : LogicalConjunctionPrecedence infix operator .^ : LogicalDisjunctionPrecedence infix operator .| : LogicalDisjunctionPrecedence infix operator .&= : AssignmentPrecedence infix operator .^= : AssignmentPrecedence infix operator .|= : AssignmentPrecedence prefix operator .! /// A type that provides storage for a SIMD vector type. /// /// The `SIMDStorage` protocol defines a storage layout and provides /// elementwise accesses. Computational operations are defined on the `SIMD` /// protocol, which refines this protocol, and on the concrete types that /// conform to `SIMD`. public protocol SIMDStorage { /// The type of scalars in the vector space. associatedtype Scalar : Codable, Hashable /// The number of scalars, or elements, in the vector. var scalarCount: Int { get } /// Creates a vector with zero in all lanes. init() /// Accesses the element at the specified index. /// /// - Parameter index: The index of the element to access. `index` must be in /// the range `0..<scalarCount`. subscript(index: Int) -> Scalar { get set } } /// A type that can be used as an element in a SIMD vector. public protocol SIMDScalar { associatedtype SIMDMaskScalar : SIMDScalar & FixedWidthInteger & SignedInteger associatedtype SIMD2Storage : SIMDStorage where SIMD2Storage.Scalar == Self associatedtype SIMD4Storage : SIMDStorage where SIMD4Storage.Scalar == Self associatedtype SIMD8Storage : SIMDStorage where SIMD8Storage.Scalar == Self associatedtype SIMD16Storage : SIMDStorage where SIMD16Storage.Scalar == Self associatedtype SIMD32Storage : SIMDStorage where SIMD32Storage.Scalar == Self associatedtype SIMD64Storage : SIMDStorage where SIMD64Storage.Scalar == Self } /// A SIMD vector of a fixed number of elements. public protocol SIMD : SIMDStorage, Codable, Hashable, CustomStringConvertible, ExpressibleByArrayLiteral { /// The mask type resulting from pointwise comparisons of this vector type. associatedtype MaskStorage : SIMD where MaskStorage.Scalar : FixedWidthInteger & SignedInteger } public extension SIMD { /// The valid indices for subscripting the vector. @_transparent var indices: Range<Int> { return 0 ..< scalarCount } /// A vector with the specified value in all lanes. @_transparent init(repeating value: Scalar) { self.init() for i in indices { self[i] = value } } /// Returns a Boolean value indicating whether two vectors are equal. @_transparent static func ==(lhs: Self, rhs: Self) -> Bool { var result = true for i in lhs.indices { result = result && lhs[i] == rhs[i] } return result } /// Hashes the elements of the vector using the given hasher. @inlinable func hash(into hasher: inout Hasher) { for i in indices { hasher.combine(self[i]) } } /// Encodes the scalars of this vector into the given encoder in an unkeyed /// container. /// /// This function throws an error if any values are invalid for the given /// encoder's format. /// /// - Parameter encoder: The encoder to write data to. func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for i in indices { try container.encode(self[i]) } } /// Creates a new vector by decoding scalars from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. init(from decoder: Decoder) throws { self.init() var container = try decoder.unkeyedContainer() guard container.count == scalarCount else { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Expected vector with exactly \(scalarCount) elements." ) ) } for i in indices { self[i] = try container.decode(Scalar.self) } } /// A textual description of the vector. var description: String { get { return "\(Self.self)(" + indices.map({"\(self[$0])"}).joined(separator: ", ") + ")" } } /// Returns a vector mask with the result of a pointwise equality comparison. @_transparent static func .==(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] == rhs[i] } return result } /// Returns a vector mask with the result of a pointwise inequality /// comparison. @_transparent static func .!=(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] != rhs[i] } return result } /// Replaces elements of this vector with elements of `other` in the lanes /// where `mask` is `true`. @_transparent mutating func replace(with other: Self, where mask: SIMDMask<MaskStorage>) { for i in indices { self[i] = mask[i] ? other[i] : self[i] } } /// Creates a vector from the specified elements. /// /// - Parameter scalars: The elements to use in the vector. `scalars` must /// have the same number of elements as the vector type. @inlinable init(arrayLiteral scalars: Scalar...) { self.init(scalars) } /// Creates a vector from the given sequence. /// /// - Parameter scalars: The elements to use in the vector. `scalars` must /// have the same number of elements as the vector type. @inlinable init<S: Sequence>(_ scalars: S) where S.Element == Scalar { self.init() var index = 0 for scalar in scalars { if index == scalarCount { _preconditionFailure("Too many elements in sequence.") } self[index] = scalar index += 1 } if index < scalarCount { _preconditionFailure("Not enough elements in sequence.") } } } // Implementations of comparison operations. These should eventually all // be replaced with @_semantics to lower directly to vector IR nodes. public extension SIMD where Scalar : Comparable { /// Returns a vector mask with the result of a pointwise less than /// comparison. @_transparent static func .<(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] < rhs[i] } return result } /// Returns a vector mask with the result of a pointwise less than or equal /// comparison. @_transparent static func .<=(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] <= rhs[i] } return result } } // These operations should never need @_semantics; they should be trivial // wrappers around the core operations defined above. public extension SIMD { /// Returns a vector mask with the result of a pointwise equality comparison. @_transparent static func .==(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .== rhs } /// Returns a vector mask with the result of a pointwise inequality comparison. @_transparent static func .!=(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .!= rhs } /// Returns a vector mask with the result of a pointwise equality comparison. @_transparent static func .==(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .== Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise inequality comparison. @_transparent static func .!=(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .!= Self(repeating: rhs) } /// Replaces elements of this vector with `other` in the lanes where `mask` /// is `true`. @_transparent mutating func replace(with other: Scalar, where mask: SIMDMask<MaskStorage>) { replace(with: Self(repeating: other), where: mask) } /// Returns a copy of this vector, with elements replaced by elements of /// `other` in the lanes where `mask` is `true`. @_transparent func replacing(with other: Self, where mask: SIMDMask<MaskStorage>) -> Self { var result = self result.replace(with: other, where: mask) return result } /// Returns a copy of this vector, with elements `other` in the lanes where /// `mask` is `true`. @_transparent func replacing(with other: Scalar, where mask: SIMDMask<MaskStorage>) -> Self { return replacing(with: Self(repeating: other), where: mask) } } public extension SIMD where Scalar : Comparable { /// Returns a vector mask with the result of a pointwise greater than or /// equal comparison. @_transparent static func .>=(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { return rhs .<= lhs } /// Returns a vector mask with the result of a pointwise greater than /// comparison. @_transparent static func .>(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { return rhs .< lhs } /// Returns a vector mask with the result of a pointwise less than comparison. @_transparent static func .<(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .< rhs } /// Returns a vector mask with the result of a pointwise less than or equal /// comparison. @_transparent static func .<=(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .<= rhs } /// Returns a vector mask with the result of a pointwise greater than or /// equal comparison. @_transparent static func .>=(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .>= rhs } /// Returns a vector mask with the result of a pointwise greater than /// comparison. @_transparent static func .>(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .> rhs } /// Returns a vector mask with the result of a pointwise less than comparison. @_transparent static func .<(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .< Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise less than or equal /// comparison. @_transparent static func .<=(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .<= Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise greater than or /// equal comparison. @_transparent static func .>=(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .>= Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise greater than /// comparison. @_transparent static func .>(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .> Self(repeating: rhs) } } public extension SIMD where Scalar : FixedWidthInteger { /// A vector with zero in all lanes. @_transparent static var zero: Self { return Self() } /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable static func random<T: RandomNumberGenerator>( in range: Range<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable static func random(in range: Range<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable static func random<T: RandomNumberGenerator>( in range: ClosedRange<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable static func random(in range: ClosedRange<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } } public extension SIMD where Scalar : FloatingPoint { /// A vector with zero in all lanes. @_transparent static var zero: Self { return Self() } } public extension SIMD where Scalar : BinaryFloatingPoint, Scalar.RawSignificand : FixedWidthInteger { /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable static func random<T: RandomNumberGenerator>( in range: Range<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable static func random(in range: Range<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable static func random<T: RandomNumberGenerator>( in range: ClosedRange<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable static func random(in range: ClosedRange<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } } @_fixed_layout public struct SIMDMask<Storage> : SIMD where Storage : SIMD, Storage.Scalar : FixedWidthInteger & SignedInteger { public var _storage : Storage public typealias MaskStorage = Storage public typealias Scalar = Bool @_transparent public var scalarCount: Int { return _storage.scalarCount } @_transparent public init() { _storage = Storage() } @_transparent public init(_ _storage: Storage) { self._storage = _storage } public subscript(index: Int) -> Bool { @_transparent get { _precondition(indices.contains(index)) return _storage[index] < 0 } @_transparent set { _precondition(indices.contains(index)) _storage[index] = newValue ? -1 : 0 } } } public extension SIMDMask { /// Returns a vector mask with `true` or `false` randomly assigned in each /// lane, using the given generator as a source for randomness. @inlinable static func random<T: RandomNumberGenerator>(using generator: inout T) -> SIMDMask { var result = SIMDMask() for i in result.indices { result[i] = Bool.random(using: &generator) } return result } /// Returns a vector mask with `true` or `false` randomly assigned in each /// lane. @inlinable static func random() -> SIMDMask { var g = SystemRandomNumberGenerator() return SIMDMask.random(using: &g) } } // Implementations of integer operations. These should eventually all // be replaced with @_semantics to lower directly to vector IR nodes. public extension SIMD where Scalar : FixedWidthInteger { @_transparent var leadingZeroBitCount: Self { var result = Self() for i in indices { result[i] = Scalar(self[i].leadingZeroBitCount) } return result } @_transparent var trailingZeroBitCount: Self { var result = Self() for i in indices { result[i] = Scalar(self[i].trailingZeroBitCount) } return result } @_transparent var nonzeroBitCount: Self { var result = Self() for i in indices { result[i] = Scalar(self[i].nonzeroBitCount) } return result } @_transparent static prefix func ~(rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = ~rhs[i] } return result } @_transparent static func &(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] & rhs[i] } return result } @_transparent static func ^(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] ^ rhs[i] } return result } @_transparent static func |(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] | rhs[i] } return result } @_transparent static func &<<(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &<< rhs[i] } return result } @_transparent static func &>>(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &>> rhs[i] } return result } @_transparent static func &+(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &+ rhs[i] } return result } @_transparent static func &-(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &- rhs[i] } return result } @_transparent static func &*(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &* rhs[i] } return result } @_transparent static func /(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] / rhs[i] } return result } @_transparent static func %(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] % rhs[i] } return result } } // Implementations of floating-point operations. These should eventually all // be replaced with @_semantics to lower directly to vector IR nodes. public extension SIMD where Scalar : FloatingPoint { @_transparent static func +(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] + rhs[i] } return result } @_transparent static func -(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] - rhs[i] } return result } @_transparent static func *(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] * rhs[i] } return result } @_transparent static func /(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] / rhs[i] } return result } @_transparent func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = self[i].addingProduct(lhs[i], rhs[i]) } return result } @_transparent func squareRoot( ) -> Self { var result = Self() for i in result.indices { result[i] = self[i].squareRoot() } return result } @_transparent func rounded(_ rule: FloatingPointRoundingRule) -> Self { var result = Self() for i in result.indices { result[i] = self[i].rounded(rule) } return result } } public extension SIMDMask { @_transparent static prefix func .!(rhs: SIMDMask) -> SIMDMask { return SIMDMask(~rhs._storage) } @_transparent static func .&(lhs: SIMDMask, rhs: SIMDMask) -> SIMDMask { return SIMDMask(lhs._storage & rhs._storage) } @_transparent static func .^(lhs: SIMDMask, rhs: SIMDMask) -> SIMDMask { return SIMDMask(lhs._storage ^ rhs._storage) } @_transparent static func .|(lhs: SIMDMask, rhs: SIMDMask) -> SIMDMask { return SIMDMask(lhs._storage | rhs._storage) } } // These operations should never need @_semantics; they should be trivial // wrappers around the core operations defined above. public extension SIMD where Scalar : FixedWidthInteger { @_transparent static func &(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) & rhs } @_transparent static func ^(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) ^ rhs } @_transparent static func |(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) | rhs } @_transparent static func &<<(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &<< rhs } @_transparent static func &>>(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &>> rhs } @_transparent static func &+(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &+ rhs } @_transparent static func &-(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &- rhs } @_transparent static func &*(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &* rhs } @_transparent static func /(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) / rhs } @_transparent static func %(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) % rhs } @_transparent static func &(lhs: Self, rhs: Scalar) -> Self { return lhs & Self(repeating: rhs) } @_transparent static func ^(lhs: Self, rhs: Scalar) -> Self { return lhs ^ Self(repeating: rhs) } @_transparent static func |(lhs: Self, rhs: Scalar) -> Self { return lhs | Self(repeating: rhs) } @_transparent static func &<<(lhs: Self, rhs: Scalar) -> Self { return lhs &<< Self(repeating: rhs) } @_transparent static func &>>(lhs: Self, rhs: Scalar) -> Self { return lhs &>> Self(repeating: rhs) } @_transparent static func &+(lhs: Self, rhs: Scalar) -> Self { return lhs &+ Self(repeating: rhs) } @_transparent static func &-(lhs: Self, rhs: Scalar) -> Self { return lhs &- Self(repeating: rhs) } @_transparent static func &*(lhs: Self, rhs: Scalar) -> Self { return lhs &* Self(repeating: rhs) } @_transparent static func /(lhs: Self, rhs: Scalar) -> Self { return lhs / Self(repeating: rhs) } @_transparent static func %(lhs: Self, rhs: Scalar) -> Self { return lhs % Self(repeating: rhs) } @_transparent static func &=(lhs: inout Self, rhs: Self) { lhs = lhs & rhs } @_transparent static func ^=(lhs: inout Self, rhs: Self) { lhs = lhs ^ rhs } @_transparent static func |=(lhs: inout Self, rhs: Self) { lhs = lhs | rhs } @_transparent static func &<<=(lhs: inout Self, rhs: Self) { lhs = lhs &<< rhs } @_transparent static func &>>=(lhs: inout Self, rhs: Self) { lhs = lhs &>> rhs } @_transparent static func &+=(lhs: inout Self, rhs: Self) { lhs = lhs &+ rhs } @_transparent static func &-=(lhs: inout Self, rhs: Self) { lhs = lhs &- rhs } @_transparent static func &*=(lhs: inout Self, rhs: Self) { lhs = lhs &* rhs } @_transparent static func /=(lhs: inout Self, rhs: Self) { lhs = lhs / rhs } @_transparent static func %=(lhs: inout Self, rhs: Self) { lhs = lhs % rhs } @_transparent static func &=(lhs: inout Self, rhs: Scalar) { lhs = lhs & rhs } @_transparent static func ^=(lhs: inout Self, rhs: Scalar) { lhs = lhs ^ rhs } @_transparent static func |=(lhs: inout Self, rhs: Scalar) { lhs = lhs | rhs } @_transparent static func &<<=(lhs: inout Self, rhs: Scalar) { lhs = lhs &<< rhs } @_transparent static func &>>=(lhs: inout Self, rhs: Scalar) { lhs = lhs &>> rhs } @_transparent static func &+=(lhs: inout Self, rhs: Scalar) { lhs = lhs &+ rhs } @_transparent static func &-=(lhs: inout Self, rhs: Scalar) { lhs = lhs &- rhs } @_transparent static func &*=(lhs: inout Self, rhs: Scalar) { lhs = lhs &* rhs } @_transparent static func /=(lhs: inout Self, rhs: Scalar) { lhs = lhs / rhs } @_transparent static func %=(lhs: inout Self, rhs: Scalar) { lhs = lhs % rhs } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead") static func +(lhs: Self, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead") static func -(lhs: Self, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead") static func *(lhs: Self, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead") static func +(lhs: Self, rhs: Scalar) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead") static func -(lhs: Self, rhs: Scalar) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead") static func *(lhs: Self, rhs: Scalar) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead") static func +(lhs: Scalar, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead") static func -(lhs: Scalar, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead") static func *(lhs: Scalar, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead") static func +=(lhs: inout Self, rhs: Self) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead") static func -=(lhs: inout Self, rhs: Self) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead") static func *=(lhs: inout Self, rhs: Self) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead") static func +=(lhs: inout Self, rhs: Scalar) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead") static func -=(lhs: inout Self, rhs: Scalar) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead") static func *=(lhs: inout Self, rhs: Scalar) { fatalError() } } public extension SIMD where Scalar : FloatingPoint { @_transparent static prefix func -(rhs: Self) -> Self { return 0 - rhs } @_transparent static func +(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) + rhs } @_transparent static func -(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) - rhs } @_transparent static func *(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) * rhs } @_transparent static func /(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) / rhs } @_transparent static func +(lhs: Self, rhs: Scalar) -> Self { return lhs + Self(repeating: rhs) } @_transparent static func -(lhs: Self, rhs: Scalar) -> Self { return lhs - Self(repeating: rhs) } @_transparent static func *(lhs: Self, rhs: Scalar) -> Self { return lhs * Self(repeating: rhs) } @_transparent static func /(lhs: Self, rhs: Scalar) -> Self { return lhs / Self(repeating: rhs) } @_transparent static func +=(lhs: inout Self, rhs: Self) { lhs = lhs + rhs } @_transparent static func -=(lhs: inout Self, rhs: Self) { lhs = lhs - rhs } @_transparent static func *=(lhs: inout Self, rhs: Self) { lhs = lhs * rhs } @_transparent static func /=(lhs: inout Self, rhs: Self) { lhs = lhs / rhs } @_transparent static func +=(lhs: inout Self, rhs: Scalar) { lhs = lhs + rhs } @_transparent static func -=(lhs: inout Self, rhs: Scalar) { lhs = lhs - rhs } @_transparent static func *=(lhs: inout Self, rhs: Scalar) { lhs = lhs * rhs } @_transparent static func /=(lhs: inout Self, rhs: Scalar) { lhs = lhs / rhs } @_transparent func addingProduct(_ lhs: Scalar, _ rhs: Self) -> Self { return self.addingProduct(Self(repeating: lhs), rhs) } @_transparent func addingProduct(_ lhs: Self, _ rhs: Scalar) -> Self { return self.addingProduct(lhs, Self(repeating: rhs)) } @_transparent mutating func addProduct(_ lhs: Self, _ rhs: Self) { self = self.addingProduct(lhs, rhs) } @_transparent mutating func addProduct(_ lhs: Scalar, _ rhs: Self) { self = self.addingProduct(lhs, rhs) } @_transparent mutating func addProduct(_ lhs: Self, _ rhs: Scalar) { self = self.addingProduct(lhs, rhs) } @_transparent mutating func formSquareRoot( ) { self = self.squareRoot() } @_transparent mutating func round(_ rule: FloatingPointRoundingRule) { self = self.rounded(rule) } } public extension SIMDMask { @_transparent static func .&(lhs: Bool, rhs: SIMDMask) -> SIMDMask { return SIMDMask(repeating: lhs) .& rhs } @_transparent static func .^(lhs: Bool, rhs: SIMDMask) -> SIMDMask { return SIMDMask(repeating: lhs) .^ rhs } @_transparent static func .|(lhs: Bool, rhs: SIMDMask) -> SIMDMask { return SIMDMask(repeating: lhs) .| rhs } @_transparent static func .&(lhs: SIMDMask, rhs: Bool) -> SIMDMask { return lhs .& SIMDMask(repeating: rhs) } @_transparent static func .^(lhs: SIMDMask, rhs: Bool) -> SIMDMask { return lhs .^ SIMDMask(repeating: rhs) } @_transparent static func .|(lhs: SIMDMask, rhs: Bool) -> SIMDMask { return lhs .| SIMDMask(repeating: rhs) } @_transparent static func .&=(lhs: inout SIMDMask, rhs: SIMDMask) { lhs = lhs .& rhs } @_transparent static func .^=(lhs: inout SIMDMask, rhs: SIMDMask) { lhs = lhs .^ rhs } @_transparent static func .|=(lhs: inout SIMDMask, rhs: SIMDMask) { lhs = lhs .| rhs } @_transparent static func .&=(lhs: inout SIMDMask, rhs: Bool) { lhs = lhs .& rhs } @_transparent static func .^=(lhs: inout SIMDMask, rhs: Bool) { lhs = lhs .^ rhs } @_transparent static func .|=(lhs: inout SIMDMask, rhs: Bool) { lhs = lhs .| rhs } }
apache-2.0
56e2627fca229880c4417d0774c65616
38.927367
136
0.663462
4.126542
false
false
false
false
practicalswift/swift
test/SILGen/without_actually_escaping_block.swift
25
1092
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name without_actually_escaping %s -sdk %S/Inputs -enable-objc-interop | %FileCheck %s // REQUIRES: objc_interop import Foundation typealias Callback = @convention(block) () -> Void // CHECK-LABEL: sil {{.*}} @$s25without_actually_escaping9testBlock5blockyyyXB_tF // CHECK: bb0([[ARG:%.*]] : @guaranteed $@convention(block) @noescape () -> ()): // CHECK: [[C1:%.*]] = copy_block [[ARG]] // CHECK: [[B1:%.*]] = begin_borrow [[C1]] // CHECK: [[C2:%.*]] = copy_value [[B1]] // CHECK: [[CVT:%.*]] = convert_function [[C2]] : $@convention(block) @noescape () -> () to [without_actually_escaping] $@convention(block) () -> () // CHECK: [[FN:%.*]] = function_ref @$s25without_actually_escaping9testBlock5blockyyyXB_tFyyyXBXEfU_ // CHECK: apply [[FN]]([[CVT]]) // CHECK: destroy_value [[CVT]] // CHECK: end_borrow [[B1]] // CHECK: destroy_value [[C1]] // CHECK: return func testBlock(block: Callback) { withoutActuallyEscaping(block) { $0() } }
apache-2.0
3c69b76a0b4cf9e18bef33a57eef65bb
41
159
0.6337
3.12
false
true
false
false
toshiapp/toshi-ios-client
Toshi/Resources/DevelopmentTokenURLPaths.swift
1
1301
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. let ToshiRatingsServiceBaseURLPath = "https://reputation.internal.service.toshi.org" let ToshiIdServiceBaseURLPath = "https://identity.internal.service.toshi.org" let ToshiDirectoryServiceURLPath = "https://directory.internal.service.toshi.org" let ToshiEthereumServiceBaseURLPath = "https://ethereum.internal.service.toshi.org" let ToshiExchangeRateServiceBaseURLPath = "https://exchange.internal.service.toshi.org" let ToshiChatServiceBaseURLPath = "https://chat.internal.service.toshi.org" let ToshiWebviewRPCURLPath = "https://node.service.tokenbrowser.com/coffee" let ToshiWebviewRCPURLNetVersion = "116"
gpl-3.0
a0d19c8891d5af4de9dbcfc7e1fb0993
55.565217
87
0.784012
4.104101
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureInterest/Sources/FeatureInterestDomain/TransactionEngines/InterestDepositTradingTransactionEngine.swift
1
9028
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import FeatureProductsDomain import FeatureTransactionDomain import MoneyKit import PlatformKit import RxSwift import ToolKit /// Transaction Engine for Interest Deposit from a Trading Account. public final class InterestDepositTradingTransactionEngine: InterestTransactionEngine { // MARK: - InterestTransactionEngine public var minimumDepositLimits: Single<FiatValue> { walletCurrencyService .displayCurrency .flatMap { [sourceCryptoCurrency, accountLimitsRepository] fiatCurrency in accountLimitsRepository .fetchInterestAccountLimitsForCryptoCurrency( sourceCryptoCurrency, fiatCurrency: fiatCurrency ) } .map(\.minDepositAmount) .asSingle() } // MARK: - TransactionEngine public var askForRefreshConfirmation: AskForRefreshConfirmation! public var sourceAccount: BlockchainAccount! public var transactionTarget: TransactionTarget! // MARK: - InterestTransactionEngine public let walletCurrencyService: FiatCurrencyServiceAPI public let currencyConversionService: CurrencyConversionServiceAPI // Used to check product eligibility private let productsService: FeatureProductsDomain.ProductsServiceAPI // MARK: - Private Properties private var minimumDepositCryptoLimits: Single<CryptoValue> { minimumDepositLimits .flatMap { [currencyConversionService, sourceAsset] fiatCurrency -> Single<(FiatValue, FiatValue)> in let quote = currencyConversionService .conversionRate(from: sourceAsset, to: fiatCurrency.currencyType) .asSingle() .map { $0.fiatValue ?? .zero(currency: fiatCurrency.currency) } return Single.zip(quote, .just(fiatCurrency)) } .map { [sourceAsset] (quote: FiatValue, deposit: FiatValue) -> CryptoValue in deposit.convert(usingInverse: quote, currency: sourceAsset.cryptoCurrency!) } } private var availableBalance: Single<MoneyValue> { sourceAccount .balance .asSingle() } private var interestAccountLimits: Single<InterestAccountLimits> { walletCurrencyService .displayCurrency .flatMap { [accountLimitsRepository, sourceAsset] fiatCurrency in accountLimitsRepository .fetchInterestAccountLimitsForCryptoCurrency( sourceAsset.cryptoCurrency!, fiatCurrency: fiatCurrency ) } .asSingle() } private let accountTransferRepository: InterestAccountTransferRepositoryAPI private let accountLimitsRepository: InterestAccountLimitsRepositoryAPI // MARK: - Init init( walletCurrencyService: FiatCurrencyServiceAPI = resolve(), currencyConversionService: CurrencyConversionServiceAPI = resolve(), accountLimitsRepository: InterestAccountLimitsRepositoryAPI = resolve(), accountTransferRepository: InterestAccountTransferRepositoryAPI = resolve(), productsService: FeatureProductsDomain.ProductsServiceAPI = resolve() ) { self.walletCurrencyService = walletCurrencyService self.currencyConversionService = currencyConversionService self.accountTransferRepository = accountTransferRepository self.accountLimitsRepository = accountLimitsRepository self.productsService = productsService } public func assertInputsValid() { precondition(sourceAccount is TradingAccount) precondition(transactionTarget is InterestAccount) precondition(transactionTarget is CryptoAccount) precondition(sourceAsset == (transactionTarget as! CryptoAccount).asset) } public func initializeTransaction() -> Single<PendingTransaction> { Single .zip( minimumDepositCryptoLimits, availableBalance, walletCurrencyService .displayCurrency .asSingle() ) .map { limits, balance, fiatCurrency -> PendingTransaction in let asset = limits.currency return PendingTransaction( amount: .zero(currency: asset), available: balance, feeAmount: .zero(currency: asset), feeForFullAvailable: .zero(currency: asset), feeSelection: .init(selectedLevel: .none, availableLevels: [.none]), selectedFiatCurrency: fiatCurrency, limits: .init( currencyType: limits.currencyType, minimum: limits.moneyValue, maximum: nil, maximumDaily: nil, maximumAnnual: nil, effectiveLimit: nil, suggestedUpgrade: nil ) ) } } public func update( amount: MoneyValue, pendingTransaction: PendingTransaction ) -> Single<PendingTransaction> { availableBalance .map { balance in pendingTransaction .update( amount: amount, available: balance ) } } public func validateAmount( pendingTransaction: PendingTransaction ) -> Single<PendingTransaction> { availableBalance .flatMapCompletable(weak: self) { (self, balance) in self.checkIfAvailableBalanceIsSufficient( pendingTransaction, balance: balance ) .andThen( self.checkIfAmountIsBelowMinimumLimit( pendingTransaction ) ) } .updateTxValidityCompletable( pendingTransaction: pendingTransaction ) } public func doValidateAll( pendingTransaction: PendingTransaction ) -> Single<PendingTransaction> { guard pendingTransaction.agreementOptionValue, pendingTransaction.termsOptionValue else { return .just(pendingTransaction.update(validationState: .optionInvalid)) } return validateAmount(pendingTransaction: pendingTransaction) } public func doBuildConfirmations( pendingTransaction: PendingTransaction ) -> Single<PendingTransaction> { let source = sourceAccount.label let destination = transactionTarget.label let termsChecked = getTermsOptionValueFromPendingTransaction(pendingTransaction) let agreementChecked = getTransferAgreementOptionValueFromPendingTransaction(pendingTransaction) return fiatAmountAndFees(from: pendingTransaction) .map { fiatAmount, fiatFees -> PendingTransaction in pendingTransaction .update( confirmations: [ TransactionConfirmations.Source(value: source), TransactionConfirmations.Destination(value: destination), TransactionConfirmations.FeedTotal( amount: pendingTransaction.amount, amountInFiat: fiatAmount.moneyValue, fee: pendingTransaction.feeAmount, feeInFiat: fiatFees.moneyValue ) ] ) } .map { [weak self] pendingTransaction in guard let self = self else { unexpectedDeallocation() } return self.modifyEngineConfirmations( pendingTransaction, termsChecked: termsChecked, agreementChecked: agreementChecked ) } } public func execute( pendingTransaction: PendingTransaction ) -> Single<TransactionResult> { accountTransferRepository .createInterestAccountCustodialTransfer(pendingTransaction.amount) .mapError { _ in TransactionValidationFailure(state: .unknownError) } .map { _ in TransactionResult.unHashed(amount: pendingTransaction.amount, orderId: nil) } .asSingle() } public func doUpdateFeeLevel( pendingTransaction: PendingTransaction, level: FeeLevel, customFeeAmount: MoneyValue ) -> Single<PendingTransaction> { .just(pendingTransaction) } }
lgpl-3.0
f6ad7885ef8d91ec211ffa65be0ce897
37.088608
113
0.600089
6.736567
false
false
false
false
NeoGolightly/CartographyKit
CartographyKit/Sizes.swift
1
1142
// // Sizes.swift // CartographyKit iOS // // Created by Michael Helmbrecht on 07/01/2018. // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif import Cartography //Sizes private protocol BasicSizes{ static func width(_ view: View) -> NSLayoutConstraint? static func height(_ view: View) -> NSLayoutConstraint? static func size(_ view: View) -> [NSLayoutConstraint?] } extension CartographyKit: BasicSizes{ @discardableResult public static func width(_ view: View) -> NSLayoutConstraint? { var c: NSLayoutConstraint? constrain(view){ view in c = view.width == view.superview!.width return } return c } @discardableResult public static func height(_ view: View) -> NSLayoutConstraint? { var c: NSLayoutConstraint? constrain(view){ view in c = view.height == view.superview!.height return } return c } @discardableResult public static func size(_ view: View) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.size == view.superview!.size return } return c } }
mit
7911714e8d9d958e25bfc4a9871c97aa
20.54717
66
0.655867
4.078571
false
false
false
false
gaurav1981/Swiftz
Swiftz/List.swift
1
12486
// // List.swift // swiftz_core // // Created by Maxwell Swadling on 3/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // /// An enum representing the possible values a list can match against. public enum ListMatcher<A> { /// The empty list. case Nil /// A cons cell. case Cons(A, List<A>) } /// A lazy ordered sequence of homogenous values. /// /// A List is typically constructed by two primitives: Nil and Cons. Due to limitations of the /// language, we instead provide a nullary constructor for Nil and a Cons Constructor and an actual /// static function named `cons(: tail:)` for Cons. Nonetheless this representation of a list is /// isomorphic to the traditional inductive definition. As such, the method `match()` is provided /// that allows the list to be destructured into a more traditional `Nil | Cons(A, List<A>)` form /// that is also compatible with switch-case blocks. /// /// This kind of list is optimized for access to its length, which always occurs in O(1), and /// modifications to its head, which always occur in O(1). Access to the elements occurs in O(n). /// /// Unlike an Array, a List can potentially represent an infinite sequence of values. Because the /// List holds these values in a lazy manner, certain primitives like iteration or reversing the /// list will force evaluation of the entire list. For infinite lists this can lead to a program /// diverging. public struct List<A> { let len : Int let next : () -> (head : A, tail : List<A>) /// Constructs a potentially infinite list. init(@autoclosure(escaping) _ next : () -> (head : A, tail : List<A>), isEmpty : Bool = false) { self.len = isEmpty ? 0 : -1 self.next = next } /// Constructs the empty list. /// /// Attempts to access the head or tail of this list in an unsafe manner will throw an exception. public init() { self.init((error("Attempted to access the head of the empty list."), error("Attempted to access the tail of the empty list.")), isEmpty: true) } /// Construct a list with a given head and tail. public init(_ head : A, _ tail : List<A> = List<A>()) { if tail.len == -1 { self.len = -1 } else { self.len = tail.len.successor() } self.next = { (head, tail) } } /// Appends an element onto the front of a list. public static func cons(head : A, tail : List<A>) -> List<A> { return List(head, tail) } /// Destructures a list. If the list is empty, the result is Nil. If the list contains a value /// the result is Cons(head, tail). public func match() -> ListMatcher<A> { if self.len == 0 { return .Nil } let (hd, tl) = self.next() return .Cons(hd, tl) } /// Indexes into an array. /// /// Indexing into the empty list will throw an exception. public subscript(n : UInt) -> A { switch self.match() { case .Nil: return error("Cannot extract an element from an empty list.") case let .Cons(x, xs) where n == 0: return x case let .Cons(x, xs): return xs[n - 1] } } /// Creates a list of n repeating values. public static func replicate(n : UInt, value : A) -> List<A> { var l = List<A>() for _ in 0..<n { l = List.cons(value, tail: l) } return l } /// Returns the first element in the list, or None if the list is empty. public func head() -> Optional<A> { switch self.match() { case .Nil: return .None case let .Cons(head, _): return .Some(head) } } /// Returns the tail of the list, or None if the list is empty. public func tail() -> Optional<List<A>> { switch self.match() { case .Nil: return .None case let .Cons(_, tail): return .Some(tail) } } /// Returns whether or not the receiver is the empty list. public func isEmpty() -> Bool { return self.len == 0 } /// Returns whether or not the receiver has a countable number of elements. /// /// It may be dangerous to attempt to iterate over an infinite list of values because the loop /// will never terminate. public func isFinite() -> Bool { return self.len != -1 } /// Returns the length of the list. /// /// For infinite lists this function will throw an exception. public func length() -> UInt { if self.len == -1 { return error("Cannot take the length of an infinite list.") } return UInt(self.len) } /// Yields a new list by applying a function to each element of the receiver. public func map<B>(f : A -> B) -> List<B> { switch self.match() { case .Nil: return [] case let .Cons(hd, tl): return List<B>(f(hd), tl.map(f)) } } /// Appends two lists together. /// /// If the receiver is infinite, the result of this function will be the receiver itself. public func append(rhs : List<A>) -> List<A> { switch self.match() { case .Nil: return rhs case let .Cons(x, xs): return List.cons(x, tail: xs.append(rhs)) } } /// Maps a function over a list and concatenates the results. public func concatMap<B>(f : A -> List<B>) -> List<B> { return self.reduce({ l, r in l.append(f(r)) }, initial: List<B>()) } /// Returns a list of elements satisfying a predicate. public func filter(p : A -> Bool) -> List<A> { switch self.match() { case .Nil: return [] case let .Cons(x, xs): return p(x) ? List(x, xs.filter(p)) : xs.filter(p) } } /// Applies a binary operator to reduce the elements of the receiver to a single value. public func reduce<B>(f : B -> A -> B, initial : B) -> B { switch self.match() { case .Nil: return initial case let .Cons(x, xs): return xs.reduce(f, initial: f(initial)(x)) } } /// Applies a binary operator to reduce the elements of the receiver to a single value. public func reduce<B>(f : (B, A) -> B, initial : B) -> B { switch self.match() { case .Nil: return initial case let .Cons(x, xs): return xs.reduce(f, initial: f(initial, x)) } } /// Returns a list of successive applications of a function to the elements of the receiver. /// /// e.g. /// /// [x0, x1, x2, ...].scanl(f, initial: z) == [z, f(z)(x0), f(f(z)(x0))(x1), f(f(f(z)(x2))(x1))(x0)] /// [1, 2, 3, 4, 5].scanl(+, initial: 0) == [0, 1, 3, 6, 10, 15] /// public func scanl<B>(f : B -> A -> B, initial : B) -> List<B> { switch self.match() { case .Nil: return List<B>(initial) case let .Cons(x, xs): return List<B>.cons(initial, tail: xs.scanl(f, initial: f(initial)(x))) } } /// Returns a list of successive applications of a function to the elements of the receiver. /// /// e.g. /// /// [x0, x1, x2, ...].scanl(f, initial: z) == [z, f(z, x0), f(f(z, x0), x1), f(f(f(z, x2), x1), x0)] /// [1, 2, 3, 4, 5].scanl(+, initial: 0) == [0, 1, 3, 6, 10, 15] /// public func scanl<B>(f : (B, A) -> B, initial : B) -> List<B> { switch self.match() { case .Nil: return List<B>(initial) case let .Cons(x, xs): return List<B>.cons(initial, tail: xs.scanl(f, initial: f(initial, x))) } } /// Like scanl but draws its initial value from the first element of the receiver itself. public func scanl1(f : A -> A -> A) -> List<A> { switch self.match() { case .Nil: return [] case let .Cons(x, xs): return xs.scanl(f, initial: x) } } /// Like scanl but draws its initial value from the first element of the receiver itself. public func scanl1(f : (A, A) -> A) -> List<A> { switch self.match() { case .Nil: return [] case let .Cons(x, xs): return xs.scanl(f, initial: x) } } /// Returns the first n elements of the receiver. public func take(n : UInt) -> List<A> { if n == 0 { return [] } switch self.match() { case .Nil: return [] case let .Cons(x, xs): return List.cons(x, tail: xs.take(n - 1)) } } /// Returns the remaining list after dropping n elements from the receiver. public func drop(n : UInt) -> List<A> { if n == 0 { return self } switch self.match() { case .Nil: return [] case let .Cons(x, xs): return xs.drop(n - 1) } } /// Returns a tuple of the first n elements and the remainder of the list. public func splitAt(n : UInt) -> (List<A>, List<A>) { return (self.take(n), self.drop(n)) } /// Returns a list of the longest prefix of elements satisfying a predicate. public func takeWhile(p : A -> Bool) -> List<A> { switch self.match() { case .Nil: return [] case .Cons(let x, let xs): if p(x) { return List.cons(x, tail: xs.takeWhile(p)) } return [] } } /// Returns a list of the remaining elements after the longest prefix of elements satisfying a /// predicate has been removed. public func dropWhile(p : A -> Bool) -> List<A> { switch self.match() { case .Nil: return [] case let .Cons(x, xs): if p(x) { return xs.dropWhile(p) } return self } } /// Returns the elements of the receiver in reverse order. /// /// For infinite lists this function will diverge. public func reverse() -> List<A> { return self.reduce(flip(List.cons), initial: []) } /// Given a predicate, searches the list until it find the first match, and returns that, /// or None if no match was found. /// /// For infinite lists this function will diverge. public func find(pred: A -> Bool) -> Optional<A> { for x in self { if pred(x) { return x } } return nil } /// For an associated list, such as [(1,"one"),(2,"two")], takes a function (pass the identity /// function) and a key and returns the value for the given key, if there is one, or None /// otherwise. public func lookup<K : Equatable, V>(ev : A -> (K, V), key : K) -> Optional<V> { return { ev($0).1 } <^> self.find({ ev($0).0 == key }) } /// Returns a List of an infinite number of iteratations of applications of a function to an /// initial value. public static func iterate(f : A -> A, initial : A) -> List<A> { return List((initial, self.iterate(f, initial: f(initial)))) } /// Cycles a finite list into an infinite list. public func cycle() -> List<A> { let (hd, tl) = self.next() return List((hd, (tl + [hd]).cycle())) } } /// Flattens a list of lists into a single lists. public func concat<A>(xss : List<List<A>>) -> List<A> { return xss.reduce(+, initial: []) } /// Appends two lists together. public func +<A>(lhs : List<A>, rhs : List<A>) -> List<A> { return lhs.append(rhs) } /// MARK: Equatable public func ==<A : Equatable>(lhs : List<A>, rhs : List<A>) -> Bool { switch (lhs.match(), rhs.match()) { case (.Nil, .Nil): return true case let (.Cons(lHead, lTail), .Cons(rHead, rTail)): return lHead == rHead && lTail == rTail default: return false } } /// MARK: Collection Protocols extension List : ArrayLiteralConvertible { typealias Element = A public init(fromArray arr : [Element]) { var xs : [A] = [] var g = arr.generate() while let x : A = g.next() { xs.append(x) } var l = List() for x in xs.reverse() { l = List(x, l) } self = l } public init(arrayLiteral s : Element...) { self.init(fromArray: s) } } public final class ListGenerator<A> : GeneratorType { var l : List<A> public func next() -> Optional<A> { if l.len == 0 { return nil } let (hd, tl) = l.next() l = tl return hd } public init(_ l : List<A>) { self.l = l } } extension List : SequenceType { public func generate() -> ListGenerator<A> { return ListGenerator(self) } } extension List : CollectionType { public typealias Index = UInt public var startIndex: UInt { get { return 0 } } public var endIndex: UInt { get { return self.isFinite() ? self.length() : error("An infinite list has no end index.") } } } extension List : Printable { public var description : String { var x = ", ".join(self.fmap({ "\($0)" })) return "[\(x)]" } } /// MARK: Control.* extension List : Functor { typealias B = Any typealias FB = List<B> public func fmap<B>(f : (A -> B)) -> List<B> { return self.map(f) } } public func <^> <A, B>(f : A -> B, l : List<A>) -> List<B> { return l.fmap(f) } extension List : Pointed { public static func pure(a: A) -> List<A> { return List(a, []) } } extension List : Applicative { typealias FA = List<A> typealias FAB = List<A -> B> public func ap<B>(f : List<A -> B>) -> List<B> { return concat(f.map({ self.map($0) })) } } public func <*> <A, B>(f : List<(A -> B)>, l : List<A>) -> List<B> { return l.ap(f) } extension List : Monad { public func bind<B>(f: A -> List<B>) -> List<B> { return self.concatMap(f) } } public func >>- <A, B>(l : List<A>, f : A -> List<B>) -> List<B> { return l.bind(f) }
bsd-3-clause
9faef0f74bcbf04be481acdef382ddab
24.904564
144
0.618453
2.962981
false
false
false
false
lincoly/LLDropDownMenuSwift
core/LLDropDownMenu.swift
1
31956
// // LLDropDownMenu.swift // LLDropDownMenuViewSwift // // Created by lin on 2017/3/7. // Copyright © 2017年 lin. All rights reserved. // import UIKit struct LLIndexPath { var corlumn : Int! var row : Int? var item : Int? var index : Int? var selectedText = "" } protocol LLDropDownMenuDelegate { // 选中 func menu(_ menu:LLDropDownMenu, didSelectIndexPath:LLIndexPath) } class LLDropDownMenu: UIView { var indicatorColor = LL_HexRGB(0xC8C8C8) // 三角指示器颜色 var textColor = LL_HexRGB(0x071D41) // 正常title颜色 var textSelectedColor = LL_HexRGB(0xFF7F0C) // 选中title颜色 var titleFont = UIFont.systemFont(ofSize: 14) //title字体 var textFont = UIFont.systemFont(ofSize: 14) //选项字体 var delegate: LLDropDownMenuDelegate? // 代理 var isShow = false // 数据数组 var itemsData: [[LLOptionItem]]! { didSet { didSetItemData() } } var selectedIndexPaths : [LLIndexPath]! // 选中选项 let boundle = Bundle(url: Bundle(for: LLDropDownMenu.self).url(forResource: "LLResources", withExtension: "bundle")!) // 展示的IndexPath fileprivate var showIndexPath: LLIndexPath? // 列数 fileprivate var numOfColumn: Int { return selectedIndexPaths.count } private let backGroundView = UIView() fileprivate let firstTalbeView = UITableView() fileprivate let secondTableView = UITableView() fileprivate let thirdTabelView = UITableView() fileprivate let bottomImageView = UIImageView() fileprivate var titleLayers: [CATextLayer]? fileprivate var indicatiorLayers : [CAShapeLayer]? fileprivate var bgLayers : [CALayer]? override init(frame: CGRect) { super.init(frame: frame) configUI() } init() { super.init(frame: MenuDefaultFrame) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func configUI() { let tableviewWidth = bounds.size.width / 3 // 一级列表 firstTalbeView.frame = CGRect(x: 0, y: frame.origin.y + frame.size.height, width: tableviewWidth, height: 0) firstTalbeView.rowHeight = MenuCellHeight firstTalbeView.dataSource = self firstTalbeView.delegate = self firstTalbeView.separatorColor = MenuSepartorColor firstTalbeView.separatorInset = .zero firstTalbeView.tableFooterView = UIView() // 二级列表 secondTableView.frame = CGRect(x: tableviewWidth, y: frame.origin.y + frame.size.height, width: tableviewWidth, height: 0) secondTableView.rowHeight = MenuCellHeight secondTableView.dataSource = self secondTableView.delegate = self secondTableView.separatorColor = MenuSepartorColor secondTableView.separatorInset = .zero secondTableView.tableFooterView = UIView() // 三级列表 thirdTabelView.frame = CGRect(x: tableviewWidth * 2, y: frame.origin.y + frame.size.height, width: tableviewWidth, height: 0) thirdTabelView.rowHeight = MenuCellHeight thirdTabelView.dataSource = self thirdTabelView.delegate = self thirdTabelView.separatorColor = MenuSepartorColor thirdTabelView.separatorInset = .zero thirdTabelView.tableFooterView = UIView() // 底部装饰条 bottomImageView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.size.height, width: frame.size.width, height: MenuBottomImageHeight) bottomImageView.image = UIImage(named: "icon_chose_bottom", in: boundle, compatibleWith: nil) // 阴影 backGroundView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.size.height, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height) backGroundView.backgroundColor = UIColor(white: 0, alpha: 0) backGroundView.isOpaque = false let backTap = UITapGestureRecognizer(target: self, action: #selector(self.backTapAction)) backGroundView.addGestureRecognizer(backTap) // 底部分隔线 let bottomSeparator = UIView(frame: CGRect(x: 0, y: frame.size.height - 0.5, width: frame.size.width, height: 0.5)) bottomSeparator.backgroundColor = MenuSepartorColor self.addSubview(bottomSeparator) // 添加菜单点击手势 let menuTap = UITapGestureRecognizer(target: self, action: #selector(self.menuTapAction)) self.addGestureRecognizer(menuTap) } // 监听设置ItemData fileprivate func didSetItemData() { if itemsData == nil { return } // 设置初始选中 selectedIndexPaths = [] var index = 0 for colItems in itemsData! { var selectedIndexPath = LLIndexPath(corlumn: index, row: nil, item: nil, index: nil, selectedText:"") index += 1 if let firstRow = colItems.first { selectedIndexPath.row = 0 if let firstItem = firstRow.items?.first { selectedIndexPath.item = 0 if let firstIndex = firstItem.items?.first { selectedIndexPath.index = 0 selectedIndexPath.selectedText = firstIndex.title } else { selectedIndexPath.selectedText = firstItem.title } } else { selectedIndexPath.selectedText = firstRow.title } } else { selectedIndexPath.selectedText = "no data" } selectedIndexPaths.append(selectedIndexPath) } // 设置菜单条 let buttomWidth = frame.size.width / CGFloat(numOfColumn) let buttomHeight = frame.size.height var tempTitles = [CATextLayer]() var tempIndicators = [CAShapeLayer]() var tempBgLayers = [CALayer]() for index in 0..<numOfColumn { //bgLayer let bgLayerPosition = CGPoint(x: (CGFloat(index) + 0.5) * buttomWidth, y: buttomHeight * 0.5) let bgLayer = createBgLayer(color: UIColor.white, position: bgLayerPosition, bounds: CGRect(x: 0, y: 0, width: buttomWidth, height: buttomHeight - 0.5)) self.layer.addSublayer(bgLayer) tempBgLayers.append(bgLayer) // titleLayer let titlePosition = CGPoint(x: (CGFloat(index) + 0.5) * buttomWidth, y: buttomHeight * 0.5) let title = selectedIndexPaths[index].selectedText let titleLayer = createTextLayer(string: title, color: textColor, font: titleFont, position: titlePosition, maxWidth: buttomWidth) self.layer.addSublayer(titleLayer) tempTitles.append(titleLayer) // indicator let indicatorPosition = CGPoint(x: CGFloat(index + 1) * buttomWidth - 10, y: buttomHeight * 0.5) let indicatorLayer = createInicator(color: indicatorColor, position: indicatorPosition) self.layer.addSublayer(indicatorLayer) tempIndicators.append(indicatorLayer) //separator if index != numOfColumn - 1 { let separatorPosition = CGPoint(x: ceil(CGFloat(index + 1) * buttomWidth - 1.0), y: buttomHeight * 0.5) let separator = createSeparatorLine(color: MenuSepartorColor, position: separatorPosition) self.layer.addSublayer(separator) } titleLayers = tempTitles indicatiorLayers = tempIndicators bgLayers = tempBgLayers } } // 菜单点击 @objc fileprivate func menuTapAction(tapSender:UITapGestureRecognizer) { let touchPoint = tapSender.location(in: self) let tapIndex = Int(touchPoint.x / (frame.width / CGFloat(numOfColumn))) if isShow && showIndexPath?.corlumn == tapIndex { // 收起菜单 hiddenMenu() } else { // 展开菜单 showMenu(column: tapIndex) } } // 展开菜单 fileprivate func showMenu(column:Int) { if isShow { // 切换 // old animateIndicator(indicator: (indicatiorLayers?[showIndexPath!.corlumn])!, isShow: false, complete: { animateTitleLayer(titleLayer: (titleLayers?[showIndexPath!.corlumn])!, isShow: false, complete: { }) }) showIndexPath = selectedIndexPaths[column] reloadMenu() // new animateIndicator(indicator: (indicatiorLayers?[column])!, isShow: true, complete: { animateTitleLayer(titleLayer: (titleLayers?[column])!, isShow: true, complete: { animateTableView(show: true, complete: { self.isShow = true }) }) }) } else { // 展开 showIndexPath = selectedIndexPaths[column] reloadMenu() animateBackBroundView(view: backGroundView, isShow: true, complete: { animateIndicator(indicator: (indicatiorLayers?[column])!, isShow: true, complete: { animateTitleLayer(titleLayer: (titleLayers?[column])!, isShow: true, complete: { animateTableView(show: true, complete: { self.isShow = true }) }) }) }) } } // 收起菜单 open func hiddenMenu() { animateBackBroundView(view: backGroundView, isShow: false, complete: { animateIndicator(indicator: (indicatiorLayers?[showIndexPath!.corlumn])!, isShow: false, complete: { animateTitleLayer(titleLayer: (titleLayers?[showIndexPath!.corlumn])!, isShow: false, complete: { animateTableView(show: false, complete: { self.isShow = false self.showIndexPath = nil }) }) }) }) } // 点击阴影 @objc fileprivate func backTapAction() { hiddenMenu() } // 刷新列表 fileprivate func reloadMenu() { firstTalbeView.reloadData() secondTableView.reloadData() thirdTabelView.reloadData() } } // MARK: - UITableViewDataSource, UITableViewDelegate extension LLDropDownMenu: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard showIndexPath != nil else { return 0 } if firstTalbeView == tableView { return itemsData[showIndexPath!.corlumn].count } else if secondTableView == tableView { if let row = showIndexPath!.row, let items = itemsData[showIndexPath!.corlumn][row].items { return items.count } } else if thirdTabelView == tableView { if let row = showIndexPath!.row, let item = showIndexPath!.item, let indexs = itemsData[showIndexPath!.corlumn][row].items?[item].items { return indexs.count } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "DropDownMenuCell" var cell = tableView.dequeueReusableCell(withIdentifier: identifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: identifier) let bg = UIView() let selectline = UIView(frame: CGRect(x: 0, y: 0, width: 0.5, height: MenuCellHeight)) selectline.backgroundColor = MenuSepartorColor bg.addSubview(selectline) bg.backgroundColor = MenuCellBgColor cell?.selectedBackgroundView = bg cell?.textLabel?.highlightedTextColor = textSelectedColor cell?.textLabel?.textColor = textColor cell?.textLabel?.font = textFont let rightLine = UIView(frame: CGRect(x: 0, y: 0, width: 0.5, height: MenuCellHeight)) rightLine.backgroundColor = MenuSepartorColor cell?.contentView.addSubview(rightLine) } let selectedIndexPath = selectedIndexPaths[showIndexPath!.corlumn] if firstTalbeView == tableView { // 设置Text let rowEntity = itemsData[showIndexPath!.corlumn][indexPath.row] cell?.textLabel?.text = rowEntity.title // 设置选中 if selectedIndexPath.row == indexPath.row { tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } // 设置箭头 if let items = rowEntity.items , items.count > 0 { let image = UIImage(named: "icon_chose_arrow_nor@2x", in: boundle, compatibleWith: nil) let highlightImage = UIImage(named: "icon_chose_arrow_sel@2x", in: boundle, compatibleWith: nil) cell?.accessoryView = UIImageView(image: image , highlightedImage: highlightImage) } else { cell?.accessoryView = nil } } else if secondTableView == tableView { // 设置Text let itemEntity = itemsData[showIndexPath!.corlumn][showIndexPath!.row!].items![indexPath.row] cell?.textLabel?.text = itemEntity.title // 设置选中 if selectedIndexPath.row == showIndexPath?.row && selectedIndexPath.item == indexPath.row { tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } // 设置箭头 if let indexs = itemEntity.items, indexs.count > 0 { let image = UIImage(named: "icon_chose_arrow_nor@2x", in: boundle, compatibleWith: nil) let highlightImage = UIImage(named: "icon_chose_arrow_sel@2x", in: boundle, compatibleWith: nil) cell?.accessoryView = UIImageView(image: image , highlightedImage: highlightImage) } else { cell?.accessoryView = nil } } else if thirdTabelView == tableView { // 设置Text let indexEntity = itemsData[showIndexPath!.corlumn][showIndexPath!.row!].items![showIndexPath!.item!].items![indexPath.row] cell?.textLabel?.text = indexEntity.title // 设置选中 if selectedIndexPath.row == showIndexPath?.row && selectedIndexPath.item == showIndexPath?.item && selectedIndexPath.index == indexPath.row { tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } // 设置箭头 cell?.accessoryView = nil } return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == firstTalbeView { showIndexPath = LLIndexPath(corlumn: showIndexPath!.corlumn, row: indexPath.row, item: nil, index: nil, selectedText: "") let rowEntity = itemsData![showIndexPath!.corlumn][indexPath.row] if rowEntity.items == nil { var selectedIndexPath = showIndexPath! selectedIndexPath.selectedText = rowEntity.title updateDidSelect(indexPath: selectedIndexPath) updateTitleText(selected: selectedIndexPath) } else { self.secondTableView.reloadData() self.thirdTabelView.reloadData() animateUpateLayoutTableView(indexPath: showIndexPath!, complete: { }) } } else if tableView == secondTableView { showIndexPath = LLIndexPath(corlumn: showIndexPath!.corlumn, row: showIndexPath?.row, item: indexPath.row, index: nil, selectedText: "") let itemEntity = itemsData![showIndexPath!.corlumn][showIndexPath!.row!].items![indexPath.row] if itemEntity.items == nil { var selectedIndexPath = showIndexPath! selectedIndexPath.selectedText = itemEntity.title updateDidSelect(indexPath: selectedIndexPath) updateTitleText(selected: selectedIndexPath) } else { thirdTabelView.reloadData() animateUpateLayoutTableView(indexPath: showIndexPath!, complete: { }) } } else if tableView == thirdTabelView { showIndexPath = LLIndexPath(corlumn: showIndexPath!.corlumn, row: showIndexPath!.row, item: showIndexPath!.item, index: indexPath.row, selectedText: "") let indexEntity = itemsData![showIndexPath!.corlumn][showIndexPath!.row!].items![showIndexPath!.item!].items![indexPath.row] var selectedIndexPath = showIndexPath! selectedIndexPath.selectedText = indexEntity.title updateDidSelect(indexPath: selectedIndexPath) updateTitleText(selected: selectedIndexPath) } } func updateDidSelect(indexPath:LLIndexPath) { let rang:Range = indexPath.corlumn ..< indexPath.corlumn + 1 selectedIndexPaths.replaceSubrange(rang, with: [indexPath]) delegate?.menu(self, didSelectIndexPath: indexPath) } func updateTitleText(selected:LLIndexPath) { let titleLayer = titleLayers![selected.corlumn] titleLayer.string = selected.selectedText hiddenMenu() } } // MARK: - animation method extension LLDropDownMenu { fileprivate func animateTableView(show:Bool, complete:@escaping () -> Void) { if show { self.superview?.clipsToBounds = true firstTalbeView.frame = CGRect(x: self.frame.minX, y: self.frame.maxY, width: self.frame.width, height: 0) secondTableView.frame = CGRect(x: self.frame.maxY, y: self.frame.maxY, width: self.frame.width, height: 0) thirdTabelView.frame = CGRect(x: self.frame.maxY, y: self.frame.maxY, width: self.frame.width, height: 0) if firstTalbeView.superview == nil { self.superview?.addSubview(firstTalbeView) } else { self.superview?.bringSubview(toFront: firstTalbeView) } if secondTableView.superview == nil { self.superview?.addSubview(secondTableView) } else { self.superview?.bringSubview(toFront: secondTableView) } if thirdTabelView.superview == nil { self.superview?.addSubview(thirdTabelView) } else { self.superview?.bringSubview(toFront: thirdTabelView) } bottomImageView.frame = CGRect(x: self.frame.minX, y: self.frame.maxY, width: self.frame.width, height: MenuBottomImageHeight) self.superview?.addSubview(bottomImageView) self.superview?.addSubview(self) var columnCount = 1 let slectedIndexPath = selectedIndexPaths[showIndexPath!.corlumn] if slectedIndexPath.index != nil { columnCount = 3 } else if slectedIndexPath.item != nil { columnCount = 2 } let tableviewWidth = self.frame.width / CGFloat(columnCount) var firstFrame = firstTalbeView.frame firstFrame.size.width = tableviewWidth firstTalbeView.frame = firstFrame var secondFrame = secondTableView.frame secondFrame.size.width = tableviewWidth secondFrame.origin.x = firstTalbeView.frame.maxX secondTableView.frame = secondFrame var thirdFrame = thirdTabelView.frame thirdFrame.size.width = tableviewWidth thirdFrame.origin.x = secondTableView.frame.maxX thirdTabelView.frame = thirdFrame let numRows = firstTalbeView.numberOfRows(inSection: 0) let numItems = secondTableView.numberOfRows(inSection: 0) let numIndexs = thirdTabelView.numberOfRows(inSection: 0) var num = numRows if columnCount == 2 { num = max(numRows, numItems) } else if columnCount == 3 { num = max(max(numRows, numItems), numIndexs) } let maxNum = 9 var tableviewHeight = CGFloat(num > maxNum ? maxNum : num) * MenuCellHeight tableviewHeight += CGFloat(num > maxNum ? 10 : 0) UIView.animate(withDuration: 0.2, animations: { var firstFrame = self.firstTalbeView.frame firstFrame.size.height = tableviewHeight self.firstTalbeView.frame = firstFrame var secondFrame = self.secondTableView.frame secondFrame.size.height = tableviewHeight self.secondTableView.frame = secondFrame var thirdFrame = self.thirdTabelView.frame thirdFrame.size.height = tableviewHeight self.thirdTabelView.frame = thirdFrame var imageFrame = self.bottomImageView.frame imageFrame.origin.y += tableviewHeight - 1 self.bottomImageView.frame = imageFrame }, completion: { (_) in complete() }) } else { UIView.animate(withDuration: 0.2, animations: { var firstFrame = self.firstTalbeView.frame firstFrame.size.height = 0 self.firstTalbeView.frame = firstFrame var secondFrame = self.secondTableView.frame secondFrame.size.height = 0 self.secondTableView.frame = secondFrame var thirdFrame = self.thirdTabelView.frame thirdFrame.size.height = 0 self.thirdTabelView.frame = thirdFrame var imageFrame = self.bottomImageView.frame imageFrame.origin.y = self.frame.maxY self.bottomImageView.frame = imageFrame }, completion: { (_) in if let _ = self.firstTalbeView.superview { self.firstTalbeView.removeFromSuperview() } if let _ = self.secondTableView.superview { self.secondTableView.removeFromSuperview() } if let _ = self.thirdTabelView.superview { self.thirdTabelView.removeFromSuperview() } self.bottomImageView.removeFromSuperview() complete() }) } } fileprivate func animateUpateLayoutTableView(indexPath:LLIndexPath, complete:@escaping () -> Void) { let numRows = self.tableView(firstTalbeView, numberOfRowsInSection: 0) let numItems = self.tableView(secondTableView, numberOfRowsInSection: 0) let numIndexs = self.tableView(thirdTabelView, numberOfRowsInSection: 0) var columnCount = 1 if indexPath.item == nil && numItems > 0 { // 点击了第一列 columnCount = 2 } else if numIndexs > 0 { // 点击了第二列 columnCount = 3 } let tableviewWidth = self.frame.width / CGFloat(columnCount) var num = numRows if columnCount == 2 { num = max(numRows, numItems) } else if columnCount == 3 { num = max(max(numRows, numItems), numIndexs) } let maxNum = 9 var tableviewHeight = CGFloat(num > maxNum ? maxNum : num) * MenuCellHeight tableviewHeight += CGFloat(num > maxNum ? 10 : 0) UIView.animate(withDuration: 0.2, animations: { var firstFrame = self.firstTalbeView.frame firstFrame.size.height = tableviewHeight firstFrame.size.width = tableviewWidth self.firstTalbeView.frame = firstFrame var secondFrame = self.secondTableView.frame secondFrame.size.height = tableviewHeight secondFrame.size.width = tableviewWidth secondFrame.origin.x = self.firstTalbeView.frame.maxX self.secondTableView.frame = secondFrame var thirdFrame = self.thirdTabelView.frame thirdFrame.size.height = tableviewHeight thirdFrame.size.width = tableviewWidth thirdFrame.origin.x = self.secondTableView.frame.maxX self.thirdTabelView.frame = thirdFrame var imageFrame = self.bottomImageView.frame imageFrame.origin.y = self.frame.maxY + tableviewHeight - 1 self.bottomImageView.frame = imageFrame }, completion: { (_) in complete() }) } fileprivate func animateIndicator(indicator:CAShapeLayer, isShow:Bool, complete: () -> Void) { CATransaction.begin() CATransaction.setAnimationDuration(0.25) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.2, 1.0)) let animation = CAKeyframeAnimation(keyPath: "transform.rotation") animation.values = isShow ? [0, M_PI] : [M_PI, 0] if !animation.isRemovedOnCompletion { indicator.add(animation, forKey: animation.keyPath) } else { indicator.add(animation, forKey: animation.keyPath) indicator.setValue(animation.values?.last, forKeyPath: animation.keyPath!) } CATransaction.commit() if isShow { indicator.fillColor = textSelectedColor.cgColor } else { indicator.fillColor = indicatorColor.cgColor } complete() } fileprivate func animateBackBroundView(view:UIView, isShow:Bool, complete:() -> Void) { if isShow { self.superview?.addSubview(view) view.superview?.addSubview(self) UIView.animate(withDuration: 0.2, animations: { view.backgroundColor = UIColor(white: 0, alpha: 0.3) }) } else { UIView.animate(withDuration: 0.2, animations: { view.backgroundColor = UIColor(white: 0, alpha: 0) }, completion: { (_) in view.removeFromSuperview() }) } complete() } fileprivate func animateTitleLayer(titleLayer: CATextLayer, isShow: Bool, complete:() -> Void) { let maxWidth = frame.size.width / CGFloat(numOfColumn) let size = calculateTitleSize(string: titleLayer.string as! String, font: titleFont) let width = size.width < (maxWidth - 25) ? size.width : maxWidth - 25 titleLayer.bounds = CGRect(x: 0, y: 0, width: width, height: size.height) if isShow { titleLayer.foregroundColor = textSelectedColor.cgColor } else { titleLayer.foregroundColor = textColor.cgColor } complete() } } // MARK: - Layer Tool extension LLDropDownMenu { fileprivate func createBgLayer(color:UIColor, position:CGPoint, bounds:CGRect) -> CALayer { let layer = CALayer() layer.position = position layer.bounds = bounds layer.backgroundColor = color.cgColor return layer } fileprivate func createInicator(color:UIColor, position:CGPoint) -> CAShapeLayer { let layer = CAShapeLayer() let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: 8, y: 0)) path.addLine(to: CGPoint(x: 4, y: 5)) path.close() layer.path = path.cgPath layer.lineWidth = 0.8 layer.fillColor = color.cgColor let pathCopy = layer.path?.copy(strokingWithWidth: layer.lineWidth, lineCap: .butt, lineJoin: .miter, miterLimit: layer.miterLimit) layer.bounds = (pathCopy?.boundingBoxOfPath)! layer.position = position return layer } fileprivate func createSeparatorLine(color:UIColor, position:CGPoint) -> CAShapeLayer { let layer = CAShapeLayer() let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: 0, y: 20)) layer.path = path.cgPath layer.lineWidth = 1 layer.strokeColor = color.cgColor let pathCopy = layer.path?.copy(strokingWithWidth: layer.lineWidth, lineCap: .butt, lineJoin: .miter, miterLimit: layer.miterLimit) layer.bounds = (pathCopy?.boundingBoxOfPath)! layer.position = position return layer } fileprivate func createTextLayer(string:String, color:UIColor, font:UIFont, position:CGPoint, maxWidth:CGFloat) -> CATextLayer { let size = calculateTitleSize(string: string, font:font) let layer = CATextLayer() let width = size.width < (maxWidth - 25) ? size.width : maxWidth - 25 layer.bounds = CGRect(x: 0, y: 0, width: width, height: size.height) layer.string = string layer.fontSize = font.pointSize layer.alignmentMode = kCAAlignmentCenter layer.truncationMode = kCATruncationEnd layer.foregroundColor = color.cgColor layer.contentsScale = UIScreen.main.scale layer.position = position return layer } fileprivate func calculateTitleSize(string:String, font:UIFont) -> CGSize { let dict = [NSFontAttributeName:font] let size = (string as NSString).boundingRect(with: bounds.size, options: [.truncatesLastVisibleLine, .usesFontLeading, .usesLineFragmentOrigin], attributes: dict, context: nil).size return CGSize(width: ceil(size.width) + 2, height: size.height) } }
mit
f85487d6df914b27c477894bb40f8536
36.482227
189
0.566682
5.570523
false
false
false
false
johntvolk/TableViewConfigurator
TableViewConfigurator/Classes/ModelRowConfiguration.swift
1
8789
// // ModelRowConfiguration.swift // Pods // // Created by John Volk on 3/1/16. // Copyright © 2016 John Volk. All rights reserved. // import UIKit import Dwifft public protocol RowModel: class, Equatable { var identityTag: String? { get set } } public func == <T: RowModel>(lhs: T, rhs: T) -> Bool { return lhs.identityTag == rhs.identityTag } private var identityTagAssociationKey: UInt8 = 0 public extension RowModel { var identityTag: String? { get { return objc_getAssociatedObject(self, &identityTagAssociationKey) as? String } set(value) { objc_setAssociatedObject(self, &identityTagAssociationKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } public class ModelRowConfiguration<CellType, ModelType>: RowConfiguration where CellType: UITableViewCell, CellType: ModelConfigurableTableViewCell, ModelType == CellType.ModelType { private let optimizeModels: Bool private var models: [ModelType]? private let modelGenerator: (() -> [ModelType]?)? private var modelSnapshot = [ModelType]() private var heightGenerator: ((_ model: ModelType) -> CGFloat)? private var estimatedHeightGenerator: ((_ model: ModelType) -> CGFloat)? private var additionalConfig: ((_ cell: CellType, _ model: ModelType, _ index: Int) -> Void)? private var selectionHandler: ((_ model: ModelType, _ index: Int) -> Void)? private var canEditHandler: ((_ model: ModelType, _ index: Int) -> Bool)? private var editHandler: ((_ editingStyle: UITableViewCellEditingStyle, _ model: ModelType, _ index: Int) -> Void)? private var hideWhen: ((_ model: ModelType) -> Bool)? public init(models: [ModelType]) { self.optimizeModels = true self.models = models self.modelGenerator = nil } public init(modelGenerator: @escaping () -> [ModelType]?, optimizeModels: Bool = false) { self.optimizeModels = optimizeModels self.modelGenerator = modelGenerator self.models = modelGenerator() } public func heightGenerator(_ heightGenerator: @escaping (_ model: ModelType) -> CGFloat) -> Self { self.heightGenerator = heightGenerator return self } public func estimatedHeightGenerator(_ estimatedHeightGenerator: @escaping (_ model: ModelType) -> CGFloat) -> Self { self.estimatedHeightGenerator = estimatedHeightGenerator return self } public func additionalConfig(_ additionalConfig: @escaping (_ cell: CellType, _ model: ModelType, _ index: Int) -> Void) -> Self { self.additionalConfig = additionalConfig return self } public func selectionHandler(_ selectionHandler: @escaping (_ model: ModelType, _ index: Int) -> Void) -> Self { self.selectionHandler = selectionHandler return self } public func canEditHandler(_ canEditHandler: @escaping (_ model: ModelType, _ index: Int) -> Bool) -> Self { self.canEditHandler = canEditHandler return self } public func editHandler(_ editHandler: @escaping (_ editingStyle: UITableViewCellEditingStyle, _ model: ModelType, _ index: Int) -> Void) -> Self { self.editHandler = editHandler return self } public func hideWhen(_ hideWhen: @escaping (_ model: ModelType) -> Bool) -> Self { self.hideWhen = hideWhen return self } override internal func numberOfRows() -> Int { if let models = getModels() { if let hideWhen = self.hideWhen { return models.reduce(0) { (totalRows, model) -> Int in return totalRows + (hideWhen(model) ? 0 : 1) } } return models.count } return 0 } override func saveSnapshot() { self.modelSnapshot.removeAll(keepingCapacity: true) self.refreshModels() if let models = getModels() { for i in 0 ..< models.count { let model = models[i] if model.identityTag == nil { model.identityTag = String(i) } } if let hideWhen = self.hideWhen { self.modelSnapshot.append(contentsOf: models.filter { !hideWhen($0) }) } else { self.modelSnapshot.append(contentsOf: models) } } } override func snapshotChangeSet() -> SnapshotChangeSet? { let before = self.modelSnapshot saveSnapshot() var rowInsertions = [Int]() var rowDeletions = [Int]() let diff = Dwifft.diff(before, self.modelSnapshot) for result in diff { switch result { case let .insert(i, _): rowInsertions.append(i) case let .delete(i, _): rowDeletions.append(i) } } return (before.count, rowInsertions, rowDeletions) } override func cellFor(row: Int, inTableView tableView: UITableView) -> UITableViewCell? { let reuseId = self.cellReuseId ?? CellType.buildReuseIdentifier() if let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) as? CellType { return configure(cell: cell, forRow: row) } return nil } override func refreshCellFor(row: Int, withIndexPath indexPath: IndexPath, inTableView tableView: UITableView) { if let cell = tableView.cellForRow(at: indexPath) as? CellType { _ = configure(cell: cell, forRow: row) } } private func configure(cell: CellType, forRow row: Int) -> CellType { if let model = self.selectModelFor(row: row) { cell.configure(model: model) if let additionalConfig = self.additionalConfig { additionalConfig(cell, model, originalIndexFor(row: row)) } } return cell } override func heightFor(row: Int) -> CGFloat? { if let heightGenerator = self.heightGenerator, let model = selectModelFor(row: row) { return heightGenerator(model) } return super.heightFor(row: row) } override func estimatedHeightFor(row: Int) -> CGFloat? { if let estimatedHeightGenerator = self.estimatedHeightGenerator, let model = selectModelFor(row: row) { return estimatedHeightGenerator(model) } return super.estimatedHeightFor(row: row) } override internal func didSelect(row: Int) { if let model = selectModelFor(row: row) { self.selectionHandler?(model, originalIndexFor(row: row)) } } override func canEdit(row: Int) -> Bool { if let model = selectModelFor(row: row) { return self.canEditHandler?(model, originalIndexFor(row: row)) ?? false } return false } override func commit(editingStyle: UITableViewCellEditingStyle, forRow row: Int) { if let model = selectModelFor(row: row) { self.editHandler?(editingStyle, model, originalIndexFor(row: row)) } } private func selectModelFor(row: Int) -> ModelType? { if let models = getModels() { if let hideWhen = self.hideWhen { var unhiddenTotal = 0 for model in models { unhiddenTotal += (hideWhen(model) ? 0 : 1) if unhiddenTotal - 1 == row { return model } } } return models[row] } return nil } private func originalIndexFor(row: Int) -> Int { if let hideWhen = self.hideWhen, let models = getModels() { var total = 0 var unhiddenTotal = 0 for model in models { total += 1 unhiddenTotal += (hideWhen(model) ? 0 : 1) if unhiddenTotal - 1 == row { return total - 1 } } } return row } private func getModels() -> [ModelType]? { if self.optimizeModels { return self.models } else if let modelGenerator = self.modelGenerator { return modelGenerator() } return nil } private func refreshModels() { if self.optimizeModels, let modelGenerator = self.modelGenerator { self.models = modelGenerator() } } }
mit
4b61dd47e3beb6d10f34fa36d7be4f25
31.428044
151
0.573737
5.154252
false
true
false
false
Ryce/flickrpickr
Carthage/Checkouts/judokit/Tests/PreAuthTests.swift
2
8600
// // PreAuthTests.swift // JudoTests // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest @testable import JudoKit class PreAuthTests: JudoTestCase { func testPreAuth() { guard let references = Reference(consumerRef: "consumer0053252") else { return } let amount = Amount(amountString: "30", currency: .GBP) do { let preauth = try judo.preAuth(myJudoId, amount: amount, reference: references) XCTAssertNotNil(preauth) } catch { XCTFail("exception thrown: \(error)") } } func testJudoMakeValidPreAuth() { do { // Given I have a Pre-authorization let preAuth = try judo.preAuth(myJudoId, amount: oneGBPAmount, reference: validReference) // When I provide all the required fields preAuth.card(validVisaTestCard) // Then I should be able to make a Pre-authorization let expectation = self.expectation(description: "payment expectation") try preAuth.completion({ (response, error) -> () in if let error = error { XCTFail("api call failed with error: \(error)") } XCTAssertNotNil(response) XCTAssertNotNil(response?.items.first) expectation.fulfill() }) XCTAssertNotNil(preAuth) XCTAssertEqual(preAuth.judoId, myJudoId) } catch { XCTFail("exception thrown: \(error)") } self.waitForExpectations(timeout: 30, handler: nil) } func testJudoMakeValidPreAuthWithDeviceSignals() { do { // Given I have a Payment let payment = try judo.payment(myJudoId, amount: oneGBPAmount, reference: validReference) // When I provide all the required fields payment.card(validVisaTestCard) // Then I should be able to make a payment let expectation = self.expectation(description: "payment expectation") try judo.completion(payment, block: { (response, error) in if let error = error { XCTFail("api call failed with error: \(error)") } XCTAssertNotNil(response) XCTAssertNotNil(response?.items.first) expectation.fulfill() }) XCTAssertNotNil(payment) XCTAssertEqual(payment.judoId, myJudoId) } catch { XCTFail("exception thrown: \(error)") } self.waitForExpectations(timeout: 30, handler: nil) } func testJudoMakePreAuthWithoutCurrency() { do { // Given I have a Pre-authorization // When I do not provide a currency let preAuth = try judo.preAuth(myJudoId, amount: invalidCurrencyAmount, reference: validReference) preAuth.card(validVisaTestCard) // Then I should receive an error let expectation = self.expectation(description: "payment expectation") try preAuth.completion({ (response, error) -> () in XCTAssertNil(response) XCTAssertNotNil(error) XCTAssertEqual(error!.code, JudoErrorCode.general_Model_Error) //This should be three. This is a known bug with the platform returning an uneeded extra model error about amount formattting. XCTAssertEqual(error?.details?.count, 4) expectation.fulfill() }) XCTAssertNotNil(preAuth) XCTAssertEqual(preAuth.judoId, myJudoId) } catch { XCTFail("exception thrown: \(error)") } self.waitForExpectations(timeout: 30, handler: nil) } func testJudoMakePreAuthWithoutReference() { do { // Given I have a Pre-authorization // When I do not provide a consumer reference let preAuth = try judo.preAuth(myJudoId, amount: oneGBPAmount, reference: invalidReference) preAuth.card(validVisaTestCard) // Then I should receive an error let expectation = self.expectation(description: "payment expectation") try preAuth.completion({ (response, error) -> () in XCTAssertNil(response) XCTAssertNotNil(error) XCTAssertEqual(error!.code, JudoErrorCode.general_Model_Error) XCTAssertEqual(error?.details?.count, 2) expectation.fulfill() }) XCTAssertNotNil(preAuth) XCTAssertEqual(preAuth.judoId, myJudoId) } catch { XCTFail("exception thrown: \(error)") } self.waitForExpectations(timeout: 30, handler: nil) } func testJudoMakeInvalidJudoIDPreAuth() throws { // Given // allowed length for judoId is 6 to 10 chars let tooShortJudoID = "33412" // 5 chars not allowed let tooLongJudoID = "33224433441" // 11 chars not allowed let luhnInvalidJudoID = "33224433" var parameterError = false guard let references = Reference(consumerRef: "consumer0053252") else { return } let amount = Amount(amountString: "30", currency: .GBP) // When too short do { try _ = judo.preAuth(tooShortJudoID, amount: amount, reference: references) // this should fail } catch let error as JudoError { // Then switch error.code { case .judoIDInvalidError, .luhnValidationError: parameterError = true default: XCTFail("exception thrown: \(error)") } } XCTAssertTrue(parameterError) parameterError = false // When too long do { try _ = judo.preAuth(tooLongJudoID, amount: amount, reference: references) // this should fail } catch let error as JudoError { switch error.code { case .judoIDInvalidError, .luhnValidationError: parameterError = true default: XCTFail("exception thrown: \(error)") } } XCTAssertTrue(parameterError) parameterError = false // When do { try _ = judo.preAuth(luhnInvalidJudoID, amount: amount, reference: references) // this should fail } catch let error as JudoError { switch error.code { case .judoIDInvalidError, .luhnValidationError: parameterError = true default: XCTFail("exception thrown: \(error)") } } XCTAssertTrue(parameterError) } func testJudoMakeInvalidReferencesPreAuth() { // Given guard let references = Reference(consumerRef: "") else { return } let amount = Amount(amountString: "30", currency: .GBP) // When do { try _ = judo.preAuth(myJudoId, amount: amount, reference: references) } catch { XCTFail("exception thrown: \(error)") } } }
mit
8c510c9c33a9e8a62c6dc913f2875cf4
36.229437
142
0.576395
5.321782
false
true
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/DataSources/UserDataManager.swift
1
4520
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ /** * Asks ManagerHelper to initiate a resource request to get authorized User data */ class UserDataManager: NSObject { var oneUserCallback: ((User)->())! /// Callback object to return data to the requesting class, NOTE: if using mfp date, use this callback and parse afterward var callback: (([User])->())! /// Data dictionary to contain results data var data: [String : AnyObject]! var singleUserManHelper: ManagerHelper! var usersManHelper: ManagerHelper! /// Shared instance variable for access the currentUser static let sharedInstance: UserDataManager = UserDataManager() var currentUser = User() private override init() { super.init() var url = "/adapters/usersAdapter/getGroupLeaderboard/" self.usersManHelper = ManagerHelper(URLString: url, delegate: self) url = "/adapters/usersAdapter/getUser/" self.singleUserManHelper = ManagerHelper(URLString: url, delegate: self) // Set current user for demo, would have info after a login normally self.getUser(0) { (user: User) in self.currentUser = user } } /** Method to get a user from the backend using an ID - parameter id: the ID of the User we want - parameter callback: callback to send user object to */ func getUser(id: Int, callback: ((User)->())) { self.oneUserCallback = callback let allUsers = ApplicationDataManager.sharedInstance.loadUsersFromCoreData() let userEmail = CurrentUserDemoSettings.getCurrentUserEmail() // Return immediatly because we have data for demo if let firstUser = allUsers.filter({ $0.email == userEmail }).first { self.oneUserCallback(firstUser) } singleUserManHelper.addProcedureParams("['\(id)']") singleUserManHelper.getResource() } /** Method to get user data using a resource request created by a ManagerHelper :param: callback callback to send user data */ func getUsers(groupID: Int, callback: ([User])->()) { self.callback = callback // Return immediatly because we have data for demo let dataManager = ApplicationDataManager.sharedInstance let leaders = dataManager.loadUsersFromCoreData() self.callback(leaders) usersManHelper.addProcedureParams("['\(groupID)']") usersManHelper.getResource() } /** Method finds the user that sent out a specific invitation - parameter ID: invitation ID to find - parameter callback: callback to return the inviter `User` */ func getHostForInvitation(ID: Int, callback: (User?)->()) { // We don't have an invitation data manager, so I will get invites through users self.getUsers(self.currentUser.group.id) { (users: [User]) in for user in users { let reduced = user.invitationsSent.filter({ $0.id == ID }) if reduced.count == 1 { callback(user) return } } callback(nil) } } } extension UserDataManager: HelperDelegate { /** Method to send user data from a WLResponse if the resource request is successful :param: response WLResponse containing data */ func resourceSuccess(response: WLResponse!) { print("User Data Success with response: \(response.responseText)") MQALogger.log("User Data Success with response: \(response.responseText)", withLevel: MQALogLevelInfo) // If using MFP data, the follwoing would be used // You would need to check if this was a response for a single user or for the list of all users /*data = response.getResponseJson() as! [String: AnyObject] if data != nil { callback(data) }*/ } /** Method to send error message if the resource request fails :param: error error message for resource request failure */ func resourceFailure(error: String!) { print("UserDataManager Failure! with err: \(error)") MQALogger.log("UserDataManager failure with err: \(error)", withLevel: MQALogLevelError) // data = ["failure":error] // callback(data) } }
epl-1.0
3caf96d3b275bb8e932b323ddf4bfd4e
33.503817
126
0.622925
5.071829
false
false
false
false
SoySauceLab/CollectionKit
Sources/Addon/SpaceProvider.swift
1
1009
// // SpaceProvider.swift // CollectionKit // // Created by Luke Zhao on 2017-07-23. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit open class SpaceProvider: EmptyCollectionProvider { public enum SpaceSizeStrategy { case fill case absolute(CGFloat) } open var sizeStrategy: (SpaceSizeStrategy, SpaceSizeStrategy) public init(sizeStrategy: (SpaceSizeStrategy, SpaceSizeStrategy) = (.fill, .fill)) { self.sizeStrategy = sizeStrategy super.init() } var _contentSize: CGSize = .zero open override var contentSize: CGSize { return _contentSize } open override func layout(collectionSize: CGSize) { let width: CGFloat, height: CGFloat switch sizeStrategy.0 { case .fill: width = collectionSize.width case .absolute(let value): width = value } switch sizeStrategy.1 { case .fill: height = collectionSize.height case .absolute(let value): height = value } _contentSize = CGSize(width: width, height: height) } }
mit
740656ff8757d4eb5ada882a31881a18
26.243243
86
0.699405
4.097561
false
false
false
false
irlabs/ActionKit
ActionKit/UIBarButtonItem+ActionKit.swift
1
6761
// // UIBarButtonItem+ActionKit.swift // ActionKit // // Created by Manue on 30/6/16. // Copyright © 2016 ActionKit. All rights reserved. // import Foundation import UIKit private extension Selector { static let runBarButtonItem = #selector(UIBarButtonItem.runActionKitVoidClosure) } /** Extension to provide convenience initializers to use closures instead of target/actions. */ public extension UIBarButtonItem { // wraps an item specific closure in an ActionKitVoidClosure with a weak reference to self fileprivate func wrapItemClosure(_ actionClosure: @escaping (UIBarButtonItem) -> Void) -> ActionKitVoidClosure { return { [weak self] () -> () in guard let strongSelf = self else { return } actionClosure(strongSelf) } } // MARK: Void /** Initializes a new item using the specified image and other properties. - parameter image: The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points. The alpha values in the source image are used to create the images—opaque values are ignored. - parameter landscapeImagePhone: The style of the item. One of the constants defined in UIBarButtonItemStyle. nil by default - parameter style: The style of the item. One of the constants defined in UIBarButtonItemStyle. (.Plain by default) - parameter actionClosure: The closure to be called when the button is tapped - returns: Newly initialized item with the specified properties. */ convenience init(image: UIImage, landscapeImagePhone: UIImage? = nil, style: UIBarButtonItem.Style = .plain, actionClosure: @escaping () -> Void) { self.init(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: nil, action: nil) addActionClosure(actionClosure) } /** Initializes a new item using the specified title and other properties. - parameter title: The item’s title. - parameter style: The style of the item. One of the constants defined in UIBarButtonItemStyle. (.Plain by default) - parameter actionClosure: The closure to be called when the button is tapped - returns: Newly initialized item with the specified properties. */ convenience init(title: String, style: UIBarButtonItem.Style = .plain, actionClosure: @escaping () -> Void) { self.init(title: title, style: style, target: nil, action: nil) addActionClosure(actionClosure) } /** Initializes a new item containing the specified system item. - parameter systemItem: The system item to use as the first item on the bar. One of the constants defined in UIBarButtonSystemItem. - parameter actionClosure: The closure to be called when the button is tapped - returns: Newly initialized item with the specified properties. */ convenience init(barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, actionClosure: @escaping () -> Void) { self.init(barButtonSystemItem: systemItem, target: nil, action: nil) addActionClosure(actionClosure) } // MARK: Parameter /** Initializes a new item using the specified image and other properties. - parameter image: The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points. The alpha values in the source image are used to create the images—opaque values are ignored. - parameter landscapeImagePhone: The style of the item. One of the constants defined in UIBarButtonItemStyle. nil by default - parameter style: The style of the item. One of the constants defined in UIBarButtonItemStyle. (.Plain by default) - parameter actionClosure: The closure to be called when the button is tapped - returns: Newly initialized item with the specified properties. */ convenience init(image: UIImage, landscapeImagePhone: UIImage? = nil, style: UIBarButtonItem.Style = .plain, closureWithItem: @escaping (UIBarButtonItem) -> Void) { self.init(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: nil, action: nil) addActionClosure(wrapItemClosure(closureWithItem)) } /** Initializes a new item using the specified title and other properties. - parameter title: The item’s title. - parameter style: The style of the item. One of the constants defined in UIBarButtonItemStyle. (.Plain by default) - parameter actionClosure: The closure to be called when the button is tapped - returns: Newly initialized item with the specified properties. */ convenience init(title: String, style: UIBarButtonItem.Style = .plain, closureWithItem: @escaping (UIBarButtonItem) -> Void) { self.init(title: title, style: style, target: nil, action: nil) addActionClosure(wrapItemClosure(closureWithItem)) } /** Initializes a new item containing the specified system item. - parameter systemItem: The system item to use as the first item on the bar. One of the constants defined in UIBarButtonSystemItem. - parameter actionClosure: The closure to be called when the button is tapped - returns: Newly initialized item with the specified properties. */ convenience init(barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, closureWithItem: @escaping (UIBarButtonItem) -> Void) { self.init(barButtonSystemItem: systemItem, target: nil, action: nil) addActionClosure(wrapItemClosure(closureWithItem)) } fileprivate struct AssociatedKeys { static var ActionClosure = 0 } fileprivate var ActionClosure: ActionKitVoidClosure? { get { return (objc_getAssociatedObject(self, &AssociatedKeys.ActionClosure) as? ActionKitVoidClosureWrapper)?.closure } set { objc_setAssociatedObject(self, &AssociatedKeys.ActionClosure, ActionKitVoidClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)} } @objc fileprivate func runActionKitVoidClosure() { ActionClosure?() } /** Set a new closure to be called when the button is tapped. **NOTE**: The old closure will be removed and not called anymore */ fileprivate func addActionClosure(_ actionClosure: @escaping ActionKitVoidClosure) { ActionClosure = actionClosure self.target = self self.action = .runBarButtonItem } // MARK: Remove /** Remove the closure. */ func removeActionClosure() { ActionClosure = nil self.target = nil self.action = nil } }
mit
dc73884161d6fbebc4d4abe7f91f0ef4
40.170732
318
0.722453
4.711793
false
false
false
false
SwiftKit/Reactant
Example/Application/Sources/Wireframe/MainWireframe.swift
2
1653
// // MainWireframe.swift // Reactant // // Created by Matous Hybl on 3/24/17. // Copyright © 2017 Brightify s.r.o. All rights reserved. // import Reactant class MainWireframe: Wireframe { private let dependencyModule: DependencyModule init(dependencyModule: DependencyModule) { self.dependencyModule = dependencyModule } func entrypoint() -> UIViewController { return UINavigationController(rootViewController: mainController()) } private func mainController() -> UIViewController { return create { provider in let reactions = MainViewController.Reactions(openTable: { provider.navigation?.push(controller: self.tableViewController()) }) return MainViewController(reactions: reactions) } } private func tableViewController() -> UIViewController { return create { provider in let dependencies = TableViewController.Dependencies(nameService: dependencyModule.nameService) let reactions = TableViewController.Reactions(displayName: { name in provider.navigation?.present(controller: self.nameAlertController(name: name)) }) return TableViewController(dependencies: dependencies, reactions: reactions) } } private func nameAlertController(name: String) -> UIViewController { let controller = UIAlertController(title: "This is a name", message: name, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: "Close", style: .cancel, handler: { _ in controller.dismiss() })) return controller } }
mit
d94709fd49d4301b05268e3c5a8a4d68
33.416667
115
0.679177
5.346278
false
false
false
false
dmitriy-shmilo/portfolio-app
ios/Portfolio App/Portfolio App/Data/Profile.swift
1
1173
// // PAProfile.swift // Portfolio App // // Created by Dmitriy Shmilo on 10/14/17. // Copyright © 2017 Dmitriy Shmilo. All rights reserved. // import Foundation /** Represents information about a user. */ class Profile : CustomStringConvertible { init(firstName:String, lastName:String, title:String, birthDate:Date?, photo:String?, summary:String?) { self.firstName = firstName; self.lastName = lastName; self.title = title; self.birthDate = birthDate; self.photo = photo; self.summary = summary; } /** User's first name. */ var firstName:String; /** User's last name. */ var lastName:String; /** User's title - current position, project, education. */ var title:String; /** User's birth date. */ var birthDate:Date?; /** User's photo path. */ var photo:String?; /** Profile summary. */ var summary:String?; var description: String { return "Profile, name: \(firstName) \(lastName), \(title), born on \(String(describing: birthDate) )."; } }
mit
6eface192d8a7684df1018619a39d25c
19.206897
111
0.569113
4.231047
false
false
false
false
danielmartin/swift
stdlib/public/core/SequenceAlgorithms.swift
1
33258
//===--- SequenceAlgorithms.swift -----------------------------*- 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // enumerated() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a sequence of pairs (*n*, *x*), where *n* represents a /// consecutive integer starting at zero and *x* represents an element of /// the sequence. /// /// This example enumerates the characters of the string "Swift" and prints /// each character along with its place in the string. /// /// for (n, c) in "Swift".enumerated() { /// print("\(n): '\(c)'") /// } /// // Prints "0: 'S'" /// // Prints "1: 'w'" /// // Prints "2: 'i'" /// // Prints "3: 'f'" /// // Prints "4: 't'" /// /// When you enumerate a collection, the integer part of each pair is a counter /// for the enumeration, but is not necessarily the index of the paired value. /// These counters can be used as indices only in instances of zero-based, /// integer-indexed collections, such as `Array` and `ContiguousArray`. For /// other collections the counters may be out of range or of the wrong type /// to use as an index. To iterate over the elements of a collection with its /// indices, use the `zip(_:_:)` function. /// /// This example iterates over the indices and elements of a set, building a /// list consisting of indices of names with five or fewer letters. /// /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// var shorterIndices: [Set<String>.Index] = [] /// for (i, name) in zip(names.indices, names) { /// if name.count <= 5 { /// shorterIndices.append(i) /// } /// } /// /// Now that the `shorterIndices` array holds the indices of the shorter /// names in the `names` set, you can use those indices to access elements in /// the set. /// /// for i in shorterIndices { /// print(names[i]) /// } /// // Prints "Sofia" /// // Prints "Mateo" /// /// - Returns: A sequence of pairs enumerating the sequence. /// /// - Complexity: O(1) @inlinable // protocol-only public func enumerated() -> EnumeratedSequence<Self> { return EnumeratedSequence(_base: self) } } //===----------------------------------------------------------------------===// // min(), max() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the minimum element in the sequence, using the given predicate as /// the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `min(by:)` method on a /// dictionary to find the key-value pair with the lowest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let leastHue = hues.min { a, b in a.value < b.value } /// print(leastHue) /// // Prints "Optional(("Coral", 16))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` /// if its first argument should be ordered before its second /// argument; otherwise, `false`. /// - Returns: The sequence's minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns /// `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the sequence, using the given predicate /// as the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `max(by:)` method on a /// dictionary to find the key-value pair with the highest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let greatestHue = hues.max { a, b in a.value < b.value } /// print(greatestHue) /// // Prints "Optional(("Heliotrope", 296))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: The sequence's maximum element if the sequence is not empty; /// otherwise, `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(result, e) { result = e } } return result } } extension Sequence where Element: Comparable { /// Returns the minimum element in the sequence. /// /// This example finds the smallest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let lowestHeight = heights.min() /// print(lowestHeight) /// // Prints "Optional(58.5)" /// /// - Returns: The sequence's minimum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func min() -> Element? { return self.min(by: <) } /// Returns the maximum element in the sequence. /// /// This example finds the largest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let greatestHeight = heights.max() /// print(greatestHeight) /// // Prints "Optional(67.5)" /// /// - Returns: The sequence's maximum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func max() -> Element? { return self.max(by: <) } } //===----------------------------------------------------------------------===// // starts(with:) //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are equivalent to the elements in another sequence, using /// the given predicate as the equivalence test. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - possiblePrefix: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if the initial elements of the sequence are equivalent /// to the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix, by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool ) rethrows -> Bool { var possiblePrefixIterator = possiblePrefix.makeIterator() for e0 in self { if let e1 = possiblePrefixIterator.next() { if try !areEquivalent(e0, e1) { return false } } else { return true } } return possiblePrefixIterator.next() == nil } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are the same as the elements in another sequence. /// /// This example tests whether one countable range begins with the elements /// of another countable range. /// /// let a = 1...3 /// let b = 1...10 /// /// print(b.starts(with: a)) /// // Prints "true" /// /// Passing a sequence with no elements or an empty collection as /// `possiblePrefix` always results in `true`. /// /// print(b.starts(with: [])) /// // Prints "true" /// /// - Parameter possiblePrefix: A sequence to compare to this sequence. /// - Returns: `true` if the initial elements of the sequence are the same as /// the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix ) -> Bool where PossiblePrefix.Element == Element { return self.starts(with: possiblePrefix, by: ==) } } //===----------------------------------------------------------------------===// // elementsEqual() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain equivalent elements in the same order, using the given /// predicate as the equivalence test. /// /// At least one of the sequences must be finite. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if this sequence and `other` contain equivalent items, /// using `areEquivalent` as the equivalence test; otherwise, `false.` /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence, by areEquivalent: (Element, OtherSequence.Element) throws -> Bool ) rethrows -> Bool { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { switch (iter1.next(), iter2.next()) { case let (e1?, e2?): if try !areEquivalent(e1, e2) { return false } case (_?, nil), (nil, _?): return false case (nil, nil): return true } } } } extension Sequence where Element : Equatable { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain the same elements in the same order. /// /// At least one of the sequences must be finite. /// /// This example tests whether one countable range shares the same elements /// as another countable range and an array. /// /// let a = 1...3 /// let b = 1...10 /// /// print(a.elementsEqual(b)) /// // Prints "false" /// print(a.elementsEqual([1, 2, 3])) /// // Prints "true" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence and `other` contain the same elements /// in the same order. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.elementsEqual(other, by: ==) } } //===----------------------------------------------------------------------===// // lexicographicallyPrecedes() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the given /// predicate to compare elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areInIncreasingOrder: A predicate that returns `true` if its first /// argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that perform /// localized comparison instead. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where OtherSequence.Element == Element { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { if let e1 = iter1.next() { if let e2 = iter2.next() { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return iter2.next() != nil } } } extension Sequence where Element : Comparable { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the /// less-than operator (`<`) to compare elements. /// /// This example uses the `lexicographicallyPrecedes` method to test which /// array of integers comes first in a lexicographical ordering. /// /// let a = [1, 2, 2, 2] /// let b = [1, 2, 3, 4] /// /// print(a.lexicographicallyPrecedes(b)) /// // Prints "true" /// print(b.lexicographicallyPrecedes(b)) /// // Prints "false" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that /// perform localized comparison. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.lexicographicallyPrecedes(other, by: <) } } //===----------------------------------------------------------------------===// // contains() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence contains an /// element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that /// doesn't conform to the `Equatable` protocol, such as the /// `HTTPResponse` enumeration in this example. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)] /// let hadError = lastThreeResponses.contains { element in /// if case .error = element { /// return true /// } else { /// return false /// } /// } /// // 'hadError' == true /// /// Alternatively, a predicate can be satisfied by a range of `Equatable` /// elements or a general condition. This example shows how you can check an /// array for an expense greater than $100. /// /// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] /// let hasBigPurchase = expenses.contains { $0 > 100 } /// // 'hasBigPurchase' == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains( where predicate: (Element) throws -> Bool ) rethrows -> Bool { for e in self { if try predicate(e) { return true } } return false } /// Returns a Boolean value indicating whether every element of a sequence /// satisfies a given predicate. /// /// The following code uses this method to test whether all the names in an /// array have at least five characters: /// /// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 }) /// // allHaveAtLeastFive == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } } } extension Sequence where Element : Equatable { /// Returns a Boolean value indicating whether the sequence contains the /// given element. /// /// This example checks to see whether a favorite actor is in an array /// storing a movie's cast. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// print(cast.contains("Marlon")) /// // Prints "true" /// print(cast.contains("James")) /// // Prints "false" /// /// - Parameter element: The element to find in the sequence. /// - Returns: `true` if the element was found in the sequence; otherwise, /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return self.contains { $0 == element } } } } //===----------------------------------------------------------------------===// // count(where:) //===----------------------------------------------------------------------===// extension Sequence { /// Returns the number of elements in the sequence that satisfy the given /// predicate. /// /// You can use this method to count the number of elements that pass a test. /// For example, this code finds the number of names that are fewer than /// five characters long: /// /// let names = ["Jacqueline", "Ian", "Amy", "Juan", "Soroush", "Tiffany"] /// let shortNameCount = names.count(where: { $0.count < 5 }) /// // shortNameCount == 3 /// /// To find the number of times a specific element appears in the sequence, /// use the equal-to operator (`==`) in the closure to test for a match. /// /// let birds = ["duck", "duck", "duck", "duck", "goose"] /// let duckCount = birds.count(where: { $0 == "duck" }) /// // duckCount == 4 /// /// The sequence must be finite. /// /// - Parameter predicate: A closure that takes each element of the sequence /// as its argument and returns a Boolean value indicating whether /// the element should be included in the count. /// - Returns: The number of elements in the sequence that satisfy the given /// predicate. @inlinable public func count( where predicate: (Element) throws -> Bool ) rethrows -> Int { var count = 0 for e in self { if try predicate(e) { count += 1 } } return count } } //===----------------------------------------------------------------------===// // reduce() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements /// of an entire sequence. For example, you can use this method on an array /// of numbers to find their sum or product. /// /// The `nextPartialResult` closure is called sequentially with an /// accumulating value initialized to `initialResult` and each element of /// the sequence. This example shows how to find the sum of an array of /// numbers. /// /// let numbers = [1, 2, 3, 4] /// let numberSum = numbers.reduce(0, { x, y in /// x + y /// }) /// // numberSum == 10 /// /// When `numbers.reduce(_:_:)` is called, the following steps occur: /// /// 1. The `nextPartialResult` closure is called with `initialResult`---`0` /// in this case---and the first element of `numbers`, returning the sum: /// `1`. /// 2. The closure is called again repeatedly with the previous call's return /// value and each element of the sequence. /// 3. When the sequence is exhausted, the last value returned from the /// closure is returned to the caller. /// /// If the sequence has no elements, `nextPartialResult` is never executed /// and `initialResult` is the result of the call to `reduce(_:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// `initialResult` is passed to `nextPartialResult` the first time the /// closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the sequence into a new accumulating value, to be used /// in the next call of the `nextPartialResult` closure or returned to /// the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) throws -> Result ) rethrows -> Result { var accumulator = initialResult for element in self { accumulator = try nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on an /// array of integers to filter adjacent equal entries or count frequencies. /// /// This method is preferred over `reduce(_:_:)` for efficiency when the /// result is a copy-on-write type, for example an Array or a Dictionary. /// /// The `updateAccumulatingResult` closure is called sequentially with a /// mutable accumulating value initialized to `initialResult` and each element /// of the sequence. This example shows how to build a dictionary of letter /// frequencies of a string. /// /// let letters = "abracadabra" /// let letterCount = letters.reduce(into: [:]) { counts, letter in /// counts[letter, default: 0] += 1 /// } /// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1] /// /// When `letters.reduce(into:_:)` is called, the following steps occur: /// /// 1. The `updateAccumulatingResult` closure is called with the initial /// accumulating value---`[:]` in this case---and the first character of /// `letters`, modifying the accumulating value by setting `1` for the key /// `"a"`. /// 2. The closure is called again repeatedly with the updated accumulating /// value and each element of the sequence. /// 3. When the sequence is exhausted, the accumulating value is returned to /// the caller. /// /// If the sequence has no elements, `updateAccumulatingResult` is never /// executed and `initialResult` is the result of the call to /// `reduce(into:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating /// value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( into initialResult: __owned Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) throws -> () ) rethrows -> Result { var accumulator = initialResult for element in self { try updateAccumulatingResult(&accumulator, element) } return accumulator } } //===----------------------------------------------------------------------===// // reversed() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the elements of this sequence in reverse /// order. /// /// The sequence must be finite. /// /// - Returns: An array containing the elements of this sequence in /// reverse order. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func reversed() -> [Element] { // FIXME(performance): optimize to 1 pass? But Array(self) can be // optimized to a memcpy() sometimes. Those cases are usually collections, // though. var result = Array(self) let count = result.count for i in 0..<count/2 { result.swapAt(i, count - ((i + 1) as Int)) } return result } } //===----------------------------------------------------------------------===// // flatMap() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the concatenated results of calling the /// given transformation with each element of this sequence. /// /// Use this method to receive a single-level collection when your /// transformation produces a sequence or collection for each element. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an array. /// /// let numbers = [1, 2, 3, 4] /// /// let mapped = numbers.map { Array(repeating: $0, count: $0) } /// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] /// /// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) } /// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] /// /// In fact, `s.flatMap(transform)` is equivalent to /// `Array(s.map(transform).joined())`. /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns a sequence or collection. /// - Returns: The resulting flattened array. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable public func flatMap<SegmentOfResult : Sequence>( _ transform: (Element) throws -> SegmentOfResult ) rethrows -> [SegmentOfResult.Element] { var result: [SegmentOfResult.Element] = [] for element in self { result.append(contentsOf: try transform(element)) } return result } } extension Sequence { /// Returns an array containing the non-`nil` results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of non-optional values when your /// transformation produces an optional value. /// /// In this example, note the difference in the result of using `map` and /// `compactMap` with a transformation that returns an optional `Int` value. /// /// let possibleNumbers = ["1", "2", "three", "///4///", "5"] /// /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) } /// // [1, 2, nil, nil, 5] /// /// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) } /// // [1, 2, 5] /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns an optional value. /// - Returns: An array of the non-`nil` results of calling `transform` /// with each element of the sequence. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable // protocol-only public func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try _compactMap(transform) } // The implementation of flatMap accepting a closure with an optional result. // Factored out into a separate functions in order to be used in multiple // overloads. @inlinable // protocol-only @inline(__always) public func _compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { var result: [ElementOfResult] = [] for element in self { if let newElement = try transform(element) { result.append(newElement) } } return result } }
apache-2.0
02094a24d83fcbb7e2bfab5f4f91541c
37.805134
83
0.600072
4.358585
false
false
false
false
LukaszLiberda/Swift-Design-Patterns
PatternProj/Examples/ChainOfResponsibilityPattern.swift
1
7386
// // ChainOfResponsibilityEx1.swift // // // Created by lukasz on 05/07/15. // // import UIKit import Swift import Foundation // Design Pattern // Behavioral /* --- Chain of responsibility delegates commands to a chain of processing objects. In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. In a variation of the standard chain-of-responsibility model, some handlers may act as dispatchers, capable of sending commands out in a variety of directions, forming a tree of responsibility. In some cases, this can occur recursively, with processing objects calling higher-up processing objects with commands that attempt to solve some smaller part of the problem; in this case recursion continues until the command is processed, or the entire tree has been explored. An XML interpreter might work in this manner. This pattern promotes the idea of loose coupling, which is considered a programming best practice. */ class MoneyCoin { let value: Int var quantity: Int var nextCoin: MoneyCoin? init(value: Int, quantity: Int, nextMoney: MoneyCoin?) { self.value = value self.quantity = quantity self.nextCoin = nextMoney } func canGiveTheChange(var v: Int) -> Bool { func canTakeBill(want: Int) -> Bool { return (want / self.value) > 0 } var q = self.quantity while canTakeBill(v) { if q == 0 { break } v -= self.value q -= 1 } if v == 0 { return true } else if let next = self.nextCoin { return next.canGiveTheChange(v) } return false } } class Wallet { private var hundred: MoneyCoin private var fifty: MoneyCoin private var twenty: MoneyCoin private var ten: MoneyCoin private var five: MoneyCoin private var startTheChange: MoneyCoin { return self.hundred } init(hundred: MoneyCoin, fifty: MoneyCoin, twenty: MoneyCoin, ten: MoneyCoin, five: MoneyCoin) { self.hundred = hundred self.fifty = fifty self.twenty = twenty self.ten = ten self.five = five } func canGiveTheChange(value: Int) -> String { return "Can give the change \(self.startTheChange.canGiveTheChange(value))" } } class TestChainOfResponsibility { func test() { let five = MoneyCoin(value: 5, quantity: 5, nextMoney: nil) let ten = MoneyCoin(value: 10, quantity: 3, nextMoney: five) let twenty = MoneyCoin(value: 20, quantity: 3, nextMoney: ten) let fifty = MoneyCoin(value: 50, quantity: 3, nextMoney: twenty) let hundred = MoneyCoin(value: 100, quantity: 3, nextMoney: fifty) var wallet = Wallet(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten, five: five) wallet.canGiveTheChange(575) wallet.canGiveTheChange(25) wallet.canGiveTheChange(229) wallet.canGiveTheChange(15) println() } func test2() { let cat1 = Category(name: "Chess") let cat2 = Category(name: "Watersports") var cell1 = ProductCell(product: cat1, backgroundColor: "") var cell2 = ProductCell(product: cat2, backgroundColor: "") var cell3 = ProductCell(product: nil, backgroundColor: "") CellFormatter.createChain().formatCell(cell1) CellFormatter.createChain().formatCell(cell2) CellFormatter.createChain().formatCell(cell3) println() } func test3() { var h1 = ConcreteHandler1() var h2 = ConcreteHandler2() var h3 = ConcreteHandler3() h1.successor = h2 h2.successor = h3 var requests: [Int] = [1, 2, 5, 7, 11, 13, 17, 19, 23, 29, 31]; for req in requests { h1.handlerRequest(req) } println() } } /* /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// next example */ class Category: NSObject { let catName: String init(name: String) { self.catName = name println("cat name: \(self.catName)") } } class ProductCell { var product: Category? var backgroundColor: String init(product: Category? = nil, backgroundColor: String) { self.product = product self.backgroundColor = backgroundColor println(product) println("cell p \(self.product?.catName)") } } class CellFormatter { var name: String var nextFormatter: CellFormatter? func formatCell(cell: ProductCell) { nextFormatter?.formatCell(cell) println(" name : \(cell.product?.catName)") } init(name: String) { self.name = name println("init cell \(name)") } class func createChain() -> CellFormatter { let formatter = ChessFormater(name: "ch1") formatter.nextFormatter = WatersportsFormatter(name: "wat1") formatter.nextFormatter?.nextFormatter = DefaultFormatter(name: "def1") return formatter } } class ChessFormater: CellFormatter { override func formatCell(cell: ProductCell) { if (cell.product?.catName == "Chess") { cell.backgroundColor = "color" } else { super.formatCell(cell) } println("cat name \(cell.product?.catName)") } } class WatersportsFormatter: CellFormatter { override func formatCell(cell: ProductCell) { if (cell.product?.catName == "Watersports") { cell.backgroundColor = "color" } else { super.formatCell(cell) } } } class DefaultFormatter: CellFormatter { override func formatCell(cell: ProductCell) { cell.backgroundColor = "color" } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Handler { var successor: Handler? func handlerRequest(request: Int) { } } class ConcreteHandler1: Handler { override func handlerRequest(request: Int) { if request >= 0 && request < 10 { println("\(self) handler request \(request)") } else if successor != nil { successor?.handlerRequest(request) } } } class ConcreteHandler2: Handler { override func handlerRequest(request: Int) { if request >= 10 && request < 20 { println("\(self) handler request \(request)") } else if successor != nil { successor?.handlerRequest(request) } } } class ConcreteHandler3: Handler { override func handlerRequest(request: Int) { if request >= 20 && request < 30 { println("\(self) handler request \(request)") } else if successor != nil { successor?.handlerRequest(request) } } }
gpl-2.0
81d535448efe53ca7209c1cb3b791b3f
26.977273
516
0.59342
4.659937
false
false
false
false
AngryLi/note-iOS
iOS/Demos/Assignments_swift/assignment-2-wechat/swift课堂/Smashtag/Smashtag/TweetTableViewCell.swift
6
1859
// // TweetTableViewCell.swift // Smashtag // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class TweetTableViewCell: UITableViewCell { var tweet: Tweet? { didSet { updateUI() } } @IBOutlet weak var tweetProfileImageView: UIImageView! @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var tweetCreatedLabel: UILabel! func updateUI() { // reset any existing tweet information tweetTextLabel?.attributedText = nil tweetScreenNameLabel?.text = nil tweetProfileImageView?.image = nil tweetCreatedLabel?.text = nil // load new information from our tweet (if any) if let tweet = self.tweet { tweetTextLabel?.text = tweet.text if tweetTextLabel?.text != nil { for _ in tweet.media { tweetTextLabel.text! += " 📷" } } tweetScreenNameLabel?.text = "\(tweet.user)" // tweet.user.description if let profileImageURL = tweet.user.profileImageURL { if let imageData = NSData(contentsOfURL: profileImageURL) { // blocks main thread! tweetProfileImageView?.image = UIImage(data: imageData) } } let formatter = NSDateFormatter() if NSDate().timeIntervalSinceDate(tweet.created) > 24*60*60 { formatter.dateStyle = NSDateFormatterStyle.ShortStyle } else { formatter.timeStyle = NSDateFormatterStyle.ShortStyle } tweetCreatedLabel?.text = formatter.stringFromDate(tweet.created) } } }
mit
f0b4ce10530f43d23d574e2e456d6255
30.457627
98
0.578664
5.52381
false
false
false
false
paulz/PerspectiveTransform
Example/PerspectiveTransform/Visual.playground/Sources/QuadrilateralCalc.swift
1
4169
import UIKit public class QuadrilateralCalc { public init() {} public var topLeft = CGPoint.zero public var topRight = CGPoint.zero public var bottomLeft = CGPoint.zero public var bottomRight = CGPoint.zero public func box() -> CGRect { let xmin = min(min(min(topRight.x, topLeft.x), bottomLeft.x), bottomRight.x) let ymin = min(min(min(topRight.y, topLeft.y), bottomLeft.y), bottomRight.y) let xmax = max(max(max(topRight.x, topLeft.x), bottomLeft.x), bottomRight.x) let ymax = max(max(max(topRight.y, topLeft.y), bottomLeft.y), bottomRight.y) return CGRect(origin: CGPoint(x: xmin, y: ymin), size: CGSize(width: xmax - xmin, height: ymax - ymin)) } public func modifyPoints(transform: (CGPoint) -> CGPoint) { topLeft = transform(topLeft) topRight = transform(topRight) bottomLeft = transform(bottomLeft) bottomRight = transform(bottomRight) } public func transformToFit(bounds: CGRect, anchorPoint: CGPoint) -> CATransform3D { let boundingBox = box() let frameTopLeft = boundingBox.origin let quad = QuadrilateralCalc() quad.topLeft = CGPoint(x: topLeft.x-frameTopLeft.x, y: topLeft.y-frameTopLeft.y) quad.topRight = CGPoint(x: topRight.x-frameTopLeft.x, y: topRight.y-frameTopLeft.y) quad.bottomLeft = CGPoint(x: bottomLeft.x-frameTopLeft.x, y: bottomLeft.y-frameTopLeft.y) quad.bottomRight = CGPoint(x: bottomRight.x-frameTopLeft.x, y: bottomRight.y-frameTopLeft.y) let transform = rectToQuad(rect: bounds, quad: quad) let anchorOffset = CGPoint(x: anchorPoint.x - boundingBox.origin.x, y: anchorPoint.y - boundingBox.origin.y) let transPos = CATransform3DMakeTranslation(anchorOffset.x, anchorOffset.y, 0) let transNeg = CATransform3DMakeTranslation(-anchorOffset.x, -anchorOffset.y, 0) let fullTransform = CATransform3DConcat(CATransform3DConcat(transPos, transform), transNeg) return fullTransform } public func rectToQuad(rect: CGRect, quad: QuadrilateralCalc) -> CATransform3D { let x1a = quad.topLeft.x let y1a = quad.topLeft.y let x2a = quad.topRight.x let y2a = quad.topRight.y let x3a = quad.bottomLeft.x let y3a = quad.bottomLeft.y let x4a = quad.bottomRight.x let y4a = quad.bottomRight.y let X = rect.origin.x let Y = rect.origin.y let W = rect.size.width let H = rect.size.height let y21 = y2a - y1a let y32 = y3a - y2a let y43 = y4a - y3a let y14 = y1a - y4a let y31 = y3a - y1a let y42 = y4a - y2a let a = -H*(x2a*x3a*y14 + x2a*x4a*y31 - x1a*x4a*y32 + x1a*x3a*y42) let b = W*(x2a*x3a*y14 + x3a*x4a*y21 + x1a*x4a*y32 + x1a*x2a*y43) let c = H*X*(x2a*x3a*y14 + x2a*x4a*y31 - x1a*x4a*y32 + x1a*x3a*y42) - H*W*x1a*(x4a*y32 - x3a*y42 + x2a*y43) - W*Y*(x2a*x3a*y14 + x3a*x4a*y21 + x1a*x4a*y32 + x1a*x2a*y43) let d = H*(-x4a*y21*y3a + x2a*y1a*y43 - x1a*y2a*y43 - x3a*y1a*y4a + x3a*y2a*y4a) let e = W*(x4a*y2a*y31 - x3a*y1a*y42 - x2a*y31*y4a + x1a*y3a*y42) let f1 = (x4a*(Y*y2a*y31 + H*y1a*y32) - x3a*(H + Y)*y1a*y42 + H*x2a*y1a*y43 + x2a*Y*(y1a - y3a)*y4a + x1a*Y*y3a*(-y2a + y4a)) let f2 = x4a*y21*y3a - x2a*y1a*y43 + x3a*(y1a - y2a)*y4a + x1a*y2a*(-y3a + y4a) let f = -(W*f1 - H*X*f2) let g = H*(x3a*y21 - x4a*y21 + (-x1a + x2a)*y43) let h = W*(-x2a*y31 + x4a*y31 + (x1a - x3a)*y42) let temp = X * (-x3a*y21 + x4a*y21 + x1a*y43 - x2a*y43) + W * (-x3a*y2a + x4a*y2a + x2a*y3a - x4a*y3a - x2a*y4a + x3a*y4a) var i = W * Y * (x2a*y31 - x4a*y31 - x1a*y42 + x3a*y42) + H * temp let kEpsilon = CGFloat(0.0001) if abs(i) < kEpsilon { i = kEpsilon * (i > 0 ? 1.0 : -1.0) } return CATransform3D(m11: a/i, m12: d/i, m13: 0, m14: g/i, m21: b/i, m22: e/i, m23: 0, m24: h/i, m31: 0, m32: 0, m33: 1, m34: 0, m41: c/i, m42: f/i, m43: 0, m44: 1.0) } }
mit
6d7858285f44a62c5f2ce83e2c6b49ec
41.979381
177
0.590789
2.628625
false
false
false
false
JoshHenderson/Flatline
Flatline/Response/BaseDataMapper/BaseResponseDataMapper.swift
1
2351
// // BaseResponseDataMapper.swift // Flatline // // Created by Joshua Henderson on 6/30/16. // Copyright © 2016 Joshua Henderson. All rights reserved. // import Foundation let defaultErrorDomain: String = "com.base.response.mapper.default.error" let defaultErrorCode: Int = 601 /** Protocol used to define ResponseDataMappers and how they are interacted with from the RequestManager. */ @objc (FLResponseDataMapperProtocol) public protocol ResponseDataMapperProtocol { optional static func parsedDictionaryFromData(data: NSData!, completion:(NSDictionary?, NSError?) -> ()) } /** Default ResponseDataMapper, will be used if no other DataMapper has been registered to the RequestManager */ @objc (FLBaseResponseDataMapper) public final class BaseResponseDataMapper : NSObject, ResponseDataMapperProtocol { /** Protocol defined method. Used to parse data from a JSON Response from NSData. Initially parses for an NSError object using the key 'error' from the base NSDictionary. This does not include HTTP Errors, as those have already been Vaidated in the RequestManager - Parameter data: Data received from the Request - Parameter completion: Closure to be executed on successful or un-successful Serialization of the NSData. Returns ParsedData or NSError */ public final func parsedDictionaryFromData(data: NSData!, completion:(NSDictionary?, NSError?) -> ()) { do { let parsedDict = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary if parsedDict.objectForKey("error") != nil { let error = NSError.init(domain: defaultErrorDomain, code: defaultErrorCode, userInfo: ["error" : parsedDict.objectForKey("error")!]) completion(parsedDict, error) return } completion(parsedDict, nil) } catch { let error = NSError.init(domain: defaultErrorDomain, code: defaultErrorCode, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("Could not Convert Data", comment: "")]) completion(nil, error) } } }
mit
940c11c56c199e37c6a69497bd77b06c
42.537037
189
0.65234
5.427252
false
false
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/Operators.swift
13
13944
// // Operators.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // Copyright (c) 2014 hearst. All rights reserved. // /** * This file defines a new operator which is used to create a mapping between an object and a JSON key value. * There is an overloaded operator definition for each type of object that is supported in ObjectMapper. * This provides a way to add custom logic to handle specific types of objects */ infix operator <- {} // MARK:- Objects with Basic types /// Object of Basic type public func <- <T>(inout left: T, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.basicType(&left, object: right.value()) } else { ToJSON.basicType(left, map: right) } } /// Optional object of basic type public func <- <T>(inout left: T?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalBasicType(&left, object: right.value()) } else { ToJSON.optionalBasicType(left, map: right) } } /// Implicitly unwrapped optional object of basic type public func <- <T>(inout left: T!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalBasicType(&left, object: right.value()) } else { ToJSON.optionalBasicType(left, map: right) } } // MARK:- Raw Representable types /// Object of Raw Representable type public func <- <T: RawRepresentable>(inout left: T, right: Map) { left <- (right, EnumTransform()) } /// Optional Object of Raw Representable type public func <- <T: RawRepresentable>(inout left: T?, right: Map) { left <- (right, EnumTransform()) } /// Implicitly Unwrapped Optional Object of Raw Representable type public func <- <T: RawRepresentable>(inout left: T!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Arrays of Raw Representable type /// Array of Raw Representable object public func <- <T: RawRepresentable>(inout left: [T], right: Map) { left <- (right, EnumTransform()) } /// Array of Raw Representable object public func <- <T: RawRepresentable>(inout left: [T]?, right: Map) { left <- (right, EnumTransform()) } /// Array of Raw Representable object public func <- <T: RawRepresentable>(inout left: [T]!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Dictionaries of Raw Representable type /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(inout left: [String: T], right: Map) { left <- (right, EnumTransform()) } /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(inout left: [String: T]?, right: Map) { left <- (right, EnumTransform()) } /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(inout left: [String: T]!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Transforms /// Object of Basic type with Transform public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { let value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.basicType(&left, object: value) } else { let value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, map: right.0) } } /// Optional object of basic type with Transform public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T?, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { let value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.optionalBasicType(&left, object: value) } else { let value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, map: right.0) } } /// Implicitly unwrapped optional object of basic type with Transform public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T!, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { let value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.optionalBasicType(&left, object: value) } else { let value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, map: right.0) } } /// Array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object], right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) FromJSON.basicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, map: map) } } /// Optional array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object]?, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, map: map) } } /// Implicitly unwrapped optional array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object]!, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, map: map) } } /// Dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object], right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) FromJSON.basicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, map: map) } } /// Optional dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object]?, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, map: map) } } /// Implicitly unwrapped optional dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object]!, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, map: map) } } private func fromJSONArrayWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [T.Object] { if let values = input as? [AnyObject] { return values.flatMap { value in return transform.transformFromJSON(value) } } else { return [] } } private func fromJSONDictionaryWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [String: T.Object] { if let values = input as? [String: AnyObject] { return values.filterMap { value in return transform.transformFromJSON(value) } } else { return [:] } } private func toJSONArrayWithTransform<T: TransformType>(input: [T.Object]?, transform: T) -> [T.JSON]? { return input?.flatMap { value in return transform.transformToJSON(value) } } private func toJSONDictionaryWithTransform<T: TransformType>(input: [String: T.Object]?, transform: T) -> [String: T.JSON]? { return input?.filterMap { value in return transform.transformToJSON(value) } } // MARK:- Mappable Objects - <T: Mappable> /// Object conforming to Mappable public func <- <T: Mappable>(inout left: T, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.object(&left, object: right.currentValue) } else { ToJSON.object(left, map: right) } } /// Optional Mappable objects public func <- <T: Mappable>(inout left: T?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObject(&left, object: right.currentValue) } else { ToJSON.optionalObject(left, map: right) } } /// Implicitly unwrapped optional Mappable objects public func <- <T: Mappable>(inout left: T!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObject(&left, object: right.currentValue) } else { ToJSON.optionalObject(left, map: right) } } // MARK:- Dictionary of Mappable objects - Dictionary<String, T: Mappable> /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectDictionary(&left, object: right.currentValue) } else { ToJSON.objectDictionary(left, map: right) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionary(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionary(left, map: right) } } /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionary(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionary(left, map: right) } } /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, [T]>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectDictionaryOfArrays(&left, object: right.currentValue) } else { ToJSON.objectDictionaryOfArrays(left, map: right) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, [T]>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionaryOfArrays(left, map: right) } } /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, [T]>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionaryOfArrays(left, map: right) } } // MARK:- Array of Mappable objects - Array<T: Mappable> /// Array of Mappable objects public func <- <T: Mappable>(inout left: Array<T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectArray(&left, object: right.currentValue) } else { ToJSON.objectArray(left, map: right) } } /// Optional array of Mappable objects public func <- <T: Mappable>(inout left: Array<T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, map: right) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: Mappable>(inout left: Array<T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, map: right) } } // MARK:- Array of Array of Mappable objects - Array<Array<T: Mappable>> /// Array of Array Mappable objects public func <- <T: Mappable>(inout left: Array<Array<T>>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.twoDimensionalObjectArray(&left, object: right.currentValue) } else { ToJSON.twoDimensionalObjectArray(left, map: right) } } /// Optional array of Mappable objects public func <- <T: Mappable>(inout left:Array<Array<T>>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalTwoDimensionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalTwoDimensionalObjectArray(left, map: right) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: Mappable>(inout left: Array<Array<T>>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalTwoDimensionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalTwoDimensionalObjectArray(left, map: right) } } // MARK:- Set of Mappable objects - Set<T: Mappable where T: Hashable> /// Array of Mappable objects public func <- <T: Mappable where T: Hashable>(inout left: Set<T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectSet(&left, object: right.currentValue) } else { ToJSON.objectSet(left, map: right) } } /// Optional array of Mappable objects public func <- <T: Mappable where T: Hashable>(inout left: Set<T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectSet(&left, object: right.currentValue) } else { ToJSON.optionalObjectSet(left, map: right) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: Mappable where T: Hashable>(inout left: Set<T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectSet(&left, object: right.currentValue) } else { ToJSON.optionalObjectSet(left, map: right) } }
mit
652f442a75d1256944ade54a5303c6d5
33.260442
125
0.714931
3.909167
false
false
false
false
ZwxWhite/V2EX
V2EX/V2EX/Class/Expand/Tools/DateTool.swift
1
1001
// // DateTool.swift // V2EX // // Created by wenxuan.zhang on 15/11/17. // Copyright © 2015年 张文轩. All rights reserved. // import SwiftDate public func relationshipOfDate(firstDate: NSDate, anotherDate: NSDate) -> String { let second = firstDate.timeIntervalSinceDate(anotherDate) let minite = second / 60 let hour = minite / 60 let day = hour / 24 if minite < 60.0 { if (minite < 1.0) { return "刚刚" } return String(Int(minite)) + "分钟前" } if hour < 24.0 { return String(Int(hour)) + "小时前" } if day < 7.0 { return String(Int(day)) + "天前" } return dateStringWith(anotherDate) } public func dateStringWith(date: NSDate) -> String { let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") dateFormatter.dateFormat = "yyyy年MM月dd日" return dateFormatter.stringFromDate(date) }
mit
fac2c6be5120c1065b042ce24a8574e3
16.888889
82
0.60559
3.715385
false
false
false
false
muhlenXi/SwiftEx
projects/AudioDemo/AudioDemo/AudioPlayerViewController.swift
1
1503
// // AudioPlayerViewController.swift // AudioDemo // // Created by 席银军 on 2017/9/4. // Copyright © 2017年 muhlenXi. All rights reserved. // import UIKit import AVFoundation class AudioPlayerViewController: UIViewController { var player: AVAudioPlayer? = nil var timer: Timer? = nil let musicName = "刀郎 - 西海情歌" override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = musicName } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Event responnse @IBAction func playAction(_ sender: Any) { if let musicPath = Bundle.main.path(forResource: musicName, ofType: "mp3") { let url = URL(fileURLWithPath: musicPath) do { try player = AVAudioPlayer(contentsOf: url) player!.play() } catch { } } } /* // 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
0b52d070b971c793e14158199ba13c32
22.15625
106
0.571525
4.956522
false
false
false
false
413738916/ZhiBoTest
ZhiBoSwift/Pods/Kingfisher/Sources/AnimatedImageView.swift
33
13294
// // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2017 Reda Lemeden. // // 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. // // The name and characters used in the demo of this software are property of their // respective owners. import UIKit import ImageIO /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. open class AnimatedImageView: UIImageView { /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrame() } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is true. public var autoPlayAnimatedImage = true /// The size of the frame cache. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. public var needsPrescaling = true /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. public var runLoopMode = RunLoopMode.commonModes { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } } // MARK: - Private property /// `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D private var isDisplayLinkInitialized: Bool = false /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: self.runLoopMode) displayLink.isPaused = true return displayLink }() // MARK: - Override override open var image: Image? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } deinit { if isDisplayLinkInitialized { displayLink.invalidate() } } override open var isAnimating: Bool { if isDisplayLinkInitialized { return !displayLink.isPaused } else { return super.isAnimating } } /// Starts the animation. override open func startAnimating() { if self.isAnimating { return } else { displayLink.isPaused = false } } /// Stops the animation. override open func stopAnimating() { super.stopAnimating() if isDisplayLinkInitialized { displayLink.isPaused = true } } override open func display(_ layer: CALayer) { if let currentFrame = animator?.currentFrame { layer.contents = currentFrame.cgImage } else { layer.contents = image?.cgImage } } override open func didMoveToWindow() { super.didMoveToWindow() didMove() } override open func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular UIImageView to show animated image. override func shouldPreloadAllAnimation() -> Bool { return false } // MARK: - Private method /// Reset the animator. private func reset() { animator = nil if let imageSource = image?.kf.imageSource?.imageRef { animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount) animator?.needsPrescaling = needsPrescaling animator?.prepareFramesAsynchronously() } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, let _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrame() { let duration: CFTimeInterval // CA based display link is opt-out from ProMotion by default. // So the duration and its FPS might not match. // See [#718](https://github.com/onevcat/Kingfisher/issues/718) if #available(iOS 10.0, tvOS 10.0, *) { // By setting CADisableMinimumFrameDuration to YES in Info.plist may // cause the preferredFramesPerSecond being 0 if displayLink.preferredFramesPerSecond == 0 { duration = displayLink.duration } else { // Some devices (like iPad Pro 10.5) will have a different FPS. duration = 1.0 / Double(displayLink.preferredFramesPerSecond) } } else { duration = displayLink.duration } if animator?.updateCurrentFrame(duration: duration) ?? false { layer.setNeedsDisplay() } } } /// Keeps a reference to an `Image` instance and its duration as a GIF frame. struct AnimatedFrame { var image: Image? let duration: TimeInterval static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0) } // MARK: - Animator class Animator { // MARK: Private property fileprivate let size: CGSize fileprivate let maxFrameCount: Int fileprivate let imageSource: CGImageSource fileprivate var animatedFrames = [AnimatedFrame]() fileprivate let maxTimeStep: TimeInterval = 1.0 fileprivate var frameCount = 0 fileprivate var currentFrameIndex = 0 fileprivate var currentPreloadIndex = 0 fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0 fileprivate var needsPrescaling = true /// Loop count of animated image. private var loopCount = 0 var currentFrame: UIImage? { return frame(at: currentFrameIndex) } var contentMode = UIViewContentMode.scaleToFill private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() /** Init an animator with image source reference. - parameter imageSource: The reference of animated image. - parameter contentMode: Content mode of AnimatedImageView. - parameter size: Size of AnimatedImageView. - parameter framePreloadCount: Frame cache size. - returns: The animator object. */ init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) { self.imageSource = source self.contentMode = mode self.size = size self.maxFrameCount = count } func frame(at index: Int) -> Image? { return animatedFrames[safe: index]?.image } func prepareFramesAsynchronously() { preloadQueue.async { [weak self] in self?.prepareFrames() } } private func prepareFrames() { frameCount = CGImageSourceGetCount(imageSource) if let properties = CGImageSourceCopyProperties(imageSource, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int { self.loopCount = loopCount } let frameToProcess = min(frameCount, maxFrameCount) animatedFrames.reserveCapacity(frameToProcess) animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))} currentPreloadIndex = (frameToProcess + 1) % frameCount } private func prepareFrame(at index: Int) -> AnimatedFrame { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return AnimatedFrame.null } let defaultGIFFrameDuration = 0.100 let frameDuration = imageSource.kf.gifProperties(at: index).map { gifInfo -> Double in let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? let duration = unclampedDelayTime ?? delayTime ?? 0.0 /** http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ return duration > 0.011 ? duration : defaultGIFFrameDuration } ?? defaultGIFFrameDuration let image = Image(cgImage: imageRef) let scaledImage: Image? if needsPrescaling { scaledImage = image.kf.resize(to: size, for: contentMode) } else { scaledImage = image } return AnimatedFrame(image: scaledImage, duration: frameDuration) } /** Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. */ func updateCurrentFrame(duration: CFTimeInterval) -> Bool { timeSinceLastFrameChange += min(maxTimeStep, duration) guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else { return false } timeSinceLastFrameChange -= frameDuration let lastFrameIndex = currentFrameIndex currentFrameIndex += 1 currentFrameIndex = currentFrameIndex % animatedFrames.count if animatedFrames.count < frameCount { preloadFrameAsynchronously(at: lastFrameIndex) } return true } private func preloadFrameAsynchronously(at index: Int) { preloadQueue.async { [weak self] in self?.preloadFrame(at: index) } } private func preloadFrame(at index: Int) { animatedFrames[index] = prepareFrame(at: currentPreloadIndex) currentPreloadIndex += 1 currentPreloadIndex = currentPreloadIndex % frameCount } } extension CGImageSource: KingfisherCompatible { } extension Kingfisher where Base: CGImageSource { func gifProperties(at index: Int) -> [String: Double]? { let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary? return properties?[kCGImagePropertyGIFDictionary] as? [String: Double] } } extension Array { subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } private func pure<T>(_ value: T) -> [T] { return [value] }
mit
3606770fd7a57316b53a630623d8a57f
34.640751
184
0.640289
5.360484
false
false
false
false
aslanyanhaik/youtube-iOS
YouTube/Model/User.swift
1
2746
// MIT License // Copyright (c) 2017 Haik Aslanyan // 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 UIKit class User { //MARK: Properties let name: String let profilePic: UIImage let backgroundImage: UIImage var playlists = [Playlist]() //MARK: Methods class func fetchData(completion: @escaping ((User) -> Void)) { //Dummy Data let data = ["pl-swift": "Swift Tutorials", "pl-node": "NodeJS Tutorials", "pl-javascript": "JavaScript ES6 / ES2015 Tutorials", "pl-angular": "Angular 2 Tutorials", "pl-rest": "REST API Tutorials (Node, Express & Mongo)", "pl-react": "React development", "pl-mongo": "Mongo db"] let user = User.init(name: "Haik Aslanyan", profilePic: UIImage.init(named: "profilePic")!, backgroundImage: UIImage.init(named: "banner")!, playlists: [Playlist]()) for (key, value) in data { let image = UIImage.init(named: key) let name = value let playlist = Playlist.init(pic: image!, title: name, numberOfVideos: Int(arc4random_uniform(50))) user.playlists.append(playlist) } completion(user) } //MARK: Inits init(name: String, profilePic: UIImage, backgroundImage: UIImage, playlists: Array<Playlist>) { self.profilePic = profilePic self.backgroundImage = backgroundImage self.playlists = playlists self.name = name } } struct Playlist { let pic: UIImage let title: String let numberOfVideos: Int init(pic: UIImage, title: String, numberOfVideos: Int) { self.pic = pic self.title = title self.numberOfVideos = numberOfVideos } }
mit
a66a7f51b22958765b23da2133c9930f
39.382353
286
0.682083
4.290625
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/PostContentPresentationAnimator.swift
1
7952
// // PostContentPresentationAnimator.swift // Slide for Reddit // // Created by Jonathan Cole on 8/3/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import AVFoundation import UIKit final class PostContentPresentationAnimator: NSObject { // MARK: - Properties let isPresentation: Bool let sourceImageView: UIView // MARK: - Initializers init(isPresentation: Bool, sourceImageView: UIView) { self.isPresentation = isPresentation self.sourceImageView = sourceImageView super.init() } } extension PostContentPresentationAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration( using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } private func transformFromRect(from source: CGRect, toRect destination: CGRect) -> CGAffineTransform { return CGAffineTransform.identity .translatedBy(x: destination.midX - source.midX, y: destination.midY - source.midY) .scaledBy(x: destination.width / source.width, y: destination.height / source.height) } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from let animationDuration = transitionDuration(using: transitionContext) let controller = transitionContext.viewController(forKey: key)! if isPresentation { transitionContext.containerView.addSubview(controller.view) } let presentingViewController = transitionContext.viewController(forKey: .from)! let presentedViewController = transitionContext.viewController(forKey: .to)! // Animate picture if let vc = presentedViewController as? ModalMediaViewController { let fromRect = vc.view.convert(sourceImageView.bounds, from: sourceImageView) if let embeddedVC = vc.embeddedVC as? ImageMediaViewController { presentingViewController.view.layoutIfNeeded() let inner = AVMakeRect(aspectRatio: embeddedVC.imageView.bounds.size, insideRect: embeddedVC.view.bounds) let toRect = vc.view.convert(inner, from: embeddedVC.scrollView) let newTransform = transformFromRect(from: toRect, toRect: fromRect) embeddedVC.scrollView.transform = embeddedVC.scrollView.transform.concatenating(newTransform) let storedZ = embeddedVC.scrollView.layer.zPosition embeddedVC.scrollView.layer.zPosition = sourceImageView.layer.zPosition UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: { embeddedVC.scrollView.transform = CGAffineTransform.identity embeddedVC.scrollView.layer.zPosition = storedZ }) } else if let embeddedVC = vc.embeddedVC as? VideoMediaViewController { if embeddedVC.isYoutubeView { } else { presentingViewController.view.layoutIfNeeded() let translatedView = embeddedVC.progressView.isHidden ? embeddedVC.videoView : embeddedVC.progressView let inner = AVMakeRect(aspectRatio: translatedView.bounds.size, insideRect: embeddedVC.view.bounds) let toRect = vc.view.convert(inner, from: embeddedVC.view) let newTransform = transformFromRect(from: toRect, toRect: fromRect) let storedZ = translatedView.layer.zPosition translatedView.layer.zPosition = sourceImageView.layer.zPosition translatedView.transform = translatedView.transform.concatenating(newTransform) UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: { translatedView.transform = CGAffineTransform.identity translatedView.layer.zPosition = storedZ }, completion: nil) } } } else if let vc = presentedViewController as? AnyModalViewController { let fromRect = vc.view.convert(sourceImageView.bounds, from: sourceImageView) vc.view.layoutIfNeeded() let translatedView = vc.videoView! let inner = AVMakeRect(aspectRatio: translatedView.bounds.size, insideRect: vc.view.bounds) let toRect = vc.view.convert(inner, from: vc.view) let newTransform = transformFromRect(from: toRect, toRect: fromRect) let storedZ = translatedView.layer.zPosition translatedView.layer.zPosition = sourceImageView.layer.zPosition translatedView.transform = translatedView.transform.concatenating(newTransform) UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: { translatedView.transform = CGAffineTransform.identity translatedView.layer.zPosition = storedZ }, completion: nil) } // Animate alpha var isVideo = false if let vc = controller as? ModalMediaViewController, vc.embeddedVC is VideoMediaViewController { isVideo = true } if presentedViewController is AnyModalViewController { isVideo = true } let initialAlpha: CGFloat = isPresentation ? 0.0 : 1.0 //Assume 1, now that photos and videos have black backgrounds let finalAlpha: CGFloat = isPresentation ? 1.0 : 0.0 // Use a special animation chain for certain types of presenting VCs if let vc = controller as? ModalMediaViewController, let embed = vc.embeddedVC { vc.background?.alpha = initialAlpha vc.blurView?.alpha = initialAlpha vc.closeButton.alpha = initialAlpha embed.bottomButtons.alpha = initialAlpha UIView.animate(withDuration: animationDuration, animations: { vc.background?.alpha = finalAlpha vc.blurView?.alpha = 1 vc.closeButton.alpha = 1 embed.bottomButtons.alpha = 1 }, completion: { finished in transitionContext.completeTransition(finished) }) } else if presentedViewController is AnyModalViewController { (presentedViewController as! AnyModalViewController).background?.alpha = initialAlpha (presentedViewController as! AnyModalViewController).blurView?.alpha = initialAlpha UIView.animate(withDuration: animationDuration, animations: { (presentedViewController as! AnyModalViewController).background?.alpha = finalAlpha (presentedViewController as! AnyModalViewController).blurView?.alpha = 1 }, completion: { finished in transitionContext.completeTransition(finished) }) } else { controller.view.alpha = initialAlpha UIView.animate(withDuration: animationDuration, animations: { controller.view.alpha = 1 }, completion: { finished in transitionContext.completeTransition(finished) }) } } }
apache-2.0
03dd4c75f407c5834b406b76a34aed6d
46.327381
174
0.630738
6.285375
false
false
false
false
WJachowicz/TableViewDemo
TableViewDemo/AnimalDetailsViewController.swift
1
1525
// // AnimalDetailsViewController.swift // TableViewDemo // // Created by Wojciech Jachowicz on 03.06.2014. // Copyright (c) 2014 Wojciech Jachowicz. All rights reserved. // import UIKit class AnimalDetailsViewController: UIViewController { var animalName : String var boshLabel : UILabel init(animalName : String) { self.animalName = animalName self.boshLabel = UILabel(); self.boshLabel.setTranslatesAutoresizingMaskIntoConstraints(false) self.boshLabel.textColor = UIColor.blackColor() super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { self.title = animalName self.boshLabel.text = "Bosh!\nYou've just selected \(self.animalName) in your first Swift app!" self.boshLabel.textAlignment = NSTextAlignment.Center self.boshLabel.numberOfLines = 0 self.boshLabel.preferredMaxLayoutWidth = 200.0 self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.boshLabel) self.view.addConstraint(NSLayoutConstraint(item: self.boshLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.boshLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)) } }
mit
1f8c43493cd80832c49183f31bb8bba1
41.361111
235
0.717377
4.593373
false
false
false
false
bwhiteley/EnumTable
EnumTable/ViewModel.swift
1
2053
import UIKit enum Row { case Twitter, Facebook, Instagram, Contact, Settings case FirstName(String) case LastName(String) var displayName:String { switch self { case .Twitter: return NSLocalizedString("Twitter", comment:"") case .Facebook: return NSLocalizedString("Facebook", comment:"") case .Instagram: return NSLocalizedString("Instagram", comment:"") case .Contact: return NSLocalizedString("Contact us", comment:"") case .Settings: return NSLocalizedString("Advanced Settings", comment:"") case let .FirstName(name): return name case let .LastName(name): return name } } var icon:UIImage? { let assetId:UIImage.AssetIdentifier switch self { case .Twitter: assetId = .Twitter case .Facebook: assetId = .Facebook case .Instagram: assetId = .Instagram case .Contact: assetId = .Phone case .Settings: assetId = .Gear case .FirstName: assetId = .User case .LastName: assetId = .User } return UIImage(assetIdentifier: assetId) } var URL:String? { switch self { case .Twitter: return "http://twitter.com" case .Facebook: return "http://facebook.com" case .Instagram: return "http://instagram.com" default: return nil } } } class TableViewModel { // These are the sections. An array of tuples with the section titles and section rows. let schema:[(sectionTitle:String, rows:[Row])] = [ (NSLocalizedString("Social", comment:""), [.Facebook, .Instagram, .Twitter]), (NSLocalizedString("Other", comment:""), [.Contact, .Settings]), (NSLocalizedString("About You", comment:""), [.FirstName("John"), .LastName("Appleseed")])] }
mit
26dd37082b9158090ddd0c2968e5a94d
26.026316
99
0.54944
5.184343
false
false
false
false
samantharachelb/todolist
Pods/OctoKit.swift/OctoKit/PullRequest.swift
1
7524
import Foundation import RequestKit @objc open class PullRequest: NSObject { open var id: Int open var url: URL? open var htmlURL: URL? open var diffURL: URL? open var patchURL: URL? open var issueURL: URL? open var commitsURL: URL? open var reviewCommentsURL: URL? open var reviewCommentURL: URL? open var commentsURL: URL? open var statusesURL: URL? open var number: Int? open var state: Openness? open var title: String? open var body: String? open var assignee: User? open var milestone: Milestone? open var locked: Bool? open var createdAt: Date? open var updatedAt: Date? open var closedAt: Date? open var mergedAt: Date? open var user: User? public init(_ json: [String: AnyObject]) { if let id = json["id"] as? Int { self.id = id if let urlString = json["url"] as? String, let url = URL(string: urlString) { self.url = url } if let diffURL = json["diff_url"] as? String, let url = URL(string: diffURL) { self.diffURL = url } if let patchURL = json["patch_url"] as? String, let url = URL(string: patchURL) { self.patchURL = url } if let issueURL = json["issue_url"] as? String, let url = URL(string: issueURL) { self.patchURL = url } if let commitsURL = json["commits_url"] as? String, let url = URL(string: commitsURL) { self.commitsURL = url } if let reviewCommentsURL = json["review_comments_url"] as? String, let url = URL(string: reviewCommentsURL) { self.reviewCommentsURL = url } if let reviewCommentURL = json["review_comment_url"] as? String, let url = URL(string: reviewCommentURL) { self.reviewCommentURL = url } if let commentsURL = json["comments_url"] as? String, let url = URL(string: commentsURL) { self.commentsURL = url } if let statusesURL = json["statuses_url"] as? String, let url = URL(string: statusesURL) { self.statusesURL = url } number = json["number"] as? Int state = Openness(rawValue: json["state"] as? String ?? "") title = json["title"] as? String body = json["body"] as? String assignee = User(json["assignee"] as? [String: AnyObject] ?? [:]) milestone = Milestone(json["milestone"] as? [String: AnyObject] ?? [:]) locked = json["locked"] as? Bool closedAt = Time.rfc3339Date(json["closed_at"] as? String) createdAt = Time.rfc3339Date(json["created_at"] as? String) updatedAt = Time.rfc3339Date(json["updated_at"] as? String) mergedAt = Time.rfc3339Date(json["merged_at"] as? String) } else { id = -1 } } } // MARK: Request public extension Octokit { /** Get a single pull request - parameter session: RequestKitURLSession, defaults to NSURLSession.sharedSession() - parameter owner: The user or organization that owns the repositories. - parameter repository: The name of the repository. - parameter number: The number of the PR to fetch. - parameter completion: Callback for the outcome of the fetch. */ public func pullRequest(_ session: RequestKitURLSession = URLSession.shared, owner: String, repository: String, number: Int, completion: @escaping (_ response: Response<PullRequest>) -> Void) -> URLSessionDataTaskProtocol? { let router = PullRequestRouter.readPullRequest(configuration, owner, repository, "\(number)") return router.loadJSON(session, expectedResultType: [String: AnyObject].self) { json, error in if let error = error { completion(Response.failure(error)) } else { if let json = json { let parsedPullRequest = PullRequest(json) completion(Response.success(parsedPullRequest)) } } } } /** Get a list of pull requests - parameter session: RequestKitURLSession, defaults to NSURLSession.sharedSession() - parameter owner: The user or organization that owns the repositories. - parameter repository: The name of the repository. - parameter base: Filter pulls by base branch name. - parameter state: Filter pulls by their state. - parameter direction: The direction of the sort. - parameter completion: Callback for the outcome of the fetch. */ public func pullRequests(_ session: RequestKitURLSession = URLSession.shared, owner: String, repository: String, base: String? = nil, state: Openness = .Open, sort: SortType = .created, direction: SortDirection = .desc, completion: @escaping (_ response: Response<[PullRequest]>) -> Void) -> URLSessionDataTaskProtocol? { let router = PullRequestRouter.readPullRequests(configuration, owner, repository, base, state, sort, direction) return router.loadJSON(session, expectedResultType: [[String: AnyObject]].self) { json, error in if let error = error { completion(Response.failure(error)) } else { if let json = json { let parsedPullRequest = json.map { PullRequest($0) } completion(Response.success(parsedPullRequest)) } } } } } // MARK: Router enum PullRequestRouter: JSONPostRouter { case readPullRequest(Configuration, String, String, String) case readPullRequests(Configuration, String, String, String?, Openness, SortType, SortDirection) var method: HTTPMethod { switch self { case .readPullRequest, .readPullRequests: return .GET } } var encoding: HTTPEncoding { switch self { default: return .url } } var configuration: Configuration { switch self { case .readPullRequest(let config, _, _, _): return config case .readPullRequests(let config, _, _, _, _, _, _): return config } } var params: [String: Any] { switch self { case .readPullRequest(_, _, _, _): return [:] case .readPullRequests(_, _, _, let base, let state, let sort, let direction): var parameters = [ "state": state.rawValue, "sort": sort.rawValue, "direction": direction.rawValue ] if let base = base { parameters["base"] = base } return parameters } } var path: String { switch self { case .readPullRequest(_, let owner, let repository, let number): return "repos/\(owner)/\(repository)/pulls/\(number)" case .readPullRequests(_, let owner, let repository, _, _, _, _): return "repos/\(owner)/\(repository)/pulls" } } }
mit
c423ee51301a43b08047aa393ad53d96
35.347826
130
0.556486
4.847938
false
false
false
false
zisko/swift
stdlib/public/SDK/Foundation/JSONEncoder.swift
1
109956
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // JSON Encoder //===----------------------------------------------------------------------===// /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON. open class JSONEncoder { // MARK: Options /// The formatting of the output JSON data. public struct OutputFormatting : OptionSet { /// The format's default value. public let rawValue: UInt /// Creates an OutputFormatting value with the given raw value. public init(rawValue: UInt) { self.rawValue = rawValue } /// Produce human-readable JSON with indented output. public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0) /// Produce JSON with dictionary keys sorted in lexicographic order. @available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static let sortedKeys = OutputFormatting(rawValue: 1 << 1) } /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a JSON number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before encoding. public enum KeyEncodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload. /// /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the result. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String { guard stringKey.count > 0 else { return stringKey } var words : [Range<String.Index>] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex // Find next uppercase character while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map({ (range) in return stringKey[range].lowercased() }).joined(separator: "_") return result } } /// The output format to produce. Defaults to `[]`. open var outputFormatting: OutputFormatting = [] /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let keyEncodingStrategy: KeyEncodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, keyEncodingStrategy: keyEncodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its JSON representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded JSON data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T : Encodable>(_ value: T) throws -> Data { let encoder = _JSONEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } if topLevel is NSNull { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment.")) } else if topLevel is NSNumber { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment.")) } else if topLevel is NSString { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment.")) } let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue) do { return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions) } catch { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error)) } } } // MARK: - _JSONEncoder fileprivate class _JSONEncoder : Encoder { // MARK: Properties /// The encoder's storage. fileprivate var storage: _JSONEncodingStorage /// Options set on the top-level encoder. fileprivate let options: JSONEncoder._Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) { self.options = options self.storage = _JSONEncodingStorage() self.codingPath = codingPath } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } // MARK: - Encoding Storage and Containers fileprivate struct _JSONEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } fileprivate mutating func push(container: NSObject) { self.containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations private func _converted(_ key: CodingKey) -> CodingKey { switch encoder.options.keyEncodingStrategy { case .useDefaultKeys: return key case .convertToSnakeCase: let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue) return _JSONKey(stringValue: newKeyString, intValue: key.intValue) case .custom(let converter): return converter(codingPath + [key]) } } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { self.container[_converted(key).stringValue] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func encode(_ value: Double, forKey key: Key) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container[_converted(key).stringValue] = dictionary self.codingPath.append(key) defer { self.codingPath.removeLast() } let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() self.container[_converted(key).stringValue] = array self.codingPath.append(key) defer { self.codingPath.removeLast() } return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container) } } fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return self.container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { self.container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode(_ value: Double) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode<T : Encodable>(_ value: T) throws { self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let dictionary = NSMutableDictionary() self.container.add(dictionary) let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let array = NSMutableArray() self.container.add(array) return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension _JSONEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods fileprivate func assertCanEncodeNewValue() { precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() self.storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } } // MARK: - Concrete Value Representations extension _JSONEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ float: Float) throws -> NSObject { guard !float.isInfinite && !float.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(float, at: codingPath) } if float == Float.infinity { return NSString(string: posInfString) } else if float == -Float.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: float) } fileprivate func box(_ double: Double) throws -> NSObject { guard !double.isInfinite && !double.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(double, at: codingPath) } if double == Double.infinity { return NSString(string: posInfString) } else if double == -Double.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: double) } fileprivate func box(_ date: Date) throws -> NSObject { switch self.options.dateEncodingStrategy { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. // Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count do { try closure(date, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { switch self.options.dataEncodingStrategy { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. let depth = self.storage.count do { try data.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. // This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count do { try closure(data, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject { return try self.box_(value) ?? NSDictionary() } // This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want. fileprivate func box_<T : Encodable>(_ value: T) throws -> NSObject? { if T.self == Date.self || T.self == NSDate.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if T.self == Data.self || T.self == NSData.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if T.self == URL.self || T.self == NSURL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { // JSONSerialization can natively handle NSDecimalNumber. return (value as! NSDecimalNumber) } // The value should request a container from the _JSONEncoder. let depth = self.storage.count do { try value.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } } // MARK: - _JSONReferencingEncoder /// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). fileprivate class _JSONReferencingEncoder : _JSONEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. fileprivate let encoder: _JSONEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_JSONKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, key: CodingKey, convertedKey: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, convertedKey.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // JSON Decoder //===----------------------------------------------------------------------===// /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types. open class JSONDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a JSON number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a JSON number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Date) } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before decoding. public enum KeyDecodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type. /// /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from snake case to camel case: /// 1. Capitalizes the word starting after each `_` /// 2. Removes all `_` /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. /// /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character. case convertFromSnakeCase /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types. /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character guard let firstNonUnderscore = stringKey.index(where: { $0 != "_" }) else { // Reached the end without finding an _ return stringKey } // Find the last non-underscore character var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { stringKey.formIndex(before: &lastNonUnderscore); } let keyRange = firstNonUnderscore...lastNonUnderscore let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex var components = stringKey[keyRange].split(separator: "_") let joinedString : String if components.count == 1 { // No underscores in key, leave the word as is - maybe already camel cased joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result : String if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) { result = joinedString } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) { // Both leading and trailing underscores result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange]) } else if (!leadingUnderscoreRange.isEmpty) { // Just leading result = String(stringKey[leadingUnderscoreRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingUnderscoreRange]) } return result } } /// The strategy to use in decoding dates. Defaults to `.deferredToDate`. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let keyDecodingStrategy: KeyDecodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, keyDecodingStrategy: keyDecodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given JSON representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { let topLevel: Any do { topLevel = try JSONSerialization.jsonObject(with: data) } catch { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error)) } let decoder = _JSONDecoder(referencing: topLevel, options: self.options) guard let value = try decoder.unbox(topLevel, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.")) } return value } } // MARK: - _JSONDecoder fileprivate class _JSONDecoder : Decoder { // MARK: Properties /// The decoder's storage. fileprivate var storage: _JSONDecodingStorage /// Options set on the top-level decoder. fileprivate let options: JSONDecoder._Options /// The path to the current point in encoding. fileprivate(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) { self.storage = _JSONDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer) } let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } // MARK: - Decoding Storage fileprivate struct _JSONDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate var topContainer: Any { precondition(self.containers.count > 0, "Empty container stack.") return self.containers.last! } fileprivate mutating func push(container: Any) { self.containers.append(container) } fileprivate mutating func popContainer() { precondition(self.containers.count > 0, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) { self.decoder = decoder switch decoder.options.keyDecodingStrategy { case .useDefaultKeys: self.container = container case .convertFromSnakeCase: // Convert the snake case keys in the container to camel case. // If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries. self.container = Dictionary(container.map { key, value in (JSONDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value) }, uniquingKeysWith: { (first, _) in first }) case .custom(let converter): self.container = Dictionary(container.map { key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value) }, uniquingKeysWith: { (first, _) in first }) } self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return self.container.keys.compactMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } private func _errorDescription(of key: CodingKey) -> String { switch decoder.options.keyDecodingStrategy { case .convertFromSnakeCase: // In this case we can attempt to recover the original value by reversing the transform let original = key.stringValue let converted = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(original) if converted == original { return "\(key) (\"\(original)\")" } else { return "\(key) (\"\(original)\"), converted to \(converted)" } default: // Otherwise, just report the converted string return "\(key) (\"\(key.stringValue)\")" } } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let value: Any = self.container[key.stringValue] ?? NSNull() return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _JSONKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return self.container.count } public var isAtEnd: Bool { return self.currentIndex >= self.count! } public mutating func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if self.container[self.currentIndex] is NSNull { self.currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int.Type) throws -> Int { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } public mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } extension _JSONDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !self.decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return self.storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(type) return try self.unbox(self.storage.topContainer, as: type)! } } // MARK: - Concrete Value Representations extension _JSONDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Float.infinity } else if string == negInfString { return -Float.infinity } else if string == nanString { return Float.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Double.infinity } else if string == negInfString { return -Double.infinity } else if string == nanString { return Double.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } switch self.options.dateDecodingStrategy { case .deferredToDate: self.storage.push(container: value) defer { self.storage.popContainer() } return try Date(from: self) case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } switch self.options.dataDecodingStrategy { case .deferredToData: self.storage.push(container: value) defer { self.storage.popContainer() } return try Data(from: self) case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } // Attempt to bridge from NSDecimalNumber. if let decimal = value as? Decimal { return decimal } else { let doubleValue = try self.unbox(value, as: Double.self)! return Decimal(doubleValue) } } fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { if type == Date.self || type == NSDate.self { return try self.unbox(value, as: Date.self) as? T } else if type == Data.self || type == NSData.self { return try self.unbox(value, as: Data.self) as? T } else if type == URL.self || type == NSURL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return url as! T } else if type == Decimal.self || type == NSDecimalNumber.self { return try self.unbox(value, as: Decimal.self) as? T } else { self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) } } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _JSONKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _JSONKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) fileprivate var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// fileprivate extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
apache-2.0
cc83913a6d566ef419d07d79bfeeef2e
43.88
323
0.647504
5.033924
false
false
false
false
zhangjk4859/MyWeiBoProject
sinaWeibo/sinaWeibo/AppDelegate.swift
1
2893
// // AppDelegate.swift // sinaWeibo // // Created by 张俊凯 on 16/6/5. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit // 切换控制器通知 let JKSwitchRootVCNotification = "SwitchRootVCNotification" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { //1.程序启动时启动数据库,用来缓存微博 JKSQLiteManager.shareManager().openDB("status.sqlite") //程序一进来就设置全局外观 UINavigationBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().tintColor = UIColor.orangeColor() window = UIWindow(frame:UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() //window?.rootViewController = JKTabBarController() //window?.rootViewController = JKNewfeatureVC() window?.rootViewController = JKWelcomVC() window?.makeKeyAndVisible() print(isNewupdate()) // 注册一个通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(switchRootVC), name: JKSwitchRootVCNotification, object: nil) return true } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } //切换根控制器 func switchRootVC(notify: NSNotification) { if notify.object as! Bool { window?.rootViewController = JKTabBarController() }else { window?.rootViewController = JKWelcomVC() } } private func isNewupdate() -> Bool{ // 获取当前软件的版本号 --> info.plist let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String // 获取老版本 let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? "" print("current = \(currentVersion) sandbox = \(sandboxVersion)") // 开始比较 if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending { // iOS7以后就不用调用同步方法了 NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString") return true } // 3.2如果当前< | == --> 没有新版本 return false } func applicationDidEnterBackground(application: UIApplication) { print(#function) // 进入后台以后,清除一分钟以前缓存的数据 JKStatusDAO.cleanStatuses() } }
mit
450fc166b86406fbbfb828dcafa52bf6
27.340426
144
0.626502
5.223529
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift
14
4506
// // PublishSubject.swift // RxSwift // // Created by Krunoslav Zaher on 2/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents an object that is both an observable sequence as well as an observer. /// /// Each notification is broadcasted to all subscribed observers. public final class PublishSubject<Element> : Observable<Element> , SubjectType , Cancelable , ObserverType , SynchronizedUnsubscribeType { public typealias SubjectObserverType = PublishSubject<Element> typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType /// Indicates whether the subject has any observers public var hasObservers: Bool { self._lock.lock() let count = self._observers.count > 0 self._lock.unlock() return count } private let _lock = RecursiveLock() // state private var _isDisposed = false private var _observers = Observers() private var _stopped = false private var _stoppedEvent = nil as Event<Element>? #if DEBUG fileprivate let _synchronizationTracker = SynchronizationTracker() #endif /// Indicates whether the subject has been isDisposed. public var isDisposed: Bool { return self._isDisposed } /// Creates a subject. public override init() { super.init() #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } /// Notifies all subscribed observers about next event. /// /// - parameter event: Event to send to the observers. public func on(_ event: Event<Element>) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self._synchronizationTracker.unregister() } #endif dispatch(self._synchronized_on(event), event) } func _synchronized_on(_ event: Event<Element>) -> Observers { self._lock.lock(); defer { self._lock.unlock() } switch event { case .next: if self._isDisposed || self._stopped { return Observers() } return self._observers case .completed, .error: if self._stoppedEvent == nil { self._stoppedEvent = event self._stopped = true let observers = self._observers self._observers.removeAll() return observers } return Observers() } } /** Subscribes an observer to the subject. - parameter observer: Observer to subscribe to the subject. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self._lock.lock() let subscription = self._synchronized_subscribe(observer) self._lock.unlock() return subscription } func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { if let stoppedEvent = self._stoppedEvent { observer.on(stoppedEvent) return Disposables.create() } if self._isDisposed { observer.on(.error(RxError.disposed(object: self))) return Disposables.create() } let key = self._observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { self._lock.lock() self._synchronized_unsubscribe(disposeKey) self._lock.unlock() } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { _ = self._observers.removeKey(disposeKey) } /// Returns observer interface for subject. public func asObserver() -> PublishSubject<Element> { return self } /// Unsubscribe all observers and release resources. public func dispose() { self._lock.lock() self._synchronized_dispose() self._lock.unlock() } final func _synchronized_dispose() { self._isDisposed = true self._observers.removeAll() self._stoppedEvent = nil } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif }
mit
8d425fd92b58fee07c4920e815a23b12
29.033333
130
0.610877
5.178161
false
false
false
false
edx/edx-app-ios
Source/CelebratoryModalViewController.swift
1
21351
// // CelebratoryModalViewController.swift // edX // // Created by Salman on 22/01/2021. // Copyright © 2021 edX. All rights reserved. // import UIKit private let UTM_ParameterString = "utm_campaign=edxmilestone&utm_medium=social&utm_source=%@" enum ActivityType:String { case linkedin = "com.linkedin.LinkedIn.ShareExtension" } protocol CelebratoryModalViewControllerDelegate: AnyObject { func modalDidDismiss() } private enum ShareButtonType { case linkedin case twitter case facebook case email case none private var source: String { switch self { case .linkedin: return "linkedin" case .twitter: return "twitter" case .facebook: return "facebook" case .email: return "email" default: return "other" } } private var parameter: String { return String(format: UTM_ParameterString, source) } fileprivate static var utmParameters: CourseShareUtmParameters? { let parameters: [String: String] = [ ShareButtonType.facebook.source: ShareButtonType.facebook.parameter, ShareButtonType.twitter.source: ShareButtonType.twitter.parameter, ShareButtonType.linkedin.source: ShareButtonType.linkedin.parameter, ShareButtonType.email.source: ShareButtonType.email.parameter, ] return CourseShareUtmParameters(utmParams: parameters) } } class CelebratoryModalViewController: UIViewController, InterfaceOrientationOverriding { typealias Environment = NetworkManagerProvider & OEXInterfaceProvider & OEXConfigProvider & OEXSessionProvider & OEXStylesProvider & OEXAnalyticsProvider & DataManagerProvider private let environment: Environment private var courseID: String private let type: ShareButtonType = .none private let keepGoingButtonSize = CGSize(width: 140, height: 40) private let shareImageSize = CGSize(width: 22, height: 22) private let titleLabelHeight:CGFloat = 30.0 private let titleLabelMessageHeight:CGFloat = 40.0 private let shareButtonContainerHeight:CGFloat = 100.0 weak var delegate : CelebratoryModalViewControllerDelegate? private lazy var modalView: UIView = { let view = UIView() view.backgroundColor = environment.styles.neutralWhite() return view }() private lazy var congratulationImageView: UIImageView = { let imageView = UIImageView(image: UIImage.gifImageWithName("CelebrateClaps")) imageView.contentMode = .scaleToFill return imageView }() private lazy var titleLabel: UILabel = { let title = UILabel() let style = OEXMutableTextStyle(weight: .bold, size: .xxxxLarge, color: environment.styles.neutralBlackT()) style.alignment = .center title.attributedText = style.attributedString(withText: Strings.Celebration.title) return title }() private lazy var titleMessageLabel: UILabel = { let message = UILabel() message.numberOfLines = 0 let style = OEXMutableTextStyle(weight: .normal, size: .large, color: environment.styles.neutralBlackT()) style.alignment = .center message.attributedText = style.attributedString(withText: Strings.Celebration.titleMessage) return message }() private lazy var celebrationMessageLabel: UILabel = { let message = UILabel() message.numberOfLines = 0 message.setContentCompressionResistancePriority(.defaultHigh, for: .vertical) message.adjustsFontSizeToFitWidth = true let earneditTextStyle = OEXMutableTextStyle(weight: .bold, size: .base, color: environment.styles.neutralBlackT()) let earneditAttributedString = earneditTextStyle.attributedString(withText: Strings.Celebration.earnedItText) let messageStyle = OEXMutableTextStyle(weight: .normal, size: .base, color: environment.styles.neutralBlackT()) let messageAttributedString = messageStyle.attributedString(withText: Strings.Celebration.infoMessage) let compiledMessage = NSAttributedString.joinInNaturalLayout(attributedStrings: [earneditAttributedString, messageAttributedString]) message.sizeToFit() message.attributedText = compiledMessage return message }() private lazy var keepGoingButton: UIButton = { let button = UIButton() button.backgroundColor = environment.styles.primaryBaseColor() let buttonStyle = OEXMutableTextStyle(weight: .normal, size: .xLarge, color: environment.styles.neutralWhiteT()) button.setAttributedTitle(buttonStyle.attributedString(withText: Strings.Celebration.keepGoingButtonTitle), for: UIControl.State()) button.oex_addAction({ [weak self] _ in self?.dismiss(animated: false, completion: { [weak self] in self?.delegate?.modalDidDismiss() }) }, for: .touchUpInside) return button }() private lazy var shareImageView: UIImageView = { let shareImage = Icon.ShareCourse.imageWithFontSize(size: 24) let imageView = UIImageView(image: shareImage) return imageView }() private lazy var shareButtonView: UIButton = { let button = UIButton() button.accessibilityLabel = Strings.Accessibility.shareACourse button.oex_removeAllActions() button.oex_addAction({ [weak self] _ in if let courseID = self?.courseID, let courseURL = self?.courseURL, let shareUtmParameters = ShareButtonType.utmParameters { self?.shareCourse(courseID: courseID, courseURL: courseURL, utmParameters: shareUtmParameters) } }, for: .touchUpInside) return button }() private lazy var courseURL: String? = { return environment.interface?.enrollmentForCourse(withID: courseID)?.course.course_about }() private lazy var celebrationImageSize: CGSize = { let margin: CGFloat = isiPad() ? 240 : 80 let width = view.frame.size.width - margin let imageAspectRatio: CGFloat = 1.37 return CGSize(width: width, height: width / imageAspectRatio) }() init(courseID: String, environment: Environment) { self.courseID = courseID self.environment = environment super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .allButUpsideDown } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = environment.styles.neutralXXDark().withAlphaComponent(0.5) view.setNeedsUpdateConstraints() view.addSubview(modalView) setupViews() setIdentifiers() NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) environment.analytics.trackCourseCelebrationFirstSection(courseID: courseID) markCelebratoryModalAsViewed() } deinit { NotificationCenter.default.removeObserver(self) } private func removeViews() { modalView.subviews.forEach { $0.removeFromSuperview() } } private func setIdentifiers() { modalView.accessibilityIdentifier = "CelebratoryModalView:modal-container-view" titleLabel.accessibilityIdentifier = "CelebratoryModalView:label-title" titleMessageLabel.accessibilityIdentifier = "CelebratoryModalView:label-title-message" celebrationMessageLabel.accessibilityIdentifier = "CelebratoryModalView:label-celebration-message" congratulationImageView.accessibilityIdentifier = "CelebratoryModalView:congratulation-image-view" shareButtonView.accessibilityIdentifier = "CelebratoryModalView:share-button-view" shareImageView.accessibilityIdentifier = "CelebratoryModalView:share-image-view" } private func setupViews() { if isVerticallyCompact() { setupLandscapeView() } else { setupPortraitView() } } private func setupPortraitView() { removeViews() let imageContainer = UIView() let insideContainer = UIView() let keepGoingButtonContainer = UIView() let buttonContainer = UIView() let textContainer = UIView() modalView.addSubview(titleLabel) modalView.addSubview(titleMessageLabel) imageContainer.addSubview(congratulationImageView) modalView.addSubview(imageContainer) modalView.addSubview(insideContainer) modalView.addSubview(keepGoingButtonContainer) imageContainer.accessibilityIdentifier = "CelebratoryModalView:image-cotainer-view" insideContainer.accessibilityIdentifier = "CelebratoryModalView:share-inside-container-view" keepGoingButtonContainer.accessibilityIdentifier = "CelebratoryModalView:keep-going-button-container-view" buttonContainer.accessibilityIdentifier = "CelebratoryModalView:share-button-container-view" textContainer.accessibilityIdentifier = "CelebratoryModalView:share-text-container-view" insideContainer.backgroundColor = environment.styles.infoXXLight() insideContainer.addSubview(buttonContainer) insideContainer.addSubview(textContainer) insideContainer.addSubview(shareButtonView) shareButtonView.superview?.bringSubviewToFront(shareButtonView) textContainer.addSubview(celebrationMessageLabel) buttonContainer.addSubview(shareImageView) keepGoingButtonContainer.addSubview(keepGoingButton) titleLabel.snp.remakeConstraints { make in make.top.equalTo(modalView).offset(StandardVerticalMargin*3) make.centerX.equalTo(modalView) make.leading.equalTo(modalView).offset(StandardHorizontalMargin) make.trailing.equalTo(modalView).inset(StandardHorizontalMargin) make.height.equalTo(titleLabelHeight) } titleMessageLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(StandardVerticalMargin * 2) make.centerX.equalTo(modalView) make.width.equalTo(imageContainer.snp.width).inset(10) make.height.equalTo(titleLabelMessageHeight) } congratulationImageView.snp.remakeConstraints { make in make.edges.equalTo(imageContainer) } imageContainer.snp.remakeConstraints { make in make.top.equalTo(titleMessageLabel.snp.bottom).offset(StandardVerticalMargin * 2) make.centerX.equalTo(modalView) make.width.equalTo(celebrationImageSize.width) make.height.equalTo(celebrationImageSize.height) } insideContainer.snp.remakeConstraints { make in make.top.equalTo(imageContainer.snp.bottom).offset(StandardVerticalMargin * 2) make.centerX.equalTo(modalView) make.width.equalTo(imageContainer.snp.width) make.height.equalTo(shareButtonContainerHeight) } buttonContainer.snp.remakeConstraints { make in make.leading.equalTo(insideContainer) make.top.equalTo(insideContainer).offset(StandardVerticalMargin * 2) make.bottom.equalTo(insideContainer) } textContainer.snp.remakeConstraints { make in make.top.equalTo(insideContainer).offset(StandardVerticalMargin * 2) make.leading.equalTo(buttonContainer.snp.trailing).inset(StandardHorizontalMargin / 2) make.trailing.equalTo(insideContainer).inset(StandardHorizontalMargin * 2) make.bottom.equalTo(insideContainer).inset(StandardVerticalMargin * 2) } shareImageView.snp.remakeConstraints { make in make.top.equalTo(celebrationMessageLabel.snp.top) make.leading.equalTo(buttonContainer).offset(StandardHorizontalMargin * 2) make.trailing.equalTo(buttonContainer).inset(StandardHorizontalMargin) make.width.equalTo(shareImageSize.width) make.height.equalTo(shareImageSize.height) } celebrationMessageLabel.snp.remakeConstraints { make in make.centerX.equalTo(textContainer) make.centerY.equalTo(textContainer) make.leading.equalTo(textContainer) make.trailing.equalTo(textContainer) } shareButtonView.snp.makeConstraints { make in make.edges.equalTo(insideContainer) } keepGoingButtonContainer.snp.remakeConstraints { make in make.top.equalTo(insideContainer.snp.bottom).offset(StandardVerticalMargin * 3) make.leading.equalTo(modalView).offset(StandardHorizontalMargin) make.trailing.equalTo(modalView).inset(StandardHorizontalMargin) make.height.equalTo(keepGoingButtonSize.height) } keepGoingButton.snp.remakeConstraints { make in make.centerX.equalTo(keepGoingButtonContainer) make.height.equalTo(keepGoingButtonContainer) make.width.equalTo(keepGoingButtonSize.width) } modalView.snp.remakeConstraints { make in make.centerX.equalTo(view) make.centerY.equalTo(view) let height = titleLabelHeight + titleLabelMessageHeight + celebrationImageSize.height + shareButtonContainerHeight + keepGoingButtonSize.height + (StandardVerticalMargin * 15) make.height.equalTo(height) make.width.equalTo(celebrationImageSize.width + StandardVerticalMargin * 5) } } private func setupLandscapeView() { removeViews() let stackView = UIStackView() let rightStackView = UIStackView() let rightContainer = UIView() let insideContainer = UIView() let buttonContainer = UIView() let textContainer = UIView() let keepGoingButtonContainer = UIView() stackView.accessibilityIdentifier = "CelebratoryModalView:stack-view" rightStackView.accessibilityIdentifier = "CelebratoryModalView:stack-right-view" rightContainer.accessibilityIdentifier = "CelebratoryModalView:stack-cotainer-right-view" insideContainer.accessibilityIdentifier = "CelebratoryModalView:share-inside-container-view" keepGoingButtonContainer.accessibilityIdentifier = "CelebratoryModalView:keep-going-button-container-view" buttonContainer.accessibilityIdentifier = "CelebratoryModalView:share-button-container-view" textContainer.accessibilityIdentifier = "CelebratoryModalView:share-text-container-view" stackView.alignment = .center stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.spacing = StandardVerticalMargin * 2 insideContainer.backgroundColor = environment.styles.infoXXLight() modalView.addSubview(stackView) textContainer.addSubview(celebrationMessageLabel) buttonContainer.addSubview(shareImageView) insideContainer.addSubview(shareButtonView) insideContainer.addSubview(buttonContainer) insideContainer.addSubview(textContainer) shareButtonView.superview?.bringSubviewToFront(shareButtonView) rightStackView.alignment = .fill rightStackView.axis = .vertical rightStackView.distribution = .equalSpacing rightStackView.spacing = StandardVerticalMargin rightStackView.addArrangedSubview(titleLabel) rightStackView.addArrangedSubview(titleMessageLabel) rightStackView.addArrangedSubview(insideContainer) rightStackView.addArrangedSubview(keepGoingButtonContainer) stackView.addArrangedSubview(congratulationImageView) stackView.addArrangedSubview(rightContainer) rightContainer.addSubview(rightStackView) keepGoingButtonContainer.addSubview(keepGoingButton) rightStackView.snp.makeConstraints { make in make.edges.equalTo(rightContainer) } rightContainer.snp.remakeConstraints { make in make.height.equalTo(stackView) } titleLabel.snp.remakeConstraints { make in make.height.equalTo(titleLabelHeight) } titleMessageLabel.snp.remakeConstraints { make in make.height.equalTo(titleLabelMessageHeight) } insideContainer.snp.remakeConstraints { make in make.height.equalTo(shareButtonContainerHeight) } shareImageView.snp.remakeConstraints { make in make.top.equalTo(celebrationMessageLabel.snp.top) make.leading.equalTo(buttonContainer).offset(StandardHorizontalMargin * 2) make.trailing.equalTo(buttonContainer).inset(StandardHorizontalMargin) make.width.equalTo(shareImageSize.width) make.height.equalTo(shareImageSize.height) } celebrationMessageLabel.snp.remakeConstraints { make in make.centerX.equalTo(textContainer) make.centerY.equalTo(textContainer) make.leading.equalTo(textContainer) make.trailing.equalTo(textContainer) make.height.lessThanOrEqualTo(textContainer) } shareButtonView.snp.makeConstraints { make in make.edges.equalTo(insideContainer) } buttonContainer.snp.remakeConstraints { make in make.leading.equalTo(insideContainer) make.top.equalTo(insideContainer) make.bottom.equalTo(insideContainer) } textContainer.snp.remakeConstraints { make in make.top.equalTo(insideContainer) make.leading.equalTo(buttonContainer.snp.trailing).inset(StandardHorizontalMargin / 2) make.trailing.equalTo(insideContainer).inset(StandardHorizontalMargin * 2) make.bottom.equalTo(insideContainer).inset(StandardVerticalMargin) } keepGoingButtonContainer.snp.remakeConstraints { make in make.height.equalTo(keepGoingButtonSize.height) } keepGoingButton.snp.remakeConstraints { make in make.centerX.equalTo(keepGoingButtonContainer) make.height.equalTo(keepGoingButtonContainer) make.width.equalTo(keepGoingButtonSize.width) } modalView.snp.remakeConstraints { make in // For iPad the modal is streching to the end of the screen so we restricted the modal top, bottom, leading // and trailing margin for iPad make.leading.equalTo(view).offset(isiPad() ? 100 : 40) make.trailing.equalTo(view).inset(isiPad() ? 100 : 40) let top = isiPad() ? ((view.frame.size.height / 2.5 ) / 2) : ((view.frame.size.height / 4) / 2) let bottom = isiPad() ? ((view.frame.size.width / 2.5 ) / 2) : ((view.frame.size.height / 4) / 2) make.top.equalTo(view).offset(top) make.bottom.equalTo(view).inset(bottom) make.centerX.equalTo(view) make.centerY.equalTo(view) } stackView.snp.remakeConstraints { make in make.edges.equalTo(modalView).inset(20) } } @objc func orientationDidChange() { setupViews() } private func shareCourse(courseID: String, courseURL: String, utmParameters: CourseShareUtmParameters) { guard let courseURL = NSURL(string: courseURL), let enrollment = environment.interface?.enrollmentForCourse(withID: courseID), let courseName = enrollment.course.name else { return } let controller = shareHashtaggedTextAndALinkForCelebration(textBuilder: { hashtagOrPlatform in Strings.Celebration.shareMessage(courseName: courseName, platformName: hashtagOrPlatform, hashtagPlatformName: self.environment.config.platformName()) }, url: courseURL, utmParams: utmParameters, analyticsCallback: { [weak self] analyticsType in self?.environment.analytics.trackCourseCelebrationSocialShareClicked(courseID: courseID, type: analyticsType) }) controller.configurePresentationController(withSourceView: shareImageView) present(controller, animated: true, completion: nil) } private func markCelebratoryModalAsViewed() { let courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment) courseQuerier.updateCelebrationModalStatus(firstSection: false) } }
apache-2.0
747586e7b5fbbbac766eb7d11440b985
41.7
187
0.682014
5.586081
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCEventTableViewCell.swift
2
1343
// // NCEventTableViewCell.swift // Neocom // // Created by Artem Shimanski on 05.05.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import CoreData class NCEventTableViewCell: NCTableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! } extension Prototype { enum NCEventTableViewCell { static let `default` = Prototype(nib: nil, reuseIdentifier: "NCEventTableViewCell") } } class NCEventRow: TreeRow { let event: ESI.Calendar.Summary init(event: ESI.Calendar.Summary) { self.event = event super.init(prototype: Prototype.NCEventTableViewCell.default, route: Router.Calendar.Event(event: event)) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCEventTableViewCell else {return} cell.titleLabel.text = event.title if let date = event.eventDate { cell.dateLabel.text = DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .short) } else { cell.dateLabel.text = nil } cell.stateLabel.text = (event.eventResponse ?? .notResponded).title } override var hash: Int { return event.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCEventRow)?.hashValue == hashValue } }
lgpl-2.1
d6076289f0c3918cd05ddbd054feb338
23.4
107
0.723547
3.717452
false
false
false
false
scottrhoyt/Noonian
Sources/NoonianKit/Utilities/Logger/Logger.swift
1
1396
// // Printer.swift // Noonian // // Created by Scott Hoyt on 11/7/16. // Copyright © 2016 Scott Hoyt. All rights reserved. // import Foundation import Rainbow public var log: Logger.Type = FancyLogger.self public protocol Logger { static func start(_: String) static func process(_: String) static func info(_: String) static func complete(_: String) static func error(_: String) } public struct FancyLogger: Logger { public static func start(_ item: String) { let message = ["▶️ ", "Starting:", item.bold].joined(separator: " ") print(spaced(message)) } public static func process(_ output: String) { print(output.lightBlack, separator: " ", terminator: "") } public static func info(_ info: String) { print(info.lightCyan) } public static func complete(_ item: String) { let message = ["✅ ", "Completed:", item.bold].joined(separator: " ") print(spaced(message)) } public static func error(_ error: String) { let message = ["⛔️ ", "Error:", error.bold].joined(separator: " ") print(spaced(message, fence: "")) } private static func spaced(_ string: String, fence: String = "=") -> String { let separator = repeatElement(fence, count: 80).joined() return ["", separator, string, separator, ""].joined(separator: "\n") } }
mit
5e1a9232d30ede4dd550fb4832c9cf62
26.7
81
0.612996
4.00289
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostEditorSaveAction.swift
1
2159
import Foundation import WordPressShared /// Encapsulates the current save action of the editor, based on its /// post status, whether it's already been saved, is scheduled, etc. @objc enum PostEditorSaveAction: Int { case schedule case post case save case update } /// Some utility methods to help keep track of the current post action extension WPPostViewController { /// What action should be taken when the user taps the editor's save button? var currentSaveAction: PostEditorSaveAction { if let status = post.status, let originalStatus = post.original?.status, status != originalStatus || !post.hasRemote() { if post.isScheduled() { return .schedule } else if status == .publish { return .post } else { return .save } } else { return .update } } /// The title for the Save button, based on the current save action var saveBarButtonItemTitle: String { switch currentSaveAction { case .schedule: return NSLocalizedString("Schedule", comment: "Schedule button, this is what the Publish button changes to in the Post Editor if the post has been scheduled for posting later.") case .post: return NSLocalizedString("Publish", comment: "Label for the publish (verb) button. Tapping publishes a draft post.") case .save: return NSLocalizedString("Save", comment: "Save button label (saving content, ex: Post, Page, Comment).") case .update: return NSLocalizedString("Update", comment: "Update button label (saving content, ex: Post, Page, Comment).") } } /// The analytics stat to post when the user saves, based on the current post action func analyticsStatForSaveAction(_ action: PostEditorSaveAction) -> WPAnalyticsStat { switch action { case .post: return .editorPublishedPost case .schedule: return .editorScheduledPost case .save: return .editorSavedDraft case .update: return .editorUpdatedPost } } }
gpl-2.0
375da5c1739e64fcd3a87524902a0708
38.981481
189
0.643353
5.044393
false
false
false
false
akabekobeko/examples-ios-fmdb
UsingFMDB-Swift/UsingFMDB-Swift/DAOFactory.swift
1
1576
// // DAOFactory.swift // UsingFMDB-Swift // // Created by akabeko on 2016/12/22. // Copyright © 2016年 akabeko. All rights reserved. // import UIKit import FMDB /// Factory of a data access objects. class DAOFactory: NSObject { /// Path of the database file. private let filePath: String /// Initialize the instance. override init() { self.filePath = DAOFactory.databaseFilePath() super.init() // For debug print(self.filePath) } /// Initialize the instance with the path of the database file. /// /// - Parameter filePath: the path of the database file. init(filePath: String) { self.filePath = filePath super.init() } /// Create the data access object of the books. /// /// - Returns: Instance of the data access object. func bookDAO() -> BookDAO? { if let db = self.connect() { return BookDAO(db: db) } return nil } /// Connect to the database. /// /// - Returns: Connection instance if successful, nil otherwise. private func connect() -> FMDatabase? { let db = FMDatabase(path: self.filePath) return (db?.open())! ? db : nil } /// Get the path of database file. /// /// - Returns: Path of the database file. private static func databaseFilePath() -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let dir = paths[0] as NSString return dir.appendingPathComponent("app.db") } }
mit
65e9624b0d1a692330fec0252f47feb3
24.786885
98
0.607756
4.369444
false
false
false
false
pecuniabanking/pecunia-client
Source/ChipcardManager.swift
1
11957
// // ChipcardManager.swift // Pecunia // // Created by Frank Emminghaus on 24.06.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation import HBCI4Swift var _manager:ChipcardManager! @objcMembers open class CardBankData : NSObject { var name:String; var bankCode:String; var country:String; var host:String; var userId:String; init(name:String, bankCode:String, country:String, host:String, userId:String) { self.name = name; self.bankCode = bankCode; self.country = country; self.host = host; self.userId = userId; } } @objc open class ChipcardManager : NSObject { var card: HBCISmartcardDDV!; public override init() { super.init(); } func stringToBytes(_ s:NSString) ->Data { let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: s.length/2); for i in 0 ..< s.length/2 { var value:UInt32 = 0; let hexString = s.substring(with: NSMakeRange(2*i, 2)); let scanner = Scanner(string: hexString); scanner.scanHexInt32(&value); buffer[i] = UInt8(value & 0xff); } let result = Data(bytes: UnsafePointer<UInt8>(buffer), count: s.length/2); buffer.deinitialize(count: s.length/2); return result; } func bytesToString(_ data:Data) ->NSString { let ret = NSMutableString(); let p = UnsafeMutablePointer<UInt8>(mutating: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count)); for i in 0 ..< data.count { ret.appendFormat("%0.2X", p[i]); } return ret; } open func isCardConnected() ->Bool { if card != nil { return card.isConnected(); } return false; } @objc open func getReaders() ->Array<String>? { return HBCISmartcardDDV.readers(); } open func connectCard(_ userIdName:String?) throws { // check if reader is still available if !card.isReaderConnected() { throw NSError.errorWithMsg(msgId: "AP366", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP366", comment: ""); alert.runModal(); return false; */ } if !card.isConnected() { var result = card.connect(1); if result == HBCISmartcard.ConnectResult.not_supported { throw NSError.errorWithMsg(msgId: "AP365", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP365", comment: ""); alert.runModal(); return false; */ } if result == HBCISmartcard.ConnectResult.no_card { // no card inserted. Open dialog to wait for it let controller = ChipcardRequestController(windowNibName: "ChipcardRequestController"); controller._userIdName = userIdName; if NSApp.runModal(for: controller.window!) == NSApplication.ModalResponse.cancel { // cancelled throw HBCIError.userAbort; //return false; } result = controller.connectResult; } // verify card let controller = ChipcardPinRequestController(windowNibName: "ChipcardPinRequestController"); if NSApp.runModal(for: controller.window!) == NSApplication.ModalResponse.cancel { // verification not o.k. throw NSError.errorWithMsg(msgId: "AP369", titleId: "AP368"); } /* let notificationController = NotificationWindowController(message: NSLocalizedString("AP351", comment:""), title: NSLocalizedString("AP357", comment:"")); notificationController?.showWindow(self); notificationController?.window?.makeKeyAndOrderFront(self); if !card.verifyPin() { notificationController?.window?.close(); throw NSError.errorWithMsg(msgId: "AP369", titleId: "AP368"); } notificationController?.window?.close(); */ } } open func requestCardForUser(_ user:BankUser) throws { if card == nil { // no card object created yet if let readers = HBCISmartcardDDV.readers() { if readers.count == 0 { // no card readers found throw NSError.errorWithMsg(msgId: "AP364", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP364", comment: ""); alert.runModal(); return false; */ } var idx = user.ddvReaderIdx.intValue if idx >= readers.count { logWarning("Index in user information is wrong"); idx = 0; } let readerName = readers[idx]; card = HBCISmartcardDDV(readerName: readerName); } else { throw NSError.errorWithMsg(msgId: "AP364", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP364", comment: ""); alert.runModal(); return false; */ } } // connect card try connectCard(user.name); // check user if let bankData = card.getBankData(1) { if bankData.userId == user.userId { return; } else { // card is connected but wrong user logError("HBCIChipcard: Karte vorhanden aber falscher Anwender(%@)", bankData.userId); throw NSError.errorWithMsg(msgId: "AP362", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; let msg = String(format: NSLocalizedString("AP362", comment: ""), bankData.userId, user.userId); alert.messageText = msg; alert.runModal(); return false; */ } } else { logError("HBCIChipcard: Bankdaten konnten nicht gelesen werden"); throw NSError.errorWithMsg(msgId: "AP363", titleId: "AP368"); /* let alert = NSAlert(); alert.alertStyle = NSAlertStyle.CriticalAlertStyle; alert.messageText = NSLocalizedString("AP363", comment: ""); alert.runModal(); return false; */ } } @objc open func requestCardForReader(_ readerName:String) throws { if card == nil { card = HBCISmartcardDDV(readerName: readerName); } else if card.readerName != readerName { card.disconnect(); card = HBCISmartcardDDV(readerName: readerName); } // connect card try connectCard(nil); } open func initializeChipcard(_ paramString:NSString) ->NSString? { let params = paramString.components(separatedBy: "|"); if params.count != 2 { logError("Falsche Parameter bei der Chipkarteninitialisierung"); return nil; } // card should already be initialized... if card == nil { return nil; } return nil; } @objc open func getBankData() ->CardBankData? { if let data = card.getBankData(1) { return CardBankData(name: data.name, bankCode: data.bankCode, country: data.country, host: data.host, userId: data.userId); } return nil; } @objc open func writeBankData(_ data:CardBankData) ->Bool { let hbciData = HBCICardBankData(name: data.name, bankCode: data.bankCode, country: data.country, host: data.host, hostAdd: "", userId: data.userId, commtype: 0); return card.writeBankData(1, data: hbciData); } open func readBankData(_ paramString:NSString) ->NSString? { let idx = paramString.integerValue; if let data = card.getBankData(idx) { return NSString(format: "%@|%@|%@|%@", data.country, data.bankCode, data.host, data.userId); } return nil; } open func readKeyData(_ paramString:NSString) ->NSString? { /* let sigid = card.getSignatureId(); if sigid == 0xffff { logError("Could not read signature id"); return nil; } let keys = card.getKeyData(); if keys.count != 2 { logError("Error reading key information from chipcard"); return nil; } return NSString(format: "%d|%i|%i|%i|%i", sigid, keys[0].keyNumber, keys[0].keyVersion, keys[1].keyNumber, keys[1].keyVersion); */ return nil; } open func enterPin(_ paramString:NSString) ->Bool { //return card.verifyPin(); // card should already been verified return true; } open func saveSigId(_ paramString:NSString) ->Bool { //let sigid = paramString.integerValue; /* if !card.writeSignatureId(sigid) { logError("Error while saving new signature id to chipcard"); return false; } */ return true; } open func sign(_ paramString:NSString) ->NSString? { //let hash = stringToBytes(paramString); /* if let sig = card.sign(hash) { return bytesToString(sig); } */ return nil; } open func encrypt(_ paramString:NSString) ->NSString? { //let keyNum = paramString.integerValue; /* if let keys = card.getEncryptionKeys(UInt8(keyNum)) { return NSString(format: "%@|%@", bytesToString(keys.plain), bytesToString(keys.encrypted)); } */ return nil; } open func decrypt(_ paramString:NSString) ->NSString? { let params = paramString.components(separatedBy: "|"); if params.count != 2 { logError("Fehlende Parameter zum Entschlüsseln"); return nil; } //let keyNum = Int(params[0])!; //let encKey = params[1] as NSString; /* if let plain = card.decryptKey(UInt8(keyNum), encrypted: stringToBytes(encKey)) { return bytesToString(plain); } */ return nil; } open func close() { if card != nil { card.disconnect(); card = nil; } } @objc open var cardNumber:NSString { get { if let cardNumber = card.cardNumber { return cardNumber; } else { if card.getCardID() { if let cardNumber = card.cardNumber { return cardNumber; } } return "<unbekannt>"; } } } @objc public static var manager:ChipcardManager { get { if let manager = _manager { return manager; } else { _manager = ChipcardManager(); return _manager; } } } }
gpl-2.0
0100032262a90794c0bbaac6f19b6849
32.965909
169
0.530278
4.938455
false
false
false
false
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Models/Mapping/AttachmentModelMapping.swift
2
2246
// // AttachmentModelMapping.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 16/01/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift extension Attachment: ModelMappeable { func map(_ values: JSON, realm: Realm?) { if self.identifier == nil { self.identifier = String.random(30) } if let authorName = values["author_name"].string { self.title = "@\(authorName)" } if let title = values["title"].string { self.title = title } if let titleLink = values["title_link"].string { self.titleLink = titleLink } self.collapsed = values["collapsed"].bool ?? false self.text = values["text"].string self.thumbURL = values["thumb_url"].string self.color = values["color"].string self.titleLinkDownload = values["title_link_download"].bool ?? true self.imageURL = encode(url: values["image_url"].string) self.imageType = values["image_type"].string self.imageSize = values["image_size"].int ?? 0 self.audioURL = encode(url: values["audio_url"].string) self.audioType = values["audio_type"].string self.audioSize = values["audio_size"].int ?? 0 self.videoURL = encode(url: values["video_url"].string) self.videoType = values["video_type"].string self.videoSize = values["video_size"].int ?? 0 // Override title & value from fields object if let fields = values["fields"].array?.first { self.title = fields["title"].string ?? self.title self.text = fields["value"].string ?? self.text } } fileprivate func encode(url: String?) -> String? { guard let url = url else { return nil } let parts = url.components(separatedBy: "/") var encoded: [String] = [] for part in parts { if let string = part.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { encoded.append(string) } else { encoded.append(part) } } return encoded.joined(separator: "/") } }
mit
3b3c4f54f9cf4c5bbf4232fbd7ee1b7d
30.180556
96
0.586192
4.376218
false
false
false
false
HQL-yunyunyun/SinaWeiBo
SinaWeiBo/SinaWeiBo/Class/Module/Main/Controller/BaseTableViewController.swift
1
2678
// // BaseTableViewController.swift // SinaWeiBo // // Created by 何启亮 on 16/5/12. // Copyright © 2016年 HQL. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { // MARK: - 属性 var isLogin: Bool = HQLUserAccountViewModel.shareInstance.isUserLogin override func viewDidLoad() { if isLogin{ // 如果登陆了,就照常加载 super.viewDidLoad() }else{ // 如果没有登陆,则进入访客视图 self.view = visitor visitor.delegate = self if self.isKindOfClass(HomeController) { visitor.startRotationAnimation() }else if self is MessageController{ visitor.setupVisitorInfo("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知") }else if self is DiscoveryController{ visitor.setupVisitorInfo("visitordiscover_image_message", message: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过") }else if self is ProfileController{ visitor.setupVisitorInfo("visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人") } // 没有登录才设置导航栏 self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(visitorViewDidClickRegister)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(visitorViewDidClickLogin)) } } // MARK: - 懒加载 lazy var visitor: visitorView = visitorView() } // MARK: - 协议 /** * switf 中遵守协议有两种方式,一种是在class定义的时候,在父类后面加上“,协议名”,一种是扩展对象实现协议: 可以将一个协议对应的代码写在一起 */ extension BaseTableViewController: visitorViewDelegate{ // 实现协议方法 // 登录 func visitorViewDidClickLogin() { // CZPrint(items: "登录") // modal 出一个控制器 let oauthVC = HQLOauthViewController() let nav: UINavigationController = UINavigationController(rootViewController: oauthVC) self.presentViewController(nav, animated: true, completion: nil) } // 注册 func visitorViewDidClickRegister() { print("注册") } }
apache-2.0
dcae1a26902e6a47693c9a8c03e293e3
31.071429
177
0.638753
4.517103
false
false
false
false
wireapp/wire-ios-sync-engine
Source/UserSession/Search/SearchResult.swift
1
6239
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation public struct SearchResult { public var contacts: [ZMSearchUser] public var teamMembers: [ZMSearchUser] public var addressBook: [ZMSearchUser] public var directory: [ZMSearchUser] public var conversations: [ZMConversation] public var services: [ServiceUser] } extension SearchResult { public init?(payload: [AnyHashable: Any], query: SearchRequest.Query, searchOptions: SearchOptions, contextProvider: ContextProvider) { guard let documents = payload["documents"] as? [[String: Any]] else { return nil } let filteredDocuments = documents.filter { (document) -> Bool in let name = document["name"] as? String let handle = document["handle"] as? String return !query.isHandleQuery || name?.hasPrefix("@") ?? true || handle?.contains(query.string.lowercased()) ?? false } let searchUsers = ZMSearchUser.searchUsers(from: filteredDocuments, contextProvider: contextProvider) contacts = [] addressBook = [] directory = searchUsers.filter({ !$0.isConnected && !$0.isTeamMember }) conversations = [] services = [] if searchOptions.contains(.teamMembers) && searchOptions.isDisjoint(with: .excludeNonActiveTeamMembers) { teamMembers = searchUsers.filter({ $0.isTeamMember }) } else { teamMembers = [] } } public init?(servicesPayload servicesFullPayload: [AnyHashable: Any], query: String, contextProvider: ContextProvider) { guard let servicesPayload = servicesFullPayload["services"] as? [[String: Any]] else { return nil } let searchUsersServices = ZMSearchUser.searchUsers(from: servicesPayload, contextProvider: contextProvider) contacts = [] teamMembers = [] addressBook = [] directory = [] conversations = [] services = searchUsersServices } public init?(userLookupPayload: [AnyHashable: Any], contextProvider: ContextProvider ) { guard let userLookupPayload = userLookupPayload as? [String: Any], let searchUser = ZMSearchUser.searchUser(from: userLookupPayload, contextProvider: contextProvider), searchUser.user == nil || searchUser.user?.isTeamMember == false else { return nil } contacts = [] teamMembers = [] addressBook = [] directory = [searchUser] conversations = [] services = [] } mutating func extendWithMembershipPayload(payload: MembershipListPayload) { payload.members.forEach { (membershipPayload) in let searchUser = teamMembers.first(where: { $0.remoteIdentifier == membershipPayload.userID }) let permissions = membershipPayload.permissions.flatMap({ Permissions(rawValue: $0.selfPermissions) }) searchUser?.updateWithTeamMembership(permissions: permissions, createdBy: membershipPayload.createdBy) } } mutating func filterBy(searchOptions: SearchOptions, query: String, contextProvider: ContextProvider) { guard searchOptions.contains(.excludeNonActivePartners) else { return } let selfUser = ZMUser.selfUser(in: contextProvider.viewContext) let isHandleQuery = query.hasPrefix("@") let queryWithoutAtSymbol = (isHandleQuery ? String(query[query.index(after: query.startIndex)...]) : query).lowercased() teamMembers = teamMembers.filter({ $0.teamRole != .partner || $0.teamCreatedBy == selfUser.remoteIdentifier || isHandleQuery && $0.handle == queryWithoutAtSymbol }) } func copy(on context: NSManagedObjectContext) -> SearchResult { let copiedConversations = conversations.compactMap { context.object(with: $0.objectID) as? ZMConversation } return SearchResult(contacts: contacts, teamMembers: teamMembers, addressBook: addressBook, directory: directory, conversations: copiedConversations, services: services) } func union(withLocalResult result: SearchResult) -> SearchResult { return SearchResult(contacts: result.contacts, teamMembers: result.teamMembers, addressBook: result.addressBook, directory: directory, conversations: result.conversations, services: services) } func union(withServiceResult result: SearchResult) -> SearchResult { return SearchResult(contacts: contacts, teamMembers: teamMembers, addressBook: addressBook, directory: directory, conversations: conversations, services: result.services) } func union(withDirectoryResult result: SearchResult) -> SearchResult { return SearchResult(contacts: contacts, teamMembers: Array(Set(teamMembers).union(result.teamMembers)), addressBook: addressBook, directory: result.directory, conversations: conversations, services: services) } }
gpl-3.0
df46badd408ea9c00ac45e06c7b365c9
39.512987
139
0.618689
5.535936
false
false
false
false
imex94/KCLTech-iOS-Sessions-2014-2015
session208/session208/UIPathFollower.swift
1
1224
// // UIPathFollower.swift // session208 // // Created by Clarence Ji on 1/26/15. // Copyright (c) 2015 Clarence Ji. All rights reserved. // import UIKit class UIPathFollower: UIImageView { func startAnimate(parent: UIViewController) { image = UIImage(named: "satellite") hidden = false bounds.size.width = 100 bounds.size.height = 100 center = parent.view.center var animation = CAKeyframeAnimation(keyPath: "position") animation.path = CGPathCreateWithEllipseInRect(CGRectMake(-100, -100, 200, 200), nil) animation.duration = 10 animation.repeatCount = 1000 animation.calculationMode = kCAAnimationPaced animation.rotationMode = kCAAnimationRotateAuto animation.additive = true parent.view.addSubview(self) layer.addAnimation(animation, forKey: "rotateAnimation") } func stopAnimate() { var fadeOut = CABasicAnimation(keyPath: "opacity") fadeOut.toValue = 0.0 fadeOut.duration = 2.0 fadeOut.fillMode = kCAFillModeForwards fadeOut.removedOnCompletion = false self.layer.addAnimation(fadeOut, forKey: "fadeout") } }
mit
4e68acbe18544418135a8226410788ea
28.142857
93
0.651144
4.601504
false
false
false
false
kareman/SwiftShell
Sources/SwiftShell/Files.swift
1
2965
/* * Released under the MIT License (MIT), http://opensource.org/licenses/MIT * * Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com) * */ import Foundation /** The default FileManager */ public let Files = FileManager.default /** Appends file or directory url to directory url */ public func + (leftpath: URL, rightpath: String) -> URL { leftpath.appendingPathComponent(rightpath) } /** Error type for file commands. */ public enum FileError: Error { case notFound(path: String) public static func checkFile(_ path: String) throws { if !Files.fileExists(atPath: path) { throw notFound(path: path) } } } extension FileError: CustomStringConvertible { public var description: String { switch self { case let .notFound(path): return "Error: '\(path)' does not exist." } } } /** Opens a file for reading, throws if an error occurs. */ public func open(_ path: String, encoding: String.Encoding = main.encoding) throws -> ReadableStream { // URL does not handle leading "~/" let fixedpath = path.hasPrefix("~") ? NSString(string: path).expandingTildeInPath : path return try open(URL(fileURLWithPath: fixedpath, isDirectory: false), encoding: encoding) } /** Opens a file for reading, throws if an error occurs. */ public func open(_ path: URL, encoding: String.Encoding = main.encoding) throws -> ReadableStream { do { return FileHandleStream(try FileHandle(forReadingFrom: path), encoding: encoding) } catch { try FileError.checkFile(path.path) throw error } } /** Opens a file for writing, creates it first if it doesn't exist. If the file already exists and overwrite=false, the writing will begin at the end of the file. - parameter overwrite: If true, replace the file if it exists. */ public func open(forWriting path: URL, overwrite: Bool = false, encoding: String.Encoding = main.encoding) throws -> FileHandleStream { if overwrite || !Files.fileExists(atPath: path.path) { try Files.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) _ = Files.createFile(atPath: path.path, contents: nil, attributes: nil) } do { let filehandle = try FileHandle(forWritingTo: path) _ = filehandle.seekToEndOfFile() return FileHandleStream(filehandle, encoding: encoding) } catch { try FileError.checkFile(path.path) throw error } } /** Opens a file for writing, creates it first if it doesn't exist. If the file already exists and overwrite=false, the writing will begin at the end of the file. - parameter overwrite: If true, replace the file if it exists. */ public func open(forWriting path: String, overwrite: Bool = false, encoding: String.Encoding = main.encoding) throws -> FileHandleStream { let fixedpath = path.hasPrefix("~") ? NSString(string: path).expandingTildeInPath : path return try open(forWriting: URL(fileURLWithPath: fixedpath, isDirectory: false), overwrite: overwrite, encoding: encoding) }
mit
3892f4450746815ab0a0459f8fcec8d8
33.453488
138
0.734053
3.863103
false
false
false
false
vitormesquita/Malert
Malert/Classes/Base/BaseMalertViewController.swift
1
1195
// // BaseMalertViewController.swift // Pods // // Created by Vitor Mesquita on 01/11/16. // // import UIKit public class BaseMalertViewController: UIViewController { private(set) var keyboardRect = CGRect.zero func listenKeyboard(){ NotificationCenter.default.addObserver( self, selector: #selector(BaseMalertViewController.keyboardWillShow(sender:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(BaseMalertViewController.keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil ) } @objc func keyboardWillShow(sender: NSNotification){ guard let userInfo = sender.userInfo else { return } if let keyboardRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue{ self.keyboardRect = keyboardRect } } @objc func keyboardWillHide(sender: NSNotification){ keyboardRect = CGRect.zero } }
mit
9f4be97bdedae15d33f7dc7083b977e4
26.159091
107
0.632636
5.636792
false
false
false
false
CosmicMind/Motion
Sources/Extensions/Motion+CALayer.swift
3
9680
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit internal extension CALayer { /// Swizzle the `add(_:forKey:) selector. static var motionAddedAnimations: [(CALayer, String, CAAnimation)]? = { let swizzling: (AnyClass, Selector, Selector) -> Void = { forClass, originalSelector, swizzledSelector in if let originalMethod = class_getInstanceMethod(forClass, originalSelector), let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) { method_exchangeImplementations(originalMethod, swizzledMethod) } } swizzling(CALayer.self, #selector(add(_:forKey:)), #selector(motionAdd(anim:forKey:))) return nil }() @objc dynamic func motionAdd(anim: CAAnimation, forKey: String?) { if nil == CALayer.motionAddedAnimations { motionAdd(anim: anim, forKey: forKey) } else { let copiedAnim = anim.copy() as! CAAnimation copiedAnim.delegate = nil // having delegate resulted some weird animation behavior CALayer.motionAddedAnimations?.append((self, forKey!, copiedAnim)) } } /// Retrieves all currently running animations for the layer. var animations: [(String, CAAnimation)] { guard let keys = animationKeys() else { return [] } return keys.map { return ($0, self.animation(forKey: $0)!.copy() as! CAAnimation) } } /** Concats transforms and returns the result. - Parameters layer: A CALayer. - Returns: A CATransform3D. */ func flatTransformTo(layer: CALayer) -> CATransform3D { var l = layer var t = l.transform while let sl = l.superlayer, self != sl { t = CATransform3DConcat(sl.transform, t) l = sl } return t } /// Removes all Motion animations. func removeAllMotionAnimations() { guard let keys = animationKeys() else { return } for animationKey in keys where animationKey.hasPrefix("motion.") { removeAnimation(forKey: animationKey) } } } public extension CALayer { /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ func animate(_ animations: CAAnimation...) { animate(animations) } /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ func animate(_ animations: [CAAnimation]) { for animation in animations { if let a = animation as? CABasicAnimation { a.fromValue = (presentation() ?? self).value(forKeyPath: a.keyPath!) } updateModel(animation) if let a = animation as? CAPropertyAnimation { add(a, forKey: a.keyPath!) } else if let a = animation as? CAAnimationGroup { add(a, forKey: nil) } else if let a = animation as? CATransition { add(a, forKey: kCATransition) } } } /** A function that accepts a list of MotionAnimation values and executes them. - Parameter animations: A list of MotionAnimation values. */ func animate(_ animations: MotionAnimation...) { animate(animations) } /** A function that accepts an Array of MotionAnimation values and executes them. - Parameter animations: An Array of MotionAnimation values. - Parameter completion: An optional completion block. */ func animate(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) { startAnimations(animations, completion: completion) } } fileprivate extension CALayer { /** A function that executes an Array of MotionAnimation values. - Parameter _ animations: An Array of MotionAnimations. - Parameter completion: An optional completion block. */ func startAnimations(_ animations: [MotionAnimation], completion: (() -> Void)? = nil) { let ts = MotionAnimationState(animations: animations) Motion.delay(ts.delay) { [weak self, ts = ts, completion = completion] in guard let `self` = self else { return } var anims = [CABasicAnimation]() var duration = 0 == ts.duration ? 0.01 : ts.duration if let v = ts.backgroundColor { let a = MotionCAAnimation.background(color: UIColor(cgColor: v)) a.fromValue = self.backgroundColor anims.append(a) } if let v = ts.borderColor { let a = MotionCAAnimation.border(color: UIColor(cgColor: v)) a.fromValue = self.borderColor anims.append(a) } if let v = ts.borderWidth { let a = MotionCAAnimation.border(width: v) a.fromValue = NSNumber(floatLiteral: Double(self.borderWidth)) anims.append(a) } if let v = ts.cornerRadius { let a = MotionCAAnimation.corner(radius: v) a.fromValue = NSNumber(floatLiteral: Double(self.cornerRadius)) anims.append(a) } if let v = ts.transform { let a = MotionCAAnimation.transform(v) a.fromValue = NSValue(caTransform3D: self.transform) anims.append(a) } if let v = ts.spin { var a = MotionCAAnimation.spin(x: v.x) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) a = MotionCAAnimation.spin(y: v.y) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) a = MotionCAAnimation.spin(z: v.z) a.fromValue = NSNumber(floatLiteral: 0) anims.append(a) } if let v = ts.position { let a = MotionCAAnimation.position(v) a.fromValue = NSValue(cgPoint: self.position) anims.append(a) } if let v = ts.opacity { let a = MotionCAAnimation.fade(v) a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.opacity.rawValue) ?? NSNumber(floatLiteral: 1) anims.append(a) } if let v = ts.zPosition { let a = MotionCAAnimation.zPosition(v) a.fromValue = self.value(forKeyPath: MotionAnimationKeyPath.zPosition.rawValue) ?? NSNumber(floatLiteral: 0) anims.append(a) } if let v = ts.size { let a = MotionCAAnimation.size(v) a.fromValue = NSValue(cgSize: self.bounds.size) anims.append(a) } if let v = ts.shadowPath { let a = MotionCAAnimation.shadow(path: v) a.fromValue = self.shadowPath anims.append(a) } if let v = ts.shadowColor { let a = MotionCAAnimation.shadow(color: UIColor(cgColor: v)) a.fromValue = self.shadowColor anims.append(a) } if let v = ts.shadowOffset { let a = MotionCAAnimation.shadow(offset: v) a.fromValue = NSValue(cgSize: self.shadowOffset) anims.append(a) } if let v = ts.shadowOpacity { let a = MotionCAAnimation.shadow(opacity: v) a.fromValue = NSNumber(floatLiteral: Double(self.shadowOpacity)) anims.append(a) } if let v = ts.shadowRadius { let a = MotionCAAnimation.shadow(radius: v) a.fromValue = NSNumber(floatLiteral: Double(self.shadowRadius)) anims.append(a) } if #available(iOS 9.0, *), let (stiffness, damping) = ts.spring { for i in 0..<anims.count where nil != anims[i].keyPath { let v = anims[i] guard "cornerRadius" != v.keyPath else { continue } let a = MotionCAAnimation.convert(animation: v, stiffness: stiffness, damping: damping) anims[i] = a if a.settlingDuration > duration { duration = a.settlingDuration } } } let g = Motion.animate(group: anims, timingFunction: ts.timingFunction, duration: duration) self.animate(g) if let v = ts.completion { Motion.delay(duration, execute: v) } if let v = completion { Motion.delay(duration, execute: v) } } } } private extension CALayer { /** Updates the model with values provided in animation. - Parameter animation: A CAAnimation. */ func updateModel(_ animation: CAAnimation) { if let a = animation as? CABasicAnimation { setValue(a.toValue, forKeyPath: a.keyPath!) } else if let a = animation as? CAAnimationGroup { a.animations?.forEach { updateModel($0) } } } }
mit
abd74b1213d973680720522290509605
30.633987
157
0.631302
4.473198
false
false
false
false
anirudh24seven/wikipedia-ios
WikipediaUnitTests/Code/NumberFormatterExtrasTests.swift
1
1085
import XCTest class NumberFormatterExtrasTests: XCTestCase { func testThousands() { var number: UInt64 = 215 var format: String = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("215")) number = 1500 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("1.5")) number = 538000 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("538")) number = 867530939 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("867.5")) number = 312490123456 format = NSNumberFormatter.localizedThousandsStringFromNumber(NSNumber(unsignedLongLong: number)) XCTAssertTrue(format.containsString("312.5")) } }
mit
ae8c7ac4491443068bf03be0d31ce528
39.185185
117
0.707834
5.928962
false
true
false
false
Zewo/Epoch
Sources/HTTP/Request/Request.swift
2
5907
import Core import IO import Media import Venice public final class Request : Message { public typealias UpgradeConnection = (Response, DuplexStream) throws -> Void public var method: Method public var uri: URI public var version: Version public var headers: Headers public var body: Body public var storage: Storage = [:] public var upgradeConnection: UpgradeConnection? public init( method: Method, uri: URI, headers: Headers = [:], version: Version = .oneDotOne, body: Body ) { self.method = method self.uri = uri self.headers = headers self.version = version self.body = body } public enum Method { case get case head case post case put case patch case delete case options case trace case connect case other(String) } } extension Request { public convenience init( method: Method, uri: String, headers: Headers = [:] ) throws { self.init( method: method, uri: try URI(uri), headers: headers, version: .oneDotOne, body: .empty ) switch method { case .get, .head, .options, .connect, .trace: break default: contentLength = 0 } } public convenience init( method: Method, uri: String, headers: Headers = [:], body stream: Readable ) throws { self.init( method: method, uri: try URI(uri), headers: headers, version: .oneDotOne, body: .readable(stream) ) } public convenience init( method: Method, uri: String, headers: Headers = [:], body write: @escaping Body.Write ) throws { self.init( method: method, uri: try URI(uri), headers: headers, version: .oneDotOne, body: .writable(write) ) } public convenience init( method: Method, uri: String, headers: Headers = [:], body buffer: BufferRepresentable, timeout: Duration = 5.minutes ) throws { try self.init( method: method, uri: uri, headers: headers, body: { stream in try stream.write(buffer, deadline: timeout.fromNow()) } ) contentLength = buffer.bufferSize } public convenience init<Content : EncodingMedia>( method: Method, uri: String, headers: Headers = [:], content: Content, timeout: Duration = 5.minutes ) throws { try self.init( method: method, uri: uri, headers: headers, body: { writable in try content.encode(to: writable, deadline: timeout.fromNow()) } ) self.contentType = Content.mediaType self.contentLength = nil self.transferEncoding = "chunked" } public convenience init<Content : MediaEncodable>( method: Method, uri: String, headers: Headers = [:], content: Content, timeout: Duration = 5.minutes ) throws { let media = try Content.defaultEncodingMedia() try self.init( method: method, uri: uri, headers: headers, body: { writable in try media.encode(content, to: writable, deadline: timeout.fromNow()) } ) self.contentType = media.mediaType self.contentLength = nil self.transferEncoding = "chunked" } public convenience init<Content : MediaEncodable>( method: Method, uri: String, headers: Headers = [:], content: Content, contentType mediaType: MediaType, timeout: Duration = 5.minutes ) throws { let media = try Content.encodingMedia(for: mediaType) try self.init( method: method, uri: uri, headers: headers, body: { writable in try media.encode(content, to: writable, deadline: timeout.fromNow()) } ) self.contentType = media.mediaType self.contentLength = nil self.transferEncoding = "chunked" } } extension Request { public var path: String { return uri.path! } public var accept: [MediaType] { get { return headers["Accept"].map({ MediaType.parse(acceptHeader: $0) }) ?? [] } set(accept) { headers["Accept"] = accept.map({ $0.type + "/" + $0.subtype }).joined(separator: ", ") } } public var authorization: String? { get { return headers["Authorization"] } set(authorization) { headers["Authorization"] = authorization } } public var host: String? { get { return headers["Host"] } set(host) { headers["Host"] = host } } public var userAgent: String? { get { return headers["User-Agent"] } set(userAgent) { headers["User-Agent"] = userAgent } } } extension Request : CustomStringConvertible { /// :nodoc: public var requestLineDescription: String { return method.description + " " + uri.description + " " + version.description + "\n" } /// :nodoc: public var description: String { return requestLineDescription + headers.description } }
mit
aba2244f097ae7a2e42266afe7f48a0e
23.409091
98
0.510242
4.951383
false
false
false
false
natecook1000/swift
stdlib/public/core/NewtypeWrapper.swift
2
5299
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// An implementation detail used to implement support importing /// (Objective-)C entities marked with the swift_newtype Clang /// attribute. public protocol _SwiftNewtypeWrapper : RawRepresentable, _HasCustomAnyHashableRepresentation { } extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable { /// The hash value. @inlinable public var hashValue: Int { return rawValue.hashValue } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable // FIXME(sil-serialize-all) public func _rawHashValue(seed: (UInt64, UInt64)) -> Int { return rawValue._rawHashValue(seed: seed) } } extension _SwiftNewtypeWrapper { public func _toCustomAnyHashable() -> AnyHashable? { return nil } } extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable { public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _NewtypeWrapperAnyHashableBox(self)) } } internal struct _NewtypeWrapperAnyHashableBox<Base>: _AnyHashableBox where Base: _SwiftNewtypeWrapper & Hashable, Base.RawValue: Hashable { var _value: Base init(_ value: Base) { self._value = value } var _canonicalBox: _AnyHashableBox { return (_value.rawValue as AnyHashable)._box._canonicalBox } func _isEqual(to other: _AnyHashableBox) -> Bool? { _preconditionFailure("_isEqual called on non-canonical AnyHashable box") } var _hashValue: Int { _preconditionFailure("_hashValue called on non-canonical AnyHashable box") } func _hash(into hasher: inout Hasher) { _preconditionFailure("_hash(into:) called on non-canonical AnyHashable box") } func _rawHashValue(_seed: (UInt64, UInt64)) -> Int { _preconditionFailure("_rawHashValue(_seed:) called on non-canonical AnyHashable box") } var _base: Any { return _value } func _unbox<T: Hashable>() -> T? { return _value as? T ?? _value.rawValue as? T } func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { if let value = _value as? T { result.initialize(to: value) return true } if let value = _value.rawValue as? T { result.initialize(to: value) return true } return false } } #if _runtime(_ObjC) extension _SwiftNewtypeWrapper where Self.RawValue : _ObjectiveCBridgeable { // Note: This is the only default typealias for _ObjectiveCType, because // constrained extensions aren't allowed to define types in different ways. // Fortunately the others don't need it. public typealias _ObjectiveCType = Self.RawValue._ObjectiveCType @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> Self.RawValue._ObjectiveCType { return rawValue._bridgeToObjectiveC() } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType, result: inout Self? ) { var innerResult: Self.RawValue? Self.RawValue._forceBridgeFromObjectiveC(source, result: &innerResult) result = innerResult.flatMap { Self(rawValue: $0) } } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType, result: inout Self? ) -> Bool { var innerResult: Self.RawValue? let success = Self.RawValue._conditionallyBridgeFromObjectiveC( source, result: &innerResult) result = innerResult.flatMap { Self(rawValue: $0) } return success } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: Self.RawValue._ObjectiveCType? ) -> Self { return Self( rawValue: Self.RawValue._unconditionallyBridgeFromObjectiveC(source))! } } extension _SwiftNewtypeWrapper where Self.RawValue: AnyObject { @inlinable // FIXME(sil-serialize-all) public func _bridgeToObjectiveC() -> Self.RawValue { return rawValue } @inlinable // FIXME(sil-serialize-all) public static func _forceBridgeFromObjectiveC( _ source: Self.RawValue, result: inout Self? ) { result = Self(rawValue: source) } @inlinable // FIXME(sil-serialize-all) public static func _conditionallyBridgeFromObjectiveC( _ source: Self.RawValue, result: inout Self? ) -> Bool { result = Self(rawValue: source) return result != nil } @inlinable // FIXME(sil-serialize-all) public static func _unconditionallyBridgeFromObjectiveC( _ source: Self.RawValue? ) -> Self { return Self(rawValue: source!)! } } #endif
apache-2.0
7da8a6f12d393b12da26183a9b675488
29.28
89
0.68579
4.55632
false
false
false
false
practicalswift/swift
benchmark/single-source/ByteSwap.swift
10
1932
//===--- ByteSwap.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 // //===----------------------------------------------------------------------===// // This test checks performance of Swift byte swap. // rdar://problem/22151907 import Foundation import TestsUtils public let ByteSwap = BenchmarkInfo( name: "ByteSwap", runFunction: run_ByteSwap, tags: [.validation, .algorithm]) // a naive O(n) implementation of byteswap. @inline(never) func byteswap_n(_ a: UInt64) -> UInt64 { return ((a & 0x00000000000000FF) &<< 56) | ((a & 0x000000000000FF00) &<< 40) | ((a & 0x0000000000FF0000) &<< 24) | ((a & 0x00000000FF000000) &<< 8) | ((a & 0x000000FF00000000) &>> 8) | ((a & 0x0000FF0000000000) &>> 24) | ((a & 0x00FF000000000000) &>> 40) | ((a & 0xFF00000000000000) &>> 56) } // a O(logn) implementation of byteswap. @inline(never) func byteswap_logn(_ a: UInt64) -> UInt64 { var a = a a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32 a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16 a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8 return a } @inline(never) public func run_ByteSwap(_ N: Int) { var s: UInt64 = 0 for _ in 1...10000*N { // Check some results. let x : UInt64 = UInt64(getInt(0)) s = s &+ byteswap_logn(byteswap_n(x &+ 2457)) &+ byteswap_logn(byteswap_n(x &+ 9129)) &+ byteswap_logn(byteswap_n(x &+ 3333)) } CheckResults(s == (2457 &+ 9129 &+ 3333) &* 10000 &* N) }
apache-2.0
3b6e7f4204aa5c51152ed2bbab4694e0
32.310345
80
0.57764
3.44385
false
false
false
false
billhsu0913/VideBounceButtonView
VideBounceButtonViewExample/ViewController.swift
1
1757
// // ViewController.swift // VideBounceButtonViewExample // // Created by Oreki Houtarou on 11/29/14. // Copyright (c) 2014 Videgame. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var buttons: [UIButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. for button in buttons { button.layer.cornerRadius = button.frame.height / 2 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.whiteColor().CGColor } // let bounceButtonView = view as VideBounceButtonView // bounceButtonView.exclusiveButtons = [buttons[0]] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonTapped(sender: AnyObject) { let button = sender as UIButton let snapView = UIView(frame: button.frame) snapView.layer.cornerRadius = button.layer.cornerRadius snapView.backgroundColor = button.backgroundColor view.insertSubview(snapView, atIndex: 0) let maxScale = max(view.frame.width / snapView.frame.width * 2.0, view.frame.height / snapView.frame.height * 2.0) UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in snapView.transform = CGAffineTransformMakeScale(maxScale, maxScale) }) { (finished) -> Void in if finished { self.view.backgroundColor = button.backgroundColor snapView.removeFromSuperview() } } } }
mit
5773aca31f9a7f0132de69b86e5183a2
33.45098
122
0.652248
4.735849
false
false
false
false