repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
newlix/orz-swift
refs/heads/master
Carthage/Checkouts/Just/Docs/QuickStart.playground/Contents.swift
mit
1
//: # Just: A Quick Start //: This is an introduction to the basics of doning HTTP via //: [Just](http://JustHTTP.net). //: It's available both on the //: [web](http://docs.justhttp.net/QuickStart.html) //: and as a //: [playground](https://raw.githubusercontent.com/JustHTTP/Just/master/Docs/QuickStart.zip). //: Readers are assumed to be familiar with the basics of HTTP. //: //: ## Simple Requests //: Just's API is heavily influenced by [python-requests](http://python-requests.org), //: HTTP for Humans in Python. //: //: Here's a simple POST request via Just: Just.post("http://httpbin.org/post") //: A GET request with some URL query parameters is as simple as: Just.get("http://httpbin.org/get", params:["page": 3]) //: The URL is the only required argument when making a request. Just strives //: for a minimum interface. //: //: The following methods can be done in similar ways: //: //: - DELETE //: - GET //: - HEAD //: - OPTIONS //: - PATCH //: - POST //: - PUT //: ## Synchronous v. Asynchronous //: When working with Swift, we tend to shun sychronous network requests because //: they block when invoked on the main thread, which would prevent our //: Cocoa/Cocoa Touch apps from smooth UI rendering. However, there's nothing //: inherantly wrong with synchronous requests. In fact, synchronous code is often //: easier to understand and, therefore, a better paradigm to explore HTTP //: resources with. var r = Just.get("http://httpbin.org/get", params:["page": 3]) // … "r" becomes available here //: However, Just doesn't force you to choose. The same request can be made //: asynchronously like this Just.get("http://httpbin.org/get", params:["page": 3]) { (r) in // the same "r" is available asynchronously here } //: That is, you can switch between the two paradigm by adding/removing a //: callback. When such callback is present, the result of the request becomes //: available asynchronously as an arugment to the callback. Otherwise, //: Just will return the very same result synchronously. //: //: *Note: asynchronous callbacks does not run on main thread, which is a //: behavior inherited from NSURLSession. Be sure to dispatch code //: properly with NSOperationQueue or GCD if you need to update UI in the //: callback.* //: //: The examples in the rest of this document will be synchronous. Keep in //: mind that all of them can easily be asynchronous. //: ## HTTP Result //: The result of a HTTP request is captured in a single object. //: Let's take a look at *r* from the previous example. // is the request successful? r.ok r.statusCode //: Hopefully, that's self explainatory. **ok** is *true* if a response is //: received and the **statusCode** is not *4xx* or *5xx*. //: //: Moving on: // what did the server return? r.headers // response headers r.content // response body as NSData? r.text // response body as text? r.json // response body parsed by NSJSONSerielization r.url // the URL, as NSURL r.isRedirect // is this a redirect response //: The **headers** property is a Swift-dictionary-like object: for (k,v) in r.headers { print("\(k):\(v)") } //: It's different from a normal dictionary in that its values can be accessed //: by case-insensitive keys: r.headers["Content-Length"] == r.headers["cOnTeNt-LeNgTh"] // true //: The original request is preserved as a *NSURLRequest*: r.request // NSURLRequest sent r.request?.HTTPMethod // GET //: When things aren't going so well: let erronous = Just.get("http://httpbin.org/does/not/exist") // oops erronous.ok // nope erronous.reason // text description of the failure erronous.error // NSError from NSURLSession, if any //: The best way to "cancel" a request is to never send it. Once a request is //: made, however, you can express intent to cancel it like so: r.cancel() //: ## More Complicated Requests //: //: To send form values, use the **data** parameter: // body of this request will be firstName=Barry&lastName=Allen // a Content-Type header will be added as application/x-form-www-encoded Just.post("http://httpbin.org/post", data:["firstName":"Barry","lastName":"Allen"]) //: JSON values are similar: // body of this request will be JSON encoded. // Its Content-Type header has value 'application/json' Just.post("http://httpbin.org/post", json:["firstName":"Barry","lastName":"Allen"]) //: By default, Just follows server's redirect instrution. You can supply an //: **allowRedirects** argument to control this behavior. // redirects Just.get("http://httpbin.org/redirect/2").isRedirect // false // no redirects Just.get("http://httpbin.org/redirect/2", allowRedirects:false).isRedirect // true //: In addition, a permanent redirect can be detected this way: // permanent redirect Just.get("http://httpbin.org/status/301", allowRedirects:false).isPermanentRedirect // true // non permanent redirect Just.get("http://httpbin.org/status/302", allowRedirects:false).isPermanentRedirect // false //: ## Files //: Uploading files is easy with Just: import Foundation let elonPhotoURL = NSBundle.mainBundle().URLForResource("elon", withExtension: "jpg")! // assume the file exist let uploadResult = Just.post("http://httpbin.org/post", files:["elon":.URL(elonPhotoURL, nil)]) // <== that's it print(uploadResult.text ?? "") //: Here a file is specified with an NSURL. Alternatively, a file can be a NSData or just a string. Although in both cases, a filename is needed. let someData = "Marco".dataUsingEncoding(NSUTF8StringEncoding)! // this shouldn't fail if let text = Just.post( "http://httpbin.org/post", files:[ "a":.Data("marco.text", someData, nil), // file #1, an NSData "b":.Text("polo.txt", "Polo", nil) // file #2, a String ] ).text { print(text) } //: Two files are being uploaded here. //: //: The *nil* part of the argument in both examples is an optional String that can be used to specify the MIMEType of the files. //: //: **data** parameter can be used in conjuction with **files**. When that happens, though, the *Content-Type* of the request will be *multipart/form-data; ...*. if let json = Just.post( "http://httpbin.org/post", data:["lastName":"Musk"], files:["elon":.URL(elonPhotoURL, nil)] ).json as? [String:AnyObject] { print(json["form"] ?? [:]) // lastName:Musk print(json["files"] ?? [:]) // elon } //: ## Link Headers //: Many HTTP APIs feature Link headers. They make APIs more self describing //: and discoverable. //: //: Github uses these for pagination in their API, for example: let gh = Just.head("https://api.github.com/users/dduan/repos?page=1&per_page=5") gh.headers["link"] // <https://api.github.com/user/75067/repos?page=2&per_page=5>; rel="next", <https://api.github.com/user/75067/repos?page=9&per_page=5>; rel="last" //: Just will automatically parse these link headers and make them easily consumable: gh.links["next"] // ["rel": "next", "url":"https://api.github.com/user/75067/repos?page=2&per_page=5"] gh.links["last"] // ["rel": "last", "url":"https://api.github.com/user/75067/repos?page=9&per_page=5"] //: (be aware of Github's rate limits when you play with these) //: ## Cookies //: //: If you expect the server to return some cookie, you can find them this way: Just.get("http://httpbin.org/cookies/set/name/elon", allowRedirects:false).cookies["name"] // returns an NSHTTPCookie //: To send requests with cookies: Just.get("http://httpbin.org/cookies", cookies:["test":"just"]) // ok //: ## Authentication //: //: If a request is to be challenged by basic or digest authentication, use the **auth** parameter to provide a tuple for username and password Just.get("http://httpbin.org/basic-auth/flash/allen", auth:("flash", "allen")) // ok //: ## Timeout //: //: You can tell Just to stop waiting for a response after a given number of seconds with the timeout parameter: // this request won't finish Just.get("http://httpbin.org/delay/5", timeout:0.2).reason //: ## Upload and Download Progress //: //: When dealing with large files, you may be interested in knowing the progress //: of their uploading or downloading. You can do that by supplynig a call back //: to the parameter **asyncProgressHandler**. Just.post( "http://httpbin.org/post", files:["large file":.Text("or", "pretend this is a large file", nil)], asyncProgressHandler: {(p) in p.type // either .Upload or .Download p.bytesProcessed p.bytesExpectedToProcess p.percent } ) { (r) in // finished } //: The progress handler may be called during sending the request and receiving //: the response. You can tell them apart by checking the **type** property of the //: callback argument. In either cases, you can use **bytesProcessed**, //: **bytesExpectedToProcess** aned **percent** to check the actual progress. //: ## Customization / Advanced Usage //: Just is a thin layer with some default settings atop //: [NSURLSession](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/). //: To change these settings, one must create a separate instance of Just instead of using the //: default one. Doing so opens up the oppurtunity to customize NSURLSession in //: powerful ways. A `JustSessionDefaults` can be used to provide some customization points: let myJustDefaults = JustSessionDefaults( JSONReadingOptions: .MutableContainers, // NSJSONSerialization reading options JSONWritingOptions: .PrettyPrinted, // NSJSONSerialization writing options headers: ["OH":"MY"], // headers to include in every request multipartBoundary: "Ju5tH77P15Aw350m3", // multipart post request boundaries credentialPersistence: .None, // NSURLCredential persistence options encoding: NSUTF8StringEncoding // en(de)coding for HTTP body ) //: Just initializer accepts an `defaults` argement. Use it like this: let just = JustOf<HTTP>(defaults: myJustDefaults) just.post("http://httpbin.org/post").request?.allHTTPHeaderFields?["OH"] ?? "" // MY
f25e783330c26d4efa228664ae3a3f3a
36.477778
166
0.695622
false
false
false
false
lllyyy/LY
refs/heads/master
U17-master/U17/U17/Procedure/Comic/View/UComicTCell.swift
mit
1
// // UComicTCell.swift // U17 // // Created by charles on 2017/11/8. // Copyright © 2017年 None. All rights reserved. // import UIKit class UComicTCell: UBaseTableViewCell { var spinnerName: String? private lazy var iconView: UIImageView = { let iw = UIImageView() iw.contentMode = .scaleAspectFill iw.clipsToBounds = true return iw }() private lazy var titleLabel: UILabel = { let tl = UILabel() tl.textColor = UIColor.black return tl }() private lazy var subTitleLabel: UILabel = { let sl = UILabel() sl.textColor = UIColor.gray sl.font = UIFont.systemFont(ofSize: 14) return sl }() private lazy var descLabel: UILabel = { let dl = UILabel() dl.textColor = UIColor.gray dl.numberOfLines = 3 dl.font = UIFont.systemFont(ofSize: 14) return dl }() private lazy var tagLabel: UILabel = { let tl = UILabel() tl.textColor = UIColor.orange tl.font = UIFont.systemFont(ofSize: 14) return tl }() private lazy var orderView: UIImageView = { let ow = UIImageView() ow.contentMode = .scaleAspectFit return ow }() override func configUI() { separatorInset = .zero contentView.addSubview(iconView) iconView.snp.makeConstraints { $0.left.top.bottom.equalToSuperview().inset(UIEdgeInsetsMake(10, 10, 10, 0)) $0.width.equalTo(100) } contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { $0.left.equalTo(iconView.snp.right).offset(10) $0.right.equalToSuperview().offset(-10) $0.height.equalTo(30) $0.top.equalTo(iconView) } contentView.addSubview(subTitleLabel) subTitleLabel.snp.makeConstraints { $0.left.equalTo(iconView.snp.right).offset(10) $0.right.equalToSuperview().offset(-10) $0.height.equalTo(20) $0.top.equalTo(titleLabel.snp.bottom).offset(5) } contentView.addSubview(descLabel) descLabel.snp.makeConstraints { $0.left.equalTo(iconView.snp.right).offset(10) $0.right.equalToSuperview().offset(-10) $0.height.equalTo(60) $0.top.equalTo(subTitleLabel.snp.bottom).offset(5) } contentView.addSubview(orderView) orderView.snp.makeConstraints { $0.bottom.equalTo(iconView.snp.bottom) $0.height.width.equalTo(30) $0.right.equalToSuperview().offset(-10) } contentView.addSubview(tagLabel) tagLabel.snp.makeConstraints { $0.left.equalTo(iconView.snp.right).offset(10) $0.right.equalTo(orderView.snp.left).offset(-10) $0.height.equalTo(20) $0.bottom.equalTo(iconView.snp.bottom) } } var model: ComicModel? { didSet { guard let model = model else { return } iconView.kf.setImage(urlString: model.cover, placeholder: UIImage(named: "normal_placeholder_v")) titleLabel.text = model.name subTitleLabel.text = "\(model.tags?.joined(separator: " ") ?? "") | \(model.author ?? "")" descLabel.text = model.description if spinnerName == "更新时间" { let comicDate = Date().timeIntervalSince(Date(timeIntervalSince1970: TimeInterval(model.conTag))) var tagString = "" if comicDate < 60 { tagString = "\(Int(comicDate))秒前" } else if comicDate < 3600 { tagString = "\(Int(comicDate / 60))分前" } else if comicDate < 86400 { tagString = "\(Int(comicDate / 3600))小时前" } else if comicDate < 31536000{ tagString = "\(Int(comicDate / 86400))天前" } else { tagString = "\(Int(comicDate / 31536000))年前" } tagLabel.text = "\(spinnerName!) \(tagString)" orderView.isHidden = true } else { var tagString = "" if model.conTag > 100000000 { tagString = String(format: "%.1f亿", Double(model.conTag) / 100000000) } else if model.conTag > 10000 { tagString = String(format: "%.1f万", Double(model.conTag) / 10000) } else { tagString = "\(model.conTag)" } if tagString != "0" { tagLabel.text = "\(spinnerName ?? "总点击") \(tagString)" } orderView.isHidden = false } } } var indexPath: IndexPath? { didSet { guard let indexPath = indexPath else { return } if indexPath.row == 0 { orderView.image = UIImage.init(named: "rank_frist") } else if indexPath.row == 1 { orderView.image = UIImage.init(named: "rank_second") } else if indexPath.row == 2 { orderView.image = UIImage.init(named: "rank_third") } else { orderView.image = nil } } } }
b1f993745c0a4dd5a1b308f011eb36d7
33.115385
113
0.536077
false
false
false
false
adrfer/swift
refs/heads/master
test/SourceKit/DocSupport/Inputs/cake.swift
apache-2.0
4
public protocol Prot { associatedtype Element var p : Int { get } func foo() } public class C1 : Prot { public typealias Element = Int public var p : Int = 0 public func foo() {} public subscript(index: Int) -> Int { return 0 } public subscript(index i: Float) -> Int { return 0 } } public func genfoo<T1 : Prot, T2 : C1 where T1.Element == Int, T2.Element == T1.Element>(x ix: T1, y iy: T2) {} public extension Prot where Self.Element == Int { final func extfoo() {} } public enum MyEnum : Int { case Blah } protocol Prot1 {} typealias C1Alias = C1 extension C1Alias : Prot1 {}
a36ccaeb776ce06833a7ad54c86e1585
19.233333
111
0.654036
false
false
false
false
tehprofessor/SwiftyFORM
refs/heads/master
Example/Other/WorkInProgressViewController.swift
mit
1
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class WorkInProgressViewController: FormViewController { override func populate(builder: FormBuilder) { builder.navigationTitle = "Work In Progress" builder += stepperForm0 builder += button0 } lazy var stepperForm0: StepperFormItem = { let instance = StepperFormItem() instance.title("Number of Cats") return instance }() lazy var button0: ButtonFormItem = { let instance = ButtonFormItem() instance.title("Button 0") instance.action = { [weak self] in if let stepperValue = self?.stepperForm0.value { self?.form_simpleAlert("Button 0", "There are \(stepperValue) cats!") } } return instance }() }
9073c4af0b7f050410b16f00197193b2
26.032258
81
0.637232
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/decl/func/throwing_functions.swift
apache-2.0
12
// RUN: %target-typecheck-verify-swift enum Exception : Error { case A } // Basic syntax /////////////////////////////////////////////////////////////// func bar() throws -> Int { return 0 } func foo() -> Int { return 0 } // Currying /////////////////////////////////////////////////////////////////// func curry1() { } func curry1Throws() throws { } func curry2() -> () -> () { return curry1 } func curry2Throws() throws -> () -> () { return curry1 } func curry3() -> () throws -> () { return curry1Throws } func curry3Throws() throws -> () throws -> () { return curry1Throws } var a : () -> () -> () = curry2 var b : () throws -> () -> () = curry2Throws var c : () -> () throws -> () = curry3 var d : () throws -> () throws -> () = curry3Throws // Partial application //////////////////////////////////////////////////////// protocol Parallelogram { static func partialApply1(_ a: Int) throws } func partialApply2<T: Parallelogram>(_ t: T) { _ = T.partialApply1 } // Overload resolution///////////////////////////////////////////////////////// func barG<T>(_ t : T) throws -> T { return t } func fooG<T>(_ t : T) -> T { return t } var bGE: (_ i: Int) -> Int = barG // expected-error{{invalid conversion from throwing function of type '(_) throws -> _' to non-throwing function type '(Int) -> Int'}} var bg: (_ i: Int) throws -> Int = barG var fG: (_ i: Int) throws -> Int = fooG func fred(_ callback: (UInt8) throws -> ()) throws { } func rachel() -> Int { return 12 } func donna(_ generator: () throws -> Int) -> Int { return generator() } // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}} _ = donna(rachel) func barT() throws -> Int { return 0 } // expected-note{{}} func barT() -> Int { return 0 } // expected-error{{invalid redeclaration of 'barT()'}} func fooT(_ callback: () throws -> Bool) {} //OK func fooT(_ callback: () -> Bool) {} // Throwing and non-throwing types are not equivalent. struct X<T> { } func specializedOnFuncType1(_ x: X<(String) throws -> Int>) { } func specializedOnFuncType2(_ x: X<(String) -> Int>) { } func testSpecializedOnFuncType(_ xThrows: X<(String) throws -> Int>, xNonThrows: X<(String) -> Int>) { specializedOnFuncType1(xThrows) // ok specializedOnFuncType1(xNonThrows) // expected-error{{cannot convert value of type 'X<(String) -> Int>' to expected argument type 'X<(String) throws -> Int>'}} specializedOnFuncType2(xThrows) // expected-error{{cannot convert value of type 'X<(String) throws -> Int>' to expected argument type 'X<(String) -> Int>'}} specializedOnFuncType2(xNonThrows) // ok } // Subtyping func subtypeResult1(_ x: (String) -> ((Int) -> String)) { } func testSubtypeResult1(_ x1: (String) -> ((Int) throws -> String), x2: (String) -> ((Int) -> String)) { subtypeResult1(x1) // expected-error{{cannot convert value of type '(String) -> ((Int) throws -> String)' to expected argument type '(String) -> ((Int) -> String)'}} subtypeResult1(x2) } func subtypeResult2(_ x: (String) -> ((Int) throws -> String)) { } func testSubtypeResult2(_ x1: (String) -> ((Int) throws -> String), x2: (String) -> ((Int) -> String)) { subtypeResult2(x1) subtypeResult2(x2) } func subtypeArgument1(_ x: (_ fn: ((String) -> Int)) -> Int) { } func testSubtypeArgument1(_ x1: (_ fn: ((String) -> Int)) -> Int, x2: (_ fn: ((String) throws -> Int)) -> Int) { subtypeArgument1(x1) subtypeArgument1(x2) } func subtypeArgument2(_ x: (_ fn: ((String) throws -> Int)) -> Int) { } func testSubtypeArgument2(_ x1: (_ fn: ((String) -> Int)) -> Int, x2: (_ fn: ((String) throws -> Int)) -> Int) { subtypeArgument2(x1) // expected-error{{cannot convert value of type '(((String) -> Int)) -> Int' to expected argument type '(((String) throws -> Int)) -> Int'}} subtypeArgument2(x2) } // Closures var c1 = {() throws -> Int in 0} var c2 : () throws -> Int = c1 // ok var c3 : () -> Int = c1 // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}} var c4 : () -> Int = {() throws -> Int in 0} // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}} var c5 : () -> Int = { try c2() } // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}} var c6 : () throws -> Int = { do { _ = try c2() } ; return 0 } var c7 : () -> Int = { do { try c2() } ; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}} var c8 : () -> Int = { do { _ = try c2() } catch _ { var x = 0 } ; return 0 } // expected-warning {{initialization of variable 'x' was never used; consider replacing with assignment to '_' or removing it}} var c9 : () -> Int = { do { try c2() } catch Exception.A { var x = 0 } ; return 0 }// expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}} var c10 : () -> Int = { throw Exception.A; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}} var c11 : () -> Int = { try! c2() } var c12 : () -> Int? = { try? c2() } // Initializers struct A { init(doomed: ()) throws {} } func fi1() throws { A(doomed: ()) // expected-error {{call can throw but is not marked with 'try'}} // expected-warning{{unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} } struct B { init() throws {} init(foo: Int) {} } B(foo: 0) // expected-warning{{unused}} // rdar://problem/33040113 - Provide fix-it for missing "try" when calling throwing Swift function class E_33040113 : Error {} func rdar33040113() throws -> Int { throw E_33040113() } let _ = rdar33040113() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }}
83b5ff6318ee4f475c678e7114629583
40.903226
213
0.587067
false
false
false
false
ivngar/TDD-TodoList
refs/heads/master
TDD-TodoListTests/ItemListDataProviderTests.swift
mit
1
// // ItemListDataProviderTests.swift // TDD-TodoListTests // // Created by Ivan Garcia on 22/6/17. // Copyright © 2017 Ivan Garcia. All rights reserved. // import XCTest @testable import TDD_TodoList class ItemListDataProviderTests: XCTestCase { var sut: ItemListDataProvider! var tableView: UITableView! var controller: ItemListViewController! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. sut = ItemListDataProvider() sut.itemManager = ItemManager() let storyboard = UIStoryboard(name: "Main", bundle: nil) controller = storyboard.instantiateViewController(withIdentifier: "ItemListViewController") as! ItemListViewController _ = controller.view tableView = controller.tableView tableView.dataSource = sut tableView.delegate = sut } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. sut.itemManager?.removeAll() super.tearDown() } func test_NumberOfSections_IsTwo() { tableView.dataSource = sut let numberOfSections = tableView.numberOfSections XCTAssertEqual(numberOfSections, 2) } func test_NumberOfRows_InFirstSection_IsToDoCount() { tableView.dataSource = sut sut.itemManager?.add(ToDoItem(title: "Foo")) XCTAssertEqual(tableView.numberOfRows(inSection: 0), 1) sut.itemManager?.add(ToDoItem(title: "Bar")) tableView.reloadData() XCTAssertEqual(tableView.numberOfRows(inSection: 0), 2) } func test_NumberOfRows_InSecondSection_IsToDoneCount() { sut.itemManager?.add(ToDoItem(title: "Foo")) sut.itemManager?.add(ToDoItem(title: "Bar")) sut.itemManager?.checkItem(at: 0) XCTAssertEqual(tableView.numberOfRows(inSection: 1), 1) sut.itemManager?.checkItem(at: 0) tableView.reloadData() XCTAssertEqual(tableView.numberOfRows(inSection: 1), 2) } func test_CellForRow_RetursItemCell() { sut.itemManager?.add(ToDoItem(title: "Foo")) tableView.reloadData() let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) XCTAssertTrue(cell is ItemCell) } func test_CellForRow_DequeuesCellFromTableView() { let mockTableView = MockTableView.mockTableView(withDataSource: sut) sut.itemManager?.add(ToDoItem(title: "Foo")) mockTableView.reloadData() _ = mockTableView.cellForRow(at: IndexPath(row: 0, section: 0)) XCTAssertTrue(mockTableView.cellGotDequeued) } func test_CellForRow_CallsConfigCell() { let mockTableView = MockTableView.mockTableView(withDataSource: sut) let item = ToDoItem(title: "Foo") sut.itemManager?.add(item) mockTableView.reloadData() let cell = mockTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! MockItemCell XCTAssertEqual(cell.cachedItem, item) } func test_CellForRow_InSectionTwo_CallsConfigureCellWithDoneItem() { let mockTableView = MockTableView.mockTableView(withDataSource: sut) sut.itemManager?.add(ToDoItem(title: "Foo")) let second = ToDoItem(title: "Bar") sut.itemManager?.add(second) sut.itemManager?.checkItem(at: 1) mockTableView.reloadData() let cell = mockTableView.cellForRow(at: IndexPath(row: 0, section: 1)) as! MockItemCell XCTAssertEqual(cell.cachedItem, second) } func test_DeleteButton_InFirstSection_ShowsTitleCheck() { let deleteButtonTitle = tableView.delegate?.tableView?(tableView, titleForDeleteConfirmationButtonForRowAt: IndexPath(row: 0, section: 0)) XCTAssertEqual(deleteButtonTitle, "Check") } func test_DeleteButton_InSecondSection_ShowsTitleUncheck() { let deleteButtonTitle = tableView.delegate?.tableView?(tableView, titleForDeleteConfirmationButtonForRowAt: IndexPath(row: 0, section: 1)) XCTAssertEqual(deleteButtonTitle, "Uncheck") } func test_CheckingAnItem_ChecksItInTheItemManager() { sut.itemManager?.add(ToDoItem(title: "Foo")) tableView.dataSource?.tableView?(tableView, commit: .delete, forRowAt: IndexPath(row: 0, section: 0)) XCTAssertEqual(sut.itemManager?.todoCount, 0) XCTAssertEqual(sut.itemManager?.doneCount, 1) XCTAssertEqual(tableView.numberOfRows(inSection: 0), 0) XCTAssertEqual(tableView.numberOfRows(inSection: 1), 1) } func test_UncheckingAnItem_UnchecksInTheItemManager() { sut.itemManager?.add(ToDoItem(title: "First")) sut.itemManager?.checkItem(at: 0) tableView.reloadData() tableView.dataSource?.tableView?(tableView, commit: .delete, forRowAt: IndexPath(row: 0, section: 1)) XCTAssertEqual(sut.itemManager?.todoCount, 1) XCTAssertEqual(sut.itemManager?.doneCount, 0) XCTAssertEqual(tableView.numberOfRows(inSection: 0), 1) XCTAssertEqual(tableView.numberOfRows(inSection: 1), 0) } func test_SelectingACell_SendsNotification() { //pag.157 } } extension ItemListDataProviderTests { class MockTableView: UITableView { var cellGotDequeued = false override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell { cellGotDequeued = true return super.dequeueReusableCell(withIdentifier: identifier, for: indexPath) } class func mockTableView(withDataSource dataSource: UITableViewDataSource) -> MockTableView { let mockTableView = MockTableView( frame: CGRect(x: 0, y: 0, width: 320, height: 480), style: .plain) mockTableView.dataSource = dataSource mockTableView.register(MockItemCell.self, forCellReuseIdentifier: "ItemCell") return mockTableView } } class MockItemCell: ItemCell { var cachedItem: ToDoItem? override func configCell(with item: ToDoItem, checked: Bool) { cachedItem = item } } }
63e824b0eebbba8fdf8ec2f13c2f2035
32.461111
142
0.706127
false
true
false
false
dtycoon/twitterfly
refs/heads/master
twitterfly/ComposeViewController.swift
mit
1
// // ComposeViewController.swift // twitterfly // // Created by Deepak Agarwal on 10/7/14. // Copyright (c) 2014 Deepak Agarwal. All rights reserved. // import UIKit class ComposeViewController: UIViewController, ComposeViewControllerDelegate { @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var screenName: UILabel! @IBOutlet weak var tweetButton: UIBarButtonItem! var composeTo: String! var segueDelegate: UserViewControllerDelegate! @IBOutlet weak var userInputView: UITextView! override func viewDidLoad() { super.viewDidLoad() userName.text = User.currentUser?.name var sn = User.currentUser?.screenname screenName.text = "@" + sn! var imageUrl = User.currentUser?.profileImageUrl if(imageUrl != nil) { println(" profileImageUrl = \(imageUrl!)") userImage.setImageWithURL(NSURL(string: imageUrl!)) } userInputView.text = composeTo ?? "" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTapCancel(sender: AnyObject) { println("onTapBack cancel") goHome() } func goHome() { segueDelegate.RequestSegueToViewController("HometimelineViewController") } @IBAction func onTweetAction(sender: AnyObject) { var myTweet = userInputView.text if(myTweet != nil) { let address = myTweet! println(" tweet composition = \(address)") var parameter = ["status":address] var url_post = "1.1/statuses/update.json" as String TweetsieClient.sharedInstance.tweetSelf(url_post,index: 0, params: parameter, tweetCompletionError: { (url_post, index, error) -> () in println("error in tweetSelf = \(error)") return }) goHome() } } func composeTweet (screenID: String) { composeTo = "@" + screenID + " " } }
3f64194b91ab035842e7db55fa07e37a
27.185185
147
0.595707
false
false
false
false
1738004401/Swift3.0--
refs/heads/master
SwiftCW/SwiftCW/Views/Home/SWHomeViewControllers.swift
mit
1
// // SWHomeViewControllers.swift // SwiftCW // // Created by YiXue on 17/3/16. // Copyright © 2017年 赵刘磊. All rights reserved. // import UIKit import SnapKit import AFNetworking class SWHomeViewControllers:BaseViewController { let tableView:UITableView = { let tableView = UITableView() // tableView.register(SWHomeTableViewCell.self, forCellReuseIdentifier: kCellIdentifier_SWHomeTableViewCell) return tableView }() lazy var layouts:[WBStatusLayout] = { return [WBStatusLayout]() }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadHttp(type: RefreshType.refreshTypeTop) } private func setupUI() { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = UITableViewCellSeparatorStyle.none view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.top.equalTo(kNavgation_Status_Height) make.left.right.equalTo(0) make.bottom.equalTo(-kTabbar_Height) } } private func loadHttp(type:RefreshType){ switch type { case .refreshTypeTop: break case .refreshTypeBottom: break } //2.0 拼接参数 let url = URL(string: "https://api.weibo.com/") let manager = AFHTTPSessionManager.init(baseURL: url) manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String> var params = ["access_token":SWUser.curUser()?.access_token] ; params["since_id"] = "\(0)"; let path = "2/statuses/home_timeline.json"; manager.get(path, parameters: params, progress: { (_) in }, success: { (task:URLSessionDataTask, json) in let dict = json as? NSDictionary; let item:WBTimelineItem = WBTimelineItem.model(withJSON: json)! for status in (item.statuses)!{ let layout:WBStatusLayout = WBStatusLayout.init(status: status, style: WBLayoutStyle.timeline) self.layouts.append(layout) } self.tableView.reloadData() }) { (_, error) in print(error) } } } extension SWHomeViewControllers:UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return layouts.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier_SWHomeTableViewCell, for: indexPath) let cellID = "cell" var cell:WBStatusCell? = tableView.dequeueReusableCell(withIdentifier: cellID) as! WBStatusCell? if (cell == nil) { cell = WBStatusCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellID) } cell?.setLayout(layouts[indexPath.row] ) return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return layouts[indexPath.row].height } }
b1f5da6bd2c8e97744a0ac3f918b91da
30.324324
156
0.595053
false
false
false
false
qingtianbuyu/Mono
refs/heads/master
Moon/Classes/Other/Extension/UIImage+Extension.swift
mit
1
// // UIImage+Extension.swift // Moon // // Created by YKing on 16/5/29. // Copyright © 2016年 YKing. All rights reserved. // import UIKit extension UIImage { class func imageWithColor( _ color: UIColor, size: CGSize) -> UIImage { //开启上下文 UIGraphicsBeginImageContextWithOptions(size, false, 0.0) //获取上下文 let ctx = UIGraphicsGetCurrentContext(); let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height); ctx!.setFillColor(color.cgColor) //在画布上面绘制出来 ctx!.fill(rect) //从上下文读取Image信息 let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image!; } class func imageName(_ name: String) -> (normalImage: UIImage, highLightedImage: UIImage) { let image = UIImage(named: name)!.withRenderingMode(UIImageRenderingMode.alwaysOriginal) let imageName = "\(name)-act" let highLightImage = UIImage(named: imageName)!.withRenderingMode(UIImageRenderingMode.alwaysOriginal) return (image, highLightImage) } }
2bfe4e85b36dfa6bbbc40fb900cd2048
27.638889
106
0.700291
false
false
false
false
CodaFi/swift
refs/heads/main
test/PlaygroundTransform/init.swift
apache-2.0
21
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -whole-module-optimization -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift // RUN: %target-build-swift -Xfrontend -playground -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift -module-name main // RUN: %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test import PlaygroundSupport class B { init() { } } class C : B { var i : Int var j : Int override init() { i = 3 j = 5 i + j } } let c = C() // CHECK: [{{.*}}] __builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] __builtin_log[='8'] // CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] __builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] __builtin_log[c='main.C']
4f348bc132b7fa2080d80c849d27aba4
34.294118
255
0.648333
false
false
false
false
exevil/Keys-For-Sketch
refs/heads/master
Source/Controller/Outline View/OutlineViewDelegate.swift
mit
1
// // OutlineViewDelegate.swift // KeysForSketch // // Created by Vyacheslav Dubovitsky on 24/03/2017. // Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved. // class OutlineViewDelegate: NSObject, NSOutlineViewDelegate { @IBOutlet weak var errorHandler: ShortcutErrorHandler! func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat { var height: CGFloat = 0 // Should crash if no value is set if let menuItem = item as? NSMenuItem { if menuItem.isSeparatorItem { height = Const.Cell.separatorHeight } else { height = Const.Cell.height } } return height } func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { var cell: NSTableCellView? if let menuItem = item as? NSMenuItem { if menuItem.isSeparatorItem { cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "separatorCell"), owner: self) as? NSTableCellView } else { cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "menuCell"), owner: self, menuItem: menuItem) } } return cell } }
fee5c1a88a70c45b4f573e94dcacc8db
36.083333
150
0.638202
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
MinimedKit/Extensions/NSDateComponents.swift
mit
1
// // NSDateComponents.swift // Naterade // // Created by Nathan Racklyeft on 9/13/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation extension DateComponents { init(mySentryBytes: Data) { self.init() hour = Int(mySentryBytes[0] & 0b00011111) minute = Int(mySentryBytes[1] & 0b00111111) second = Int(mySentryBytes[2] & 0b00111111) year = Int(mySentryBytes[3]) + 2000 month = Int(mySentryBytes[4] & 0b00001111) day = Int(mySentryBytes[5] & 0b00011111) calendar = Calendar(identifier: .gregorian) } init(pumpEventData: Data, offset: Int, length: Int = 5) { self.init(pumpEventBytes: pumpEventData.subdata(in: offset..<offset + length)) } init(pumpEventBytes: Data) { self.init() if pumpEventBytes.count == 5 { second = Int(pumpEventBytes[0] & 0b00111111) minute = Int(pumpEventBytes[1] & 0b00111111) hour = Int(pumpEventBytes[2] & 0b00011111) day = Int(pumpEventBytes[3] & 0b00011111) month = Int((pumpEventBytes[0] & 0b11000000) >> 4) + Int((pumpEventBytes[1] & 0b11000000) >> 6) year = Int(pumpEventBytes[4] & 0b01111111) + 2000 } else { day = Int(pumpEventBytes[0] & 0b00011111) month = Int((pumpEventBytes[0] & 0b11100000) >> 4) + Int((pumpEventBytes[1] & 0b10000000) >> 7) year = Int(pumpEventBytes[1] & 0b01111111) + 2000 } calendar = Calendar(identifier: .gregorian) } init(glucoseEventBytes: Data) { self.init() year = Int(glucoseEventBytes[3] & 0b01111111) + 2000 month = Int((glucoseEventBytes[0] & 0b11000000) >> 4) + Int((glucoseEventBytes[1] & 0b11000000) >> 6) day = Int(glucoseEventBytes[2] & 0b00011111) hour = Int(glucoseEventBytes[0] & 0b00011111) minute = Int(glucoseEventBytes[1] & 0b00111111) calendar = Calendar(identifier: .gregorian) } }
f63bb560ea7234bfb28e3fb81a07b5df
32.650794
86
0.578774
false
false
false
false
nikHowlett/WatchHealthMedicalDoctor
refs/heads/master
mobile/SleepAndHeartsViewController.swift
mit
1
// // SleepAndHeartsViewController.swift // mobile // // Created by MAC-ATL019922 on 6/25/15. // Copyright (c) 2015 UCB+nikhowlett. All rights reserved. // import Foundation import UIKit import HealthKit import CoreData class SleepAndHeartsViewController: UIViewController { var healthStore: HKHealthStore? @IBOutlet weak var mrhr: UILabel! @IBOutlet weak var mrhrdate: UILabel! @IBOutlet weak var napstart: UILabel! @IBOutlet weak var napend: UILabel! @IBOutlet weak var sleepstart: UILabel! @IBOutlet weak var sleepend: UILabel! @IBOutlet weak var SlpQual: UILabel! var data2sendlabel: String = "" lazy var managedObjectContext : NSManagedObjectContext? = { let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if let managedContext : NSManagedObjectContext? = appDelegate.managedObjectContext { return managedContext } else { return nil } }() //var surveys : [Survey] = [Survey]() var sleeps : [SleepHistoryObject] = [SleepHistoryObject]() func handleWatchKitNotification(notification: NSNotification) { if let userInfo = notification.object as? [String : Int] { print("sleep received/text updated") let someint = userInfo["sleep massage"]! let somestring = "\(someint)" data2sendlabel = somestring } let thisstart = sleepstart.text?.substringToIndex(advance(sleepstart.text!.startIndex, 19)) let thisend = sleepend.text?.substringToIndex(advance(sleepend.text!.startIndex, 19)) let temp1 : String! = data2sendlabel SlpQual.text = temp1 let shanty = self.sleepstart.text let thisstart2 = shanty!.substringToIndex(advance(shanty!.startIndex, 19)) //println(thisstart) let lastsleepstart = self.sleeps[self.sleeps.count-1].sleepStart //println(lastsleepstart) if (thisstart == lastsleepstart) || (thisstart2 == lastsleepstart) { //self.SlpQual.text = self.sleeps[self.sleeps.count-1].sleepQuality //sleeps.removeAtIndex(sleeps.count-1) managedObjectContext?.deleteObject(sleeps[sleeps.count-1] as SleepHistoryObject) var error: NSError? = nil do { try managedObjectContext!.save() sleeps.removeAtIndex(self.sleeps.count-1) } catch var error1 as NSError { error = error1 print("Failed to delete the item \(error), \(error?.userInfo)") } } self.saveSleep(thisstart!, sleepEnd: thisend!, sleepQuality: data2sendlabel) print(data2sendlabel) print("savingSLEEPsurvey \(data2sendlabel)") } private func saveSleep(sleepStart: String, sleepEnd: String, sleepQuality: String) { if managedObjectContext != nil { let entity = NSEntityDescription.entityForName("SleepHistoryObject", inManagedObjectContext: managedObjectContext!) //@objc(sleep) let sleep = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext!) as! mobile.SleepHistoryObject sleep.sleepStart = sleepStart sleep.sleepEnd = sleepEnd sleep.sleepQuality = sleepQuality var error: NSError? = nil do { try managedObjectContext!.save() //names.append(name) } catch var error1 as NSError { error = error1 print("Could not save \(error), \(error?.userInfo)") } } else { print("Could not get managed object context") } } override func viewDidLoad() { super.viewDidLoad() /*UIApplication.sharedApplication().registerUserNotificationSettings( UIUserNotificationSettings( forTypes:UIUserNotificationType.Sound | UIUserNotificationType.Alert, categories: nil)) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleWatchKitNotification:"), name: "WatchKitReq", object: nil) ` */ self.navigationItem.title = "Heart-Rate Analysis" refresh() let fetchRequest : NSFetchRequest = NSFetchRequest(entityName: "SleepHistoryObject") UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes:[UIUserNotificationType.Sound, UIUserNotificationType.Alert], categories: nil)) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleWatchKitNotification:"), name: "WatchKitReq", object: nil) let error: NSError? = nil do { sleeps = try managedObjectContext?.executeFetchRequest(fetchRequest) as! [SleepHistoryObject] } catch let error as NSError { print("An error occurred loading the data") } //sleeps.removeAtIndex(self.sleeps.count-1) if error != nil { print("An error occurred loading the data") } } @IBAction func rfrsh(sender: AnyObject) { refresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func refresh() { updateHeartRate() updateSHeartRate() updateNapRate() updateSleepRate() } func updateHeartRate() { let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) readMostRecentSample(sampleType!, completion: { (mostRecentHeartRate, error) -> Void in if error != nil { print("Error reading HeartRate from HealthKit Store: \(error.localizedDescription)") return } let heartRate = mostRecentHeartRate as? HKQuantitySample let bpm = heartRate?.quantity.doubleValueForUnit(HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit())) print("bpm=\(bpm)") // 4. Update UI in the main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in if bpm != nil { self.mrhr.text = "\(Int(bpm!))" } else { self.mrhr.text = "?" } }); }); } func updateSHeartRate() { let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) readMostRecentSample(sampleType!, completion: { (mostRecentHeartRate, error) -> Void in if error != nil { print("Error reading HeartRate from HealthKit Store: \(error.localizedDescription)") return } let heartRate = mostRecentHeartRate.startDate let funk = mostRecentHeartRate.startDate // 4. Update UI in the main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in //self.happiness = Int(self.bpmToHappiness(bpm)) //println("self.happiness=\(self.happiness)") if heartRate == funk { self.mrhrdate.text = "\(heartRate)" } else { self.mrhrdate.text = "?" } }); }); } func updateNapRate() { let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) // 2. Call the method to read the most recent weight sample readMostRecentNapStart(sampleType!, completion: { (mostRecentwakeupfromnapRate, error) -> Void in if error != nil { print("Error reading HeartRate from HealthKit Store: \(error.localizedDescription)") return } let heartRate = mostRecentwakeupfromnapRate.startDate let fartRate = mostRecentwakeupfromnapRate.startDate // 4. Update UI in the main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in if heartRate == fartRate { self.napstart.text = "\(heartRate)" } else { self.napstart.text = "?" } }); }); readMostRecentNapEnd(sampleType!, completion: { (mostRecentwakeupfromnapRate, error) -> Void in if error != nil { print("Error reading HeartRate from HealthKit Store: \(error.localizedDescription)") return } let faghlom = mostRecentwakeupfromnapRate.startDate let insanity = mostRecentwakeupfromnapRate.startDate // 4. Update UI in the main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in if faghlom == insanity { self.napend.text = "\(faghlom)" } else { self.napend.text = "?" } }); }); } private func readMostRecentSample(sampleType: HKSampleType, completion: ((HKSample!, NSError!) -> Void)!) { // 1. Build the Predicate let past = NSDate.distantPast() as NSDate let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) // 3. we want to limit the number of samples returned by the query to just 1 (the most recent) let limit = 1 // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor], resultsHandler: { (sampleQuery, results, error ) -> Void in if let queryError = error { completion(nil,error) return } // Get the first sample let mostRecentSample = results!.first as? HKQuantitySample // Execute the completion closure if completion != nil { completion(mostRecentSample, nil) } }) // 5. Execute the Query healthStore!.executeQuery(sampleQuery) } func updateSleepRate() { let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) // 2. Call the method to read the most recent weight sample readMostRecentSLPStart(sampleType!, completion: { (mostRecentwakeupfromnapRate, error) -> Void in if error != nil { print("Error reading HeartRate from HealthKit Store: \(error.localizedDescription)") return } let heartRate = mostRecentwakeupfromnapRate.startDate let notHeartRate = mostRecentwakeupfromnapRate.startDate // 4. Update UI in the main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in if heartRate == notHeartRate { self.sleepstart.text = "\(heartRate)" var shanty = self.sleepstart.text //var thisstart2 = shanty?.substringToIndex(advance(shanty!.startIndex, 19, shanty!.endIndex)) //var thisstart = sleepstart.text?.substringToIndex(advance(sleepstart.text!.startIndex, 19, sleepstart.text?.)) var thisstart = shanty!.substringToIndex(advance(shanty!.startIndex, 19)) //println(thisstart) var lastsleepstart = self.sleeps[self.sleeps.count-1].sleepStart //println(lastsleepstart) if (thisstart == lastsleepstart) { self.SlpQual.text = self.sleeps[self.sleeps.count-1].sleepQuality } else { let alertController = UIAlertController(title: "SleepQuality", message: "Most recent sleep data has no SleepQuality attribute. Please enter this information.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) //} } } else { self.sleepstart.text = "?" } }); }); /*if (sleeps.isEmpty) || (sleepstart.text == "?") || (sleepstart.text == "StartTime") { println("nosleepdata") } else { println("ok imma try to load the quality")*/ readMostRecentSLPEnd(sampleType!, completion: { (mostRecentwakeupfromnapRate, error) -> Void in if error != nil { print("Error reading HeartRate from HealthKit Store: \(error.localizedDescription)") return } let faghlom = mostRecentwakeupfromnapRate.startDate let jghlom = mostRecentwakeupfromnapRate.startDate // 4. Update UI in the main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in if faghlom == jghlom { self.sleepend.text = "\(faghlom)" } else { self.sleepend.text = "?" } }); }); } private func readMostRecentNapStart(sampleType: HKSampleType, completion: ((HKSample!, NSError!) -> Void)!) { let yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -3, toDate: NSDate(), options: []) let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(yesterday, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let limit = 1000 // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor], resultsHandler: { (sampleQuery, results, error ) -> Void in if let queryError = error { completion(nil,error) return } let totalsamp = results!.count var jk: Int = 0 var impda: NSDate = NSDate() var nap: String var naptime: String var boooool: Bool = (jk < totalsamp) while (boooool) { var thisstep: AnyObject = results![jk] var nextstep: AnyObject = results![jk+1] //let differenceComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: thisstep.startDate, toDate: nextstep.startDate, options: NSCalendarOptions(0) ) var shoodate: NSDate = (thisstep.startDate) var slambam: NSDate = (nextstep.startDate) var age = ((shoodate.timeIntervalSinceDate(slambam)) / 60) //.timeIntervalSinceDate(nextstep.startDate) //var age: Int? = differenceComponents.minute print(age) //this next number (integer i think) controls how long the "nap/sleep" is if (age < 30 || age > 180) { print(age) jk++ } else { print("final") print("number value is: \(jk)") boooool = false //impda = thisstep } } print("number value is: \(jk)") // Get the first sample let mostRecentSample = results![jk] as? HKQuantitySample // Execute the completion closure if completion != nil { completion(mostRecentSample, nil) } }) // 5. Execute the Query healthStore!.executeQuery(sampleQuery) } private func readMostRecentSLPStart(sampleType: HKSampleType, completion: ((HKSample!, NSError!) -> Void)!) { let yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -2, toDate: NSDate(), options: []) let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(yesterday, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let limit = 1000 // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor], resultsHandler: { (sampleQuery, results, error ) -> Void in if let queryError = error { completion(nil,error) return } let totalsamp = results!.count var jk: Int = 0 var impda: NSDate = NSDate() var nap: String var naptime: String var boooool: Bool = (jk < totalsamp) while (boooool) { var thisstep: AnyObject = results![jk] var nextstep: AnyObject = results![jk+1] //let differenceComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: thisstep.startDate, toDate: nextstep.startDate, options: NSCalendarOptions(0) ) var shoodate: NSDate = (thisstep.startDate) var slambam: NSDate = (nextstep.startDate) var age = ((shoodate.timeIntervalSinceDate(slambam)) / 60) //.timeIntervalSinceDate(nextstep.startDate) //var age: Int? = differenceComponents.minute print(age) //this next number (integer i think) controls how long the "nap/sleep" is if (age < 180) { print(age) jk++ } else { print("final") print("number value is: \(jk)") boooool = false //impda = thisstep } } print("number value is: \(jk)") // Get the first sample let mostRecentSample = results![jk] as? HKQuantitySample // Execute the completion closure if completion != nil { completion(mostRecentSample, nil) } }) // 5. Execute the Query healthStore!.executeQuery(sampleQuery) } private func readMostRecentNapEnd(sampleType: HKSampleType, completion: ((HKSample!, NSError!) -> Void)!) { let yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -3, toDate: NSDate(), options: []) let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(yesterday, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let limit = 1000 // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor], resultsHandler: { (sampleQuery, results, error ) -> Void in if let queryError = error { completion(nil,error) return } let totalsamp = results!.count var jk: Int = 0 var impda: NSDate = NSDate() var nap: String var naptime: String var boooool: Bool = (jk < totalsamp) while (boooool) { var thisstep: AnyObject = results![jk] var nextstep: AnyObject = results![jk+1] //let differenceComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: thisstep.startDate, toDate: nextstep.startDate, options: NSCalendarOptions(0) ) var shoodate: NSDate = (thisstep.startDate) var slambam: NSDate = (nextstep.startDate) var age = ((shoodate.timeIntervalSinceDate(slambam)) / 60) //.timeIntervalSinceDate(nextstep.startDate) //var age: Int? = differenceComponents.minute print(age) if (age < 30 || age > 180) { print(age) jk++ } else { print("final") print("number value is: \(jk)") boooool = false //impda = thisstep } } print("number value is: \(jk)") // Get the first sample let mostRecentSample = results![jk+1] as? HKQuantitySample // Execute the completion closure if completion != nil { completion(mostRecentSample, nil) } }) // 5. Execute the Query healthStore!.executeQuery(sampleQuery) } private func readMostRecentSLPEnd(sampleType: HKSampleType, completion: ((HKSample!, NSError!) -> Void)!) { let yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -3, toDate: NSDate(), options: []) let now = NSDate() let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(yesterday, endDate:now, options: .None) // 2. Build the sort descriptor to return the samples in descending order let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let limit = 1000 // 4. Build samples query let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor], resultsHandler: { (sampleQuery, results, error ) -> Void in if let queryError = error { completion(nil,error) return } let totalsamp = results!.count var jk: Int = 0 var impda: NSDate = NSDate() var nap: String var naptime: String var boooool: Bool = (jk < totalsamp) while (boooool) { var thisstep: AnyObject = results![jk] var nextstep: AnyObject = results![jk+1] //let differenceComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: thisstep.startDate, toDate: nextstep.startDate, options: NSCalendarOptions(0) ) var shoodate: NSDate = (thisstep.startDate) var slambam: NSDate = (nextstep.startDate) var age = ((shoodate.timeIntervalSinceDate(slambam)) / 60) //.timeIntervalSinceDate(nextstep.startDate) //var age: Int? = differenceComponents.minute print(age) if (age < 180) { print(age) jk++ } else { print("final") print("number value is: \(jk)") boooool = false //impda = thisstep } } print("number value is: \(jk)") // Get the first sample let mostRecentSample = results![jk+1] as? HKQuantitySample // Execute the completion closure if completion != nil { completion(mostRecentSample, nil) } }) // 5. Execute the Query healthStore!.executeQuery(sampleQuery) } }
4702fe7d0954ecd5574316b8733f5c2f
46.67684
208
0.524251
false
false
false
false
LiuChang712/SwiftHelper
refs/heads/master
SwiftHelper/Foundation/Date+SH.swift
mit
1
// // NSDate.swift // YST // // Created by LiuChang on 16/8/16. // Copyright © 2016年 LiuChang. All rights reserved. // import Foundation public extension Date { var year: Int { return (Calendar.current as NSCalendar).components(.year, from: self).year! } var month: Int { return (Calendar.current as NSCalendar).components(.month, from: self).month! } var day: Int { return (Calendar.current as NSCalendar).components(.day, from: self).day! } var hour: Int { return (Calendar.current as NSCalendar).components(.hour, from: self).hour! } var minute: Int { return (Calendar.current as NSCalendar).components(.minute, from: self).minute! } var second: Int { return (Calendar.current as NSCalendar).components(.second, from: self).second! } var nanosecond: Int { return (Calendar.current as NSCalendar).components(.nanosecond, from: self).nanosecond! } var weekday: Int { return (Calendar.current as NSCalendar).components(.weekday, from: self).weekday! } var weekdayOrdinal: Int { return (Calendar.current as NSCalendar).components(.weekdayOrdinal, from: self).weekdayOrdinal! } var weekOfMonth: Int { return (Calendar.current as NSCalendar).components(.weekOfMonth, from: self).weekOfMonth! } var weekOfYear: Int { return (Calendar.current as NSCalendar).components(.weekOfYear, from: self).weekOfYear! } var yearForWeekOfYear: Int { return (Calendar.current as NSCalendar).components(.yearForWeekOfYear, from: self).yearForWeekOfYear! } var quarter: Int { return (Calendar.current as NSCalendar).components(.quarter, from: self).quarter! } var isLeapMonth: Bool { return (Calendar.current as NSCalendar).components(.quarter, from: self).isLeapMonth! } var isLeapYear: Bool { let year = self.year return ((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))) } var isToday: Bool { if (fabs(self.timeIntervalSinceNow) >= 60 * 60 * 24) { return false } return Date().day == self.day } var isYesterday: Bool { let date = self.addDays(1) return date.isToday } var string: String { return string(dateFormat: "yyyyMMddHHmmss") } func string(dateFormat string: String) -> String { let formatter = DateFormatter() formatter.dateFormat = string formatter.locale = Locale.current return formatter.string(from: self) } } // add public extension Date { func addYears(_ years: Int) -> Date { let calender = Calendar.current var components = DateComponents() components.year = years return (calender as NSCalendar).date(byAdding: components, to: self, options: .wrapComponents)! } func addMonths(_ months: Int) -> Date { let calender = Calendar.current var components = DateComponents() components.month = months return (calender as NSCalendar).date(byAdding: components, to: self, options: .wrapComponents)! } func addWeeks(_ weeks: Int) -> Date { let calender = Calendar.current var components = DateComponents() components.weekOfYear = weeks return (calender as NSCalendar).date(byAdding: components, to: self, options: .wrapComponents)! } func addDays(_ days: Int) -> Date { let aTimeInterval = self.timeIntervalSinceReferenceDate + Double(86400 * days) return Date.init(timeIntervalSinceReferenceDate: aTimeInterval) } func addHours(_ hours: Int) -> Date { let aTimeInterval = self.timeIntervalSinceReferenceDate + Double(3600 * hours) return Date.init(timeIntervalSinceReferenceDate: aTimeInterval) } func addMinutes(_ minutes: Int) -> Date { let aTimeInterval = self.timeIntervalSinceReferenceDate + Double(60 * minutes) return Date.init(timeIntervalSinceReferenceDate: aTimeInterval) } func addSeconds(_ seconds: Int) -> Date { let aTimeInterval = self.timeIntervalSinceReferenceDate + Double(seconds) return Date.init(timeIntervalSinceReferenceDate: aTimeInterval) } }
d5d12cdc1c2898efc62e2344df4b9f25
29.534722
109
0.63134
false
false
false
false
ayushgoel/EasyTipView
refs/heads/master
Example/EasyTipView/ViewController.swift
mit
1
// // ViewController.swift // EasyTipView // // Created by Teodor Patras on 25.03.15. // Copyright (c) 2015 Teodor Patras. All rights reserved. // import UIKit import EasyTipView class ViewController: UIViewController, EasyTipViewDelegate { @IBOutlet weak var toolbarItem: UIBarButtonItem! @IBOutlet weak var smallContainerView: UIView! @IBOutlet weak var navBarItem: UIBarButtonItem! @IBOutlet weak var buttonA: UIButton! @IBOutlet weak var buttonB: UIButton! @IBOutlet weak var buttonC: UIButton! @IBOutlet weak var buttonD: UIButton! override func viewDidLoad() { super.viewDidLoad() self.configureUI() var preferences = EasyTipView.Preferences() preferences.font = UIFont(name: "Futura-Medium", size: 13) preferences.textColor = UIColor.whiteColor() preferences.bubbleColor = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1) preferences.arrowPosition = EasyTipView.ArrowPosition.Top EasyTipView.setGlobalPreferences(preferences) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.toolbarItemAction() } func easyTipViewDidDismiss(tipView: EasyTipView) { println("\(tipView) did dismiss!") } @IBAction func barButtonAction(sender: UIBarButtonItem) { EasyTipView.showAnimated(true, forItem: self.navBarItem, withinSuperview: self.navigationController?.view, text: "Tip view for bar button item displayed within the navigation controller's view. Tap to dismiss.", preferences: nil, delegate: self) } @IBAction func toolbarItemAction() { EasyTipView.showAnimated(true, forItem: self.toolbarItem, withinSuperview: nil, text: "EasyTipView is an easy to use tooltip view. Tap the buttons to see other tooltips.", preferences: nil, delegate: nil) } @IBAction func buttonAction(sender : UIButton) { switch sender { case buttonA: var preferences = EasyTipView.Preferences() preferences.bubbleColor = UIColor(hue:0.58, saturation:0.1, brightness:1, alpha:1) preferences.textColor = UIColor.darkGrayColor() preferences.font = UIFont(name: "HelveticaNeue-Regular", size: 10) preferences.textAlignment = NSTextAlignment.Center let view = EasyTipView(text: "Tip view within the green superview. Tap to dismiss.", preferences: preferences, delegate: nil) view.showForView(buttonA, withinSuperview: self.smallContainerView, animated: true) case buttonB: var preferences = EasyTipView.globalPreferences() preferences.textColor = UIColor.whiteColor() preferences.font = UIFont(name: "HelveticaNeue-Light", size: 14) preferences.textAlignment = NSTextAlignment.Justified EasyTipView.showAnimated(true, forView: self.buttonB, withinSuperview: self.navigationController?.view, text: "Tip view inside the navigation controller's view. Tap to dismiss!", preferences: preferences, delegate: nil) case buttonC: var preferences = EasyTipView.globalPreferences() preferences.bubbleColor = buttonC.backgroundColor! EasyTipView.showAnimated(true, forView: buttonC, withinSuperview: self.navigationController?.view, text: "This tip view cannot be presented with the arrow on the top position, so position bottom has been chosen instead. Tap to dismiss.", preferences: preferences, delegate: nil) default: var preferences = EasyTipView.globalPreferences() preferences.arrowPosition = EasyTipView.ArrowPosition.Bottom preferences.font = UIFont.systemFontOfSize(14) preferences.bubbleColor = buttonD.backgroundColor! EasyTipView.showAnimated(true, forView: buttonD, withinSuperview: nil, text: "Tip view within the topmost window. Tap to dismiss.", preferences: preferences, delegate: nil) } } func configureUI () { var color = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1) buttonA.backgroundColor = UIColor(hue:0.58, saturation:0.1, brightness:1, alpha:1) self.navigationController?.view.tintColor = color self.buttonB.backgroundColor = color self.smallContainerView.backgroundColor = color } }
7214273f347020856a7116af71e16919
40.830357
290
0.653789
false
false
false
false
qmathe/Starfish
refs/heads/master
Flux/Wave.swift
mit
1
/** Copyright (C) 2017 Quentin Mathe Author: Quentin Mathe <[email protected]> Date: June 2017 License: MIT */ import Foundation open class Wave<T>: Flux<Flux<T>> { private var subscribedFluxes = [Flux<T>]() // MARK: - Combining Fluxes open func merge() -> Flux<T> { let stream = Flux<T>() _ = subscribe() { event in switch event { case .value(let value): self.subscribe(to: value, redirectingEventsTo: stream) case .error(let error): stream.append(Flux<T>.Event.error(error)) case .completed: stream.append(Flux<T>.Event.completed) } } return stream } open func switchLatest() -> Flux<T> { let stream = Flux<T>() _ = subscribe() { event in switch event { case .value(let value): self.unsubscribeFromAll() self.subscribe(to: value, redirectingEventsTo: stream) case .error(let error): stream.append(Flux<T>.Event.error(error)) case .completed: stream.append(Flux<T>.Event.completed) } } return stream } // MARK: - Redirecting Fluxes private func unsubscribeFromAll() { subscribedFluxes.forEach { $0.unsubscribe(self) } subscribedFluxes.removeAll() } private func subscribe(to inputFlux: Flux<T>, redirectingEventsTo outputFlux: Flux<T>) { subscribedFluxes += [inputFlux] _ = inputFlux.subscribe(self) { event in outputFlux.append(event) } } }
c064aafa16f46c95897fb758a2c55eb0
24.444444
89
0.570805
false
false
false
false
instacrate/tapcrate-api
refs/heads/master
Sources/api/Library/Eloquent/ModelExpander.swift
mit
1
// // ModelExpander.swift // tapcrate-api // // Created by Hakon Hanesand on 6/30/17. // import Vapor import HTTP import Fluent import FluentProvider struct Relation { let type: Model.Type let name: String let path: String let isMany: Bool init(parent: Model.Type) { type = parent name = parent.idKey path = parent.entity isMany = false } init(child: Model.Type, path: String? = nil, hasMany: Bool = true) { type = child name = child.idKey self.path = path ?? child.entity isMany = hasMany } init(type: Model.Type, path: String, isMany: Bool = false) { self.type = type self.path = path name = type.entity self.isMany = isMany } } protocol Expandable { static func expandableParents() -> [Relation]? } extension Expandable { static func expandableParents() -> [Relation]? { return nil } } func collect<R: Model, B: Model, Identifier: StructuredDataWrapper>(identifiers: [Identifier], base: B.Type, relation: Relation) throws -> [[R]] { let ids: [Node] = try identifiers.converted(in: jsonContext) let models = try R.makeQuery().filter(.subset(relation.name, .in, ids)).all() return identifiers.map { (id: Identifier) -> [R] in return models.filter { let node = (try? $0.id.makeNode(in: emptyContext)) ?? Node.null return node.wrapped == id.wrapped } } } struct Expander<T: BaseModel>: QueryInitializable { static var key: String { return "expand" } let expandKeyPaths: [String] init(node: Node) throws { expandKeyPaths = node.string?.components(separatedBy: ",") ?? [] } func expand<N: StructuredDataWrapper, T: BaseModel>(for models: [T], mappings: @escaping (Relation, [N]) throws -> [[NodeRepresentable]]) throws -> [Node] { let ids = try models.map { try $0.id().converted(to: N.self) } guard let expandlableRelationships = T.expandableParents() else { throw Abort.custom(status: .badRequest, message: "Could not find any expandable relationships on \(T.self).") } let relationships = try expandKeyPaths.map { (path: String) -> (Relation, [[NodeRepresentable]]) in guard let relation = expandlableRelationships.filter({ $0.path == path }).first else { throw Abort.custom(status: .badRequest, message: "\(path) is not a valid expansion on \(T.self).") } return try (relation, mappings(relation, ids)) } var result: [Node] = [] for (index, owner) in models.enumerated() { var ownerNode = try owner.makeNode(in: jsonContext) for (relationship, allEntities) in relationships { let entities = allEntities[index] ownerNode[relationship.type.foreignIdKey] = nil if entities.count == 0 { ownerNode[relationship.path] = Node.null } else if entities.count == 1 && !relationship.isMany { ownerNode[relationship.path] = try entities[0].makeNode(in: jsonContext) } else { ownerNode[relationship.path] = try Node.array(entities.map { try $0.makeNode(in: jsonContext) }) } } result.append(ownerNode) } return result } func expand<N: StructuredDataWrapper, T: BaseModel>(for model: T, mappings: @escaping (Relation, N) throws -> [NodeRepresentable]) throws -> Node { let node = try expand(for: [model], mappings: { (relation, identifiers: [N]) -> [[NodeRepresentable]] in return try [mappings(relation, identifiers[0])] }) if node.count == 0 { return Node.null } else if node.count == 1 { return node[0] } else { return Node.array(node) } } }
19687f2e7a8089e67b40e73388b4c7a2
28.81203
160
0.586885
false
false
false
false
OscarSwanros/swift
refs/heads/master
stdlib/public/core/UTF8.swift
apache-2.0
4
//===--- UTF8.swift -------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Unicode { @_fixed_layout public enum UTF8 { case _swift3Buffer(Unicode.UTF8.ForwardParser) } } extension Unicode.UTF8 : _UnicodeEncoding { public typealias CodeUnit = UInt8 public typealias EncodedScalar = _ValidUTF8Buffer<UInt32> @_inlineable // FIXME(sil-serialize-all) public static var encodedReplacementCharacter : EncodedScalar { return EncodedScalar.encodedReplacementCharacter } @inline(__always) @_inlineable public static func _isScalar(_ x: CodeUnit) -> Bool { return x & 0x80 == 0 } @inline(__always) @_inlineable public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { switch source.count { case 1: return Unicode.Scalar(_unchecked: source._biasedBits &- 0x01) case 2: let bits = source._biasedBits &- 0x0101 var value = (bits & 0b0_______________________11_1111__0000_0000) &>> 8 value |= (bits & 0b0________________________________0001_1111) &<< 6 return Unicode.Scalar(_unchecked: value) case 3: let bits = source._biasedBits &- 0x010101 var value = (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 16 value |= (bits & 0b0_______________________11_1111__0000_0000) &>> 2 value |= (bits & 0b0________________________________0000_1111) &<< 12 return Unicode.Scalar(_unchecked: value) default: _sanityCheck(source.count == 4) let bits = source._biasedBits &- 0x01010101 var value = (bits & 0b0_11_1111__0000_0000__0000_0000__0000_0000) &>> 24 value |= (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 10 value |= (bits & 0b0_______________________11_1111__0000_0000) &<< 4 value |= (bits & 0b0________________________________0000_0111) &<< 18 return Unicode.Scalar(_unchecked: value) } } @inline(__always) @_inlineable public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { var c = source.value if _fastPath(c < (1&<<7)) { return EncodedScalar(_containing: UInt8(c)) } var o = c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<5)) { return EncodedScalar(_biasedBits: (o | c) &+ 0b0__1000_0001__1100_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 if _fastPath(c < (1&<<4)) { return EncodedScalar( _biasedBits: (o | c) &+ 0b0__1000_0001__1000_0001__1110_0001) } o |= c & 0b0__0011_1111 c &>>= 6 o &<<= 8 return EncodedScalar( _biasedBits: (o | c ) &+ 0b0__1000_0001__1000_0001__1000_0001__1111_0001) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public static func transcode<FromEncoding : _UnicodeEncoding>( _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type ) -> EncodedScalar? { if _fastPath(FromEncoding.self == UTF16.self) { let c = _identityCast(content, to: UTF16.EncodedScalar.self) var u0 = UInt16(truncatingIfNeeded: c._storage) if _fastPath(u0 < 0x80) { return EncodedScalar(_containing: UInt8(truncatingIfNeeded: u0)) } var r = UInt32(u0 & 0b0__11_1111) r &<<= 8 u0 &>>= 6 if _fastPath(u0 < (1&<<5)) { return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1100_0001) } r |= UInt32(u0 & 0b0__11_1111) r &<<= 8 if _fastPath(u0 & (0xF800 &>> 6) != (0xD800 &>> 6)) { u0 &>>= 6 return EncodedScalar( _biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1000_0001__1110_0001) } } else if _fastPath(FromEncoding.self == UTF8.self) { return _identityCast(content, to: UTF8.EncodedScalar.self) } return encode(FromEncoding.decode(content)) } @_fixed_layout public struct ForwardParser { public typealias _Buffer = _UIntBuffer<UInt32, UInt8> @inline(__always) @_inlineable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } @_fixed_layout public struct ReverseParser { public typealias _Buffer = _UIntBuffer<UInt32, UInt8> @inline(__always) @_inlineable public init() { _buffer = _Buffer() } public var _buffer: _Buffer } } extension UTF8.ReverseParser : Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @_inlineable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _sanityCheck(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1110_0000__1100_0000 == 0b0__1100_0000__1000_0000 { // 2-byte sequence. Top 4 bits of decoded result must be nonzero let top4Bits = _buffer._storage & 0b0__0001_1110__0000_0000 if _fastPath(top4Bits != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1111_0000__1100_0000__1100_0000 == 0b0__1110_0000__1000_0000__1000_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000__0000_0000 if _fastPath( top5Bits != 0 && top5Bits != 0b0__1101__0010_0000__0000_0000) { return (true, 3*8) } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000__1000_0000 { // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000__0000_0000 if _fastPath( top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that ends with the LSB of /// buffer. @inline(never) @_inlineable // FIXME(sil-serialize-all) @_versioned internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1111_0000__1100_0000 == 0b0__1110_0000__1000_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__1111__0010_0000 if top5Bits != 0 && top5Bits != 0b0__1101__0010_0000 { return 2 } } else if _buffer._storage & 0b1111_1000__1100_0000 == 0b1111_0000__1000_0000 { // 2-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000 { return 2 } } else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000 == 0b0__1111_0000__1000_0000__1000_0000 { // 3-byte prefix of 4-byte sequence // Make sure the top 5 bits of the decoded result would be in range let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000 if top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000 { return 3 } } return 1 } @inline(__always) @_inlineable public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(truncatingIfNeeded: _buffer._storage.byteSwapped) let shift = 32 &- bitCount return Encoding.EncodedScalar(_biasedBits: (x &+ 0x01010101) &>> shift) } } extension Unicode.UTF8.ForwardParser : Unicode.Parser, _UTFParser { public typealias Encoding = Unicode.UTF8 @inline(__always) @_inlineable public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) { _sanityCheck(_buffer._storage & 0x80 != 0) // this case handled elsewhere if _buffer._storage & 0b0__1100_0000__1110_0000 == 0b0__1000_0000__1100_0000 { // 2-byte sequence. At least one of the top 4 bits of the decoded result // must be nonzero. if _fastPath(_buffer._storage & 0b0_0001_1110 != 0) { return (true, 2*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1111_0000 == 0b0__1000_0000__1000_0000__1110_0000 { // 3-byte sequence. The top 5 bits of the decoded result must be nonzero // and not a surrogate let top5Bits = _buffer._storage & 0b0___0010_0000__0000_1111 if _fastPath(top5Bits != 0 && top5Bits != 0b0___0010_0000__0000_1101) { return (true, 3*8) } } else if _buffer._storage & 0b0__1100_0000__1100_0000__1100_0000__1111_1000 == 0b0__1000_0000__1000_0000__1000_0000__1111_0000 { // 4-byte sequence. The top 5 bits of the decoded result must be nonzero // and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if _fastPath( top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 ) { return (true, 4*8) } } return (false, _invalidLength() &* 8) } /// Returns the length of the invalid sequence that starts with the LSB of /// buffer. @inline(never) @_inlineable // FIXME(sil-serialize-all) @_versioned internal func _invalidLength() -> UInt8 { if _buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if _buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 { return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } @_inlineable // FIXME(sil-serialize-all) public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar { let x = UInt32(_buffer._storage) &+ 0x01010101 return _ValidUTF8Buffer(_biasedBits: x & ._lowBits(bitCount)) } }
317ce2048d16ecde745a63c812a6c24c
38.142361
80
0.572075
false
false
false
false
AndreMuis/STGTISensorTag
refs/heads/master
STGTISensorTag/STGAccelerometer.swift
mit
1
// // STGAccelerometer.swift // STGTISensorTag // // Created by Andre Muis on 5/11/16. // Copyright © 2016 Andre Muis. All rights reserved. // import CoreBluetooth public class STGAccelerometer { weak var delegate : STGAccelerometerDelegate! var measurementPeriod : Int var lowPassFilteringFactor : Float let serviceUUID : CBUUID var service : CBService? let dataCharacteristicUUID : CBUUID var dataCharacteristic : CBCharacteristic? let configurationCharacteristicUUID : CBUUID var configurationCharacteristic : CBCharacteristic? let periodCharacteristicUUID : CBUUID var periodCharacteristic : CBCharacteristic? var oldSmoothedAcceleration : STGVector init(delegate : STGAccelerometerDelegate) { self.delegate = delegate self.measurementPeriod = 0 self.lowPassFilteringFactor = 0.0 self.serviceUUID = CBUUID(string: STGConstants.Accelerometer.serviceUUIDString) self.service = nil self.dataCharacteristicUUID = CBUUID(string: STGConstants.Accelerometer.dataCharacteristicUUIDString) self.dataCharacteristic = nil self.configurationCharacteristicUUID = CBUUID(string: STGConstants.Accelerometer.configurationCharacteristicUUIDString) self.configurationCharacteristic = nil self.periodCharacteristicUUID = CBUUID(string: STGConstants.Accelerometer.periodCharacteristicUUIDString) self.periodCharacteristic = nil self.oldSmoothedAcceleration = STGVector(x: 0.0, y: 0.0, z: 0.0) } public func enable(measurementPeriodInMilliseconds measurementPeriod : Int, lowPassFilteringFactor : Float) { self.measurementPeriod = measurementPeriod self.lowPassFilteringFactor = lowPassFilteringFactor self.delegate.accelerometerEnable(self, measurementPeriod: measurementPeriod) } public func disable() { self.delegate.accelerometerDisable(self) } func characteristicUpdated(characteristic : CBCharacteristic) { if characteristic.UUID == self.dataCharacteristicUUID { if let value = characteristic.value { let acceleration : STGVector = self.accelerationWithCharacteristicValue(value) self.delegate.accelerometer(self, didUpdateAcceleration: acceleration) let smoothedAcceleration : STGVector = self.smoothedAccelerationWithCharacteristicValue(value) self.delegate.accelerometer(self, didUpdateSmoothedAcceleration: smoothedAcceleration) } } } func accelerationWithCharacteristicValue(characteristicValue : NSData) -> STGVector { let bytes : [Int8] = characteristicValue.signedIntegers let acceleration : STGVector = STGVector(x: -1.0 * (Float(bytes[0]) / 64.0) * STGConstants.Accelerometer.range, y: -1.0 * (Float(bytes[1]) / 64.0) * STGConstants.Accelerometer.range, z: -1.0 * (Float(bytes[2]) / 64.0) * STGConstants.Accelerometer.range) return acceleration } func smoothedAccelerationWithCharacteristicValue(characteristicValue : NSData) -> STGVector { let acceleration : STGVector = self.accelerationWithCharacteristicValue(characteristicValue) var smoothedAcceleration : STGVector = STGVector(x: 0.0, y: 0.0, z: 0.0) smoothedAcceleration.x = self.lowPassFilteringFactor * acceleration.x + (1.0 - self.lowPassFilteringFactor) * self.oldSmoothedAcceleration.x smoothedAcceleration.y = self.lowPassFilteringFactor * acceleration.y + (1.0 - self.lowPassFilteringFactor) * self.oldSmoothedAcceleration.y smoothedAcceleration.z = self.lowPassFilteringFactor * acceleration.z + (1.0 - self.lowPassFilteringFactor) * self.oldSmoothedAcceleration.z self.oldSmoothedAcceleration = smoothedAcceleration return smoothedAcceleration } }
fb38a76af4e93ecf73d69a018b117f19
31.232558
148
0.678211
false
false
false
false
RoRoche/iOSSwiftStarter
refs/heads/master
iOSSwiftStarter/Pods/CoreStore/CoreStore/Saving and Processing/UnsafeDataTransaction.swift
apache-2.0
1
// // UnsafeDataTransaction.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData #if USE_FRAMEWORKS import GCDKit #endif @available(*, deprecated=1.3.1, renamed="UnsafeDataTransaction") public typealias DetachedDataTransaction = UnsafeDataTransaction // MARK: - UnsafeDataTransaction /** The `UnsafeDataTransaction` provides an interface for non-contiguous `NSManagedObject` creates, updates, and deletes. This is useful for making temporary changes, such as partially filled forms. An unsafe transaction object should typically be only used from the main queue. */ public final class UnsafeDataTransaction: BaseDataTransaction { /** Saves the transaction changes asynchronously. For a `UnsafeDataTransaction`, multiple commits are allowed, although it is the developer's responsibility to ensure a reasonable leeway to prevent blocking the main thread. - parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block. */ public func commit(completion: (result: SaveResult) -> Void) { self.context.saveAsynchronouslyWithCompletion { (result) -> Void in self.result = result completion(result: result) } } /** Saves the transaction changes and waits for completion synchronously. For a `UnsafeDataTransaction`, multiple commits are allowed, although it is the developer's responsibility to ensure a reasonable leeway to prevent blocking the main thread. - returns: a `SaveResult` containing the success or failure information */ public func commitAndWait() -> SaveResult { let result = self.context.saveSynchronously() self.result = result return result } /** Rolls back the transaction. */ public func rollback() { CoreStore.assert( self.supportsUndo, "Attempted to rollback a \(typeName(self)) with Undo support disabled." ) self.context.rollback() } /** Undo's the last change made to the transaction. */ public func undo() { CoreStore.assert( self.supportsUndo, "Attempted to undo a \(typeName(self)) with Undo support disabled." ) self.context.undo() } /** Immediately flushes all pending changes to the transaction's observers. This is useful in conjunction with `ListMonitor`s and `ObjectMonitor`s created from `UnsafeDataTransaction`s used to manage temporary "scratch" data. - Important: Note that unlike `commit()`, `flush()` does not propagate/save updates to the `DataStack` and the persistent store. However, the flushed changes will be seen by children transactions created further from the current transaction (i.e. through `transaction.beginUnsafe()`) - throws: an error thrown from `closure`, or an error thrown by Core Data (usually validation errors or conflict errors) */ public func flush() { self.context.processPendingChanges() } /** Flushes all pending changes to the transaction's observers at the end of the `closure`'s execution. This is useful in conjunction with `ListMonitor`s and `ObjectMonitor`s created from `UnsafeDataTransaction`s used to manage temporary "scratch" data. - Important: Note that unlike `commit()`, `flush()` does not propagate/save updates to the `DataStack` and the persistent store. However, the flushed changes will be seen by children transactions created further from the current transaction (i.e. through `transaction.beginUnsafe()`) - parameter closure: the closure where changes can be made prior to the flush - throws: an error thrown from `closure`, or an error thrown by Core Data (usually validation errors or conflict errors) */ public func flush(@noescape closure: () throws -> Void) rethrows { try closure() self.context.processPendingChanges() } /** Redo's the last undone change to the transaction. */ public func redo() { CoreStore.assert( self.supportsUndo, "Attempted to redo a \(typeName(self)) with Undo support disabled." ) self.context.redo() } /** Begins a child transaction where `NSManagedObject` creates, updates, and deletes can be made. This is useful for making temporary changes, such as partially filled forms. - prameter supportsUndo: `undo()`, `redo()`, and `rollback()` methods are only available when this parameter is `true`, otherwise those method will raise an exception. Defaults to `false`. Note that turning on Undo support may heavily impact performance especially on iOS or watchOS where memory is limited. - returns: a `UnsafeDataTransaction` instance where creates, updates, and deletes can be made. */ @warn_unused_result public func beginUnsafe(supportsUndo supportsUndo: Bool = false) -> UnsafeDataTransaction { return UnsafeDataTransaction( mainContext: self.context, queue: self.transactionQueue, supportsUndo: supportsUndo ) } /** Returns the `NSManagedObjectContext` for this unsafe transaction. Use only for cases where external frameworks need an `NSManagedObjectContext` instance to work with. - Important: Note that it is the developer's responsibility to ensure the following: - that the `UnsafeDataTransaction` that owns this context should be strongly referenced and prevented from being deallocated during the context's lifetime - that all saves will be done either through the `UnsafeDataTransaction`'s `commit(...)` method, or by calling `save()` manually on the context, its parent, and all other ancestor contexts if there are any. */ public var internalContext: NSManagedObjectContext { return self.context } @available(*, deprecated=1.3.1, renamed="beginUnsafe") @warn_unused_result public func beginDetached() -> UnsafeDataTransaction { return self.beginUnsafe() } // MARK: Internal internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, supportsUndo: Bool) { super.init(mainContext: mainContext, queue: queue, supportsUndo: supportsUndo, bypassesQueueing: true) } }
85e48405ffd38d1a1d4066283ccf00df
43.418605
312
0.696859
false
false
false
false
SiddharthChopra/KahunaSocialMedia
refs/heads/master
KahunaSocialMedia/Classes/Instagram/InstagramFeedDataInfo.swift
mit
1
// // InstagramFeedDetails.swift // MyCity311 // // Created by Nehru on 3/17/17. // Copyright © 2017 Kahuna Systems. All rights reserved. // import UIKit public class InstagramFeedDataInfo: NSObject { public var createdDate: NSDate? public var webLink = String() public var userFullName = String() public var userName = String() public var userID = String() public var likeCount = String() public var commentCount = String() public var feedText = String() public var mediaID = String() public var thumbnailImg = String() public var standardImg = String() }
bc7b6991ba0bd1b1662eded7e349c72a
23.36
57
0.684729
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClientIntegrationTests/Spec/Gallery/GalleryViewsCountIncrementResponseHandlerSpec.swift
mit
1
// // GalleryViewsCountIncrementResponseHandlerSpec.swift // CreatubblesAPIClientIntegrationTests // // Copyright (c) 2017 Creatubbles Pte. 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 Quick import Nimble @testable import CreatubblesAPIClient class GalleryViewsCountIncrementResponseHandlerSpec: QuickSpec { override func spec() { describe("GalleryViewsCountIncrementResponseHandler") { context("user logged in") { it("Should increment gallery views count") { guard let galleryIdentifier = TestConfiguration.testGalleryIdentifier else { return } let requestSender = TestComponentsFactory.requestSender let request = GalleryViewsCountIncrementRequest(galleryIdentifier: galleryIdentifier) waitUntil(timeout: TestConfiguration.timeoutShort) { done in _ = requestSender.login(TestConfiguration.username, password: TestConfiguration.password) { (error: Error?) -> Void in expect(error).to(beNil()) _ = requestSender.send(request, withResponseHandler: GalleryViewsCountIncrementResponseHandler(completion: { (error) -> (Void) in expect(error).to(beNil()) done() })) } } } } context("User not logged in") { it("Should increment gallery views count") { guard let galleryIdentifier = TestConfiguration.testGalleryIdentifier else { return } let requestSender = TestComponentsFactory.requestSender let request = GalleryViewsCountIncrementRequest(galleryIdentifier: galleryIdentifier) waitUntil(timeout: TestConfiguration.timeoutShort) { done in _ = requestSender.authenticate { (error: Error?) -> Void in expect(error).to(beNil()) _ = requestSender.send(request, withResponseHandler: GalleryViewsCountIncrementResponseHandler(completion: { (error) -> (Void) in expect(error).to(beNil()) done() })) } } } } } } }
586968604ea9b25bf94912193c7b9f37
44.011765
136
0.564036
false
true
false
false
zacwood9/attics
refs/heads/master
Attics/Controllers/SourcesViewController.swift
bsd-3-clause
1
// // SourcesViewController.swift // Attics // // Created by Zachary Wood on 6/15/18. // Copyright © 2018 Zachary Wood. All rights reserved. // import UIKit class SourcesViewController: UICollectionViewController, Refreshable { var refreshControl = UIRefreshControl() var show: Show! var sources: [Source] = [] var dataStore: DataStore! var onSourceTap: (Source) -> () = { _ in } override func viewDidLoad() { super.viewDidLoad() setupViews() refresh() } func setupViews() { navigationItem.title = "\(show.date) sources" let backItem = UIBarButtonItem(title: "Sources", style: .plain, target: nil, action: nil) navigationItem.backBarButtonItem = backItem extendedLayoutIncludesOpaqueBars = true collectionView.refreshControl = refreshControl refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged) } func refresh() { dataStore.fetchSources(for: show) { [weak self] result in switch result { case .success(let sources): self?.sources = sources DispatchQueue.main.async { self?.collectionView.reloadData() self?.refreshControl.endRefreshing() // let indexPaths = (0..<sources.count).map { IndexPath(item: $0, section: 0) } // self?.collectionView.insertItems(at: indexPaths) } case .failure(let error): print(error) } } } } extension SourcesViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sources.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Source Cell", for: indexPath) as? SourceCollectionViewCell else { fatalError("Incorrect Cell type") } let source = sources[indexPath.item] cell.lineageLabel.text = source.lineage cell.downloadsLabel.text = "\(source.downloads) downloads" cell.reviewsLabel.text = "\(source.numReviews) reviews" cell.transfererLabel.text = source.transferer cell.transfererLabel.font = UIFont.preferredFont(forTextStyle: .title2, withSymbolicTraits: .traitBold) cell.stars.rating = source.avgRating cell.recordingTypeLabel.text = "" cell.view.roundCorners() cell.view.setShadow() return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { onSourceTap(sources[indexPath.item]) } } extension SourcesViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collectionView.frame.size.width if collectionView.traitCollection.horizontalSizeClass == .regular { // iPad return CGSize(width: width/2 - 24, height: 110) } return CGSize(width: width-24, height: 110) } }
8c6cb92136dc09ed3a69c1576c8a6362
36.719101
183
0.650879
false
false
false
false
vibeswift/SwiftPatterns
refs/heads/master
Singleton/ManagedSingleton.swift
apache-2.0
1
// // ManagedSingleton.swift // // Created by Carsten Klein on 15-03-07. // import Foundation // MARK: Public /// Protocol to which all singletons must conform. protocol Singleton : AnyObject {} /// Protocol to which all long lived singletons must conform. protocol LongLivedSingleton : Singleton {} /// The class `SingletonManager` models a singelton manager for instances of /// `Singleton`. class SingletonManager : LongLivedSingleton { /// Gets the singleton instance for this. class var INSTANCE : SingletonManager { return SingletonManager.getInstance(SingletonManager.self) { SingletonManager() } } /// Returns the singleton instance for the specified type. func getInstance<T: Singleton>( type: T.Type, factory: () -> AnyObject) -> T { return SingletonManager.getInstance(type, factory: factory) } /// Removes all singletons except for instances of `LongLivedSingleton`. class func gc() { for key in instances.keys { let instance : Instance = instances[key]! if !(instance.type is LongLivedSingleton) { instance.gc() } } } /// Destroys all instances. class func destroy() { instances.removeAll(keepCapacity: false) } /// private class func getInstance<T: Singleton>( type: T.Type, factory: () -> AnyObject) -> T { let fqname : String = toString(type) var instance : Instance? = instances[fqname] if instance == nil { instance = Instance(type: type, factory: factory as () -> AnyObject) instances[fqname] = instance } return instance!.getInstance() as! T } } // MARK: Private /// The class `Instance` models a holder for singleton instances and their /// respective factories. class Instance { var factory: () -> AnyObject var type: AnyClass var token: dispatch_once_t = 0 var instance: AnyObject? = nil func getInstance() -> AnyObject { dispatch_once(&self.token) { self.instance = self.factory() } return self.instance! } init(type: AnyClass, factory: () -> AnyObject) { self.type = type self.factory = factory } func gc() { self.instance = nil self.token = 0 } } /// The singleton instances. var instances = [String: Instance]() // MARK: Usage class ExampleShortLivedSingleton : Singleton { /// Use either computed properties or getters or methods here. /// /// **Note** Do not use stored properties as we do not want to hold a /// reference to the instance here. class var INSTANCE : ExampleShortLivedSingleton { return SingletonManager.INSTANCE.getInstance( ExampleShortLivedSingleton.self) { ExampleShortLivedSingleton() } } // The same but with a getter. class var INSTANCE2 : ExampleShortLivedSingleton { get { return SingletonManager.INSTANCE.getInstance( ExampleShortLivedSingleton.self) { ExampleShortLivedSingleton() } } } // The same but with a function class func INSTANCE3() -> ExampleShortLivedSingleton { return SingletonManager.INSTANCE.getInstance( ExampleShortLivedSingleton.self) { ExampleShortLivedSingleton() } } } class ExampleLongLivedSingleton : LongLivedSingleton { class var INSTANCE : ExampleLongLivedSingleton { return SingletonManager.INSTANCE.getInstance(ExampleLongLivedSingleton.self) { ExampleLongLivedSingleton() } } } // Access the instances so that they become available ExampleShortLivedSingleton.INSTANCE ExampleLongLivedSingleton.INSTANCE // Garbage collect all short lived singletons SingletonManager.gc() // We will get a new instance... ExampleShortLivedSingleton.INSTANCE2 // The same instance as before ExampleLongLivedSingleton.INSTANCE // Garbage collect all singletons SingletonManager.destroy() // A new instance SingletonManager.INSTANCE ExampleShortLivedSingleton.INSTANCE3() // Also a new instance ExampleLongLivedSingleton.INSTANCE
a0d0fa825b42f89a9cdce5d0fea5f23a
25.675
86
0.647142
false
false
false
false
mortenjust/find-for-kindle
refs/heads/master
here/ActionViewController.swift
mit
1
// // ActionViewController.swift // here // // Created by Morten Just Petersen on 6/18/16. // Copyright © 2016 Morten Just Petersen. All rights reserved. // import UIKit import MobileCoreServices class ActionViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var webView: UIWebView! // @IBOutlet weak var topBar: UINavigationBar! @IBOutlet weak var doneButton: UIButton! override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func doneButtonPressed(sender: AnyObject) { print("We just pressed the button") extensionContext?.completeRequestReturningItems(nil, completionHandler: nil) } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return .Slide } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { let draggedTo = scrollView.contentOffset.y if draggedTo < -140 { self.done() print("DONE") } // print("did end dragging at "+String(scrollView.contentOffset.y)) } override func viewDidLoad() { super.viewDidLoad() doneButton.hidden = true // overscroll may be enough for now webView.scrollView.delegate = self view.backgroundColor = UIColor(red:0.135, green:0.183, blue:0.246, alpha:1) navigationController?.navigationBar.barStyle = .Black for item: AnyObject in self.extensionContext!.inputItems { let inputItem = item as! NSExtensionItem for provider: AnyObject in inputItem.attachments! { let itemProvider = provider as! NSItemProvider if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeText as String) { // this is text itemProvider.loadItemForTypeIdentifier(kUTTypeText as String, options: nil, completionHandler: { (text, error) in if let searchString = text { print("let's do something about \(searchString)") self.loadPage(self.webView, query: searchString as! String) // load the web view } else { print("we don't know what to do ") } }) } } // let's only do something about the last item (would there ever be several?) } } func loadPage(webView:UIWebView, query:String){ let escapedQuery = query .stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLHostAllowedCharacterSet())! let urlString = "https://www.amazon.com/gp/aw/s/ref=is_s?n=154606011&n=154606011&k=\(escapedQuery)" let req = NSURLRequest(URL: NSURL(string: urlString)!) webView.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func done() { // Return any edited content to the host app. // This template doesn't do anything, so we just echo the passed in items. self.extensionContext!.completeRequestReturningItems(self.extensionContext!.inputItems, completionHandler: nil) } }
0b5dc00e0abace682ea4ed610aa8f50f
34.504854
133
0.605688
false
false
false
false
nathanlentz/rivals
refs/heads/master
Rivals/Rivals/RegisterViewController.swift
apache-2.0
1
// // RegisterViewController.swift // Rivals // // Created by Nate Lentz on 3/29/17. // Copyright © 2017 ntnl.design. All rights reserved. // import UIKit import Firebase class RegisterViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var confirmField: UITextField! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var registerButton: UIButton! @IBOutlet weak var chooseImageText: UIButton! var ref: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() ref = FIRDatabase.database().reference() profileImageView.layer.cornerRadius = 50 profileImageView.layer.masksToBounds = true let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController.dismissKeyboard)) view.addGestureRecognizer(tap) /* Theme */ view.backgroundColor = RIVALS_SECONDARY registerButton.backgroundColor = RIVALS_PRIMARY chooseImageText.titleLabel?.textColor = RIVALS_PRIMARY } /* Actions */ @IBAction func registerButton(_ sender: Any) { if validateFields(){ // Create our user in Firebase createUser() } } @IBAction func returnToLogin(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func chooseProfileImageDidPress(_ sender: Any) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = true let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in imagePicker.sourceType = UIImagePickerControllerSourceType.camera self.present(imagePicker, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(imagePicker, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } /** Functions */ func dismissKeyboard() { view.endEditing(true) } // Handle tap on profile pic func handleSelectProfileImageView() { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true // TODO: Implement taking a selfie to add a profile pic // need to create a different picker and set source to camera then do thte same thing as image picker controller // also need to add a new key to info.plist // Implement action sheet https://www.youtube.com/watch?v=4CbcMZOSmEk //picker.sourceType = UIImagePickerControllerSourceType.camera present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var imageFromPicker: UIImage? if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage { imageFromPicker = editedImage } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage{ imageFromPicker = originalImage } if let selectedImage = imageFromPicker { profileImageView.image = selectedImage } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } // Ensure user information is valid func validateFields() -> Bool { guard nameField.text != "", emailField.text != "", passwordField.text != "", confirmField.text != "" else { return false } if passwordField.text != confirmField.text { // TODO: Impelement validate visibility stuff print("Passwords do not match") return false } return true } // Create Firebase User func createUser(){ FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user, error) in if error == nil { let changeRequest = FIRAuth.auth()!.currentUser!.profileChangeRequest() changeRequest.displayName = self.nameField.text! changeRequest.commitChanges(completion: nil) // Generate unique string for naming in firebase storage let imgName = NSUUID().uuidString let storageRef = FIRStorage.storage().reference().child("profile_images").child(imgName) // Compress to 10% of quality if let uploadData = UIImageJPEGRepresentation(self.profileImageView.image!, 0.1) { storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in if error != nil { print(error!) return } if let imageProfileUrl = metadata?.downloadURL()?.absoluteString { if let user = user { let userInfo: [String : Any] = ["uid": user.uid, "name":self.nameField.text!, "email": self.emailField.text!, "wins": 0, "losses": 0, "profileImageUrl": imageProfileUrl] createUserInDatabase(uid: user.uid, userInfo: userInfo) //self.ref.child("profiles").child(user.uid).setValue(userInfo) let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SWRevealViewController") self.present(vc, animated: true, completion: nil) } } }) } } else { print(error!) } }) } }
90b1b0029777dbd14f6403985f50a91a
36.565217
201
0.58695
false
false
false
false
17thDimension/AudioKit
refs/heads/develop
Tests/Tests/AKEqualizerFilter.swift
lgpl-3.0
2
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/26/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let filename = "CsoundLib64.framework/Sounds/PianoBassDrumLoop.wav" let audio = AKFileInput(filename: filename) let mono = AKMix(monoAudioFromStereoInput: audio) auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:mono) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let frequencyLine = AKLine( firstPoint: 200.ak, secondPoint: 2500.ak, durationBetweenPoints: testDuration.ak ) let bandWidthLine = AKLine( firstPoint: 1.ak, secondPoint: 100.ak, durationBetweenPoints: testDuration.ak ) let equalizerFilter = AKEqualizerFilter(input: audioSource) equalizerFilter.centerFrequency = frequencyLine equalizerFilter.bandwidth = bandWidthLine equalizerFilter.gain = 100.ak enableParameterLog( "Center Frequency = ", parameter: equalizerFilter.centerFrequency, timeInterval:0.1 ) enableParameterLog( "Bandwidth = ", parameter: equalizerFilter.bandwidth, timeInterval:1.0 ) let output = AKBalance(input: equalizerFilter, comparatorAudioSource: audioSource) setAudioOutput(output) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() let manager = AKManager.sharedManager() while(manager.isRunning) {} //do nothing println("Test complete!")
f10b7eb913008ac8d5562abbcc5b9f56
24.536585
90
0.661414
false
true
false
false
mcxiaoke/learning-ios
refs/heads/master
ios_programming_4th/NerdFeed/NerdFeed/ViewController.swift
apache-2.0
1
// // ViewController.swift // NerdFeed // // Created by Xiaoke Zhang on 2017/9/5. // Copyright © 2017年 Xiaoke Zhang. All rights reserved. // import UIKit class ViewController: UITableViewController { let cities: [CityInfo] = [] var webViewController: WebViewController! override func viewDidLoad() { super.viewDidLoad() self.tableView.register(SimpleCell.self, forCellReuseIdentifier: "Cell") self.navigationController?.hidesBarsOnSwipe = false WeatherCenter.shared.fetchCities { self.tableView.reloadData() } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return WeatherCenter.shared.cities.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) // cell.accessoryType = .disclosureIndicator let city = WeatherCenter.shared.cities[indexPath.row] cell.textLabel?.text = city.name cell.detailTextLabel?.text = city.detail return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let city = WeatherCenter.shared.cities[indexPath.row] print("didSelectRowAt \(indexPath)") self.webViewController.city = city if self.splitViewController == nil { self.navigationController?.present(webViewController, animated: true, completion: nil) } } }
62d39e0c75f63ad085cbdce6366ed339
31.557692
109
0.676314
false
false
false
false
Boris-Em/ARCharts
refs/heads/master
SampleApp/Settings.swift
mit
1
// // Settings.swift // ARChartsSampleApp // // Created by Boris Emorine on 7/26/17. // Copyright © 2017 Boris Emorine. All rights reserved. // import Foundation import ARCharts struct Settings { var animationType: ARChartPresenter.AnimationType = .fade var longPressAnimationType : ARChartHighlighter.AnimationStyle = .shrink var barOpacity: Float = 1.0 var showLabels = true var numberOfSeries = 10 var numberOfIndices = 10 var graphWidth: Float = 0.3 var graphHeight: Float = 0.3 var graphLength: Float = 0.3 var dataSet: Int = 0 public func index(forEntranceAnimationType animationType: ARChartPresenter.AnimationType?) -> Int { guard let animationType = animationType else { return 0 } switch animationType { case .fade: return 0 case .progressiveFade: return 1 case .grow: return 2 case .progressiveGrow: return 3 } } public func entranceAnimationType(forIndex index: Int) -> ARChartPresenter.AnimationType? { switch index { case 0: return .fade case 1: return .progressiveFade case 2: return .grow case 3: return .progressiveGrow default: return .fade } } public func index(forLongPressAnimationType animationType: ARChartHighlighter.AnimationStyle?) -> Int { guard let animationType = animationType else { return 0 } switch animationType { case .shrink: return 0 case .fade: return 1 } } public func longPressAnimationType(forIndex index: Int) -> ARChartHighlighter.AnimationStyle? { switch index { case 0: return .shrink case 1: return .fade default: return .shrink } } }
ae1a9d2cd1ff42335ddd5ccc004413e3
24.227848
107
0.57702
false
false
false
false
noremac/Textile
refs/heads/master
TextileTests/Source/TextileTests.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2017 Cameron Pulsford 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 Textile class TextileTests: XCTestCase { var style: TextStyle! var defaultParagraphStyle = NSMutableParagraphStyle() override func setUp() { super.setUp() style = TextStyle() } override func tearDown() { style = nil super.tearDown() } // MARK: - Test attributes func tryAttributeKeyPath<T>(_ keyPath: WritableKeyPath<TextStyle, T?>, key: NSAttributedStringKey, value: T) where T: Equatable { style[keyPath: keyPath] = value XCTAssertEqual(style[keyPath: keyPath], value) XCTAssertEqual(style.attributes[key] as? T, value) } func testCustomAttribute() { style.color = .green style.attributes[.attachment] = "" XCTAssertEqual(style.attributes[.attachment] as? String, "") XCTAssertEqual(style.attributes[.foregroundColor] as? UIColor, .green) style.color = .red XCTAssertEqual(style.attributes[.foregroundColor] as? UIColor, .red) } func testForegroundColor() { tryAttributeKeyPath(\.color, key: .foregroundColor, value: .green) } func testBackgroundColor() { tryAttributeKeyPath(\.backgroundColor, key: .backgroundColor, value: .green) } func testLigature() { tryAttributeKeyPath(\.ligature, key: .ligature, value: 1) } func testKern() { tryAttributeKeyPath(\.kern, key: .kern, value: 1) } func testStrikethroughStyle() { tryAttributeKeyPath(\.strikethroughStyle, key: .strikethroughStyle, value: .styleSingle) } func testStrikethroughColor() { tryAttributeKeyPath(\.strikethroughColor, key: .strikethroughColor, value: .green) } func testUnderlineStyle() { tryAttributeKeyPath(\.underlineStyle, key: .underlineStyle, value: .styleSingle) } func testUnderlineColor() { tryAttributeKeyPath(\.underlineColor, key: .underlineColor, value: .green) } func testStrokeWidth() { tryAttributeKeyPath(\.strokeWidth, key: .strokeWidth, value: 1) } func testStrokeColor() { tryAttributeKeyPath(\.strokeColor, key: .strokeColor, value: .green) } func testShadow() { let shadow = NSShadow() tryAttributeKeyPath(\.shadow, key: .shadow, value: shadow) } func testTextEffect() { tryAttributeKeyPath(\.textEffect, key: .textEffect, value: .letterpressStyle) } func testBaselineoffset() { tryAttributeKeyPath(\.baselineOffset, key: .baselineOffset, value: 1) } func testObliqueness() { style.obliqueness = [1] XCTAssertEqual(style.obliqueness ?? [], [1]) XCTAssertEqual(style.attributes[.obliqueness] as? [CGFloat] ?? [], [1]) } func testExpansion() { style.expansion = [1] XCTAssertEqual(style.expansion ?? [], [1]) XCTAssertEqual(style.attributes[.expansion] as? [CGFloat] ?? [], [1]) } func testWritingDirection() { style.writingDirection = [.rightToLeft] XCTAssertEqual(style.writingDirection ?? [], [.rightToLeft]) XCTAssertEqual(style.attributes[.writingDirection] as? [NSWritingDirection] ?? [], [.rightToLeft]) } func testVerticalGlyphs() { tryAttributeKeyPath(\.verticalGlyphForm, key: .verticalGlyphForm, value: 1) } // MARK: - Test paragraph style func testParagraphForWritingDoesNotChange() { let style1 = style._paragraphStyleForWriting() style.lineSpacing = 1 let style2 = style._paragraphStyleForWriting() style.paragraphSpacing = 1 let style3 = style._paragraphStyleForWriting() XCTAssertTrue(style1 === style2) XCTAssertTrue(style1 === style3) } func tryParagraphStyleKeyPath<T>(_ styleKeyPath: WritableKeyPath<TextStyle, T>, _ paragraphStyleKeyPath: WritableKeyPath<NSMutableParagraphStyle, T>, value: T) where T: Equatable { XCTAssertEqual(style[keyPath: styleKeyPath], defaultParagraphStyle[keyPath: paragraphStyleKeyPath]) XCTAssertNil(style._mutableParagraphStyleStorage) style[keyPath: styleKeyPath] = value XCTAssertEqual(style[keyPath: styleKeyPath], value) XCTAssertEqual(style._mutableParagraphStyleStorage?[keyPath: paragraphStyleKeyPath], style[keyPath: styleKeyPath]) } func testLineSpacing() { tryParagraphStyleKeyPath(\.lineSpacing, \.lineSpacing, value: 1) } func testParagraphSpacing() { tryParagraphStyleKeyPath(\.paragraphSpacing, \.paragraphSpacing, value: 1) } func testAlignment() { tryParagraphStyleKeyPath(\.alignment, \.alignment, value: .center) } func testFirstLineHeadIndent() { tryParagraphStyleKeyPath(\.firstLineHeadIndent, \.firstLineHeadIndent, value: 1) } func testHeadIndent() { tryParagraphStyleKeyPath(\.headIndent, \.headIndent, value: 1) } func testTailIndent() { tryParagraphStyleKeyPath(\.tailIndent, \.tailIndent, value: 1) } func testLineBreakMode() { tryParagraphStyleKeyPath(\.lineBreakMode, \.lineBreakMode, value: .byCharWrapping) } func testMinimumLineHeight() { tryParagraphStyleKeyPath(\.minimumLineHeight, \.minimumLineHeight, value: 1) } func testMaximumLineHeight() { tryParagraphStyleKeyPath(\.maximumLineHeight, \.maximumLineHeight, value: 1) } func testBaseWritingDirection() { tryParagraphStyleKeyPath(\.baseWritingDirection, \.baseWritingDirection, value: .rightToLeft) } func testLineHeightMultiple() { tryParagraphStyleKeyPath(\.lineHeightMultiple, \.lineHeightMultiple, value: 1) } func testParagraphSpacingBefore() { tryParagraphStyleKeyPath(\.paragraphSpacingBefore, \.paragraphSpacingBefore, value: 1) } func testHyphenationFactor() { tryParagraphStyleKeyPath(\.hyphenationFactor, \.hyphenationFactor, value: 1) } func testTabStops() { let value = [NSTextTab(textAlignment: .center, location: 0, options: [:])] XCTAssertEqual(style.tabStops, defaultParagraphStyle.tabStops) XCTAssertNil(style._mutableParagraphStyleStorage) style.tabStops = value XCTAssertEqual(style.tabStops, value) XCTAssertEqual(style._mutableParagraphStyleStorage!.tabStops, style.tabStops) } func testDefaultTabInterval() { tryParagraphStyleKeyPath(\.defaultTabInterval, \.defaultTabInterval, value: 1) } func testAllowsDefaultTighteningForTruncation() { tryParagraphStyleKeyPath(\.allowsDefaultTighteningForTruncation, \.allowsDefaultTighteningForTruncation, value: true) } /// MARK: - Test fonts func testThatFontFeaturesAreApplied() { style.setFont(.systemFont(ofSize: 10), withFeatures: [UppercaseType.small]) guard let font = style.font else { return XCTFail("No font was created") } guard font.fontDescriptor.fontAttributes[fontFeatureSettingsAttribute] != nil else { return XCTFail("No features were added") } } /// MARK: - Test strings func testStyledWith() { let string = "Hello, world!" let color = UIColor.red let font = UIFont.systemFont(ofSize: 10) let attributedString1 = NSAttributedString(string: string, attributes: [.foregroundColor: color, .font: font]) style.color = color style.font = font let attributedString2 = string.styledWith(style) XCTAssertEqual(attributedString1, attributedString2) } }
010ef2ed0a5d2113982446aed186556b
33.86747
184
0.687054
false
true
false
false
accepton/accepton-apple
refs/heads/master
Pod/Classes/AcceptOnViewController/Views/CreditCardForm/AcceptOnCreditCardValidatableField.swift
mit
1
import UIKit @objc protocol AcceptOnUICreditCardValidatableFieldDelegate { func validatableFieldTapped(field: AcceptOnUICreditCardValidatableField, withName: String?) } //Each credit-card field contains one of these validatable fields behind it. It containts the //actual white oblong shape that goes red when a validation occurrs. It does not contain //the actual input field, etc. class AcceptOnUICreditCardValidatableField : UIView { //----------------------------------------------------------------------------------------------------- //Constants //----------------------------------------------------------------------------------------------------- let validBorderColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1).CGColor let errorBorderColor = UIColor(red:0.871, green:0.267, blue:0.220, alpha: 0.6).CGColor //----------------------------------------------------------------------------------------------------- //Properties //----------------------------------------------------------------------------------------------------- weak var delegate: AcceptOnUICreditCardValidatableFieldDelegate? var name: String? //View that gains first responder status & disabled touch when this view //does not have touch enabled weak var _responderView: UIView? var responderView: UIView? { set { _responderView = newValue _responderView?.userInteractionEnabled = false } get { return _responderView } } //Adds an error to the view, animates it in var _error: String? var error: String? { get { return _error } set { _error = newValue animateError() } } //----------------------------------------------------------------------------------------------------- //Constructors, Initializers, and UIView lifecycle //----------------------------------------------------------------------------------------------------- override init(frame: CGRect) { super.init(frame: frame) defaultInit() } required init(coder: NSCoder) { super.init(coder: coder)! defaultInit() } convenience init() { self.init(frame: CGRectZero) } func defaultInit() { self.layer.borderColor = validBorderColor self.layer.borderWidth = 1 self.layer.masksToBounds = true let tap = UITapGestureRecognizer(target: self, action: "viewWasTapped") tap.delaysTouchesBegan = false tap.delaysTouchesEnded = false self.addGestureRecognizer(tap) } override func resignFirstResponder() -> Bool { responderView?.resignFirstResponder() responderView?.userInteractionEnabled = false return true } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.bounds.size.height/2 } //----------------------------------------------------------------------------------------------------- //Animation helpers //----------------------------------------------------------------------------------------------------- //Animates the current error status. If the error status is nil, the field //is animated to no error func animateError() { //If there is an error if (error != nil) { //Animate the border color let anim = CABasicAnimation(keyPath: "borderColor") anim.beginTime = 0 anim.duration = 0.3 anim.toValue = errorBorderColor self.layer.addAnimation(anim, forKey: "error") self.layer.borderColor = errorBorderColor return } //No error, remove border color change self.layer.borderColor = validBorderColor } //----------------------------------------------------------------------------------------------------- //Signal / Action Handlers //----------------------------------------------------------------------------------------------------- //User tapped this field, gain first-responder status func viewWasTapped() { //Notify the delegate that we are the first-responder self.delegate?.validatableFieldTapped(self, withName: name) //Enable user-interaction temporarily responderView?.userInteractionEnabled = true responderView?.becomeFirstResponder() } }
1825da91d3d9a177eaec4388dcd795e5
36.561983
107
0.482508
false
false
false
false
Ataraxiis/MGW-Esport
refs/heads/develop
Carthage/Checkouts/RxSwift/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift
apache-2.0
19
// // RxTableViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif let tableViewDataSourceNotSet = TableViewDataSourceNotSet() class TableViewDataSourceNotSet : NSObject , UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { rxAbstractMethodWithMessage(dataSourceNotSet) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { rxAbstractMethodWithMessage(dataSourceNotSet) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { rxAbstractMethodWithMessage(dataSourceNotSet) } } /** For more information take a look at `DelegateProxyType`. */ public class RxTableViewDataSourceProxy : DelegateProxy , UITableViewDataSource , DelegateProxyType { /** Typed parent object. */ public weak private(set) var tableView: UITableView? private weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet /** Initializes `RxTableViewDataSourceProxy` - parameter parentObject: Parent object for delegate proxy. */ public required init(parentObject: AnyObject) { self.tableView = (parentObject as! UITableView) super.init(parentObject: parentObject) } // MARK: delegate /** Required delegate method implementation. */ public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSectionsInTableView?(tableView) ?? 1 } /** Required delegate method implementation. */ public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section) } /** Required delegate method implementation. */ public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAtIndexPath: indexPath) } // MARK: proxy /** For more information take a look at `DelegateProxyType`. */ public override class func createProxyForObject(object: AnyObject) -> AnyObject { let tableView = (object as! UITableView) return castOrFatalError(tableView.rx_createDataSourceProxy()) } /** For more information take a look at `DelegateProxyType`. */ public override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> { return _pointer(&dataSourceAssociatedTag) } /** For more information take a look at `DelegateProxyType`. */ public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let tableView: UITableView = castOrFatalError(object) tableView.dataSource = castOptionalOrFatalError(delegate) } /** For more information take a look at `DelegateProxyType`. */ public class func currentDelegateFor(object: AnyObject) -> AnyObject? { let tableView: UITableView = castOrFatalError(object) return tableView.dataSource } /** For more information take a look at `DelegateProxyType`. */ public override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UITableViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? tableViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
e718dc5f593c87ffeb0dcba8293759e8
30.511811
127
0.716392
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Source/UserSession/Search/SearchRequest.swift
gpl-3.0
1
// // 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 import WireDataModel public struct SearchOptions: OptionSet { public let rawValue: Int /// Users you are connected to via connection request public static let contacts = SearchOptions(rawValue: 1 << 0) /// Users found in your address book public static let addressBook = SearchOptions(rawValue: 1 << 1) /// Users which are a member of the same team as you public static let teamMembers = SearchOptions(rawValue: 1 << 2) /// Exclude team members which aren't in an active conversation with you public static let excludeNonActiveTeamMembers = SearchOptions(rawValue: 1 << 3) /// Exclude team members with the role .partner which aren't in an active conversation with you public static let excludeNonActivePartners = SearchOptions(rawValue: 1 << 4) /// Users from the public directory public static let directory = SearchOptions(rawValue: 1 << 5) /// Group conversations you are or were a participant of public static let conversations = SearchOptions(rawValue: 1 << 6) /// Services which are enabled in your team public static let services = SearchOptions(rawValue: 1 << 7) /// Users from federated servers public static let federated = SearchOptions(rawValue: 1 << 8) public init(rawValue: Int) { self.rawValue = rawValue } } extension SearchOptions { public mutating func updateForSelfUserTeamRole(selfUser: ZMUser) { if selfUser.teamRole == .partner { insert(.excludeNonActiveTeamMembers) remove(.directory) } else { insert(.excludeNonActivePartners) } } } public struct SearchRequest { public enum Query { case exactHandle(String) case fullTextSearch(String) var isHandleQuery: Bool { switch self { case .exactHandle: return true case .fullTextSearch: return false } } var string: String { switch self { case .exactHandle(let handle): return handle case .fullTextSearch(let text): return text } } } var team: Team? let query: Query let searchDomain: String? let searchOptions: SearchOptions public init(query: String, searchOptions: SearchOptions, team: Team? = nil) { let (query, searchDomain) = Self.parseQuery(query) self.query = query self.searchDomain = searchDomain self.searchOptions = searchOptions self.team = team } var normalizedQuery: String { query.string.normalizedAndTrimmed() } } private extension SearchRequest { static let maxQueryLength = 200 static func parseQuery(_ searchString: String) -> (Query, domain: String?) { let components = searchString .truncated(at: maxQueryLength) .split(separator: "@") .map { String($0).trimmingCharacters(in: .whitespaces).lowercased() } .filter { !$0.isEmpty } guard let text = components.element(atIndex: 0) else { return (.fullTextSearch(""), domain: nil) } let domain = components.element(atIndex: 1) if searchString.hasPrefix("@") { return (.exactHandle(text), domain) } else { return (.fullTextSearch(text), domain) } } } fileprivate extension String { func normalizedAndTrimmed() -> String { guard let normalized = self.normalizedForSearch() as String? else { return "" } return normalized.trimmingCharacters(in: .whitespaces) } }
4c9ce91d36b21b57806dbdb86caabc36
30.417266
99
0.647355
false
false
false
false
dfreniche/SpriteKit-Playground
refs/heads/master
Spritekit-playgorund.playground/Pages/Particle effects.xcplaygroundpage/Sources/SceneConfig.swift
mit
2
import SpriteKit import PlaygroundSupport // Create your view public func setupView() -> SKView { let view = SKView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768)) // Show the view in the Playground PlaygroundPage.current.liveView = view return view } public func setupScene() -> SKScene { let scene = SKScene(size: CGSize(width: 1024, height: 768)) scene.scaleMode = .aspectFit // define the scaleMode for this scene scene.backgroundColor = SKColor.lightGray return scene }
cca820df13877d98a4f387339e933fb9
24
74
0.689524
false
false
false
false
SimpleApp/evc-swift
refs/heads/master
EVC/EVC/AppDelegate.swift
mit
1
// // AppDelegate.swift // EVC // // Created by Benjamin Garrigues on 04/09/2017. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var engine: EVCEngine? = nil func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. #if DEBUG let env = EVCEngineEnvironment.development #else let env = EVCEngineEnvironment.integration #endif engine = EVCEngine(initialContext: EVCEngineContext(environment: env, applicationForeground: UIApplication.shared.applicationState == .active)) /* //Because this sample uses a storyboard, keyWindow is nil. //If you were to instanciate your root view controller manually, then you would configure its engine at this point. if let rootVC = UIApplication.shared.keyWindow?.rootViewController as? ViewController { rootVC.engine = engine } */ return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. engine?.onApplicationDidEnterBackground() } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. engine?.onApplicationDidBecomeActive() } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
33f75c11ce221ee5e5a62eeb030602d0
45.65625
285
0.713664
false
false
false
false
Tornquist/cocoaconfappextensionsclass
refs/heads/master
CocoaConf App Extensions Class/CocoaConfExtensions_03_Keyboard_End/CocoaConf Keyboard/KeyboardViewController.swift
cc0-1.0
6
// // KeyboardViewController.swift // CocoaConf Keyboard // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit class KeyboardViewController: UIInputViewController, UICollectionViewDataSource, UICollectionViewDelegate { let keys = ["α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ", "ο", "π", "ρ", "ς", "σ", "τ", "υ", "φ", "χ", "ψ", "ω", "ϊ", "ϋ", "ό", "ύ", "ώ"] override func textDidChange(textInput: UITextInput) { // The app has just changed the document's contents, the document context has been updated. var textColor: UIColor var proxy = self.textDocumentProxy as! UITextDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.Dark { textColor = UIColor.whiteColor() } else { textColor = UIColor.blackColor() } } @IBAction func handleNextKeyboardButtonTapped(sender: AnyObject) { self.advanceToNextInputMode() } @IBAction func handleKeyPress(sender: UIButton) { if let keyInputProxy = textDocumentProxy as? UIKeyInput { keyInputProxy.insertText(sender.titleLabel!.text!) } } // MARK: collection view data source func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return keys.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("KeyCell", forIndexPath: indexPath) as! UICollectionViewCell let button = cell.viewWithTag(1000) as! UIButton button.setTitle(keys[indexPath.row], forState: .Normal) return cell } }
a4c0c70f622f7a8095366ee63864f53e
31.578947
127
0.695746
false
false
false
false
taketo1024/SwiftyAlgebra
refs/heads/develop
Tests/SwmCoreTests/Numbers/RationalTests.swift
cc0-1.0
1
// // SwiftyMathTests.swift // SwiftyMathTests // // Created by Taketo Sano on 2017/05/03. // Copyright © 2017年 Taketo Sano. All rights reserved. // import XCTest @testable import SwmCore class RationalTests: XCTestCase { typealias A = 𝐐 func testEquality() { XCTAssertEqual(A(1), A(1, 1)) XCTAssertEqual(A(2), A(2, 1)) XCTAssertEqual(A(2, 1), A(4, 2)) XCTAssertEqual(A(-2, 1), A(4, -2)) } func testIntLiteral() { let a: A = 5 XCTAssertEqual(a, A(5, 1)) } func testRationalDivOp() { let a = 2./3 XCTAssertEqual(a, A(2, 3)) } func testSum() { let a = A(3, 2) let b = A(4, 5) XCTAssertEqual(a + b, A(23, 10)) } func testZero() { let a = A(3) let o = A.zero XCTAssertEqual(o + o, o) XCTAssertEqual(a + o, a) XCTAssertEqual(o + a, a) } func testNeg() { let a = A(3, 2) XCTAssertEqual(-a, A(-3, 2)) } func testMul() { let a = A(3, 5) let b = A(13, 6) XCTAssertEqual(a * b, A(13, 10)) } func testId() { let a = A(3, 4) let e = A.identity XCTAssertEqual(e * e, e) XCTAssertEqual(a * e, a) XCTAssertEqual(e * a, a) } func testInv() { let a = A(3, 5) XCTAssertEqual(a.inverse!, A(5, 3)) let o = A.zero XCTAssertNil(o.inverse) } func testDiv() { let a = A(3, 5) let b = A(3, 2) XCTAssertEqual(a / b, A(2, 5)) } func testPow() { let a = A(2, 3) XCTAssertEqual(a.pow(0), A(1)) XCTAssertEqual(a.pow(1), A(2, 3)) XCTAssertEqual(a.pow(2), A(4, 9)) XCTAssertEqual(a.pow(3), A(8, 27)) XCTAssertEqual(a.pow(-1), A(3, 2)) XCTAssertEqual(a.pow(-2), A(9, 4)) XCTAssertEqual(a.pow(-3), A(27, 8)) } func testIneq() { let a = A(4, 5) let b = A(3, 2) XCTAssertTrue(a < b) } func testSign() { let a = A(4, 5) let b = A(-4, 5) XCTAssertEqual(a.sign, 1) XCTAssertEqual(b.sign, -1) XCTAssertEqual(A.zero, 0) } func testAbs() { let a = A(4, 5) let b = A(-4, 5) XCTAssertEqual(a.abs, a) XCTAssertEqual(b.abs, a) } func testRandom() { var results: Set<A> = [] for _ in 0 ..< 100 { let x = A.random() results.insert(x) } XCTAssertTrue(results.isUnique) XCTAssertTrue(results.contains{ $0 > 0 }) XCTAssertTrue(results.contains{ $0 < 0 }) } func testRandomInRange() { let range: Range<A> = -100 ..< 100 var results: Set<A> = [] for _ in 0 ..< 100 { let x = A.random(in: range) results.insert(x) } XCTAssertTrue(results.allSatisfy{ range.contains($0) }) XCTAssertTrue(results.isUnique) XCTAssertTrue(results.contains{ $0 > 0 }) XCTAssertTrue(results.contains{ $0 < 0 }) } func testRandomInClosedRange() { let range: ClosedRange<A> = -100 ... 100 var results: Set<A> = [] for _ in 0 ..< 100 { let x = A.random(in: range) results.insert(x) } XCTAssertTrue(results.allSatisfy{ range.contains($0) }) XCTAssertTrue(results.isUnique) XCTAssertTrue(results.contains{ $0 > 0 }) XCTAssertTrue(results.contains{ $0 < 0 }) } }
66aef92651997670ebbd36e82b8ea6c8
22.699346
63
0.480695
false
true
false
false
PairOfNewbie/BeautifulDay
refs/heads/master
BeautifulDay/Controller/Album/AlbumCommentController.swift
mit
1
// // AlbumCommentController.swift // BeautifulDay // // Created by DaiFengyi on 16/5/30. // Copyright © 2016年 PairOfNewbie. All rights reserved. // import UIKit import SlackTextViewController private let albumZanCellIdentifier = "AlbumZanCell" private let albumCommentCellIdentifier = "AlbumCommentCell" class AlbumCommentController: SLKTextViewController { var pipWindow: UIWindow? var albumDetail: AlbumDetail? { didSet { tableView?.reloadData() } } override class func tableViewStyleForCoder(decoder: NSCoder) -> UITableViewStyle { return .Plain } func commonInit() { NSNotificationCenter.defaultCenter().addObserver(self.tableView!, selector: #selector(UITableView.reloadData), name: UIContentSizeCategoryDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AlbumCommentController.textInputbarDidMove(_:)), name: SLKTextInputbarDidMoveNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() commonInit() tableView?.estimatedRowHeight = 44 tableView?.rowHeight = UITableViewAutomaticDimension tableView?.registerNib(UINib(nibName: albumCommentCellIdentifier,bundle: nil), forCellReuseIdentifier: albumCommentCellIdentifier) tableView?.registerNib(UINib(nibName: albumZanCellIdentifier,bundle: nil), forCellReuseIdentifier: albumZanCellIdentifier) // SLKTVC's configuration self.bounces = true self.shakeToClearEnabled = true self.keyboardPanningEnabled = true self.shouldScrollToBottomAfterKeyboardShows = false self.inverted = false self.textInputbar.autoHideRightButton = true self.textInputbar.maxCharCount = 256 self.textInputbar.counterStyle = .Split self.textInputbar.counterPosition = .Top self.textInputbar.editorTitle.textColor = UIColor.darkGrayColor() self.textInputbar.editorLeftButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1) self.textInputbar.editorRightButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1) // self.autoCompletionView.registerClass(MessageTableViewCell.classForCoder(), forCellReuseIdentifier: AutoCompletionCellIdentifier) self.registerPrefixesForAutoCompletion(["@", "#", ":", "+:", "/"]) self.textView.registerMarkdownFormattingSymbol("*", withTitle: "Bold") self.textView.registerMarkdownFormattingSymbol("_", withTitle: "Italics") self.textView.registerMarkdownFormattingSymbol("~", withTitle: "Strike") self.textView.registerMarkdownFormattingSymbol("`", withTitle: "Code") self.textView.registerMarkdownFormattingSymbol("```", withTitle: "Preformatted") self.textView.registerMarkdownFormattingSymbol(">", withTitle: "Quote") } // MARK: - Action @objc func zan(sender: UIButton) { sender.selected = !sender.selected let keyframeAni = CAKeyframeAnimation(keyPath: "transform.scale") keyframeAni.duration = 0.5; keyframeAni.values = [0.1, 1.5, 1.0]; keyframeAni.keyTimes = [0, 0.8, 1]; keyframeAni.calculationMode = kCAAnimationLinear; sender.layer.addAnimation(keyframeAni, forKey: "zan") zanAction(sender.selected) } private func zanAction(status: Bool) { // todo postZan(albumDetail!.albuminfo!.albumId!, zanStatus: status, failure: { (error) in print("zan failure") SAIUtil.showMsg("点赞失败") }, success:{ (z) in print("zan success") }) } func textInputbarDidMove(note: NSNotification) { guard let pipWindow = self.pipWindow else { return } guard let userInfo = note.userInfo else { return } guard let value = userInfo["origin"] as? NSValue else { return } var frame = pipWindow.frame frame.origin.y = value.CGPointValue().y - 60.0 pipWindow.frame = frame } override func didPressRightButton(sender: AnyObject!) { // This little trick validates any pending auto-correction or auto-spelling just after hitting the 'Send' button self.textView.resignFirstResponder() postComment((albumDetail?.albuminfo?.albumId)!, content: textView.text, failure: { (error) in print("comment fail: \(error.description)") }) { [weak self](comment) in guard let weakSelf = self else { return } let indexPath = NSIndexPath(forRow: 0, inSection: 1) let rowAnimation: UITableViewRowAnimation = weakSelf.inverted ? .Bottom : .Top let scrollPosition: UITableViewScrollPosition = weakSelf.inverted ? .Bottom : .Top dispatch_async(dispatch_get_main_queue(), { weakSelf.tableView!.beginUpdates() weakSelf.albumDetail?.commentList?.insert(comment, atIndex: 0) weakSelf.tableView!.insertRowsAtIndexPaths([indexPath], withRowAnimation: rowAnimation) weakSelf.tableView!.endUpdates() weakSelf.tableView!.scrollToRowAtIndexPath(indexPath, atScrollPosition: scrollPosition, animated: true) weakSelf.tableView!.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) }) } super.didPressRightButton(sender) } // MARK: - UITableView override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: if let list = albumDetail?.commentList { return list.count }else { return 0 } default: return 0 } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: let header = UILabel(); header.backgroundColor = UIColor.lightGrayColor() header.text = "喜欢" return header case 1: let header = UILabel(); header.backgroundColor = UIColor.lightGrayColor() header.text = "评论" return header default: return nil } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCellWithIdentifier(albumZanCellIdentifier, forIndexPath: indexPath) if let button = cell.accessoryView as? UIButton { button.addTarget(self, action: #selector(AlbumCommentController.zan(_:)), forControlEvents: .TouchUpInside) } return cell case 1: let cell = tableView.dequeueReusableCellWithIdentifier(albumCommentCellIdentifier, forIndexPath: indexPath) return cell default: return UITableViewCell() } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.transform = tableView.transform switch indexPath.section { case 0: let c = cell as! AlbumZanCell var zlist = String() if let zanlist = albumDetail?.zanList { for z in zanlist { if let userName = z.userName { if zlist.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 { zlist = userName }else { zlist = zlist + (",\(userName)") } } } } if zlist.isEmpty { zlist = "还没人点赞,赶紧点赞吧!" } c.zanList.text = zlist break; case 1: let c = cell as! AlbumCommentCell if let comment = albumDetail?.commentList![indexPath.row] { // todo // c.name.text = comment. c.content.text = comment.content } default: break; } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } // override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // return 100 // } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cf12e5bd82e4fa3f0417e245d7d3ca0e
36.81323
187
0.610928
false
false
false
false
blomma/stray
refs/heads/master
stray/Tag+CoreDataClass.swift
gpl-3.0
1
import Foundation import CoreData import CloudKit class Tag: NSManagedObject, CoreDataStackEntity { override func awakeFromInsert() { super.awakeFromInsert() self.id = UUID().uuidString } } extension Tag: CloudKitStackEntity { var recordType: String { return Tag.entityName } var recordName: String { return "\(recordType).\(id)" } var recordZoneName: String { return Tag.entityName } func record() -> CKRecord { let id = recordID() let record = CKRecord(recordType: recordType, recordID: id) if let name = name { record["name"] = name as CKRecordValue } record["sortIndex"] = sortIndex as CKRecordValue return record } }
ea338def898fd93b61c7280aaf374ba2
23.037037
63
0.727273
false
false
false
false
suifengqjn/swiftDemo
refs/heads/master
Swift基本语法-黑马笔记/构造方法/main.swift
apache-2.0
1
// // main.swift // 构造方法 // // Created by 李南江 on 15/4/4. // Copyright (c) 2015年 itcast. All rights reserved. // import Foundation /* 构造方法: 作用: 对实例对象的内容进行初始化 Swift要求类或者结构体中的存储属性(非lazy的)在对象构造完毕后要有初始化值 语法: init(参数列表){ 初始化代码 } 注意: 1.在Swift中类/结构体/枚举都需要构造方法 2.构造方法的作用仅仅是用于初始化属性, 而不是分配内容, 分配内存是系统帮我们做的 3.构造方法是隐式调用的, 通过 类名称() 形式创建一个对象就会隐式调用init()构造方法 4.如果所有的存储属性都有默认值, 可以不提供构造方法, 系统会提供一个隐式的构造方法 5.如果存储属性可以提供缺省, 那么提倡大家使用设置缺省值的方式, 这样可以简化代码(不用自定义构造方法, 不用写存储属性类型) */ class Person { var name:String = "lnj" // var age:Int = 30 var age:Int func description() ->String{ return "name = \(name) age = \(age)" } init() { print("init") age = 30 } } // 1.分配内存 2.初始化name和age 3.构造方法是隐式调用的 var p = Person() p.description() //显示调用 /* 带参数的构造方法 */ class Person2 { var name:String var age:Int func description() ->String{ return "name = \(name) age = \(age)" } // 构造方法的内部参数, 默认也是外部参数 // 而函数的内部参数默认不会当做外部参数 // 而方法的内部参数, 从第二个开始才会当做外部参数 // init(name:String, age:Int) // 构造方法对属性的顺序没有要求, 只要保证对象构造完时所有存储属性被初始化即可 init(age:Int, name:String) { self.name = name self.age = age } func setName(name:String, age:Int) { } } //var p2 = Person(name: "lnj", age: 30) var p2 = Person2(age: 30, name: "lnj") p2.setName("lnj", age: 30) func setName(name:String, age:Int) { } p2.setName("lnj", age: 30) /* 常量存储属性与构造方法 常量存储属性只能通过缺省值或在构造方法中被修改, 其它任何地方都不能修改 */ class Person3 { var name:String = "lnj" var age:Int init(age:Int, name:String) { self.age = age self.name = name } func description() ->String{ return "name = \(name) age = \(age)" } } var p3 = Person3(age: 30, name:"zs") print(p3.description()) p3.age = 55 //p3.name = "xxx" // 常量存储属性初始化之后不允许被修改 /* 可选属性与构造方法 */ class Car{ let name:String init(name:String) { self.name = name } } class Person4 { let name:String var age:Int var car:Car? // 可选值存储属性可以不再构造方法中初始化, // 也就是说可选值在对象构造完毕后不用初始化 // 其实如果不对可选存储属性进行初始化, 默认就是nil init(age:Int, name:String) { self.age = age self.name = name } func description() ->String{ return "name = \(name) age = \(age)" } } /* 结构体构造方法 */ struct Rect{ // 此事即没有提供缺省值, 也没有提供构造方法, 但是编译通过 // 因为默认情况下, 结构体会给结构体提供一个默认的成员逐一构造器 var width:Double = 0.0 var heigth:Double = 0.0 /* // 系统默认会提供一个类似的方法 init(width:Double, height:Double) { self.width = width self.heigth = heigth } */ /* init() { self.width = 0.0 self.heigth = 0.0 } */ } // 注意: 1.在类中默认是没有逐一构造器的 // 2.如果在结构体中自定义了构造方法, 那么系统不会生成默认的逐一构造器 // 3.如果给存储属性提供了缺省值, 系统还是会提供默认的逐一构造器 //var r = Rect(width: 1.0, heigth: 1.0) // 4.如果给存储属性提供了缺省值, 可以使用不带参数的方法初始化结构体 var r = Rect() /* "值类型"的构造器代理 构造器代理: 构造方法之间的相互调用 构造方法可以调用其他构造方法来完成实例的构造, 称之为构造器代理 好处: 减少构造方法之间的重复代码 */ struct Rect2 { var width:Double var height:Double init(width:Double, height:Double) { self.width = width self.height = height } init() { // self.width = 0 // self.height = 0 // 构造器代理 self.init(width:0, height:0) } func show(){ print("width = \(width) height = \(height)") } } var r2 = Rect2() r2.show() var r3 = Rect2(width: 100, height: 100) r3.show() /* 通过闭包或者全局函数/类方法 设置存储属性的缺省值 如果需要经过计算, 或者需要进行一些额外的操作才能确定初始值时就可以通过闭包或全局函数设置存储属性的缺省值 */ func getValue() ->Int { print("getValue") return 55 } class Person5 { var name: String // 系统在初始化的时候会隐式执行闭包, 将闭包的执行结果赋值给存储属性 // 注意: 闭包后面一定要有(), 代表执行闭包 var age: Int = { // () -> Int in // 返回值可以省略, 默认返回值的类型就是存储属性的类型 print("age 闭包") return 30 }() lazy var height:Double = { print("lazy 闭包") return 175.0 }() var age2:Int = getValue() var age3:Int = Person5.getValue2() // 不能这样写, 因为调用方法时对象还没有初始化完毕 // self只有当所有的存储属性都初始化完毕之后才可以用 // var age3:Int = self.getValue3() init(name:String) { print("init") self.name = name } class func getValue2() -> Int{ print("class getValue2") return 100 } func getValue3() -> Int { return 88 } } var p5 = Person5(name: "lnj") // 懒加载是用到时才执行, 而闭包赋值是初始化时就会执行 print(p5.height)
570b29c975f41cb9518944e05f78a07f
17.133333
64
0.589844
false
false
false
false
digitalcatnip/Pace-SSS-iOS
refs/heads/master
SSSFreshmanApp/SSSFreshmanApp/RealmModels.swift
mit
1
// // RealmModels.swift // Pace SSS // // Created by James McCarthy on 8/31/16. // Copyright © 2016 Digital Catnip. All rights reserved. // import RealmSwift import GoogleAPIClient class BaseObject: Object { dynamic var id = 0 override static func primaryKey() -> String? { return "id" } } class Course: BaseObject { dynamic var campus = "" dynamic var course_number = "" dynamic var title = "" dynamic var subject_code = "" dynamic var subject_desc = "" dynamic var term_desc = "" dynamic var course_level = "" dynamic var subject_course = "" func initializeFromSpreadsheet(values: [String]) { campus = values[0] course_number = values[1] title = values[2] subject_code = values[3] subject_desc = values[4] if subject_code.characters.count > 0 && course_number.characters.count > 0 { subject_course = "\(subject_code) \(course_number)" } else { subject_course = "" } // term_desc = values[5] // course_level = values[6] id = getHashForID(subject_desc, course_number: course_number) } func getHashForID(subject: String, course_number: String) -> Int { return "\(subject) \(course_number)".hash } func fullSubject() -> String { if subject_course.characters.count > 0 { return "\(subject_desc) (\(subject_course))" } return subject_desc } } class Tutor: BaseObject { dynamic var first_name = "" dynamic var last_name = "" dynamic var email = "" dynamic var subjects = "" func initializeFromSpreadsheet(values: [String]) { first_name = values[0] last_name = values[1] email = values[2] subjects = values[3] id = getHashForID(first_name, lastName: last_name) } func getHashForID(firstName: String, lastName: String) -> Int { return "\(firstName) \(lastName)".hash } func fullName() -> String { return "\(first_name) \(last_name)" } } class Mentor: BaseObject { dynamic var first_name = "" dynamic var last_name = "" dynamic var email = "" dynamic var role = "" dynamic var major = "" func initializeFromSpreadsheet(values: [String]) { first_name = values[0] last_name = values[1] email = values[2] role = values[3] major = values[4] id = getHashForID(first_name, lastName: last_name) } func getHashForID(firstName: String, lastName: String) -> Int { return "\(firstName) \(lastName)".hash } func fullName() -> String { return "\(first_name) \(last_name)" } } class CalEvent: Object { dynamic var event_id = "" dynamic var start_time = NSDate() dynamic var end_time = NSDate() dynamic var title = "" dynamic var desc = "" //description func initializeFromGoogle(event: GTLCalendarEvent) { event_id = event.identifier var temp : GTLDateTime! = event.start.dateTime ?? event.start.date start_time = temp.date temp = event.end.dateTime ?? event.end.date end_time = temp.date title = event.summary if event.descriptionProperty != nil { desc = event.descriptionProperty } } override static func primaryKey() -> String? { return "event_id" } func eventTimeRange() -> String { let formatter = NSDateFormatter() formatter.dateFormat = "h:mm a" formatter.timeZone = NSTimeZone.defaultTimeZone() return "\(formatter.stringFromDate(start_time)) - \(formatter.stringFromDate(end_time))" } }
e49a4c6425aa5cd8cd6d0411df112006
26.423358
96
0.584243
false
false
false
false
tndatacommons/Compass-iOS
refs/heads/master
Compass/src/Controller/SourcesController.swift
mit
1
// // SourcesController.swift // Compass // // Created by Ismael Alonso on 7/13/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import UIKit class SourcesController: UITableViewController{ private var sources: [Source] = [Source](); override func viewDidLoad(){ sources.removeAll(); sources.append(Source(caption: "\"Stay strong with Compass\" messaging inspired by the work of the Character Lab. Thanks, Dr. Duckworth!", url: "https://characterlab.org/resources")); sources.append(Source(caption: "Illustrations: Michael Cook (Cookicons)", url: "http://cookicons.co")); sources.append(Source(caption: "Icons: designed by flaticon", url: "http://www.flaticon.com")); sources.append(Source(caption: "Misc art: designed by freepik", url: "http://www.freepik.com")); sources.append(Source(caption: "Just", url: "https://github.com/justhttp/Just")); sources.append(Source(caption: "Object Mapper", url: "https://github.com/Hearst-DD/ObjectMapper")); sources.append(Source(caption: "Locksmith", url: "https://github.com/matthewpalmer/Locksmith/")); sources.append(Source(caption: "Nuke", url: "https://github.com/kean/Nuke")); //Automatic height calculation tableView.rowHeight = UITableViewAutomaticDimension; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ print("Sources \(sources.count)"); return sources.count; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("SourceCell", forIndexPath: indexPath) as! SourceCell; cell.bind(sources[indexPath.row]); return cell; } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{ return 200; } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ CompassUtil.openUrl(NSURL(string: sources[indexPath.row].getUrl())!); } class Source{ private var caption: String; private var url: String; init(caption: String, url: String){ self.caption = caption; self.url = url; } func getCaption() -> String{ return caption; } func getUrl() -> String{ return url; } } }
fa8802da4de7a983f3e288328fd65ac8
36.57971
191
0.646356
false
false
false
false
mac-cain13/DocumentStore
refs/heads/master
DocumentStoreTests/Mocks/MockLogger.swift
mit
1
// // MockLogger.swift // DocumentStore // // Created by Mathijs Kadijk on 07-11-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation @testable import DocumentStore class MockLogger: Logger { struct LogMessage: Equatable { let level: LogLevel let message: String static func == (lhs: LogMessage, rhs: LogMessage) -> Bool { return lhs.level == rhs.level && lhs.message == rhs.message } } private(set) var loggedMessages: [LogMessage] = [] var logCallback: ((LogMessage) -> Void)? func log(level: LogLevel, message: String) { let logMessage = LogMessage(level: level, message: message) loggedMessages.append(logMessage) logCallback?(logMessage) } }
8d2b509eea23ead33cd87606931a9a85
23.366667
65
0.683995
false
false
false
false
matthewpurcell/firefox-ios
refs/heads/master
Utils/TimeConstants.swift
mpl-2.0
1
/* 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 typealias Timestamp = UInt64 public typealias MicrosecondTimestamp = UInt64 public let ThreeWeeksInSeconds = 3 * 7 * 24 * 60 * 60 public let OneMonthInMilliseconds = 30 * OneDayInMilliseconds public let OneWeekInMilliseconds = 7 * OneDayInMilliseconds public let OneDayInMilliseconds = 24 * OneHourInMilliseconds public let OneHourInMilliseconds = 60 * OneMinuteInMilliseconds public let OneMinuteInMilliseconds: UInt64 = 60 * 1000 extension NSDate { public class func now() -> Timestamp { return UInt64(1000 * NSDate().timeIntervalSince1970) } public class func nowNumber() -> NSNumber { return NSNumber(unsignedLongLong: now()) } public class func nowMicroseconds() -> MicrosecondTimestamp { return UInt64(1000000 * NSDate().timeIntervalSince1970) } public class func fromTimestamp(timestamp: Timestamp) -> NSDate { return NSDate(timeIntervalSince1970: Double(timestamp) / 1000) } public class func fromMicrosecondTimestamp(microsecondTimestamp: MicrosecondTimestamp) -> NSDate { return NSDate(timeIntervalSince1970: Double(microsecondTimestamp) / 1000000) } public func toRelativeTimeString() -> String { let now = NSDate() let units: NSCalendarUnit = [NSCalendarUnit.Second, NSCalendarUnit.Minute, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour] let components = NSCalendar.currentCalendar().components(units, fromDate: self, toDate: now, options: []) if components.year > 0 { return String(format: NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle)) } if components.month == 1 { return String(format: NSLocalizedString("more than a month ago", comment: "Relative date for dates older than a month and less than two months.")) } if components.month > 1 { return String(format: NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle)) } if components.weekOfYear > 0 { return String(format: NSLocalizedString("more than a week ago", comment: "Description for a date more than a week ago, but less than a month ago.")) } if components.day == 1 { return String(format: NSLocalizedString("yesterday", comment: "Relative date for yesterday.")) } if components.day > 1 { return String(format: NSLocalizedString("this week", comment: "Relative date for date in past week."), String(components.day)) } if components.hour > 0 || components.minute > 0 { let absoluteTime = NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.ShortStyle) let format = NSLocalizedString("today at %@", comment: "Relative date for date older than a minute.") return String(format: format, absoluteTime) } return String(format: NSLocalizedString("just now", comment: "Relative time for a tab that was visited within the last few moments.")) } } public func decimalSecondsStringToTimestamp(input: String) -> Timestamp? { var double = 0.0 if NSScanner(string: input).scanDouble(&double) { return Timestamp(double * 1000) } return nil } public func millisecondsToDecimalSeconds(input: Timestamp) -> String { let val: Double = Double(input) / 1000 return String(format: "%.2F", val) }
bda78ad724c098a7d83131ac99b4ed61
40.617021
193
0.697597
false
false
false
false
icylydia/PlayWithLeetCode
refs/heads/master
121. Best Time to Buy and Sell Stock/solution.swift
mit
1
class Solution { func maxProfit(prices: [Int]) -> Int { if prices.count < 1 { return 0 } var profits = [0] var best = 0 for i in 1..<prices.count { var profit = profits[i-1] + prices[i] - prices[i-1] if profit < 0 { profit = 0 } profits += [profit] if profit > best { best = profit } } return best } }
05d6bdb6a6cb66060e8b25132da08fbc
19.65
57
0.461165
false
false
false
false
elkanaoptimove/OptimoveSDK
refs/heads/master
OptimoveSDK/Common/Singletons/UserInSession.swift
mit
1
// // UserInSession.swift // OptimoveSDKDev // // Created by Mobile Developer Optimove on 11/09/2017. // Copyright © 2017 Optimove. All rights reserved. // import Foundation class UserInSession: Synchronizable { let lock:NSLock enum UserDefaultsKeys: String { case configurationEndPoint = "configurationEndPoint" case isMbaasOptIn = "isMbaasOptIn" case isOptiTrackOptIn = "isOptiTrackOptIn" case isFirstConversion = "isFirstConversion" case tenantToken = "tenantToken" case siteID = "siteID" case version = "version" case customerID = "customerID" case visitorID = "visitorID" case deviceToken = "deviceToken" case fcmToken = "fcmToken" case defaultFcmToken = "defaultFcmToken" case isFirstLaunch = "isFirstLaunch" case userAgentHeader = "userAgentHeader" case unregistrationSuccess = "unregistrationSuccess" case registrationSuccess = "registrationSuccess" case optSuccess = "optSuccess" case isSetUserIdSucceed = "isSetUserIdSucceed" case isClientHasFirebase = "userHasFirebase" case isClientUseFirebaseMessaging = "isClientUseFirebaseMessaging" case apnsToken = "apnsToken" case hasConfigurationFile = "hasConfigurationFile" case topics = "topic" case openAppTime = "openAppTime" case clientUseBackgroundExecution = "clientUseBackgroundExecution" case lastPingTime = "lastPingTime" case realtimeSetUserIdFailed = "realtimeSetUserIdFailed" } static let shared = UserInSession() private init() { lock = NSLock() } //MARK: Persist data var customerID:String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.customerID.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.customerID.rawValue) } } var visitorID:String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.visitorID.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.visitorID.rawValue) } } var apnsToken: Data? { get { return UserDefaults.standard.data(forKey: UserDefaultsKeys.apnsToken.rawValue) } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.apnsToken.rawValue) } } //MARK: Initializtion Flags var configurationEndPoint: String { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.configurationEndPoint.rawValue) { return id } return "" } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.configurationEndPoint.rawValue) } } var siteID:Int? { get { if let id = UserDefaults.standard.value(forKey: UserDefaultsKeys.siteID.rawValue) as? Int { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.siteID.rawValue) } } var tenantToken: String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.tenantToken.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.tenantToken.rawValue) } } var version:String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.version.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.version.rawValue) } } var hasConfigurationFile : Bool? { get { return UserDefaults.standard.value(forKey: UserDefaultsKeys.hasConfigurationFile.rawValue) as? Bool } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.hasConfigurationFile.rawValue) } } var isClientHasFirebase : Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.isClientHasFirebase.rawValue)} set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isClientHasFirebase.rawValue) } } var isClientUseFirebaseMessaging : Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.isClientUseFirebaseMessaging.rawValue)} set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isClientUseFirebaseMessaging.rawValue) } } // MARK: Optipush Flags var isMbaasOptIn: Bool? { get { lock.lock() let val = UserDefaults.standard.value(forKey: UserDefaultsKeys.isMbaasOptIn.rawValue) as? Bool lock.unlock() return val } set { lock.lock() self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isMbaasOptIn.rawValue) lock.unlock() } } var isUnregistrationSuccess : Bool { get { return (UserDefaults.standard.value(forKey: UserDefaultsKeys.unregistrationSuccess.rawValue) as? Bool) ?? true } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.unregistrationSuccess.rawValue) } } var isRegistrationSuccess : Bool { get { return (UserDefaults.standard.value(forKey: UserDefaultsKeys.registrationSuccess.rawValue) as? Bool) ?? true } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.registrationSuccess.rawValue) } } var isOptRequestSuccess : Bool { get { return (UserDefaults.standard.value(forKey: UserDefaultsKeys.optSuccess.rawValue) as? Bool) ?? true } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.optSuccess.rawValue) } } var isFirstConversion : Bool? { get { return UserDefaults.standard.value(forKey: UserDefaultsKeys.isFirstConversion.rawValue) as? Bool } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isFirstConversion.rawValue) } } var defaultFcmToken: String? { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.defaultFcmToken.rawValue) ?? nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.defaultFcmToken.rawValue) } } var fcmToken: String? { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.fcmToken.rawValue) ?? nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.fcmToken.rawValue) } } // MARK: OptiTrack Flags var isOptiTrackOptIn: Bool? { get { lock.lock() let val = UserDefaults.standard.value(forKey: UserDefaultsKeys.isOptiTrackOptIn.rawValue) as? Bool lock.unlock() return val } set { lock.lock() self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isOptiTrackOptIn.rawValue) lock.unlock() } } var lastPingTime: TimeInterval { get { return UserDefaults.standard.double(forKey: UserDefaultsKeys.lastPingTime.rawValue)} set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.lastPingTime.rawValue) } } var isSetUserIdSucceed : Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.isSetUserIdSucceed.rawValue)} set { self.setDefaultObject(forObject: newValue as Bool, key: UserDefaultsKeys.isSetUserIdSucceed.rawValue) } } // MARK: Real time flags var realtimeSetUserIdFailed: Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.realtimeSetUserIdFailed.rawValue) } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.realtimeSetUserIdFailed.rawValue) } } }
0bdd0ca86849f735a73a074ed3cdac73
31.554098
122
0.550307
false
false
false
false
FreddyZeng/Charts
refs/heads/master
Source/Charts/Charts/ChartViewBase.swift
apache-2.0
1
// // ChartViewBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // // Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880 import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif @objc public protocol ChartViewDelegate { /// Called when a value has been selected inside the chart. /// - parameter entry: The selected Entry. /// - parameter highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc. @objc optional func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) // Called when nothing has been selected or an "un-select" has been made. @objc optional func chartValueNothingSelected(_ chartView: ChartViewBase) // Callbacks when the chart is scaled / zoomed via pinch zoom gesture. @objc optional func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) // Callbacks when the chart is moved / translated via drag gesture. @objc optional func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) } open class ChartViewBase: NSUIView, ChartDataProvider, AnimatorDelegate { // MARK: - Properties /// - returns: The object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) @objc open var xAxis: XAxis { return _xAxis } /// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values. internal var _defaultValueFormatter: IValueFormatter? = DefaultValueFormatter(decimals: 0) /// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied internal var _data: ChartData? /// Flag that indicates if highlighting per tap (touch) is enabled private var _highlightPerTapEnabled = true /// If set to true, chart continues to scroll after touch up @objc open var dragDecelerationEnabled = true /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. private var _dragDecelerationFrictionCoef: CGFloat = 0.9 /// if true, units are drawn next to the values in the chart internal var _drawUnitInChart = false /// The object representing the labels on the x-axis internal var _xAxis: XAxis! /// The `Description` object of the chart. /// This should have been called just "description", but @objc open var chartDescription: Description? /// The legend object containing all data associated with the legend internal var _legend: Legend! /// delegate to receive chart events @objc open weak var delegate: ChartViewDelegate? /// text that is displayed when the chart is empty @objc open var noDataText = "No chart data available." /// Font to be used for the no data text. @objc open var noDataFont: NSUIFont! = NSUIFont(name: "HelveticaNeue", size: 12.0) /// color of the no data text @objc open var noDataTextColor: NSUIColor = NSUIColor.black /// alignment of the no data text open var noDataTextAlignment: NSTextAlignment = .left internal var _legendRenderer: LegendRenderer! /// object responsible for rendering the data @objc open var renderer: DataRenderer? @objc open var highlighter: IHighlighter? /// object that manages the bounds and drawing constraints of the chart internal var _viewPortHandler: ViewPortHandler! /// object responsible for animations internal var _animator: Animator! /// flag that indicates if offsets calculation has already been done or not private var _offsetsCalculated = false /// array of Highlight objects that reference the highlighted slices in the chart internal var _indicesToHighlight = [Highlight]() /// `true` if drawing the marker is enabled when tapping on values /// (use the `marker` property to specify a marker) @objc open var drawMarkers = true /// - returns: `true` if drawing the marker is enabled when tapping on values /// (use the `marker` property to specify a marker) @objc open var isDrawMarkersEnabled: Bool { return drawMarkers } /// The marker that is displayed when a value is clicked on the chart @objc open var marker: IMarker? private var _interceptTouchEvents = false /// An extra offset to be appended to the viewport's top @objc open var extraTopOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's right @objc open var extraRightOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's bottom @objc open var extraBottomOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's left @objc open var extraLeftOffset: CGFloat = 0.0 @objc open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { extraLeftOffset = left extraTopOffset = top extraRightOffset = right extraBottomOffset = bottom } // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } deinit { self.removeObserver(self, forKeyPath: "bounds") self.removeObserver(self, forKeyPath: "frame") } internal func initialize() { #if os(iOS) self.backgroundColor = NSUIColor.clear #endif _animator = Animator() _animator.delegate = self _viewPortHandler = ViewPortHandler(width: bounds.size.width, height: bounds.size.height) chartDescription = Description() _legend = Legend() _legendRenderer = LegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend) _xAxis = XAxis() self.addObserver(self, forKeyPath: "bounds", options: .new, context: nil) self.addObserver(self, forKeyPath: "frame", options: .new, context: nil) } // MARK: - ChartViewBase /// The data for the chart open var data: ChartData? { get { return _data } set { _data = newValue _offsetsCalculated = false guard let _data = _data else { setNeedsDisplay() return } // calculate how many digits are needed setupDefaultFormatter(min: _data.getYMin(), max: _data.getYMax()) for set in _data.dataSets { if set.needsFormatter || set.valueFormatter === _defaultValueFormatter { set.valueFormatter = _defaultValueFormatter } } // let the chart know there is new data notifyDataSetChanged() } } /// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()). @objc open func clear() { _data = nil _offsetsCalculated = false _indicesToHighlight.removeAll() lastHighlighted = nil setNeedsDisplay() } /// Removes all DataSets (and thereby Entries) from the chart. Does not set the data object to nil. Also refreshes the chart by calling setNeedsDisplay(). @objc open func clearValues() { _data?.clearValues() setNeedsDisplay() } /// - returns: `true` if the chart is empty (meaning it's data object is either null or contains no entries). @objc open func isEmpty() -> Bool { guard let data = _data else { return true } if data.entryCount <= 0 { return true } else { return false } } /// Lets the chart know its underlying data has changed and should perform all necessary recalculations. /// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour. @objc open func notifyDataSetChanged() { fatalError("notifyDataSetChanged() cannot be called on ChartViewBase") } /// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position internal func calculateOffsets() { fatalError("calculateOffsets() cannot be called on ChartViewBase") } /// calcualtes the y-min and y-max value and the y-delta and x-delta value internal func calcMinMax() { fatalError("calcMinMax() cannot be called on ChartViewBase") } /// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter internal func setupDefaultFormatter(min: Double, max: Double) { // check if a custom formatter is set or not var reference = Double(0.0) if let data = _data , data.entryCount >= 2 { reference = fabs(max - min) } else { let absMin = fabs(min) let absMax = fabs(max) reference = absMin > absMax ? absMin : absMax } if _defaultValueFormatter is DefaultValueFormatter { // setup the formatter with a new number of digits let digits = reference.decimalPlaces (_defaultValueFormatter as? DefaultValueFormatter)?.decimals = digits } } open override func draw(_ rect: CGRect) { let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } let frame = self.bounds if _data === nil && noDataText.count > 0 { context.saveGState() defer { context.restoreGState() } let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.minimumLineHeight = noDataFont.lineHeight paragraphStyle.lineBreakMode = .byWordWrapping paragraphStyle.alignment = noDataTextAlignment ChartUtils.drawMultilineText( context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), attributes: [.font: noDataFont, .foregroundColor: noDataTextColor, .paragraphStyle: paragraphStyle], constrainedToSize: self.bounds.size, anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: 0.0) return } if !_offsetsCalculated { calculateOffsets() _offsetsCalculated = true } } /// Draws the description text in the bottom right corner of the chart (per default) internal func drawDescription(context: CGContext) { // check if description should be drawn guard let description = chartDescription, description.isEnabled, let descriptionText = description.text, descriptionText.count > 0 else { return } let position = description.position ?? CGPoint(x: bounds.width - _viewPortHandler.offsetRight - description.xOffset, y: bounds.height - _viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight) var attrs = [NSAttributedStringKey : Any]() attrs[NSAttributedStringKey.font] = description.font attrs[NSAttributedStringKey.foregroundColor] = description.textColor ChartUtils.drawText( context: context, text: descriptionText, point: position, align: description.textAlign, attributes: attrs) } // MARK: - Highlighting /// - returns: The array of currently highlighted values. This might an empty if nothing is highlighted. @objc open var highlighted: [Highlight] { return _indicesToHighlight } /// Set this to false to prevent values from being highlighted by tap gesture. /// Values can still be highlighted via drag or programmatically. /// **default**: true @objc open var highlightPerTapEnabled: Bool { get { return _highlightPerTapEnabled } set { _highlightPerTapEnabled = newValue } } /// - returns: `true` if values can be highlighted via tap gesture, `false` ifnot. @objc open var isHighLightPerTapEnabled: Bool { return highlightPerTapEnabled } /// Checks if the highlight array is null, has a length of zero or if the first object is null. /// - returns: `true` if there are values to highlight, `false` ifthere are no values to highlight. @objc open func valuesToHighlight() -> Bool { return _indicesToHighlight.count > 0 } /// Highlights the values at the given indices in the given DataSets. Provide /// null or an empty array to undo all highlighting. /// This should be used to programmatically highlight values. /// This method *will not* call the delegate. @objc open func highlightValues(_ highs: [Highlight]?) { // set the indices to highlight _indicesToHighlight = highs ?? [Highlight]() if _indicesToHighlight.isEmpty { self.lastHighlighted = nil } else { self.lastHighlighted = _indicesToHighlight[0] } // redraw the chart setNeedsDisplay() } /// Highlights any y-value at the given x-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// This method will call the delegate. /// - parameter x: The x-value to highlight /// - parameter dataSetIndex: The dataset index to search in /// - parameter dataIndex: The data index to search in (only used in CombinedChartView currently) @objc open func highlightValue(x: Double, dataSetIndex: Int, dataIndex: Int = -1) { highlightValue(x: x, dataSetIndex: dataSetIndex, dataIndex: dataIndex, callDelegate: true) } /// Highlights the value at the given x-value and y-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// This method will call the delegate. /// - parameter x: The x-value to highlight /// - parameter y: The y-value to highlight. Supply `NaN` for "any" /// - parameter dataSetIndex: The dataset index to search in /// - parameter dataIndex: The data index to search in (only used in CombinedChartView currently) @objc open func highlightValue(x: Double, y: Double, dataSetIndex: Int, dataIndex: Int = -1) { highlightValue(x: x, y: y, dataSetIndex: dataSetIndex, dataIndex: dataIndex, callDelegate: true) } /// Highlights any y-value at the given x-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// - parameter x: The x-value to highlight /// - parameter dataSetIndex: The dataset index to search in /// - parameter dataIndex: The data index to search in (only used in CombinedChartView currently) /// - parameter callDelegate: Should the delegate be called for this change @objc open func highlightValue(x: Double, dataSetIndex: Int, dataIndex: Int = -1, callDelegate: Bool) { highlightValue(x: x, y: .nan, dataSetIndex: dataSetIndex, dataIndex: dataIndex, callDelegate: callDelegate) } /// Highlights the value at the given x-value and y-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// - parameter x: The x-value to highlight /// - parameter y: The y-value to highlight. Supply `NaN` for "any" /// - parameter dataSetIndex: The dataset index to search in /// - parameter dataIndex: The data index to search in (only used in CombinedChartView currently) /// - parameter callDelegate: Should the delegate be called for this change @objc open func highlightValue(x: Double, y: Double, dataSetIndex: Int, dataIndex: Int = -1, callDelegate: Bool) { guard let data = _data else { Swift.print("Value not highlighted because data is nil") return } if dataSetIndex < 0 || dataSetIndex >= data.dataSetCount { highlightValue(nil, callDelegate: callDelegate) } else { highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex, dataIndex: dataIndex), callDelegate: callDelegate) } } /// Highlights the values represented by the provided Highlight object /// This method *will not* call the delegate. /// - parameter highlight: contains information about which entry should be highlighted @objc open func highlightValue(_ highlight: Highlight?) { highlightValue(highlight, callDelegate: false) } /// Highlights the value selected by touch gesture. @objc open func highlightValue(_ highlight: Highlight?, callDelegate: Bool) { var entry: ChartDataEntry? var h = highlight if h == nil { self.lastHighlighted = nil _indicesToHighlight.removeAll(keepingCapacity: false) } else { // set the indices to highlight entry = _data?.entryForHighlight(h!) if entry == nil { h = nil _indicesToHighlight.removeAll(keepingCapacity: false) } else { _indicesToHighlight = [h!] } } if callDelegate, let delegate = delegate { if let h = h { // notify the listener delegate.chartValueSelected?(self, entry: entry!, highlight: h) } else { delegate.chartValueNothingSelected?(self) } } // redraw the chart setNeedsDisplay() } /// - returns: The Highlight object (contains x-index and DataSet index) of the /// selected value at the given touch point inside the Line-, Scatter-, or /// CandleStick-Chart. @objc open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } return self.highlighter?.getHighlight(x: pt.x, y: pt.y) } /// The last value that was highlighted via touch. @objc open var lastHighlighted: Highlight? // MARK: - Markers /// draws all MarkerViews on the highlighted positions internal func drawMarkers(context: CGContext) { // if there is no marker view or drawing marker is disabled guard let marker = marker , isDrawMarkersEnabled && valuesToHighlight() else { return } for i in 0 ..< _indicesToHighlight.count { let highlight = _indicesToHighlight[i] guard let set = data?.getDataSetByIndex(highlight.dataSetIndex), let e = _data?.entryForHighlight(highlight) else { continue } let entryIndex = set.entryIndex(entry: e) if entryIndex > Int(Double(set.entryCount) * _animator.phaseX) { continue } let pos = getMarkerPosition(highlight: highlight) // check bounds if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y) { continue } // callbacks to update the content marker.refreshContent(entry: e, highlight: highlight) // draw the marker marker.draw(context: context, point: pos) } } /// - returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet. @objc open func getMarkerPosition(highlight: Highlight) -> CGPoint { return CGPoint(x: highlight.drawX, y: highlight.drawY) } // MARK: - Animation /// - returns: The animator responsible for animating chart values. @objc open var chartAnimator: Animator! { return _animator } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingX: an easing function for the animation on the x axis /// - parameter easingY: an easing function for the animation on the y axis @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOptionX: the easing function for the animation on the x axis /// - parameter easingOptionY: the easing function for the animation on the y axis @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easing: an easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easingOption: the easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis @objc open func animate(xAxisDuration: TimeInterval) { _animator.animate(xAxisDuration: xAxisDuration) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation @objc open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation @objc open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis @objc open func animate(yAxisDuration: TimeInterval) { _animator.animate(yAxisDuration: yAxisDuration) } // MARK: - Accessors /// - returns: The current y-max value across all DataSets open var chartYMax: Double { return _data?.yMax ?? 0.0 } /// - returns: The current y-min value across all DataSets open var chartYMin: Double { return _data?.yMin ?? 0.0 } open var chartXMax: Double { return _xAxis._axisMaximum } open var chartXMin: Double { return _xAxis._axisMinimum } open var xRange: Double { return _xAxis.axisRange } /// * /// - note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)* /// - returns: The center point of the chart (the whole View) in pixels. @objc open var midPoint: CGPoint { let bounds = self.bounds return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0) } /// - returns: The center of the chart taking offsets under consideration. (returns the center of the content rectangle) open var centerOffsets: CGPoint { return _viewPortHandler.contentCenter } /// - returns: The Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend. @objc open var legend: Legend { return _legend } /// - returns: The renderer object responsible for rendering / drawing the Legend. @objc open var legendRenderer: LegendRenderer! { return _legendRenderer } /// - returns: The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn). @objc open var contentRect: CGRect { return _viewPortHandler.contentRect } /// - returns: The ViewPortHandler of the chart that is responsible for the /// content area of the chart and its offsets and dimensions. @objc open var viewPortHandler: ViewPortHandler! { return _viewPortHandler } /// - returns: The bitmap that represents the chart. @objc open func getChartImage(transparent: Bool) -> NSUIImage? { NSUIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque || !transparent, NSUIMainScreen()?.nsuiScale ?? 1.0) guard let context = NSUIGraphicsGetCurrentContext() else { return nil } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size) if isOpaque || !transparent { // Background color may be partially transparent, we must fill with white if we want to output an opaque image context.setFillColor(NSUIColor.white.cgColor) context.fill(rect) if let backgroundColor = self.backgroundColor { context.setFillColor(backgroundColor.cgColor) context.fill(rect) } } nsuiLayer?.render(in: context) let image = NSUIGraphicsGetImageFromCurrentImageContext() NSUIGraphicsEndImageContext() return image } public enum ImageFormat { case jpeg case png } /// Saves the current chart state with the given name to the given path on /// the sdcard leaving the path empty "" will put the saved file directly on /// the SD card chart is saved as a PNG image, example: /// saveToPath("myfilename", "foldername1/foldername2") /// /// - parameter to: path to the image to save /// - parameter format: the format to save /// - parameter compressionQuality: compression quality for lossless formats (JPEG) /// /// - returns: `true` if the image was saved successfully open func save(to path: String, format: ImageFormat, compressionQuality: Double) -> Bool { guard let image = getChartImage(transparent: format != .jpeg) else { return false } let imageData: Data? switch (format) { case .png: imageData = NSUIImagePNGRepresentation(image) case .jpeg: imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality)) } guard let data = imageData else { return false } do { try data.write(to: URL(fileURLWithPath: path), options: .atomic) } catch { return false } return true } internal var _viewportJobs = [ViewPortJob]() open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "bounds" || keyPath == "frame" { let bounds = self.bounds if (_viewPortHandler !== nil && (bounds.size.width != _viewPortHandler.chartWidth || bounds.size.height != _viewPortHandler.chartHeight)) { _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) // This may cause the chart view to mutate properties affecting the view port -- lets do this // before we try to run any pending jobs on the view port itself notifyDataSetChanged() // Finish any pending viewport changes while (!_viewportJobs.isEmpty) { let job = _viewportJobs.remove(at: 0) job.doJob() } } } } @objc open func removeViewportJob(_ job: ViewPortJob) { if let index = _viewportJobs.index(where: { $0 === job }) { _viewportJobs.remove(at: index) } } @objc open func clearAllViewportJobs() { _viewportJobs.removeAll(keepingCapacity: false) } @objc open func addViewportJob(_ job: ViewPortJob) { if _viewPortHandler.hasChartDimens { job.doJob() } else { _viewportJobs.append(job) } } /// **default**: true /// - returns: `true` if chart continues to scroll after touch up, `false` ifnot. @objc open var isDragDecelerationEnabled: Bool { return dragDecelerationEnabled } /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. /// /// **default**: true @objc open var dragDecelerationFrictionCoef: CGFloat { get { return _dragDecelerationFrictionCoef } set { var val = newValue if val < 0.0 { val = 0.0 } if val >= 1.0 { val = 0.999 } _dragDecelerationFrictionCoef = val } } /// The maximum distance in screen pixels away from an entry causing it to highlight. /// **default**: 500.0 open var maxHighlightDistance: CGFloat = 500.0 /// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled open var maxVisibleCount: Int { return Int(INT_MAX) } // MARK: - AnimatorDelegate open func animatorUpdated(_ chartAnimator: Animator) { setNeedsDisplay() } open func animatorStopped(_ chartAnimator: Animator) { } // MARK: - Touches open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesBegan(touches, withEvent: event) } } open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesMoved(touches, withEvent: event) } } open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesEnded(touches, withEvent: event) } } open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesCancelled(touches, withEvent: event) } } }
42ef8f98345a33851532a8d35c42ce89
36.099798
199
0.627395
false
false
false
false
PiHanHsu/myscorebaord_lite
refs/heads/master
myscoreboard_lite/Protocol/RoundedView.swift
mit
1
// // RoundedView.swift // myscoreboard_lite // // Created by PiHan on 2017/10/10. // Copyright © 2017年 PiHan. All rights reserved. // import Foundation import UIKit protocol RoundedView {} extension RoundedView where Self: UIView { func roundedView() { if (self.frame.size.height != self.frame.size.width){ self.frame.size.height = min(self.frame.size.height, self.frame.size.width) self.frame.size.width = min(self.frame.size.height, self.frame.size.width) } layer.cornerRadius = layer.frame.size.height * 0.5 self.clipsToBounds = true self.contentMode = .scaleAspectFill } } extension UIImageView: RoundedView{}
1b7489430395a7ba04ae376f65e36181
25.730769
87
0.669065
false
false
false
false
Barry-Wang/iOS-Animation-Guide-Swift
refs/heads/master
AnimationGuide1-circle/AnimationGuide/YMCircleLayer.swift
apache-2.0
1
// // YMCircleLayer.swift // AnimationGuide // // Created by barryclass on 15/11/13. // Copyright © 2015年 barry. All rights reserved. // import UIKit enum MovePoint { // 连接点 A B C D 生成一个圆, Move_B 表示向左移动,移动B点 case Move_B, Move_D } let OutSideRectSize:CGFloat = 120 class YMCircleLayer: CALayer { var outSideRect = CGRectZero var movePoint:MovePoint = MovePoint.Move_B var progress:Float = 0.5{ didSet { let paddingWidth:CGFloat = (self.bounds.size.width - OutSideRectSize) / 2 self.outSideRect = CGRectMake( (self.position.x - OutSideRectSize / 2) + CGFloat(progress - 0.5) * paddingWidth, self.position.y - OutSideRectSize / 2, OutSideRectSize, OutSideRectSize) if progress > 0.5 { self.movePoint = MovePoint.Move_B } else { self.movePoint = MovePoint.Move_D } // CALayer在第一次出现的时候不会主动调用 drawInContext self.setNeedsDisplay() } } override func drawInContext(ctx: CGContext) { //画最外面的正方形,在这个正方形里面画圆 CGContextSetLineWidth(ctx, 5) CGContextSetStrokeColorWithColor(ctx, UIColor.greenColor().CGColor) // 设置为虚线模式 CGContextSetLineDash(ctx, 0, [3,3], 2) CGContextStrokeRect(ctx, self.outSideRect) CGContextStrokePath(ctx) CGContextSetStrokeColorWithColor(ctx, UIColor.yellowColor().CGColor) // offset, moveDistance 都是些经验值 let offset = OutSideRectSize / 3.6 let moveDistance = (self.outSideRect.width * 1 / 6) * CGFloat(fabs(self.progress - 0.5) * 2) let rectCenter = CGPointMake(self.outSideRect.origin.x + OutSideRectSize / 2, self.outSideRect.origin.y + OutSideRectSize / 2) let point_A = CGPointMake(rectCenter.x, self.outSideRect.origin.y + moveDistance) // 当向左移动时,使B的x坐标增加,使其成近似椭圆状 let point_B = CGPointMake(self.movePoint == MovePoint.Move_B ? rectCenter.x + OutSideRectSize / 2 + moveDistance * 2 : rectCenter.x + OutSideRectSize / 2, rectCenter.y) let point_C = CGPointMake(rectCenter.x, rectCenter.y + OutSideRectSize / 2 - moveDistance) let point_D = CGPointMake(self.movePoint == MovePoint.Move_D ? self.outSideRect.origin.x - moveDistance * 2 : self.outSideRect.origin.x, rectCenter.y) // let rectBizerpath = UIBezierPath() // rectBizerpath.moveToPoint(point_A) // rectBizerpath.addLineToPoint(point_B) // rectBizerpath.addLineToPoint(point_C) // rectBizerpath.addLineToPoint(point_D) // rectBizerpath.closePath() // CGContextAddPath(ctx, rectBizerpath.CGPath) // CGContextStrokePath(ctx) // 合成贝塞尔曲线所需要的控制点 let point_AB1 = CGPointMake(point_A.x + offset, point_A.y) //判断控制点的位置使其形状变化更加真实 let point_AB2 = CGPointMake(point_B.x, self.movePoint == MovePoint.Move_B ? point_B.y - offset + moveDistance : point_B.y - offset) let point_BC1 = CGPointMake(point_B.x, self.movePoint == MovePoint.Move_B ? point_B.y + offset - moveDistance : point_B.y + offset) let point_BC2 = CGPointMake(point_C.x + offset, point_C.y) let point_CD1 = CGPointMake(point_C.x - offset, point_C.y) let point_CD2 = CGPointMake(point_D.x, self.movePoint == MovePoint.Move_D ? point_D.y + offset - moveDistance : point_D.y + offset) let point_DA1 = CGPointMake(point_D.x, self.movePoint == MovePoint.Move_D ? point_D.y - offset + moveDistance : point_D.y - offset ) let point_DA2 = CGPointMake(point_A.x - offset, point_A.y) let circlePath = UIBezierPath() CGContextSetLineDash(ctx, 0, nil, 0) CGContextSetStrokeColorWithColor(ctx, UIColor.purpleColor().CGColor) circlePath.moveToPoint(point_A) circlePath.addCurveToPoint(point_B, controlPoint1: point_AB1, controlPoint2: point_AB2) circlePath.addCurveToPoint(point_C, controlPoint1: point_BC1, controlPoint2: point_BC2) circlePath.addCurveToPoint(point_D, controlPoint1: point_CD1, controlPoint2: point_CD2) circlePath.addCurveToPoint(point_A, controlPoint1: point_DA1, controlPoint2: point_DA2) CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor) CGContextSetFillColorWithColor(ctx, UIColor.orangeColor().CGColor) CGContextAddPath(ctx, circlePath.CGPath) CGContextDrawPath(ctx, CGPathDrawingMode.EOFillStroke) } }
239ab211a71f246f27e0f91a56970d4f
40.558559
197
0.643616
false
false
false
false
terietor/GTForms
refs/heads/master
Source/Forms/TextFields/TextFieldView.swift
mit
1
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SnapKit protocol FormTextFieldViewType { var textFieldViewType: TextFieldViewType { get } } protocol TextFieldViewType: class { var textField: UITextField { get } weak var delegate: TextFieldViewDelegate? { get set } } protocol TextFieldViewDelegate: class { func textFieldViewShouldReturn( _ textFieldView: TextFieldViewType ) -> Bool } class TextFieldView<T: UITextField, L: UILabel> : ControlLabelView<L>, TextFieldViewType, UITextFieldDelegate { override var formAxis: FormAxis { didSet { configureUI() } } var textField: UITextField { return self.field } lazy private(set) var field: T = { let textField = T() textField.addTarget( self, action: #selector(editingChanged), for: .editingChanged ) textField.borderStyle = .none textField.delegate = self textField.translatesAutoresizingMaskIntoConstraints = false return textField }() var textWillChange: ((_ text: String) -> (Bool))? var textDidChange: ((_ text: String) -> ())? var didPressReturnButton: (() -> ())? weak var delegate: TextFieldViewDelegate? override init() { super.init() self.control = self.field configureUI() } private func configureUI() { configureView() { (label, control) in if self.formAxis == .horizontal { label.snp.remakeConstraints() { make in make.left.equalTo(self) make.top.equalTo(self) make.width.equalTo(self).multipliedBy(0.3) make.bottom.equalTo(self) } // end label control.snp.remakeConstraints() { make in make.left.equalTo(label.snp.right).offset(10) make.right.equalTo(self) make.top.equalTo(self) make.bottom.equalTo(self) } // end control } else { label.snp.remakeConstraints() { make in make.top.equalTo(self) make.leading.equalTo(self).offset(10) make.trailing.equalTo(self).offset(-10) } control.snp.remakeConstraints() { make in make.top.equalTo(label.snp.bottom).offset(10) make.bottom.equalTo(self) make.leading.equalTo(self).offset(10) make.trailing.equalTo(self).offset(-10) } } } // end configureView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func editingChanged() { guard let text = self.field.text else { return } self.textDidChange?(text) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let delegate = self.delegate else { print("\(#file):\(#line): Missing Delegate!!") return false } if !delegate.textFieldViewShouldReturn(self) { textField.resignFirstResponder() } return false } func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String ) -> Bool { guard let textWillChange = self.textWillChange else { return true } return textWillChange(string) } func textFieldDidEndEditing(_ textField: UITextField) { self.didPressReturnButton?() } }
422c07ba438eca61d97ddc97bd7ff398
30.343949
82
0.603536
false
false
false
false
Jnosh/swift
refs/heads/master
test/ClangImporter/optional.swift
apache-2.0
18
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -emit-silgen -o - %s | %FileCheck %s // REQUIRES: objc_interop import ObjectiveC import Foundation import objc_ext import TestProtocols class A { @objc func foo() -> String? { return "" } // CHECK-LABEL: sil hidden [thunk] @_T08optional1AC3fooSSSgyFTo : $@convention(objc_method) (A) -> @autoreleased Optional<NSString> // CHECK: bb0([[SELF:%.*]] : $A): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[T0:%.*]] = function_ref @_T08optional1AC3fooSSSgyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: switch_enum [[T1]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // Something branch: project value, translate, inject into result. // CHECK: [[SOME_BB]]([[STR:%.*]] : $String): // CHECK: [[T0:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-NEXT: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_STR]]) // CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: end_borrow [[BORROWED_STR:%.*]] from [[STR]] // CHECK-NEXT: destroy_value [[STR]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // // CHECK: [[NONE_BB]]: // CHECK-NEXT: enum $Optional<NSString>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<NSString>): // CHECK-NEXT: return [[T0]] @objc func bar(x x : String?) {} // CHECK-LABEL: sil hidden [thunk] @_T08optional1AC3barySSSg1x_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> () // CHECK: bb0([[ARG:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: switch_enum [[ARG_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // Something branch: project value, translate, inject into result. // CHECK: [[SOME_BB]]([[NSSTR:%.*]] : $NSString): // CHECK: [[T0:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // Make a temporary initialized string that we're going to clobber as part of the conversion process (?). // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString // CHECK-NEXT: [[STRING_META:%.*]] = metatype $@thin String.Type // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]], [[STRING_META]]) // CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: br // // Nothing branch: inject nothing into result. // CHECK: [[NONE_BB]]: // CHECK: enum $Optional<String>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<String>): // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[T1:%.*]] = function_ref @_T08optional1AC3barySSSg1x_tF // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[T2]] : $() } // rdar://15144951 class TestWeak : NSObject { weak var b : WeakObject? = nil } class WeakObject : NSObject {}
2ce82e283aefaf903cc463d67cdeed34
46.076923
165
0.624728
false
false
false
false
richardpiazza/GraphPoint
refs/heads/main
Sources/GraphPoint/CartesianPoint.swift
mit
1
import Foundation import Swift2D /// A point within a `CartesianPlane` /// /// The x & y coordinates of a `CartesianPoint` represent the offset from the planes 'origin' {0, 0}. /// /// ## Example /// /// ```swift /// let plane = CartesianPlane(size: Size(width: 100, height: 100)) /// // plane.cartesianOrigin == Point(x: 50, y: 50) /// let point1 = Point(x: 75, y: 25) /// let cartesianPoint1 = CartesianPoint(x: 25, y: 25) /// // point1 == cartesianPoint1 /// let point2 = Point(x: 25, y: 75) /// let cartesianPoint2 = CartesianPoint(x: -25, y: -25) /// // point2 == cartesianPoint2 /// ``` public typealias CartesianPoint = Point public extension CartesianPoint { /// The minimum axis for a `CartesianPlane` that would contain this point. var minimumAxis: Double { return max(abs(x), abs(y)) } } public extension CartesianPoint { /// Calculates the `CartesianPoint` for a given degree and radius from the _origin_. /// /// Uses the mathematical **Law of Sines**. /// /// - parameters: /// - radius: The straight line distance from the _origin_. /// - degree: The angular degree (0-360), clockwise from the x-axis. /// - returns:A `CartesianPoint` with offsets from the _origin_. static func make(for radius: Radius, degree: Degree, clockwise: Bool = true) throws -> CartesianPoint { guard degree >= 0.0, degree <= 360.0 else { throw GraphPointError.invalidDegree(degree) } guard radius >= 0.0 else { throw GraphPointError.invalidRadius(radius) } guard radius > 0.0 else { return .zero } let rightAngle: Double = 90.0 let sinRight = sin(rightAngle.radians) var rise: Double = 0.0 var run: Double = 0.0 var point: CartesianPoint = .zero switch clockwise { case true: if degree > 315 { rise = 360.0 - degree run = 180.0 - rightAngle - rise point.x = (radius / sinRight) * sin(run.radians) point.y = (radius / sinRight) * sin(rise.radians) } else if degree > 270 { run = degree - 270.0 rise = 180.0 - rightAngle - run point.x = (radius / sinRight) * sin(run.radians) point.y = (radius / sinRight) * sin(rise.radians) } else if degree > 225 { run = 270.0 - degree rise = 180.0 - rightAngle - run point.x = -1.0 * (radius / sinRight) * sin(run.radians) point.y = (radius / sinRight) * sin(rise.radians) } else if degree > 180 { rise = degree - 180.0 run = 180.0 - rightAngle - rise point.x = -1.0 * (radius / sinRight) * sin(run.radians) point.y = (radius / sinRight) * sin(rise.radians) } else if degree > 135 { rise = 180.0 - degree run = 180.0 - rightAngle - rise point.x = -1.0 * (radius / sinRight) * sin(run.radians) point.y = -1.0 * (radius / sinRight) * sin(rise.radians) } else if degree > 90 { run = degree - 90.0 rise = 180.0 - rightAngle - run point.x = -1.0 * (radius / sinRight) * sin(run.radians) point.y = -1.0 * (radius / sinRight) * sin(rise.radians) } else if degree > 45 { run = 90.0 - degree rise = 180.0 - rightAngle - run point.x = (radius / sinRight) * sin(run.radians) point.y = -1.0 * (radius / sinRight) * sin(rise.radians) } else if degree >= 0 { rise = degree run = 180.0 - rightAngle - rise point.x = (radius / sinRight) * sin(run.radians) point.y = -1.0 * (radius / sinRight) * sin(rise.radians) } case false: // TODO: Handled anti-clockwise break } return point } /// Calculates the `CartesianPoint` for a given degree and radius from the _origin_ limited by another point. /// /// Uses the **Pythagorean Theorem** to solve for the intercept: /// * **c**: calculated based on `degree` and `radius`. /// * **a**: supplied via the `point` (x/y based on closest axis) /// /// - parameters: /// - radius: The straight line distance from the _origin_. /// - degree: The angular degree (0-360), clockwise from the x-axis. /// - modifier: The point used to clip or expand the result. The nearest axis value is used. static func make(for radius: Radius, degree: Degree, modifier: CartesianPoint, clockwise: Bool = true) throws -> CartesianPoint { guard degree >= 0.0, degree <= 360.0 else { throw GraphPointError.invalidDegree(degree) } guard radius >= 0.0 else { throw GraphPointError.invalidRadius(radius) } guard radius > 0.0 else { return .zero } var point = CartesianPoint() switch clockwise { case true: if (degree >= 315) { point.x = sqrt(pow(radius, 2) - pow(modifier.y, 2)) point.y = modifier.y } else if (degree >= 270) { point.x = modifier.x point.y = sqrt(pow(radius, 2) - pow(modifier.x, 2)) } else if (degree >= 225) { point.x = modifier.x point.y = sqrt(pow(radius, 2) - pow(modifier.x, 2)) } else if (degree >= 180) { point.x = -(sqrt(pow(radius, 2) - pow(modifier.y, 2))) point.y = modifier.y } else if (degree >= 135) { point.x = -(sqrt(pow(radius, 2) - pow(modifier.y, 2))) point.y = modifier.y } else if (degree >= 90) { point.x = modifier.x point.y = -(sqrt(pow(radius, 2) - pow(modifier.x, 2))) } else if (degree >= 45) { point.x = modifier.x point.y = -(sqrt(pow(radius, 2) - pow(modifier.x, 2))) } else if (degree >= 0) { point.x = sqrt(pow(radius, 2) - pow(modifier.y, 2)) point.y = modifier.y } case false: //TODO: Determine if calculations should be modified. break } return point } }
a61711319a2037a001dc65b76ab72321
38.383234
133
0.512544
false
false
false
false
v2panda/DaysofSwift
refs/heads/master
swift2.3/My-CarouselEffect/Interest.swift
mit
1
// // Interest.swift // My-CarouselEffect // // Created by Panda on 16/2/22. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit class Interest { // MARK: - Public API var title = "" var description = "" var numberOfMembers = 0 var numberOfPosts = 0 var featuredImage : UIImage! init(title : String, description : String, featuredImage : UIImage!){ self.title = title self.description = description self.featuredImage = featuredImage numberOfMembers = 1 numberOfPosts = 1 } // MARK: - Private // dummy data static func createInterests() -> [Interest]{ return [ Interest(title: "Hello there, i miss you", description: "We love backpack and adventures! We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "hello")), Interest(title: "🐳🐳🐳🐳🐳", description: "We love romantic stories. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "dudu")!), Interest(title: "Training like this, #bodyline", description: "Create beautiful apps. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "bodyline")!), Interest(title: "I'm hungry, indeed.", description: "Cars and aircrafts and boats and sky. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "wave")!), Interest(title: "Dark Varder, #emoji", description: "Meet life with full presence. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "darkvarder")!), Interest(title: "I have no idea, bitch", description: "Get up to date with breaking-news. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "hhhhh")!), ] } }
c6bd4bf139df0e72efc66fb9aaa53ffc
50.840909
263
0.672807
false
false
false
false
wibosco/ASOS-Consumer
refs/heads/master
ASOSConsumer/ViewControllers/Category/CategoryViewController.swift
mit
1
// // CategoryViewController.swift // ASOSConsumer // // Created by William Boles on 02/03/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit import PureLayout class CategoryViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, ProductCollectionViewCellDelegate { //MARK: - Accessors var category : Category? { didSet { self.categoryLabel.text = self.category?.title self.refresh(self.category!) } } var categoryProducts: Array<CategoryProduct>? private lazy var categoryLabel: UILabel = { let categoryLabel = UILabel.newAutoLayoutView() categoryLabel.textAlignment = NSTextAlignment.Center categoryLabel.backgroundColor = UIColor.lightGrayColor() return categoryLabel }() private lazy var collectionView: UICollectionView = { let verticalPadding: CGFloat = 8.0 let hozitionalPadding: CGFloat = 10.0 let scalingFactor: CGFloat = 0.87 let cellWidth = (self.view.frame.size.width - (hozitionalPadding * 4)) / 2 let cellHeight = cellWidth * scalingFactor let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: verticalPadding, left: hozitionalPadding, bottom: verticalPadding, right: hozitionalPadding) layout.itemSize = CGSize(width: cellWidth, height: cellHeight) let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.whiteColor() collectionView.dataSource = self collectionView.delegate = self collectionView.registerClass(ProductCollectionViewCell.self, forCellWithReuseIdentifier: ProductCollectionViewCell.reuseIdentifier()) return collectionView }() private lazy var loadingView: LoadingView = { let loadingView = LoadingView.init(frame: self.view.frame) return loadingView }() //MARK: - ViewLifecycle override func viewDidLoad() { super.viewDidLoad() /*-----------------*/ self.view.addSubview(self.collectionView) self.view.addSubview(self.categoryLabel) } //MARK: - Constraints override func updateViewConstraints() { self.categoryLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view) self.categoryLabel.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Top, ofView: self.view, withOffset: 44.0) self.categoryLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view) self.categoryLabel.autoSetDimension(ALDimension.Height, toSize: 20.0) /*-----------------*/ self.collectionView.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view) self.collectionView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: self.categoryLabel, withOffset: -44.0) self.collectionView.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view) self.collectionView.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: self.view) /*-----------------*/ super.updateViewConstraints() } //MARK: - DataRetrieval private func refresh(category: Category) { self.view.addSubview(self.loadingView) CategoryProductsAPIManager.retrieveCategoryProducts(category) {[weak self] (category, categoryProducts) -> Void in if let strongSelf = self { if (category.isEqual(strongSelf.category)) { strongSelf.categoryProducts = categoryProducts strongSelf.collectionView.reloadData() strongSelf.loadingView.removeFromSuperview() } } } } //MARK: - UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var numberOfItemsInSection = 0 if (self.categoryProducts != nil) { numberOfItemsInSection = self.categoryProducts!.count } return numberOfItemsInSection } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ProductCollectionViewCell.reuseIdentifier(), forIndexPath: indexPath) as! ProductCollectionViewCell let categoryProduct = self.categoryProducts![indexPath.row] cell.productPriceLabel.text = categoryProduct.displayPrice! cell.favourited = SessionManager.sharedInstance.isFavourited(categoryProduct) cell.delegate = self let preview = categoryProduct.preview! MediaAPIManager.retrieveMediaAsset(preview) { (media, mediaImage) -> Void in if (preview.isEqual(media)) { cell.productImageView.image = mediaImage } } return cell } //MARK: - UICollectionViewDelegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let categoryProduct = self.categoryProducts![indexPath.row] let productViewController = ProductViewController.init(categoryProduct: categoryProduct) self.navigationController?.pushViewController(productViewController, animated: true) } //MARK: - ProductCollectionViewCellDelegate func didDoubleTapOnProduct(sender: ProductCollectionViewCell) { let indexPath = self.collectionView.indexPathForCell(sender) let categoryProduct = self.categoryProducts![indexPath!.row] if (SessionManager.sharedInstance.isFavourited(categoryProduct)) { let indexOfCategoryProduct = SessionManager.sharedInstance.favouriteProducts.indexOf(categoryProduct) SessionManager.sharedInstance.favouriteProducts.removeAtIndex(indexOfCategoryProduct!) } else { SessionManager.sharedInstance.favouriteProducts.append(categoryProduct) } } }
49c3310fc96ec0e39fe7023c1a7599a5
36.465517
172
0.65823
false
false
false
false
HaloWang/FangYuan
refs/heads/master
FangYuan/ConstraintManager.swift
mit
1
// // ConstraintManager.swift // FangYuan // // Created by 王策 on 16/5/6. // Copyright © 2016年 WangCe. All rights reserved. // import UIKit // MARK: - Init & Properties /// 约束依赖管理者 class ConstraintManager { fileprivate init() {} static let singleton = ConstraintManager() var holder = ConstraintHolder() /// - Todo: 重要的还是做到按照 superview 分组遍历以提高性能 /// - Todo: 有没有集散型的并发遍历? /// 还没有被赋值到 UIView.Ruler 上的约束 var unsetConstraints = Set<Constraint>() /// 已经被设定好的,存储起来的约束,用于以后抽取出来再次使用 var storedConstraints = Set<Constraint>() } // MARK: - Public Methods extension ConstraintManager { /** 从某个视图得到约束 - parameter from: 约束依赖视图 - parameter section: 约束区间 */ class func pushConstraintFrom(_ from:UIView, section: Constraint.Section) { assert(!Thread.isMainThread, _fy_noMainQueueAssert) let newConstraint = Constraint(from: from, to: nil, section: section) singleton.holder.set(newConstraint, at: section) } /// - Todo: setConstraint 是生成『渲染队列』的最佳时机了吧 /// - Todo: 这个『渲染队列』还可以抽象成一个专门计算高度的类方法? /** 设定约束到某个视图上 - parameter to: 约束目标 - parameter section: 约束区间 - parameter value: 约束固定值 */ class func popConstraintTo(_ to:UIView, section: Constraint.Section, value:CGFloat) { assert(!Thread.isMainThread, _fy_noMainQueueAssert) // 这个方法应该被优先调用,可能出现 fy_XXX(a) 替换 fy_XXX(chainXXX) 的情况 singleton.removeDuplicateConstraintOf(to, at: section) // 如果对应区间上没有 holder,则认为 fy_XXX() 的参数中没有调用 chainXXX,直接返回,不进行后续操作 guard let _constraint = singleton.holder.constraintAt(section) else { return } _constraint.to = to _constraint.value = value singleton.unsetConstraints.insert(_constraint) singleton.holder.clearConstraintAt(section) assert(singleton.noConstraintCirculationWith(_constraint), "There is a constraint circulation between\n\(to)\n- and -\n\(_constraint.from)\n".fy_alert) } class func layout(_ view:UIView) { let usingFangYuanSubviews = view.usingFangYuanSubviews guard usingFangYuanSubviews.count > 0 else { return } _fy_waitLayoutQueue() singleton.layout(usingFangYuanSubviews) } /// 当某个依赖发生变化时,寻找相关的依赖,并重新根据存储的值赋值 /// 为了能保证『自动重置相关约束』,这个方法会在 `UIView.fy_XXX` 时从 `settedConstraints` 中检查相关的约束。 /// 并将其从新添加到 `constraints` 中 /// /// - Important: /// 这里面已经产生了递归调用了:fy_XXX -> [This Method] -> fy_XXX -> [This Method] -> ... /// 这样可以保证每次设定了约束了之后,所有与之相关的约束都会被重新设定 /// - Todo: 部分方法不应该遍历两次的!这里的性能还有提升空间 /// - Todo: horizontal 的意义并不明显啊 class func resetRelatedConstraintFrom(_ view:UIView, isHorizontal horizontal:Bool) { assert(!Thread.isMainThread, _fy_noMainQueueAssert) singleton.storedConstraints.forEach { constraint in if let _from = constraint.from , _from == view { if horizontal == constraint.section.horizontal { switch constraint.section { case .left: constraint.to.fy_left(view.chainRight + constraint.value) case .right: constraint.to.fy_right(view.chainLeft + constraint.value) case .top: constraint.to.fy_top(view.chainBottom + constraint.value) case .bottom: constraint.to.fy_bottom(view.chainTop + constraint.value) } } } } } } // MARK: - Private Methods // MARK: Layout private extension ConstraintManager { /// - Todo: UITableView.addSubiew 后,调用 UITableView 的 layoutSubviews 并不会被触发? /// 核心布局方法 /// - Todo: 这个算法相当于使用了什么排序? /// - Todo: 能不能尽量写成函数而非方法? /// - Todo: 还是把两部分合并一下,整理成一步算法吧 func layout(_ views: [UIView]) { assert(Thread.isMainThread, _fy_MainQueueAssert) guard hasUnsetConstraints(unsetConstraints, of: views) else { views.forEach { view in view.layoutWithFangYuan() } return } // 注意,应该保证下面的代码在执行时,不能直接遍历 constraints 来设定 layoutingViews,因为 _fangyuan_layout_queue 可能会对 layoutingViews 中的 UIView 添加新的约束,导致 hasSetConstraints 始终为 false // 当然,objc_sync_enter 也是一种解决方案,但是这里我并不想阻塞 _fangyuan_layout_queue 对 unsetConstraints 的访问 var _views = Set(views) var constraints = unsetConstraints var shouldRepeat: Bool repeat { shouldRepeat = false _views.forEach { view in if hasSetConstraints(constraints, to: view) { view.layoutWithFangYuan() constraints = setConstraints(constraints, from: view) // 在被遍历的数组中移除该 view _views.remove(view) } else { shouldRepeat = true } } } while shouldRepeat } func hasUnsetConstraints(_ constraints:Set<Constraint>, of views:[UIView]) -> Bool { guard constraints.count != 0 else { return false } /// - Todo: 外层遍历遍历谁会更快?或者两个一起遍历? for view in views { if !hasSetConstraints(constraints, to: view) { return true } } return false } /// 给定的约束中,已经没有用来约束 view 的约束了 func hasSetConstraints(_ constraints:Set<Constraint>, to view:UIView) -> Bool { for constraint in constraints { // ⚠️ Crash when scroll tableview too fast // "fatal error: unexpectedly found nil while unwrapping an Optional value" // `constraint.to` is nil if constraint.to == view { return false } } return true } /// 确定了该 UIView.frame 后,装载指定 Constraint 至 to.ruler.section 中 /// - Todo: 参数可变性还是一个问题! func setConstraints(_ constraints:Set<Constraint>, from view: UIView) -> Set<Constraint> { var _constraints = constraints _constraints.forEach { constraint in if constraint.from == view { _fy_layoutQueue { self.storedConstraintsInsert(constraint) } let _from = constraint.from let _to = constraint.to let _value = constraint.value switch constraint.section { case .top: _to?.rulerY.a = (_from?.frame.origin.y)! + (_from?.frame.height)! + _value case .bottom: _to?.rulerY.c = (_from?.superview!.frame.height)! - (_from?.frame.origin.y)! + _value case .left: _to?.rulerX.a = (_from?.frame.origin.x)! + (_from?.frame.width)! + _value case .right: _to?.rulerX.c = (_from?.superview!.frame.width)! - (_from?.frame.origin.x)! + _value } _constraints.remove(constraint) } } return _constraints } } // MARK: Assistant private extension ConstraintManager { func storedConstraintsInsert(_ constraint:Constraint) { assert(!Thread.isMainThread, _fy_noMainQueueAssert) storedConstraints.forEach { constraint in if constraint.to == nil || constraint.from == nil { storedConstraints.remove(constraint) } else if constraint.to == constraint.to && constraint.section == constraint.section { storedConstraints.remove(constraint) } } storedConstraints.insert(constraint) } /// 按照程序逻辑,一个 view 最多同时只能在一个区间上拥有一个约束 func removeDuplicateConstraintOf(_ view:UIView, at section: Constraint.Section) { assert(!Thread.isMainThread, _fy_noMainQueueAssert) unsetConstraints.forEach { constraint in if constraint.to == nil || constraint.from == nil { unsetConstraints.remove(constraint) } else if constraint.to == view && constraint.section == section { unsetConstraints.remove(constraint) } } } /// Check constraint circulation /// /// - Todo: Only 2 ? What about 3, 4, 5...? func noConstraintCirculationWith(_ constraint:Constraint) -> Bool { assert(!Thread.isMainThread, _fy_noMainQueueAssert) return unsetConstraints.filter { $0.to == constraint.from && $0.from == constraint.to }.count == 0 } }
5c0526273a68a3e08194a9b83cceefe7
32.906615
160
0.572756
false
false
false
false
huonw/swift
refs/heads/master
test/SILGen/guaranteed_closure_context.swift
apache-2.0
3
// RUN: %target-swift-emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s func use<T>(_: T) {} func escape(_ f: () -> ()) {} protocol P {} class C: P {} struct S {} // CHECK-LABEL: sil hidden @$S26guaranteed_closure_context0A9_capturesyyF func guaranteed_captures() { // CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box ${ var S } var mutableTrivial = S() // CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box ${ var C } var mutableRetainable = C() // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box ${ var P } var mutableAddressOnly: P = C() // CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S let immutableTrivial = S() // CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C let immutableRetainable = C() // CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack $P let immutableAddressOnly: P = C() func captureEverything() { use((mutableTrivial, mutableRetainable, mutableAddressOnly, immutableTrivial, immutableRetainable, immutableAddressOnly)) } // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[B_MUTABLE_TRIVIAL_BOX:%.*]] = begin_borrow [[MUTABLE_TRIVIAL_BOX]] : ${ var S } // CHECK: [[B_MUTABLE_RETAINABLE_BOX:%.*]] = begin_borrow [[MUTABLE_RETAINABLE_BOX]] : ${ var C } // CHECK: [[B_MUTABLE_ADDRESS_ONLY_BOX:%.*]] = begin_borrow [[MUTABLE_ADDRESS_ONLY_BOX]] : ${ var P } // CHECK: [[B_IMMUTABLE_RETAINABLE:%.*]] = begin_borrow [[IMMUTABLE_RETAINABLE]] : $C // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[B_IMMUTABLE_AO_BOX:%.*]] = begin_borrow [[IMMUTABLE_AO_BOX]] : ${ var P } // CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@\$S26guaranteed_closure_context0A9_capturesyyF17captureEverythingL_yyF]] // CHECK: apply [[FN]]([[B_MUTABLE_TRIVIAL_BOX]], [[B_MUTABLE_RETAINABLE_BOX]], [[B_MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[B_IMMUTABLE_RETAINABLE]], [[B_IMMUTABLE_AO_BOX]]) captureEverything() // CHECK: destroy_value [[IMMUTABLE_AO_BOX]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // -- partial_apply still takes ownership of its arguments. // CHECK: [[FN:%.*]] = function_ref [[FN_NAME]] // CHECK: [[MUTABLE_TRIVIAL_BOX_COPY:%.*]] = copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK: [[MUTABLE_RETAINABLE_BOX_COPY:%.*]] = copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_COPY:%.*]] = copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK: [[IMMUTABLE_RETAINABLE_COPY:%.*]] = copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX_COPY]], [[MUTABLE_RETAINABLE_BOX_COPY]], [[MUTABLE_ADDRESS_ONLY_BOX_COPY]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE_COPY]], [[IMMUTABLE_AO_BOX]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE]] // CHECK: apply {{.*}}[[CONVERT]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK-NOT: destroy_value [[IMMUTABLE_AO_BOX]] escape(captureEverything) } // CHECK: sil private [[FN_NAME]] : $@convention(thin) (@guaranteed { var S }, @guaranteed { var C }, @guaranteed { var P }, S, @guaranteed C, @guaranteed { var P })
344667ffb509a43f9688e7a459cee3ce
48.746667
224
0.635754
false
false
false
false
zendobk/SwiftUtils
refs/heads/master
Sources/Classes/Label.swift
apache-2.0
1
// // Label.swift // SwiftUtils // // Created by DaoNV on 10/5/15. // Copyright © 2016 Asian Tech Co., Ltd. All rights reserved. // import UIKit open class Label: UILabel { open var edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) override open func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var rect = edgeInsets.inset(bounds) rect = super.textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines) return edgeInsets.inverse.inset(rect) } override open func drawText(in rect: CGRect) { super.drawText(in: edgeInsets.inset(rect)) } open override var intrinsicContentSize: CGSize { var size = super.intrinsicContentSize size.width += (edgeInsets.left + edgeInsets.right) size.height += (edgeInsets.top + edgeInsets.bottom) return size } }
48c5b7f0aba92abf1350b2e80b149f63
29.266667
112
0.674009
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Reader/ReaderCommentAction.swift
gpl-2.0
1
/// Encapsulates a command to navigate to a post's comments final class ReaderCommentAction { func execute(post: ReaderPost, origin: UIViewController, promptToAddComment: Bool = false, navigateToCommentID: Int? = nil, source: ReaderCommentsSource) { guard let postInMainContext = ReaderActionHelpers.postInMainContext(post), let controller = ReaderCommentsViewController(post: postInMainContext, source: source) else { return } controller.navigateToCommentID = navigateToCommentID as NSNumber? controller.promptToAddComment = promptToAddComment controller.trackCommentsOpened() origin.navigationController?.pushViewController(controller, animated: true) } }
33fa7bedc0ec34cb3cb03b1b695ab3d3
44.611111
107
0.667479
false
false
false
false
CodaFi/Bedrock
refs/heads/master
Bedrock/IndexSet.swift
mit
1
// // IndexSet.swift // Bedrock // // Created by Robert Widmann on 6/14/15. // Copyright © 2015 Robert Mozayeni. All rights reserved. // /// An `IndexSet` is an immutable collection of unique Index Types. public struct IndexSet<T: protocol<ForwardIndexType, Comparable>> { public var count : Int { return _ranges.reduce(0, combine: { (total, r) in countRange(r) + total }) } /// Creates an empty index set. public init() { _ranges = [] } /// Creates an index set with an index. public init(index: T) { self = IndexSet().indexSetByAddingIndex(index) } /// Creates an index set with an index range. public init(indexesInRange : Range<T>) { self = IndexSet().indexSetByAddingRange(indexesInRange) } /// Creates an index set that contains all the indexes of the receiver plus a given index. public func indexSetByAddingIndex(i: T) -> IndexSet<T> { return self.indexSetByAddingRange(i...i) } /// Creates an index set that contains all the indexes of the receiver plus a given range. public func indexSetByAddingRange(r: Range<T>) -> IndexSet<T> { let idx = insertionIndexForIndex(r.startIndex, rightBound: _ranges.count - 1) var copiedRanges = _ranges copiedRanges.insert(r, atIndex: idx) mergeRangesUpToIndex(&copiedRanges, idx: idx) if idx > 0 { mergeRangesAroundIndex(&copiedRanges, idx: idx - 1) } if idx < (self.count - 1) { mergeRangesAroundIndex(&copiedRanges, idx: idx) } return IndexSet(copiedRanges) } /// Indicates whether the index set contains a specific index. public func containsIndex(i: T) -> Bool { return self.rangeIndexForIndex(i, rightBound: _ranges.count - 1) != -1 } private let _ranges : Array<Range<T>> } /// MARK: Private Bits /// NSIndexSet is really a bunch of NSRanges stuck up in series. We have to take extra care when /// inserting or removing ranges that we don't perturb their neighbors, or split and merge them as /// necessary. Every index in the set belongs somewhere in some range. extension IndexSet { private init(_ ranges: Array<Range<T>>) { _ranges = ranges } private func mergeRangesAroundIndex(inout mRanges: [Range<T>], idx: Int) { if idx >= mRanges.count - 1 { return } // If we don't quite stretch to reach the start of the next range we're done. if advance(mRanges[idx].endIndex, 1) != mRanges[idx + 1].startIndex { return } removeRanges(&mRanges, idx: idx + 1, count: 1) } /// Tries to find the rightmost range a range at the given position can be merged into, then /// merges it. private func mergeRangesUpToIndex(inout ranges: [Range<T>], idx: Int) { let targetRange = ranges[idx] var rightmostRangeindex = idx for var i = idx; i < ranges.count; i++ { // Search until we can search no more if !rangeIntersectsRange(ranges[i], targetRange) { break } rightmostRangeindex = i } // No sense in merging ourself if rightmostRangeindex == idx { return } // Merge let r = unionRanges(targetRange, ranges[rightmostRangeindex]) removeRanges(&ranges, idx: idx + 1, count: rightmostRangeindex - idx) ranges[idx] = r } /// Mostly for convenience. private func removeRanges(inout ranges: [Range<T>], idx: Int, count: Int) { ranges.removeRange((idx + count)..<ranges.endIndex) } /// Searches the ranges for the position of the range containing the index. /// /// On error this function returns -1. It is _not helpful_ for insertion. Use /// `insertionIndexForIndex` for that. private func rangeIndexForIndex(idx: T, leftBound: Int = 0, rightBound: Int) -> Int { if self.count == 0 { return -1 } let mid = (leftBound + rightBound) / 2 let midRange = _ranges[mid] if leftBound == rightBound { if contains(midRange, idx) { return leftBound } else { return -1 } } if contains(midRange, idx) { return mid } /// Look ma, a binary search. if idx < midRange.startIndex { return self.rangeIndexForIndex(idx, leftBound: leftBound, rightBound: mid) } else { return self.rangeIndexForIndex(idx, leftBound: mid + 1, rightBound: rightBound) } } /// Searches the ranges for the first position of a range that could contain the index. private func insertionIndexForIndex(idx: T, leftBound: Int = 0, rightBound: Int) -> Int { if self.count == 0 { return 0 } let mid = (leftBound + rightBound) / 2 let midRange = _ranges[mid] if leftBound == rightBound { if idx <= midRange.endIndex { return leftBound } else { return leftBound + 1 } } if idx <= midRange.endIndex { return self.insertionIndexForIndex(idx, leftBound: leftBound, rightBound: mid) } else { return self.insertionIndexForIndex(idx, leftBound: mid + 1, rightBound: rightBound) } } } private func countRange<T: ForwardIndexType>(r: Range<T>) -> Int { var count = 0 for _ in r { count++ } return count } /// Because no Foundation. private func rangeIntersectsRange<T: protocol<ForwardIndexType, Comparable>>(range: Range<T>, other: Range<T>) -> Bool { if range.endIndex <= other.startIndex { return true } else if range.startIndex <= other.endIndex { return true } return false } /// Turns out Comparable Ranges are Monoids. private func unionRanges<T: protocol<ForwardIndexType, Comparable>>(xs: Range<T>...) -> Range<T> { return xs.reduce(xs[0], combine: { (rng, next) in (min(rng.startIndex, next.startIndex)...max(rng.startIndex, next.startIndex)) }) }
8db8cbe181f152506cc9893a02bf28c9
27.829787
131
0.68893
false
false
false
false
rsaenzi/MyCurrencyConverterApp
refs/heads/master
MyCurrencyConverterApp/MyCurrencyConverterApp/App/BusinessRules/BusinessRules.swift
mit
1
// // BusinessRules.swift // MyCurrencyConverterApp // // Created by Rigoberto Sáenz Imbacuán on 8/6/16. // Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved. // class BusinessRules { // -------------------------------------------------- // Members // -------------------------------------------------- var rates = RuleGetExchangeRates.getUniqueInstance()! // -------------------------------------------------- // Singleton: Unique Instance // -------------------------------------------------- private static let instance = BusinessRules() private init() {} // -------------------------------------------------- // Singleton: One-Time Access // -------------------------------------------------- private static var instanceDelivered = false /** Creates and returns the unique allowed instance of this class - returns: Unique instance the first time this method is called, nil otherwise */ static func getUniqueInstance() -> BusinessRules? { // If this is the first time this method is called... if instanceDelivered == false { // Create and return the instance instanceDelivered = true return instance } return nil } }
3b5bd4851cb4d328322794c25f904265
30.272727
105
0.469091
false
false
false
false
wmcginty/Shifty
refs/heads/main
Sources/Shifty/Model/Shift/Shift.Target.swift
mit
1
// // Shift.Target.swift // Shifty // // Created by Will McGinty on 5/2/16. // Copyright © 2016 will.mcginty. All rights reserved. // import UIKit public extension Shift { /// Represents a single target of a shifting `UIView` - usually either the source or the destination. struct Target { // MARK: - Typealias public typealias AlongsideAnimation = (_ replicant: UIView, _ destination: Shift.Target, _ snapshot: Snapshot) -> Void // MARK: - ReplicantInsertionStrategy Subtype public enum ReplicantInsertionStrategy { case standard case above(UIView) case below(UIView) case custom((_ replicant: UIView, _ container: UIView) -> Void) func insert(replicant: UIView, into container: UIView) { switch self { case .standard: container.addSubview(replicant) case .above(let other): container.insertSubview(replicant, aboveSubview: other) case .below(let other): container.insertSubview(replicant, belowSubview: other) case .custom(let handler): handler(replicant, container) } } } // MARK: - Properties /// The view acting as a target of the shift. This view can be either the source or the destination. public let view: UIView /// The identifier assigned to this `Target`. Each identifier in the source will match an identifier in the destination. public let identifier: Identifier /// The method used to configure the view. Defaults to .snapshot. public let replicationStrategy: ReplicationStrategy /// A set of animations that will be executed simultaneously with animations that drive the shift (both positional and visual). /// - Important: In the case that the `Shift` is utilizing a `VisualAnimationBehavior` not equal to `.none`, these animations will take precendence - though creating an /// animation that contradicts an animation created by the `VisualAnimationBehavior` may produce undesirable visual side effects. public var alongsideAnimations: AlongsideAnimation? // MARK: - Initializers public init(view: UIView, identifier: Identifier, replicationStrategy: ReplicationStrategy = .snapshot, alongsideAnimations: AlongsideAnimation? = nil) { self.view = view self.identifier = identifier self.replicationStrategy = replicationStrategy self.alongsideAnimations = alongsideAnimations } // MARK: - Modification var debug: Target { return Target(view: view, identifier: identifier, replicationStrategy: .debug()) } public func replicating(using strategy: ReplicationStrategy) -> Shift.Target { return Shift.Target(view: view, identifier: identifier, replicationStrategy: strategy) } } } // MARK: - Interface public extension Shift.Target { func configuredReplicant(in container: UIView, with insertionStrategy: ReplicantInsertionStrategy = .standard, afterScreenUpdates: Bool) -> UIView { let replicant = replicationStrategy.configuredShiftingView(for: view, afterScreenUpdates: afterScreenUpdates) insertionStrategy.insert(replicant: replicant, into: container) applyPositionalState(to: replicant, in: container) return replicant } func applyPositionalState(to view: UIView, in container: UIView) { snapshot().applyPositionalState(to: view) } func cleanup(replicant: UIView, restoreNativeView: Bool = true) { replicant.removeFromSuperview() if restoreNativeView { configureNativeView(hidden: false) } } /// Returns a `Snapshot` of the current state of the `Target`. func snapshot() -> Snapshot { return Snapshot(view: view) } func configureNativeView(hidden: Bool) { view.isHidden = hidden } } // MARK: - Hashable extension Shift.Target: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(identifier) } public static func == (lhs: Shift.Target, rhs: Shift.Target) -> Bool { return lhs.identifier == rhs.identifier } }
b23e173c5664a759c13b46cff29adf9f
37.911504
176
0.647259
false
false
false
false
xmartlabs/XLForm
refs/heads/master
Examples/Swift/SwiftExample/DynamicSelector/UsersTableViewController.swift
mit
1
// // UsersTableViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class UserCell : UITableViewCell { lazy var userImage : UIImageView = { let tempUserImage = UIImageView() tempUserImage.translatesAutoresizingMaskIntoConstraints = false tempUserImage.layer.masksToBounds = true tempUserImage.layer.cornerRadius = 10.0 return tempUserImage }() lazy var userName : UILabel = { let tempUserName = UILabel() tempUserName.translatesAutoresizingMaskIntoConstraints = false tempUserName.font = UIFont.systemFont(ofSize: 15.0) return tempUserName }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // Initialization code contentView.addSubview(userImage) contentView.addSubview(userName) contentView.addConstraints(layoutConstraints()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // MARK: - Layout Constraints func layoutConstraints() -> [NSLayoutConstraint]{ let views = ["image": self.userImage, "name": self.userName ] as [String : Any] let metrics = [ "imgSize": 50.0, "margin": 12.0] var result = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(margin)-[image(imgSize)]-[name]", options:.alignAllTop, metrics: metrics, views: views) result += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(margin)-[image(imgSize)]", options:NSLayoutConstraint.FormatOptions(), metrics:metrics, views: views) return result } } private let _UsersJSONSerializationSharedInstance = UsersJSONSerialization() class UsersJSONSerialization { lazy var userData : Array<AnyObject>? = { let dataString = "[" + "{\"id\":1,\"name\":\"Apu Nahasapeemapetilon\",\"imageName\":\"Apu_Nahasapeemapetilon.png\"}," + "{\"id\":7,\"name\":\"Bart Simpsons\",\"imageName\":\"Bart_Simpsons.png\"}," + "{\"id\":8,\"name\":\"Homer Simpsons\",\"imageName\":\"Homer_Simpsons.png\"}," + "{\"id\":9,\"name\":\"Lisa Simpsons\",\"imageName\":\"Lisa_Simpsons.png\"}," + "{\"id\":2,\"name\":\"Maggie Simpsons\",\"imageName\":\"Maggie_Simpsons.png\"}," + "{\"id\":3,\"name\":\"Marge Simpsons\",\"imageName\":\"Marge_Simpsons.png\"}," + "{\"id\":4,\"name\":\"Montgomery Burns\",\"imageName\":\"Montgomery_Burns.png\"}," + "{\"id\":5,\"name\":\"Ned Flanders\",\"imageName\":\"Ned_Flanders.png\"}," + "{\"id\":6,\"name\":\"Otto Mann\",\"imageName\":\"Otto_Mann.png\"}]" let jsonData = dataString.data(using: String.Encoding.utf8, allowLossyConversion: true) do { let result = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions()) as! Array<AnyObject> return result } catch let error as NSError { print("\(error)") } return nil }() class var sharedInstance: UsersJSONSerialization { return _UsersJSONSerializationSharedInstance } } class User: NSObject, XLFormOptionObject { let userId: Int let userName : String let userImage: String init(userId: Int, userName: String, userImage: String){ self.userId = userId self.userImage = userImage self.userName = userName } func formDisplayText() -> String { return self.userName } func formValue() -> Any { return self.userId as Any } } class UsersTableViewController : UITableViewController, XLFormRowDescriptorViewController { var rowDescriptor : XLFormRowDescriptor? var userCell : UserCell? fileprivate let kUserCellIdentifier = "UserCell" override init(style: UITableView.Style) { super.init(style: style); } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() tableView.register(UserCell.self, forCellReuseIdentifier: kUserCellIdentifier) tableView.tableFooterView = UIView(frame: CGRect.zero) } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return UsersJSONSerialization.sharedInstance.userData!.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: self.kUserCellIdentifier, for: indexPath) as! UserCell let usersData = UsersJSONSerialization.sharedInstance.userData! as! Array<Dictionary<String, AnyObject>> let userData = usersData[(indexPath as NSIndexPath).row] as Dictionary<String, AnyObject> let userId = userData["id"] as! Int cell.userName.text = userData["name"] as? String cell.userImage.image = UIImage(named: (userData["imageName"] as? String)!) if let value = rowDescriptor?.value { cell.accessoryType = ((value as? XLFormOptionObject)?.formValue() as? Int) == userId ? .checkmark : .none } return cell; } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 73.0 } //MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let usersData = UsersJSONSerialization.sharedInstance.userData! as! Array<Dictionary<String, AnyObject>> let userData = usersData[(indexPath as NSIndexPath).row] as Dictionary<String, AnyObject> let user = User(userId: (userData["id"] as! Int), userName: userData["name"] as! String, userImage: userData["imageName"] as! String) self.rowDescriptor!.value = user; if let popOver = self.presentedViewController, popOver.modalPresentationStyle == .popover { dismiss(animated: true, completion: nil) } else if parent is UINavigationController { navigationController?.popViewController(animated: true) } } }
89563c669ca961dc508712480e281e53
37.432039
174
0.661741
false
false
false
false
Mindera/Alicerce
refs/heads/master
Sources/View/ReusableView.swift
mit
1
import UIKit public protocol ReusableView { static var reuseIdentifier: String { get } } public extension ReusableView where Self: UIView { static var reuseIdentifier: String { return "\(self)" } } extension UICollectionReusableView: ReusableView {} extension UITableViewCell: ReusableView {} extension UITableViewHeaderFooterView: ReusableView {} // MARK: - UICollectionView Reusable properties public extension UICollectionView { func register<T: UICollectionViewCell>(_ cellType: T.Type) { register(cellType, forCellWithReuseIdentifier: cellType.reuseIdentifier) } func register<T: UICollectionViewCell & NibView>(_ cellType: T.Type) { register(cellType.nib, forCellWithReuseIdentifier: cellType.reuseIdentifier) } func register<T: UICollectionReusableView>(_ viewType: T.Type, forSupplementaryViewOfKind kind: String) { register(viewType, forSupplementaryViewOfKind: kind, withReuseIdentifier: viewType.reuseIdentifier) } func register<T: UICollectionReusableView & NibView>(_ viewType: T.Type, forSupplementaryViewOfKind kind: String) { register(viewType.nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: viewType.reuseIdentifier) } func dequeueCell<T: UICollectionViewCell>(`for` indexPath: IndexPath) -> T { let anyCell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) guard let cell = anyCell as? T else { fatalError("🔥 Dequeued Cell with identifier `\(T.reuseIdentifier)` for \(indexPath) is not of " + "type `\(T.self)`! Found: `\(type(of: anyCell))`. Forgot to register?") } return cell } func dequeueSupplementaryView<T: UICollectionReusableView>(forElementKind elementKind: String, at indexPath: IndexPath) -> T { let anySupplementaryView = dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) guard let supplementaryView = anySupplementaryView as? T else { fatalError("🔥 Dequeued SupplementaryView with element kind `\(elementKind)`, " + "identifier `\(T.reuseIdentifier)` for \(indexPath) is not of type `\(T.self)`! " + "Found: `\(type(of: anySupplementaryView))`. Forgot to register?") } return supplementaryView } func cell<T: UICollectionViewCell>(`for` indexPath: IndexPath) -> T { guard let anyCell = cellForItem(at: indexPath) else { fatalError("🔥 No Cell returned for \(indexPath)! Looking for `dequeueCell`?") } guard let cell = anyCell as? T else { fatalError("🔥 Cell at \(indexPath) is not of type: `\(T.self)`! Found: `\(type(of: anyCell))`") } return cell } func supplementaryView<T: UICollectionReusableView>(forElementKind elementKind: String, at indexPath: IndexPath) -> T { guard let anySupplementaryView = supplementaryView(forElementKind: elementKind, at: indexPath) else { fatalError("🔥 No supplementary view returned with element kind `\(elementKind)` for \(indexPath)! " + "Looking for `dequeueSupplementaryView`?") } guard let supplementaryView = anySupplementaryView as? T else { fatalError("🔥 SupplementaryView with element kind `\(elementKind)` is not of type: `\(T.self)`! " + "Found `\(type(of: anySupplementaryView))`") } return supplementaryView } } // MARK: - UITableView Reusable properties public extension UITableView { func register<T: UITableViewCell>(_ cellType: T.Type) { register(cellType, forCellReuseIdentifier: cellType.reuseIdentifier) } func register<T: UITableViewCell & NibView>(_ cellType: T.Type) { register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier) } func registerHeaderFooterView<T: UITableViewHeaderFooterView>(_ viewType: T.Type) { register(viewType, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier) } func registerHeaderFooterView<T: UITableViewHeaderFooterView & NibView>(_ viewType: T.Type) { register(viewType.nib, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier) } func dequeueCell<T: UITableViewCell>(`for` indexPath: IndexPath) -> T { let anyCell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) guard let cell = anyCell as? T else { fatalError("🔥 Dequeued Cell with identifier `\(T.reuseIdentifier)` for \(indexPath) is not of " + "type `\(T.self)`! Found: `\(type(of: anyCell))`. Forgot to register?") } return cell } func dequeueHeaderFooterView<T: UITableViewHeaderFooterView>() -> T { let anyHeaderFooterView = dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) guard let view = anyHeaderFooterView as? T else { fatalError("🔥 Dequeued HeaderFooterView with identifier `\(T.reuseIdentifier)` is not of " + "type `\(T.self)`! Found: `\(type(of: anyHeaderFooterView))`. Forgot to register?") } return view } func cell<T: UITableViewCell>(`for` indexPath: IndexPath) -> T { guard let anyCell = cellForRow(at: indexPath) else { fatalError("🔥 No Cell returned for \(indexPath)! Looking for `dequeueCell`?") } guard let cell = anyCell as? T else { fatalError("🔥 Cell at \(indexPath) is not of type: `\(T.self)`! Found: `\(type(of: anyCell))`. " + "Forgot to register?") } return cell } func headerView<T: UITableViewHeaderFooterView>(forSection section: Int) -> T { guard let anyHeaderView = headerView(forSection: section) else { fatalError("🔥 No HeaderView returned for section: \(section)! Looking for `dequeueHeaderFooterView`?") } guard let view = anyHeaderView as? T else { fatalError("🔥 HeaderView for section: \(section) is not of type: `\(T.self)`! " + "Found `\(type(of: anyHeaderView))`. Forgot to register?") } return view } func footerView<T: UITableViewHeaderFooterView>(forSection section: Int) -> T { guard let anyFooterView = footerView(forSection: section) else { fatalError("🔥 No FooterView returned for section: \(section)! Looking for `dequeueHeaderFooterView`?") } guard let view = anyFooterView as? T else { fatalError("🔥 FooterView for section: \(section) is not of type: `\(T.self)`! " + "Found `\(type(of: anyFooterView))`. Forgot to register?") } return view } }
af96929496c97b05799ac8819e880640
40.552941
119
0.629955
false
false
false
false
ytfhqqu/iCC98
refs/heads/master
iCC98/iCC98/MessageContentViewController.swift
mit
1
// // MessageContentViewController.swift // iCC98 // // Created by Duo Xu on 5/20/17. // Copyright © 2017 Duo Xu. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CC98Kit class MessageContentViewController: BaseWebViewController { @IBOutlet weak var replyButton: UIBarButtonItem! // MARK: - Data /** 设置数据。 - parameter messageInfo: 短消息的信息。 - parameter currentUserName: 当前登录用户的用户名。 */ func setData(messageInfo: MessageInfo, currentUserName: String?) { super.setData(code: messageInfo.content ?? "", codeType: .ubb) self.messageInfo = messageInfo self.currentUserName = currentUserName updateUI() } /// 短消息的信息。 private var messageInfo: MessageInfo? /// 当前登录用户的用户名。 private var currentUserName: String? // MARK: - UI // 更新 UI private func updateUI() { if let messageInfo = messageInfo { if let senderName = messageInfo.senderName, senderName != currentUserName { replyButton?.isEnabled = true } else { // 系统消息和自己发出的消息都不能回复 replyButton?.isEnabled = false } } } // 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. // 目标控制器可能包含 `UINavigationController`,这种情况下需要把它下面的控制器取出来 var destinationVC = segue.destination if let navigationController = destinationVC as? UINavigationController { destinationVC = navigationController.visibleViewController ?? destinationVC } // 发消息 if segue.identifier == "Reply To Message", let messageInfo = messageInfo, let newMessageTVC = destinationVC as? NewMessageTableViewController { newMessageTVC.setData(newMessageType: .reply(quotedMessageInfo: messageInfo)) } } }
b998f13b1865a808797ac62242a5e5a5
38.222222
151
0.684293
false
false
false
false
kingsic/SGPagingView
refs/heads/master
SGPagingView/Example/SuspensionPro/SuspensionProVC.swift
mit
2
// // SuspensionProVC.swift // SGPagingView // // Created by kingsic on 2021/10/20. // Copyright © 2021 kingsic. All rights reserved. // import UIKit let pro_headerViewHeight: CGFloat = 270 let pro_pagingTitleViewHeight: CGFloat = 40 let navHeight: CGFloat = 44 + UIScreen.statusBarHeight class SuspensionProVC: UIViewController { lazy var pagingTitleView: SGPagingTitleView = { let configure = SGPagingTitleViewConfigure() configure.color = .lightGray configure.selectedColor = .black configure.indicatorType = .Dynamic configure.indicatorColor = .orange configure.showBottomSeparator = false let frame = CGRect.init(x: 0, y: pro_headerViewHeight, width: view.frame.size.width, height: pro_pagingTitleViewHeight) let titles = ["精选", "微博", "相册"] let pagingTitle = SGPagingTitleView(frame: frame, titles: titles, configure: configure) pagingTitle.delegate = self return pagingTitle }() var tempBaseSubVCs: [BaseSubProVC] = [] lazy var pagingContentView: SGPagingContentScrollView = { let vc1 = SubProVC() let vc2 = SubTitleProVC() let vc3 = SubProVC() let vcs = [vc1, vc2, vc3] tempBaseSubVCs = vcs let tempRect: CGRect = CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) let pagingContent = SGPagingContentScrollView(frame: tempRect, parentVC: self, childVCs: vcs) pagingContent.delegate = self return pagingContent }() lazy var headerView: UIView = { let headerView: UIView = UIView() headerView.backgroundColor = .red headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: pro_headerViewHeight) let pan = UIPanGestureRecognizer(target: self, action: #selector(pan_action)) headerView.addGestureRecognizer(pan) let btn = UIButton(type: .custom) let btn_width: CGFloat = 200 let btn_x = 0.5 * (view.frame.width - btn_width) btn.frame = CGRect(x: btn_x, y: pro_headerViewHeight - 100, width: btn_width, height: 50) btn.layer.cornerRadius = 10 btn.backgroundColor = .black btn.setTitle("You know?I can click", for: .normal) btn.addTarget(self, action: #selector(temp_btn_action), for: .touchUpInside) headerView.addSubview(btn) return headerView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = .white view.addSubview(UIView()) view.addSubview(pagingContentView) view.addSubview(headerView) view.addSubview(pagingTitleView) tempLastPagingTitleViewY = pro_headerViewHeight // 监听子视图发出的通知 NotificationCenter.default.addObserver(self, selector: #selector(subTableViewDidScroll), name: NSNotification.Name(NNProSubScrollViewDidScroll), object: nil) } var tempSubScrollView: UIScrollView? var tempLastPagingTitleViewY: CGFloat = 0 var tempLastPoint: CGPoint = .zero deinit { print("SuspensionProVC") } } extension SuspensionProVC { @objc func pan_action(pan: UIPanGestureRecognizer) { if pan.state == .began { } else if pan.state == .changed { let currenrPoint: CGPoint = pan.translation(in: pan.view) let distanceY = currenrPoint.y - tempLastPoint.y tempLastPoint = currenrPoint let baseSubVC = tempBaseSubVCs[pagingTitleView.index] var contentOffset: CGPoint = baseSubVC.scrollView!.contentOffset contentOffset.y += -distanceY if contentOffset.y <= -pro_subScrollViewContentOffsetY { contentOffset.y = -pro_subScrollViewContentOffsetY } baseSubVC.scrollView?.contentOffset = contentOffset } else { pan.setTranslation(.zero, in: pan.view) tempLastPoint = .zero } } } extension SuspensionProVC { @objc func subTableViewDidScroll(noti: Notification) { let scrollingScrollView = noti.userInfo!["scrollingScrollView"] as! UIScrollView let offsetDifference: CGFloat = noti.userInfo!["offsetDifference"] as! CGFloat var distanceY: CGFloat = 0 let baseSubVC = tempBaseSubVCs[pagingTitleView.index] // 当前滚动的 scrollView 不是当前显示的 scrollView 直接返回 guard scrollingScrollView == baseSubVC.scrollView else { return } var pagingTitleViewFrame: CGRect = pagingTitleView.frame guard pagingTitleViewFrame.origin.y >= navHeight else { return } let scrollViewContentOffsetY = scrollingScrollView.contentOffset.y // 往上滚动 if offsetDifference > 0 && scrollViewContentOffsetY + pro_subScrollViewContentOffsetY > 0 { if (scrollViewContentOffsetY + pro_subScrollViewContentOffsetY + pagingTitleView.frame.origin.y) > pro_headerViewHeight || scrollViewContentOffsetY + pro_subScrollViewContentOffsetY < 0 { pagingTitleViewFrame.origin.y += -offsetDifference if pagingTitleViewFrame.origin.y <= navHeight { pagingTitleViewFrame.origin.y = navHeight } } } else { // 往下滚动 if (scrollViewContentOffsetY + pagingTitleView.frame.origin.y + pro_subScrollViewContentOffsetY) < pro_headerViewHeight { pagingTitleViewFrame.origin.y = -scrollViewContentOffsetY - pro_pagingTitleViewHeight if pagingTitleViewFrame.origin.y >= pro_headerViewHeight { pagingTitleViewFrame.origin.y = pro_headerViewHeight } } } // 更新 pagingTitleView 的 frame pagingTitleView.frame = pagingTitleViewFrame // 更新 headerView 的 frame var headerViewFrame: CGRect = headerView.frame headerViewFrame.origin.y = pagingTitleView.frame.origin.y - pro_headerViewHeight headerView.frame = headerViewFrame distanceY = pagingTitleViewFrame.origin.y - tempLastPagingTitleViewY tempLastPagingTitleViewY = pagingTitleView.frame.origin.y /// 让其余控制器的 scrollView 跟随当前正在滚动的 scrollView 而滚动 otherScrollViewFollowingScrollingScrollView(scrollView: scrollingScrollView, distanceY: distanceY) } /// 让其余控制器的 scrollView 跟随当前正在滚动的 scrollView 而滚动 func otherScrollViewFollowingScrollingScrollView(scrollView: UIScrollView, distanceY: CGFloat) { var baseSubVC: BaseSubProVC for (index, _) in tempBaseSubVCs.enumerated() { baseSubVC = tempBaseSubVCs[index] if baseSubVC.scrollView == scrollView { continue } else { if let tempScrollView = baseSubVC.scrollView { var contentOffSet: CGPoint = tempScrollView.contentOffset contentOffSet.y += -distanceY tempScrollView.contentOffset = contentOffSet } } } } } extension SuspensionProVC: SGPagingTitleViewDelegate, SGPagingContentViewDelegate { func pagingTitleView(titleView: SGPagingTitleView, index: Int) { pagingContentView.setPagingContentView(index: index) } func pagingContentView(contentView: SGPagingContentView, progress: CGFloat, currentIndex: Int, targetIndex: Int) { pagingTitleView.setPagingTitleView(progress: progress, currentIndex: currentIndex, targetIndex: targetIndex) } func pagingContentViewDidScroll() { let baseSubVC: BaseSubProVC = tempBaseSubVCs[pagingTitleView.index] if let tempScrollView = baseSubVC.scrollView { if (tempScrollView.contentSize.height) < UIScreen.main.bounds.size.width { tempScrollView.setContentOffset(CGPoint(x: 0, y: -pro_subScrollViewContentOffsetY), animated: false) } } } } extension SuspensionProVC { @objc func temp_btn_action() { print("temp_btn_action") } }
f61f33e2ae4a42e721d5bcc5cd7fc817
38.68599
199
0.650639
false
false
false
false
AjayOdedara/CoreKitTest
refs/heads/master
CoreKit/CoreKit/ImageService.swift
mit
1
// // ImageService.swift // CllearworksCoreKit // // Created by Tim Sneed on 6/22/15. // Copyright (c) 2015 Cllearworks. All rights reserved. // import UIKit public class ImageService: NSObject { public enum ImageMode:String { case Uniform = "Uniform" case Zoom = "Zoom" case Pad = "Pad" var description : String { get { return self.rawValue } } } public enum VerticalCrop: String { case Center = "Center" case Top = "Top" case Bottom = "Bottom" var verticalValue : String { get { return self.rawValue } } } public enum HorizontalCrop: String { case Center = "Center" case Left = "Left" case Right = "Right" var horizontalValue : String { get { return self.rawValue } } } public func buildImageString(imageName:String, imageMode:ImageMode, size:CGSize, scale:CGFloat)-> NSURL{ return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)&mode=\(imageMode.description)&width=\(Int(size.width * scale))&height=\(Int(size.height * scale))")! } public func buildImageString(imageName:String, imageMode:ImageMode, size:CGSize)-> NSURL{ return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)&mode=\(imageMode.description)&width=\(Int(size.width))&height=\(Int(size.height))")! } //removed the imagemode to get full image public func buildImageString(imageName:String, size:CGSize)-> NSURL{ return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)")! } public func buildImageString(imageName:String, imageMode:ImageMode, size:CGSize, scale:CGFloat, cropAnchorV:VerticalCrop, cropAnchorH: HorizontalCrop)-> NSURL{ return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)&mode=\(imageMode.description)&width=\(Int(size.width * scale))&height=\(Int(size.height * scale))&cropAnchorV=\(cropAnchorV.verticalValue)&cropAnchorH=\(cropAnchorH.horizontalValue)")! } public func buildImageUrl(urlString: String, imageMode: ImageMode, size: CGSize) -> NSURL { let scale = UIScreen().scale return NSURL(string: urlString + "&mode=\(imageMode)&width=\(Int(size.width * scale))&height=\(Int(size.height * scale))")! } }
031cd9645e4f5c9c594801c71e4e0682
34.126761
285
0.642743
false
false
false
false
FUKUZAWA-Tadashi/FHCCommander
refs/heads/master
fhcc/State.swift
mit
1
// // State.swift // fhcc // // Created by 福澤 正 on 2014/06/25. // Copyright (c) 2014年 Fukuzawa Technology. All rights reserved. // import Foundation class State { // 測位精度がこれより低ければ(大きければ)、その位置情報は捨てる class var ACCURACY_LIMIT: Double { return 100.0 } private let USER_DEFAULTS_KEY = "FHC_State" var fhcAddress: String var mailAddr: String var password: String var homeLatitude: Double var homeLongitude: Double var homeRegionRadius: Double var farRegionRadius: Double var homeSSID: String var fhcSecret: String var fhcOfficialSite: String var applianceOfOutgo: String var actionOfOutgo: String var applianceOfReturnHome: String var actionOfReturnHome: String var sensorUpdateInterval: Int var actionsDict: Dictionary<String, [String]> var judgeUsingLan: Bool class var VOICE_COMMAND: String { return "< 音声コマンド >" } class var ACTIONS_DICT_DEFAULTS: Dictionary<String, [String]> { return [ VOICE_COMMAND : [ "いってきます", "ただいま" ], "家電1" : [ "すいっちおん", "でんげんきって" ], "家電2" : [ "でんげんいれて", "すいっちおふ" ] ] } private let KEY_FHC_ADDRESS = "fhcAddress" private let KEY_MAIL_ADDR = "mailAddr" private let KEY_PASSWORD = "password" private let KEY_HOME_LATITUDE = "homeLatitude" private let KEY_HOME_LONGITUDE = "homeLongitude" private let KEY_HOME_REGION_RADIUS = "homeRegionRadius" private let KEY_FAR_REGION_RADIUS = "farRegionRadius" private let KEY_HOME_SSID = "homeSSID" private let KEY_FHC_SECRET = "fhcSecret" private let KEY_FHC_OFFICIAL_SITE = "fhcOfficialSite" private let KEY_APPLIANCE_OF_OUTGO = "applianceOfOutgo" private let KEY_ACTION_OF_OUTGO = "actionOfOutgo" private let KEY_APPLIANCE_OF_RETURN_HOME = "applianceOfReturnHome" private let KEY_ACTION_OF_RETURN_HOME = "actionOfReturnHome" private let KEY_SENSOR_UPDATE_INTERVAL = "sensorUpdateInterval" private let KEY_JUDGE_USING_LAN = "judgeUsingLan" private let KEY_AD_KEYS = "ad_keys" private let KEY_AD_VAL = "ad_val_" init () { fhcAddress = "fhc.local" mailAddr = "" password = "" homeLatitude = 0.0 homeLongitude = 0.0 homeRegionRadius = 20.0 farRegionRadius = 200.0 homeSSID = "" fhcSecret = "" fhcOfficialSite = "fhc.rti-giken.jp" applianceOfOutgo = "" actionOfOutgo = "" applianceOfReturnHome = "" actionOfReturnHome = "" sensorUpdateInterval = 30 actionsDict = State.ACTIONS_DICT_DEFAULTS judgeUsingLan = true } func loadFromUserDefaults () -> Bool { var defaults = NSUserDefaults.standardUserDefaults() var failed = false func chk_load_string(key:String) -> String! { let x = defaults.stringForKey(key) if x == nil { NSLog("load state failed on '\(key)'") failed = true } return x } func chk_load_object(key:String) -> AnyObject! { let x: AnyObject! = defaults.objectForKey(key) if x == nil { NSLog("load state failed on '\(key)'") failed = true } return x } func chk_load_string_array(key:String) -> [String]! { let x: [AnyObject]! = defaults.stringArrayForKey(key) if x == nil { NSLog("load state failed on '\(key)'") failed = true return nil } return x as [String] } fhcAddress = chk_load_string(KEY_FHC_ADDRESS) ?? "fhc.local" mailAddr = chk_load_string(KEY_MAIL_ADDR) ?? "" password = chk_load_string(KEY_PASSWORD) ?? "" homeLatitude = defaults.doubleForKey(KEY_HOME_LATITUDE) homeLongitude = defaults.doubleForKey(KEY_HOME_LONGITUDE) homeRegionRadius = defaults.doubleForKey(KEY_HOME_REGION_RADIUS) farRegionRadius = defaults.doubleForKey(KEY_FAR_REGION_RADIUS) homeSSID = chk_load_string(KEY_HOME_SSID) ?? "" fhcSecret = chk_load_string(KEY_FHC_SECRET) ?? "" fhcOfficialSite = chk_load_string(KEY_FHC_OFFICIAL_SITE) ?? "fhc.rti-giken.jp" applianceOfOutgo = chk_load_string(KEY_APPLIANCE_OF_OUTGO) ?? "" actionOfOutgo = chk_load_string(KEY_ACTION_OF_OUTGO) ?? "" applianceOfReturnHome = chk_load_string(KEY_APPLIANCE_OF_RETURN_HOME) ?? "" actionOfReturnHome = chk_load_string(KEY_ACTION_OF_RETURN_HOME) ?? "" if homeRegionRadius == 0.0 { homeRegionRadius = 20.0 } if farRegionRadius == 0.0 { farRegionRadius = 200.0 } if (failed) { sensorUpdateInterval = 30 judgeUsingLan = true } else { sensorUpdateInterval = defaults.integerForKey(KEY_SENSOR_UPDATE_INTERVAL) judgeUsingLan = defaults.boolForKey(KEY_JUDGE_USING_LAN) } var adict = Dictionary<String, [String]>() let ad_keys = chk_load_string_array(KEY_AD_KEYS) if ad_keys != nil { for (i,k) in enumerate(ad_keys!) { let x = chk_load_string_array(KEY_AD_VAL + "\(i)") if x != nil { adict[k] = x } } } if adict.count > 0 { actionsDict = adict } return !failed } func saveToUserDefaults () { var defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(fhcAddress, forKey: KEY_FHC_ADDRESS) defaults.setObject(mailAddr, forKey: KEY_MAIL_ADDR) defaults.setObject(password, forKey: KEY_PASSWORD) defaults.setDouble(homeLatitude, forKey: KEY_HOME_LATITUDE) defaults.setDouble(homeLongitude, forKey: KEY_HOME_LONGITUDE) defaults.setDouble(homeRegionRadius, forKey: KEY_HOME_REGION_RADIUS) defaults.setDouble(farRegionRadius, forKey: KEY_FAR_REGION_RADIUS) defaults.setObject(homeSSID, forKey: KEY_HOME_SSID) defaults.setObject(fhcSecret, forKey: KEY_FHC_SECRET) defaults.setObject(fhcOfficialSite, forKey: KEY_FHC_OFFICIAL_SITE) defaults.setObject(applianceOfOutgo, forKey: KEY_APPLIANCE_OF_OUTGO) defaults.setObject(actionOfOutgo, forKey: KEY_ACTION_OF_OUTGO) defaults.setObject(applianceOfReturnHome, forKey: KEY_APPLIANCE_OF_RETURN_HOME) defaults.setObject(actionOfReturnHome, forKey: KEY_ACTION_OF_RETURN_HOME) defaults.setInteger(sensorUpdateInterval, forKey: KEY_SENSOR_UPDATE_INTERVAL) defaults.setBool(judgeUsingLan, forKey: KEY_JUDGE_USING_LAN) let ad_keys = actionsDict.keys.array defaults.setObject(ad_keys.map{NSString(string:$0)}, forKey: KEY_AD_KEYS) for (i,k) in enumerate(ad_keys) { let ad_val = actionsDict[k]!.map{NSString(string:$0)} defaults.setObject(ad_val, forKey: KEY_AD_VAL + "\(i)") } defaults.synchronize() } }
06d7c9b66e9e4860bfb6ff93966ddca3
36.03125
87
0.612463
false
false
false
false
rhwood/roster-decoder
refs/heads/master
Carthage/Checkouts/Fuzi/Sources/Document.swift
mit
1
// Document.swift // Copyright (c) 2015 Ce Zheng // // 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 libxml2 /// XML document which can be searched and queried. open class XMLDocument { // MARK: - Document Attributes /// The XML version. open fileprivate(set) lazy var version: String? = { return ^-^self.cDocument.pointee.version }() /// The string encoding for the document. This is NSUTF8StringEncoding if no encoding is set, or it cannot be calculated. open fileprivate(set) lazy var encoding: String.Encoding = { if let encodingName = ^-^self.cDocument.pointee.encoding { let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?) if encoding != kCFStringEncodingInvalidId { return String.Encoding(rawValue: UInt(CFStringConvertEncodingToNSStringEncoding(encoding))) } } return String.Encoding.utf8 }() // MARK: - Accessing the Root Element /// The root element of the document. open fileprivate(set) var root: XMLElement? // MARK: - Accessing & Setting Document Formatters /// The formatter used to determine `numberValue` for elements in the document. By default, this is an `NSNumberFormatter` instance with `NSNumberFormatterDecimalStyle`. open lazy var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() /// The formatter used to determine `dateValue` for elements in the document. By default, this is an `NSDateFormatter` instance configured to accept ISO 8601 formatted timestamps. open lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter }() // MARK: - Creating XML Documents fileprivate let cDocument: xmlDocPtr /** Creates and returns an instance of XMLDocument from an XML string, throwing XMLError if an error occured while parsing the XML. - parameter string: The XML string. - parameter encoding: The string encoding. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws { guard let cChars = string.cString(using: encoding) else { throw XMLError.invalidData } try self.init(cChars: cChars) } /** Creates and returns an instance of XMLDocument from XML data, throwing XMLError if an error occured while parsing the XML. - parameter data: The XML data. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(data: Data) throws { let cChars = data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> [CChar] in let buffer = UnsafeBufferPointer(start: bytes, count: data.count) return [CChar](buffer) } try self.init(cChars: cChars) } /** Creates and returns an instance of XMLDocument from C char array, throwing XMLError if an error occured while parsing the XML. - parameter cChars: cChars The XML data as C char array - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(cChars: [CChar]) throws { let options = Int32(XML_PARSE_NOWARNING.rawValue | XML_PARSE_NOERROR.rawValue | XML_PARSE_RECOVER.rawValue) try self.init(cChars: cChars, options: options) } fileprivate typealias ParseFunction = (UnsafePointer<Int8>?, Int32, UnsafePointer<Int8>?, UnsafePointer<Int8>?, Int32) -> xmlDocPtr? fileprivate convenience init(cChars: [CChar], options: Int32) throws { try self.init(parseFunction: { xmlReadMemory($0, $1, $2, $3, $4) }, cChars: cChars, options: options) } fileprivate convenience init(parseFunction: ParseFunction, cChars: [CChar], options: Int32) throws { guard let document = parseFunction(UnsafePointer(cChars), Int32(cChars.count), "", nil, options) else { throw XMLError.lastError(defaultError: .parserFailure) } xmlResetLastError() self.init(cDocument: document) } fileprivate init(cDocument: xmlDocPtr) { self.cDocument = cDocument if let cRoot = xmlDocGetRootElement(cDocument) { root = XMLElement(cNode: cRoot, document: self) } } deinit { xmlFreeDoc(cDocument) } // MARK: - XML Namespaces var defaultNamespaces = [String: String]() /** Define a prefix for a default namespace. - parameter prefix: The prefix name - parameter ns: The default namespace URI that declared in XML Document */ open func definePrefix(_ prefix: String, defaultNamespace ns: String) { defaultNamespaces[ns] = prefix } } extension XMLDocument: Equatable {} /** Determine whether two documents are the same - parameter lhs: XMLDocument on the left - parameter rhs: XMLDocument on the right - returns: whether lhs and rhs are equal */ public func ==(lhs: XMLDocument, rhs: XMLDocument) -> Bool { return lhs.cDocument == rhs.cDocument } /// HTML document which can be searched and queried. open class HTMLDocument: XMLDocument { // MARK: - Convenience Accessors /// HTML title of current document open var title: String? { return root?.firstChild(tag: "head")?.firstChild(tag: "title")?.stringValue } /// HTML head element of current document open var head: XMLElement? { return root?.firstChild(tag: "head") } /// HTML body element of current document open var body: XMLElement? { return root?.firstChild(tag: "body") } // MARK: - Creating HTML Documents /** Creates and returns an instance of HTMLDocument from C char array, throwing XMLError if an error occured while parsing the HTML. - parameter cChars: cChars The HTML data as C char array - throws: `XMLError` instance if an error occurred - returns: An `HTMLDocument` with the contents of the specified HTML string. */ public convenience init(cChars: [CChar]) throws { let options = Int32(HTML_PARSE_NOWARNING.rawValue | HTML_PARSE_NOERROR.rawValue | HTML_PARSE_RECOVER.rawValue) try self.init(cChars: cChars, options: options) } fileprivate convenience init(cChars: [CChar], options: Int32) throws { try self.init(parseFunction: { htmlReadMemory($0, $1, $2, $3, $4) }, cChars: cChars, options: options) } }
6c6591d22608cb8357cf0ebbf61c0fa6
35.946602
181
0.716857
false
false
false
false
DanielAsher/XLForm
refs/heads/master
Examples/Swift/SwiftExample/AccessoryViews/AccessoryViewFormViewController.swift
mit
7
// // AccessoryViewFormViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class AccessoryViewFormViewController : XLFormViewController { private enum Tags : String { case AccessoryViewRowNavigationEnabled = "RowNavigationEnabled" case AccessoryViewRowNavigationShowAccessoryView = "RowNavigationShowAccessoryView" case AccessoryViewRowNavigationStopDisableRow = "rowNavigationStopDisableRow" case AccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow = "rowNavigationSkipCanNotBecomeFirstResponderRow" case AccessoryViewRowNavigationStopInlineRow = "rowNavigationStopInlineRow" case AccessoryViewName = "name" case AccessoryViewEmail = "email" case AccessoryViewTwitter = "twitter" case AccessoryViewUrl = "url" case AccessoryViewDate = "date" case AccessoryViewTextView = "textView" case AccessoryViewCheck = "check" case AccessoryViewNotes = "notes" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.initializeForm() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initializeForm() } func initializeForm() { let form : XLFormDescriptor var section : XLFormSectionDescriptor var row : XLFormRowDescriptor form = XLFormDescriptor(title: "Accessory View") form.rowNavigationOptions = XLFormRowNavigationOptions.Enabled // Configuration section section = XLFormSectionDescriptor() section.title = "Row Navigation Settings" section.footerTitle = "Changing the Settings values you will navigate differently" form.addFormSection(section) // RowNavigationEnabled row = XLFormRowDescriptor(tag: Tags.AccessoryViewRowNavigationEnabled.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Row Navigation Enabled?") row.value = true section.addFormRow(row) // RowNavigationShowAccessoryView row = XLFormRowDescriptor(tag: Tags.AccessoryViewRowNavigationShowAccessoryView.rawValue, rowType:XLFormRowDescriptorTypeBooleanCheck, title:"Show input accessory row?") row.value = (form.rowNavigationOptions & XLFormRowNavigationOptions.Enabled) == XLFormRowNavigationOptions.Enabled row.hidden = "$\(Tags.AccessoryViewRowNavigationEnabled.rawValue) == 0" section.addFormRow(row) // RowNavigationStopDisableRow row = XLFormRowDescriptor(tag: Tags.AccessoryViewRowNavigationStopDisableRow.rawValue, rowType: XLFormRowDescriptorTypeBooleanCheck, title:"Stop when reach disabled row?") row.value = (form.rowNavigationOptions & XLFormRowNavigationOptions.StopDisableRow) == XLFormRowNavigationOptions.StopDisableRow row.hidden = "$\(Tags.AccessoryViewRowNavigationEnabled.rawValue) == 0" section.addFormRow(row) // RowNavigationStopInlineRow row = XLFormRowDescriptor(tag: Tags.AccessoryViewRowNavigationStopInlineRow.rawValue, rowType: XLFormRowDescriptorTypeBooleanCheck, title: "Stop when reach inline row?") row.value = (form.rowNavigationOptions & XLFormRowNavigationOptions.StopInlineRow) == XLFormRowNavigationOptions.StopInlineRow row.hidden = "$\(Tags.AccessoryViewRowNavigationEnabled.rawValue) == 0" section.addFormRow(row) // RowNavigationSkipCanNotBecomeFirstResponderRow row = XLFormRowDescriptor(tag: Tags.AccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow.rawValue, rowType:XLFormRowDescriptorTypeBooleanCheck, title:"Skip Can Not Become First Responder Row?") row.value = (form.rowNavigationOptions & XLFormRowNavigationOptions.SkipCanNotBecomeFirstResponderRow) == XLFormRowNavigationOptions.SkipCanNotBecomeFirstResponderRow row.hidden = "$\(Tags.AccessoryViewRowNavigationEnabled.rawValue) == 0" section.addFormRow(row) section = XLFormSectionDescriptor() form.addFormSection(section) // Name row = XLFormRowDescriptor(tag: Tags.AccessoryViewName.rawValue, rowType: XLFormRowDescriptorTypeText, title: "Name") row.required = true section.addFormRow(row) // Email row = XLFormRowDescriptor(tag: Tags.AccessoryViewEmail.rawValue, rowType: XLFormRowDescriptorTypeEmail, title: "Email") // validate the email row.addValidator(XLFormValidator.emailValidator()) section.addFormRow(row) // Twitter row = XLFormRowDescriptor(tag: Tags.AccessoryViewTwitter.rawValue, rowType: XLFormRowDescriptorTypeTwitter, title: "Twitter") row.disabled = NSNumber(bool: true) row.value = "@no_editable" section.addFormRow(row) // Url row = XLFormRowDescriptor(tag: Tags.AccessoryViewUrl.rawValue, rowType: XLFormRowDescriptorTypeURL, title: "Url") section.addFormRow(row) // Date row = XLFormRowDescriptor(tag: Tags.AccessoryViewDate.rawValue, rowType:XLFormRowDescriptorTypeDateInline, title:"Date Inline") row.value = NSDate.new() section.addFormRow(row) section = XLFormSectionDescriptor() form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.AccessoryViewTextView.rawValue, rowType:XLFormRowDescriptorTypeTextView) row.cellConfigAtConfigure["textView.placeholder"] = "TEXT VIEW EXAMPLE" section.addFormRow(row) row = XLFormRowDescriptor(tag: Tags.AccessoryViewCheck.rawValue, rowType:XLFormRowDescriptorTypeBooleanCheck, title:"Ckeck") section.addFormRow(row) section = XLFormSectionDescriptor() form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.AccessoryViewNotes.rawValue, rowType:XLFormRowDescriptorTypeTextView, title:"Notes") section.addFormRow(row) self.form = form } override func inputAccessoryViewForRowDescriptor(rowDescriptor: XLFormRowDescriptor!) -> UIView! { if self.form.formRowWithTag(Tags.AccessoryViewRowNavigationShowAccessoryView.rawValue)!.value!.boolValue == false { return nil } return super.inputAccessoryViewForRowDescriptor(rowDescriptor) } //MARK: XLFormDescriptorDelegate override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!) { super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue) if formRow.tag == Tags.AccessoryViewRowNavigationStopDisableRow.rawValue { if formRow.value!.boolValue == true { self.form.rowNavigationOptions = self.form.rowNavigationOptions | XLFormRowNavigationOptions.StopDisableRow } else{ self.form.rowNavigationOptions = self.form.rowNavigationOptions & (~XLFormRowNavigationOptions.StopDisableRow) } } else if formRow.tag == Tags.AccessoryViewRowNavigationStopInlineRow.rawValue { if formRow.value!.boolValue == true { self.form.rowNavigationOptions = self.form.rowNavigationOptions | XLFormRowNavigationOptions.StopInlineRow } else{ self.form.rowNavigationOptions = self.form.rowNavigationOptions & (~XLFormRowNavigationOptions.StopInlineRow) } } else if formRow.tag == Tags.AccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow.rawValue { if formRow.value!.boolValue == true { self.form.rowNavigationOptions = self.form.rowNavigationOptions | XLFormRowNavigationOptions.SkipCanNotBecomeFirstResponderRow } else{ self.form.rowNavigationOptions = self.form.rowNavigationOptions & (~XLFormRowNavigationOptions.SkipCanNotBecomeFirstResponderRow) } } } }
b23c698b98fea154601d678c59d31e76
46.492386
208
0.710239
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPressKit/WordPressKitTests/PeopleServiceRemoteTests.swift
gpl-2.0
2
import Foundation import XCTest @testable import WordPressKit class PeopleServiceRemoteTests: RemoteTestCase, RESTTestable { // MARK: - Constants let siteID = 321 let userID = 1111 let validUsername = "jimthetester" let viewerID = 123 let followerID = 987 let invalidSiteID = 888 let invalidUserID = 9999 let invalidUsername = "someInvalidUser" let newInviteEndpoint = "invites/new" let validateInviteEndpoint = "invites/validate" let getRolesSuccessMockFilename = "site-roles-success.json" let getRolesBadJsonFailureMockFilename = "site-roles-bad-json-failure.json" let getRolesBadAuthMockFilename = "site-roles-auth-failure.json" let updateRoleSuccessMockFilename = "site-users-update-role-success.json" let updateRoleUnknownUserFailureMockFilename = "site-users-update-role-unknown-user-failure.json" let updateRoleUnknownSiteFailureMockFilename = "site-users-update-role-unknown-site-failure.json" let updateRoleBadJsonFailureMockFilename = "site-users-update-role-bad-json-failure.json" let validationSuccessMockFilename = "people-validate-invitation-success.json" let validationFailureMockFilename = "people-validate-invitation-failure.json" let sendSuccessMockFilename = "people-send-invitation-success.json" let sendFailureMockFilename = "people-send-invitation-failure.json" let deleteUserSuccessMockFilename = "site-users-delete-success.json" let deleteUserAuthFailureMockFilename = "site-users-delete-auth-failure.json" let deleteUserBadJsonFailureMockFilename = "site-users-delete-bad-json-failure.json" let deleteUserNonMemberFailureMockFilename = "site-users-delete-not-member-failure.json" let deleteUserSiteOwnerFailureMockFilename = "site-users-delete-site-owner-failure.json" let deleteFollowerSuccessMockFilename = "site-followers-delete-success.json" let deleteFollowerFailureMockFilename = "site-followers-delete-failure.json" let deleteFollowerAuthFailureMockFilename = "site-followers-delete-auth-failure.json" let deleteFollowerBadJsonFailureMockFilename = "site-followers-delete-bad-json-failure.json" let deleteViewerSuccessMockFilename = "site-viewers-delete-success.json" let deleteViewerFailureMockFilename = "site-viewers-delete-failure.json" let deleteViewerAuthFailureMockFilename = "site-viewers-delete-auth-failure.json" let deleteViewerBadJsonFailureMockFilename = "site-viewers-delete-bad-json.json" // MARK: - Properties var remote: PeopleServiceRemote! var siteRolesEndpoint: String { return "sites/\(siteID)/roles" } var siteUserEndpoint: String { return "sites/\(siteID)/users/\(userID)" } var siteUnknownUserEndpoint: String { return "sites/\(siteID)/users/\(invalidUserID)" } var unknownSiteUserEndpoint: String { return "sites/\(invalidSiteID)/users/\(userID)" } var siteUserDeleteEndpoint: String { return "sites/\(siteID)/users/\(userID)/delete" } var siteViewerDeleteEndpoint: String { return "sites/\(siteID)/viewers/\(viewerID)/delete" } var siteFollowerDeleteEndpoint: String { return "sites/\(siteID)/followers/\(followerID)/delete" } // MARK: - Overridden Methods override func setUp() { super.setUp() remote = PeopleServiceRemote(wordPressComRestApi: getRestApi()) } override func tearDown() { super.tearDown() remote = nil } // MARK: - User Tests func testDeleteUserWithBadAuthUserFails() { let expect = expectation(description: "Delete user with bad auth failure") stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserAuthFailureMockFilename, contentType: .ApplicationJSON, status: 403) remote.deleteUser(siteID, userID: userID, success: { roles in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteUserWithSiteOwnerFails() { let expect = expectation(description: "Delete user with site owner failure") stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserSiteOwnerFailureMockFilename, contentType: .ApplicationJSON, status: 403) remote.deleteUser(siteID, userID: userID, success: { roles in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteUserWithNonMemberFails() { let expect = expectation(description: "Delete user with non site member failure") stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserNonMemberFailureMockFilename, contentType: .ApplicationJSON, status: 400) remote.deleteUser(siteID, userID: userID, success: { roles in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.invalidInput.rawValue, "The error code should be 0 - invalid input") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteUserWithValidUserSucceeds() { let expect = expectation(description: "Delete user success") stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserSuccessMockFilename, contentType: .ApplicationJSON) remote.deleteUser(siteID, userID: userID, success: { expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteUserWithServerErrorFails() { let expect = expectation(description: "Delete user with server error failure") stubRemoteResponse(siteUserDeleteEndpoint, data: Data(), contentType: .NoContentType, status: 500) remote.deleteUser(siteID, userID: userID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteUserWithBadJsonFails() { let expect = expectation(description: "Delete user with invalid json response failure") stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200) remote.deleteUser(siteID, userID: userID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } // MARK: - Follower Tests func testDeleteFollowerWithInvalidFollowerFails() { let expect = expectation(description: "Delete non-follower failure") stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerFailureMockFilename, contentType: .ApplicationJSON, status: 404) remote.deleteFollower(siteID, userID: followerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteFollowerWithBadAuthFails() { let expect = expectation(description: "Delete follower with bad auth failure") stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerAuthFailureMockFilename, contentType: .ApplicationJSON, status: 403) remote.deleteFollower(siteID, userID: followerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteFollowerWithValidFollowerSucceeds() { let expect = expectation(description: "Delete follower success") stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerSuccessMockFilename, contentType: .ApplicationJSON) remote.deleteFollower(siteID, userID: followerID, success: { expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteFollowerWithServerErrorFails() { let expect = expectation(description: "Delete follower with server error failure") stubRemoteResponse(siteFollowerDeleteEndpoint, data: Data(), contentType: .NoContentType, status: 500) remote.deleteFollower(siteID, userID: followerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteFollowerWithBadJsonFails() { let expect = expectation(description: "Delete follower with invalid json response failure") stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200) remote.deleteFollower(siteID, userID: followerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } // MARK: - Viewer Tests func testDeleteViewerWithInvalidViewerFails() { let expect = expectation(description: "Delete viewer failure") stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerFailureMockFilename, contentType: .ApplicationJSON, status: 404) remote.deleteViewer(siteID, userID: viewerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteViewerWithValidViewerSucceeds() { let expect = expectation(description: "Delete viewer success") stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerSuccessMockFilename, contentType: .ApplicationJSON) remote.deleteViewer(siteID, userID: viewerID, success: { expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteViewerWithBadAuthFails() { let expect = expectation(description: "Delete viewer with bad auth failure") stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerAuthFailureMockFilename, contentType: .ApplicationJSON, status: 403) remote.deleteViewer(siteID, userID: viewerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteViewerWithServerErrorFails() { let expect = expectation(description: "Delete viewer with server error failure") stubRemoteResponse(siteViewerDeleteEndpoint, data: Data(), contentType: .NoContentType, status: 500) remote.deleteViewer(siteID, userID: viewerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testDeleteViewerWithBadJsonFails() { let expect = expectation(description: "Delete viewer with invalid json response failure") stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200) remote.deleteViewer(siteID, userID: viewerID, success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } // MARK: - Role Tests func testGetSiteRolesSucceeds() { let expect = expectation(description: "Get site roles success") stubRemoteResponse(siteRolesEndpoint, filename: getRolesSuccessMockFilename, contentType: .ApplicationJSON) remote.getUserRoles(siteID, success: { roles in XCTAssertFalse(roles.isEmpty, "The returned roles array should not be empty") XCTAssertTrue(roles.count == 4, "There should be 4 roles returned") expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testGetSiteRolesWithServerErrorFails() { let expect = expectation(description: "Get site roles with server error failure") stubRemoteResponse(siteRolesEndpoint, data: Data(), contentType: .NoContentType, status: 500) remote.getUserRoles(siteID, success: { roles in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testGetSiteRolesWithBadAuthFails() { let expect = expectation(description: "Get site roles with bad auth failure") stubRemoteResponse(siteRolesEndpoint, filename: getRolesBadAuthMockFilename, contentType: .ApplicationJSON, status: 403) remote.getUserRoles(siteID, success: { roles in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testGetSiteRolesWithBadJsonFails() { let expect = expectation(description: "Get site roles with invalid json response failure") stubRemoteResponse(siteRolesEndpoint, filename: getRolesBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200) remote.getUserRoles(siteID, success: { roles in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testUpdateUserRoleSucceeds() { let expect = expectation(description: "Update user role success") stubRemoteResponse(siteUserEndpoint, filename: updateRoleSuccessMockFilename, contentType: .ApplicationJSON) let change = "administrator" remote.updateUserRole(siteID, userID: userID, newRole: change, success: { updatedPerson in XCTAssertEqual(updatedPerson.role, change, "The returned user's role should be the same as the updated role.") expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testUpdateUserRoleWithUnknownUserFails() { let expect = expectation(description: "Update role with unknown user failure") stubRemoteResponse(siteUnknownUserEndpoint, filename: updateRoleUnknownUserFailureMockFilename, contentType: .ApplicationJSON, status: 404) let change = "administrator" remote.updateUserRole(siteID, userID: invalidUserID, newRole: change, success: { updatedPerson in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testUpdateUserRoleWithUnknownSiteFails() { let expect = expectation(description: "Update role with unknown site failure") stubRemoteResponse(unknownSiteUserEndpoint, filename: updateRoleUnknownSiteFailureMockFilename, contentType: .ApplicationJSON, status: 403) let change = "administrator" remote.updateUserRole(invalidSiteID, userID: userID, newRole: change, success: { updatedPerson in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testUpdateUserRoleWithServerErrorFails() { let expect = expectation(description: "Update role with server error failure") stubRemoteResponse(siteUserEndpoint, data: Data(), contentType: .NoContentType, status: 500) let change = "administrator" remote.updateUserRole(siteID, userID: userID, newRole: change, success: { updatedPerson in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in let error = error as NSError XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError") XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testUpdateUserRoleWithBadJsonFails() { let expect = expectation(description: "Update role with invalid json response failure") stubRemoteResponse(siteUserEndpoint, filename: updateRoleBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200) let change = "administrator" remote.updateUserRole(siteID, userID: userID, newRole: change, success: { updatedPerson in XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } // MARK: - Invite Tests func testSendInvitationToInvalidUsernameFails() { let expect = expectation(description: "Send invite failure") stubRemoteResponse(newInviteEndpoint, filename: sendFailureMockFilename, contentType: .ApplicationJSON) remote.sendInvitation(siteID, usernameOrEmail: invalidUsername, role: "follower", message: "", success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testSendInvitationToValidUsernameSucceeds() { let expect = expectation(description: "Send invite success") stubRemoteResponse(newInviteEndpoint, filename: sendSuccessMockFilename, contentType: .ApplicationJSON) remote.sendInvitation(siteID, usernameOrEmail: validUsername, role: "follower", message: "", success: { expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testValidateInvitationWithInvalidUsernameFails() { let expect = expectation(description: "Validate invite failure") stubRemoteResponse(validateInviteEndpoint, filename: validationFailureMockFilename, contentType: .ApplicationJSON) remote.validateInvitation(siteID, usernameOrEmail: invalidUsername, role: "follower", success: { XCTFail("This callback shouldn't get called") expect.fulfill() }, failure: { error in expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } func testValidateInvitationWithValidUsernameSucceeds() { let expect = expectation(description: "Validate invite success") stubRemoteResponse(validateInviteEndpoint, filename: validationSuccessMockFilename, contentType: .ApplicationJSON) remote.validateInvitation(siteID, usernameOrEmail: validUsername, role: "follower", success: { expect.fulfill() }, failure: { error in XCTFail("This callback shouldn't get called") expect.fulfill() }) waitForExpectations(timeout: timeout, handler: nil) } }
e23372a26084ea98733b1fba56f82e41
44.620626
150
0.680163
false
true
false
false
parkera/swift-corelibs-foundation
refs/heads/master
Foundation/HTTPCookie.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // public struct HTTPCookiePropertyKey : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: HTTPCookiePropertyKey, _ rhs: HTTPCookiePropertyKey) -> Bool { return lhs.rawValue == rhs.rawValue } } extension HTTPCookiePropertyKey { /// Key for cookie name public static let name = HTTPCookiePropertyKey(rawValue: "Name") /// Key for cookie value public static let value = HTTPCookiePropertyKey(rawValue: "Value") /// Key for cookie origin URL public static let originURL = HTTPCookiePropertyKey(rawValue: "OriginURL") /// Key for cookie version public static let version = HTTPCookiePropertyKey(rawValue: "Version") /// Key for cookie domain public static let domain = HTTPCookiePropertyKey(rawValue: "Domain") /// Key for cookie path public static let path = HTTPCookiePropertyKey(rawValue: "Path") /// Key for cookie secure flag public static let secure = HTTPCookiePropertyKey(rawValue: "Secure") /// Key for cookie expiration date public static let expires = HTTPCookiePropertyKey(rawValue: "Expires") /// Key for cookie comment text public static let comment = HTTPCookiePropertyKey(rawValue: "Comment") /// Key for cookie comment URL public static let commentURL = HTTPCookiePropertyKey(rawValue: "CommentURL") /// Key for cookie discard (session-only) flag public static let discard = HTTPCookiePropertyKey(rawValue: "Discard") /// Key for cookie maximum age (an alternate way of specifying the expiration) public static let maximumAge = HTTPCookiePropertyKey(rawValue: "Max-Age") /// Key for cookie ports public static let port = HTTPCookiePropertyKey(rawValue: "Port") // For Cocoa compatibility internal static let created = HTTPCookiePropertyKey(rawValue: "Created") } /// `HTTPCookie` represents an http cookie. /// /// An `HTTPCookie` instance represents a single http cookie. It is /// an immutable object initialized from a dictionary that contains /// the various cookie attributes. It has accessors to get the various /// attributes of a cookie. open class HTTPCookie : NSObject { let _comment: String? let _commentURL: URL? let _domain: String let _expiresDate: Date? let _HTTPOnly: Bool let _secure: Bool let _sessionOnly: Bool let _name: String let _path: String let _portList: [NSNumber]? let _value: String let _version: Int var _properties: [HTTPCookiePropertyKey : Any] // See: https://tools.ietf.org/html/rfc2616#section-3.3.1 // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 static let _formatter1: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O" formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format static let _formatter2: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE MMM d HH:mm:ss yyyy" formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() // Sun, 06-Nov-1994 08:49:37 GMT ; Tomcat servers sometimes return cookies in this format static let _formatter3: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE, dd-MMM-yyyy HH:mm:ss O" formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() static let _allFormatters: [DateFormatter] = [_formatter1, _formatter2, _formatter3] static let _attributes: [HTTPCookiePropertyKey] = [.name, .value, .originURL, .version, .domain, .path, .secure, .expires, .comment, .commentURL, .discard, .maximumAge, .port] /// Initialize a HTTPCookie object with a dictionary of parameters /// /// - Parameter properties: The dictionary of properties to be used to /// initialize this cookie. /// /// Supported dictionary keys and value types for the /// given dictionary are as follows. /// /// All properties can handle an NSString value, but some can also /// handle other types. /// /// <table border=1 cellspacing=2 cellpadding=4> /// <tr> /// <th>Property key constant</th> /// <th>Type of value</th> /// <th>Required</th> /// <th>Description</th> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.comment</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Comment for the cookie. Only valid for version 1 cookies and /// later. Default is nil.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.commentURL</td> /// <td>NSURL or NSString</td> /// <td>NO</td> /// <td>Comment URL for the cookie. Only valid for version 1 cookies /// and later. Default is nil.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.domain</td> /// <td>NSString</td> /// <td>Special, a value for either .originURL or /// HTTPCookiePropertyKey.domain must be specified.</td> /// <td>Domain for the cookie. Inferred from the value for /// HTTPCookiePropertyKey.originURL if not provided.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.discard</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string stating whether the cookie should be discarded at /// the end of the session. String value must be either "TRUE" or /// "FALSE". Default is "FALSE", unless this is cookie is version /// 1 or greater and a value for HTTPCookiePropertyKey.maximumAge is not /// specified, in which case it is assumed "TRUE".</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.expires</td> /// <td>NSDate or NSString</td> /// <td>NO</td> /// <td>Expiration date for the cookie. Used only for version 0 /// cookies. Ignored for version 1 or greater.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.maximumAge</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string containing an integer value stating how long in /// seconds the cookie should be kept, at most. Only valid for /// version 1 cookies and later. Default is "0".</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.name</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Name of the cookie</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.originURL</td> /// <td>NSURL or NSString</td> /// <td>Special, a value for either HTTPCookiePropertyKey.originURL or /// HTTPCookiePropertyKey.domain must be specified.</td> /// <td>URL that set this cookie. Used as default for other fields /// as noted.</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.path</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Path for the cookie</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.port</td> /// <td>NSString</td> /// <td>NO</td> /// <td>comma-separated integer values specifying the ports for the /// cookie. Only valid for version 1 cookies and later. Default is /// empty string ("").</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.secure</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string stating whether the cookie should be transmitted /// only over secure channels. String value must be either "TRUE" /// or "FALSE". Default is "FALSE".</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.value</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Value of the cookie</td> /// </tr> /// <tr> /// <td>HTTPCookiePropertyKey.version</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Specifies the version of the cookie. Must be either "0" or /// "1". Default is "0".</td> /// </tr> /// </table> /// /// All other keys are ignored. /// /// - Returns: An initialized `HTTPCookie`, or nil if the set of /// dictionary keys is invalid, for example because a required key is /// missing, or a recognized key maps to an illegal value. /// /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public init?(properties: [HTTPCookiePropertyKey : Any]) { func stringValue(_ strVal: Any?) -> String? { if let subStr = strVal as? Substring { return String(subStr) } return strVal as? String } guard let path = stringValue(properties[.path]), let name = stringValue(properties[.name]), let value = stringValue(properties[.value]) else { return nil } let canonicalDomain: String if let domain = properties[.domain] as? String { canonicalDomain = domain } else if let originURL = properties[.originURL] as? URL, let host = originURL.host { canonicalDomain = host } else { return nil } _path = path _name = name _value = value _domain = canonicalDomain.lowercased() if let secureString = properties[.secure] as? String, !secureString.isEmpty { _secure = true } else { _secure = false } let version: Int if let versionString = properties[.version] as? String, versionString == "1" { version = 1 } else { version = 0 } _version = version if let portString = properties[.port] as? String { let portList = portString.split(separator: ",") .compactMap { Int(String($0)) } .map { NSNumber(value: $0) } if version == 1 { _portList = portList } else { // Version 0 only stores a single port number _portList = portList.count > 0 ? [portList[0]] : nil } } else { _portList = nil } var expDate: Date? = nil // Maximum-Age is preferred over expires-Date but only version 1 cookies use Maximum-Age if let maximumAge = properties[.maximumAge] as? String, let secondsFromNow = Int(maximumAge) { if version == 1 { expDate = Date(timeIntervalSinceNow: Double(secondsFromNow)) } } else { let expiresProperty = properties[.expires] if let date = expiresProperty as? Date { expDate = date } else if let dateString = expiresProperty as? String { let results = HTTPCookie._allFormatters.compactMap { $0.date(from: dateString) } expDate = results.first } } _expiresDate = expDate if let discardString = properties[.discard] as? String { _sessionOnly = discardString == "TRUE" } else { _sessionOnly = properties[.maximumAge] == nil && version >= 1 } _comment = properties[.comment] as? String if let commentURL = properties[.commentURL] as? URL { _commentURL = commentURL } else if let commentURL = properties[.commentURL] as? String { _commentURL = URL(string: commentURL) } else { _commentURL = nil } _HTTPOnly = false _properties = [ .created : Date().timeIntervalSinceReferenceDate, // Cocoa Compatibility .discard : _sessionOnly, .domain : _domain, .name : _name, .path : _path, .secure : _secure, .value : _value, .version : _version ] if let comment = properties[.comment] { _properties[.comment] = comment } if let commentURL = properties[.commentURL] { _properties[.commentURL] = commentURL } if let expires = properties[.expires] { _properties[.expires] = expires } if let maximumAge = properties[.maximumAge] { _properties[.maximumAge] = maximumAge } if let originURL = properties[.originURL] { _properties[.originURL] = originURL } if let _portList = _portList { _properties[.port] = _portList } } /// Return a dictionary of header fields that can be used to add the /// specified cookies to the request. /// /// - Parameter cookies: The cookies to turn into request headers. /// - Returns: A dictionary where the keys are header field names, and the values /// are the corresponding header field values. open class func requestHeaderFields(with cookies: [HTTPCookie]) -> [String : String] { var cookieString = cookies.reduce("") { (sum, next) -> String in return sum + "\(next._name)=\(next._value); " } //Remove the final trailing semicolon and whitespace if ( cookieString.length > 0 ) { cookieString.removeLast() cookieString.removeLast() } if cookieString == "" { return [:] } else { return ["Cookie": cookieString] } } /// Return an array of cookies parsed from the specified response header fields and URL. /// /// This method will ignore irrelevant header fields so /// you can pass a dictionary containing data other than cookie data. /// - Parameter headerFields: The response header fields to check for cookies. /// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpreted. /// - Returns: An array of HTTPCookie objects open class func cookies(withResponseHeaderFields headerFields: [String : String], for URL: URL) -> [HTTPCookie] { //HTTP Cookie parsing based on RFC 6265: https://tools.ietf.org/html/rfc6265 //Though RFC6265 suggests that multiple cookies cannot be folded into a single Set-Cookie field, this is //pretty common. It also suggests that commas and semicolons among other characters, cannot be a part of // names and values. This implementation takes care of multiple cookies in the same field, however it doesn't //support commas and semicolons in names and values(except for dates) guard let cookies: String = headerFields["Set-Cookie"] else { return [] } let nameValuePairs = cookies.components(separatedBy: ";") //split the name/value and attribute/value pairs .map({$0.trim()}) //trim whitespaces .map({removeCommaFromDate($0)}) //get rid of commas in dates .flatMap({$0.components(separatedBy: ",")}) //cookie boundaries are marked by commas .map({$0.trim()}) //trim again .filter({$0.caseInsensitiveCompare("HTTPOnly") != .orderedSame}) //we don't use HTTPOnly, do we? .flatMap({createNameValuePair(pair: $0)}) //create Name and Value properties //mark cookie boundaries in the name-value array var cookieIndices = (0..<nameValuePairs.count).filter({nameValuePairs[$0].hasPrefix("Name")}) cookieIndices.append(nameValuePairs.count) //bake the cookies var httpCookies: [HTTPCookie] = [] for i in 0..<cookieIndices.count-1 { if let aCookie = createHttpCookie(url: URL, pairs: nameValuePairs[cookieIndices[i]..<cookieIndices[i+1]]) { httpCookies.append(aCookie) } } return httpCookies } //Bake a cookie private class func createHttpCookie(url: URL, pairs: ArraySlice<String>) -> HTTPCookie? { var properties: [HTTPCookiePropertyKey : Any] = [:] for pair in pairs { let name = pair.components(separatedBy: "=")[0] var value = pair.components(separatedBy: "\(name)=")[1] //a value can have an "=" if canonicalize(name) == .expires { value = value.unmaskCommas() //re-insert the comma } properties[canonicalize(name)] = value } // If domain wasn't provided, extract it from the URL if properties[.domain] == nil { properties[.domain] = url.host } //the default Path is "/" if properties[.path] == nil { properties[.path] = "/" } return HTTPCookie(properties: properties) } //we pass this to a map() private class func removeCommaFromDate(_ value: String) -> String { if value.hasPrefix("Expires") || value.hasPrefix("expires") { return value.maskCommas() } return value } //These cookie attributes are defined in RFC 6265 and 2965(which is obsolete) //HTTPCookie supports these private class func isCookieAttribute(_ string: String) -> Bool { return _attributes.first(where: {$0.rawValue.caseInsensitiveCompare(string) == .orderedSame}) != nil } //Cookie attribute names are case-insensitive as per RFC6265: https://tools.ietf.org/html/rfc6265 //but HTTPCookie needs only the first letter of each attribute in uppercase private class func canonicalize(_ name: String) -> HTTPCookiePropertyKey { let idx = _attributes.firstIndex(where: {$0.rawValue.caseInsensitiveCompare(name) == .orderedSame})! return _attributes[idx] } //A name=value pair should be translated to two properties, Name=name and Value=value private class func createNameValuePair(pair: String) -> [String] { if pair.caseInsensitiveCompare(HTTPCookiePropertyKey.secure.rawValue) == .orderedSame { return ["Secure=TRUE"] } let name = pair.components(separatedBy: "=")[0] let value = pair.components(separatedBy: "\(name)=")[1] if !isCookieAttribute(name) { return ["Name=\(name)", "Value=\(value)"] } return [pair] } /// Returns a dictionary representation of the receiver. /// /// This method returns a dictionary representation of the /// `HTTPCookie` which can be saved and passed to /// `init(properties:)` later to reconstitute an equivalent cookie. /// /// See the `HTTPCookie` `init(properties:)` method for /// more information on the constraints imposed on the dictionary, and /// for descriptions of the supported keys and values. /// /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open var properties: [HTTPCookiePropertyKey : Any]? { return _properties } /// The version of the receiver. /// /// Version 0 maps to "old-style" Netscape cookies. /// Version 1 maps to RFC2965 cookies. There may be future versions. open var version: Int { return _version } /// The name of the receiver. open var name: String { return _name } /// The value of the receiver. open var value: String { return _value } /// Returns The expires date of the receiver. /// /// The expires date is the date when the cookie should be /// deleted. The result will be nil if there is no specific expires /// date. This will be the case only for *session-only* cookies. /*@NSCopying*/ open var expiresDate: Date? { return _expiresDate } /// Whether the receiver is session-only. /// /// `true` if this receiver should be discarded at the end of the /// session (regardless of expiration date), `false` if receiver need not /// be discarded at the end of the session. open var isSessionOnly: Bool { return _sessionOnly } /// The domain of the receiver. /// /// This value specifies URL domain to which the cookie /// should be sent. A domain with a leading dot means the cookie /// should be sent to subdomains as well, assuming certain other /// restrictions are valid. See RFC 2965 for more detail. open var domain: String { return _domain } /// The path of the receiver. /// /// This value specifies the URL path under the cookie's /// domain for which this cookie should be sent. The cookie will also /// be sent for children of that path, so `"/"` is the most general. open var path: String { return _path } /// Whether the receiver should be sent only over secure channels /// /// Cookies may be marked secure by a server (or by a javascript). /// Cookies marked as such must only be sent via an encrypted connection to /// trusted servers (i.e. via SSL or TLS), and should not be delivered to any /// javascript applications to prevent cross-site scripting vulnerabilities. open var isSecure: Bool { return _secure } /// Whether the receiver should only be sent to HTTP servers per RFC 2965 /// /// Cookies may be marked as HTTPOnly by a server (or by a javascript). /// Cookies marked as such must only be sent via HTTP Headers in HTTP Requests /// for URL's that match both the path and domain of the respective Cookies. /// Specifically these cookies should not be delivered to any javascript /// applications to prevent cross-site scripting vulnerabilities. open var isHTTPOnly: Bool { return _HTTPOnly } /// The comment of the receiver. /// /// This value specifies a string which is suitable for /// presentation to the user explaining the contents and purpose of this /// cookie. It may be nil. open var comment: String? { return _comment } /// The comment URL of the receiver. /// /// This value specifies a URL which is suitable for /// presentation to the user as a link for further information about /// this cookie. It may be nil. /*@NSCopying*/ open var commentURL: URL? { return _commentURL } /// The list ports to which the receiver should be sent. /// /// This value specifies an NSArray of NSNumbers /// (containing integers) which specify the only ports to which this /// cookie should be sent. /// /// The array may be nil, in which case this cookie can be sent to any /// port. open var portList: [NSNumber]? { return _portList } open override var description: String { var str = "<\(type(of: self)) " str += "version:\(self._version) name:\"\(self._name)\" value:\"\(self._value)\" expiresDate:" if let expires = self._expiresDate { str += "\(expires)" } else { str += "nil" } str += " sessionOnly:\(self._sessionOnly) domain:\"\(self._domain)\" path:\"\(self._path)\" isSecure:\(self._secure) comment:" if let comments = self._comment { str += "\(comments)" } else { str += "nil" } str += " ports:{ " if let ports = self._portList { str += "\(NSArray(array: (ports)).componentsJoined(by: ","))" } else { str += "0" } str += " }>" return str } } //utils for cookie parsing fileprivate extension String { func trim() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } func maskCommas() -> String { return self.replacingOccurrences(of: ",", with: "&comma") } func unmaskCommas() -> String { return self.replacingOccurrences(of: "&comma", with: ",") } }
21f2397c8632ab3603eb87fb30e24cf9
36.878561
134
0.597309
false
false
false
false
ajsnow/Shear
refs/heads/master
Shear/Sequence.swift
mit
1
// Copyright 2016 The Shear Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. import Foundation // MARK: - Sequence public extension TensorProtocol { /// Slices the TensorProtocol into a sequence of `TensorSlice`s on its nth `deminsion`. func sequence(_ deminsion: Int) -> [Tensor<Element>] { if (isEmpty || isScalar) && deminsion == 0 { // TODO: Consider making sequencing scalar or empty arrays an error. return [Tensor(self)] } guard deminsion < rank else { fatalError("An array cannot be sequenced on a deminsion it does not have") } let viewIndices = [TensorIndex](repeating: TensorIndex.all, count: rank) return (0..<shape[deminsion]).map { var nViewIndices = viewIndices nViewIndices[deminsion] = .singleValue($0) return self[nViewIndices] } } /// Slices the TensorProtocol on its first dimension. /// Since our DenseTensor is stored in Row-Major order, sequencing on the first /// dimension allows for better memory access patterns than any other sequence. var sequenceFirst: [Tensor<Element>] { return sequence(0) } /// Slices the TensorProtocol on its last dimension. /// Tends to not be cache friendly... var sequenceLast: [Tensor<Element>] { return sequence(rank != 0 ? rank - 1 : 0) } /// Returns a sequence containing pairs of cartesian indices and `Element`s. public func coordinate() -> AnySequence<([Int], Element)> { let indexGenerator = makeRowMajorIndexGenerator(shape) return AnySequence(AnyIterator { guard let indices = indexGenerator.next() else { return nil } return (indices, self[indices]) // TODO: Linear indexing is cheaper for DenseTensors. Consider specializing. }) } }
0c46cf817c1cb519586d57dc17067862
39.708333
121
0.646366
false
false
false
false
aleph7/HDF5Kit
refs/heads/master
Source/Dataspace.swift
mit
1
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of HDF5Kit. The full HDF5Kit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #if SWIFT_PACKAGE import CHDF5 #endif public class Dataspace { var id: hid_t init(id: hid_t) { self.id = id guard id >= 0 else { fatalError("Failed to create Dataspace") } selectionDims = [] selectionDims = dims } deinit { let status = H5Sclose(id) assert(status >= 0, "Failed to close Dataspace") } public internal(set) var selectionDims: [Int] /// Create a Dataspace public init(dims: [Int]) { let dims64 = dims.map({ hsize_t(bitPattern: hssize_t($0)) }) id = dims64.withUnsafeBufferPointer { pointer in return H5Screate_simple(Int32(dims.count), pointer.baseAddress, nil) } guard id >= 0 else { fatalError("Failed to create Dataspace") } selectionDims = dims } /// Create a Dataspace for use in a chunked Dataset. No component of `maxDims` should be less than the corresponding element of `dims`. Elements of `maxDims` can have a value of -1, those dimension will have an unlimited size. public init(dims: [Int], maxDims: [Int]) { let dims64 = dims.map({ hsize_t(bitPattern: hssize_t($0)) }) let maxDims64 = maxDims.map({ hsize_t(bitPattern: hssize_t($0)) }) id = withExtendedLifetime((dims64, maxDims64)) { return H5Screate_simple(Int32(dims.count), dims64, maxDims64) } guard id >= 0 else { fatalError("Failed to create Dataspace") } selectionDims = dims } public convenience init(_ space: Dataspace) { self.init(id: H5Scopy(space.id)) } /// The total number of elements in the Dataspace public var size: Int { let result = H5Sget_simple_extent_npoints(id) guard result >= 0 else { fatalError("Failed to get Dataspace size") } return Int(result) } /// The size of each dimension in the Dataspace public var dims: [Int] { let rank = Int(H5Sget_simple_extent_ndims(id)) var dims = [hsize_t](repeating: 0, count: rank) dims.withUnsafeMutableBufferPointer { pointer in guard H5Sget_simple_extent_dims(id, pointer.baseAddress, nil) >= 0 else { fatalError("Coulnd't get the dimensons of the Dataspace") } } return dims.map({ Int(hssize_t(bitPattern: $0)) }) } /// The maximum size of each dimension in the Dataspace public var maxDims: [Int] { let rank = Int(H5Sget_simple_extent_ndims(id)) var maxDims = [hsize_t](repeating: 0, count: rank) maxDims.withUnsafeMutableBufferPointer { pointer in guard H5Sget_simple_extent_dims(id, nil, pointer.baseAddress) >= 0 else { fatalError("Coulnd't get the dimensons of the Dataspace") } } return maxDims.map({ Int(hssize_t(bitPattern: $0)) }) } // MARK: - Selection public var hasValidSelection: Bool { return H5Sselect_valid(id) > 0 } public var selectionSize: Int { return Int(H5Sget_select_npoints(id)) } /// Selects the entire dataspace. public func selectAll() { H5Sselect_all(id) selectionDims = dims } /// Resets the selection region to include no elements. public func selectNone() { H5Sselect_none(id) for i in 0..<selectionDims.count { selectionDims[i] = 0 } } /// Select a hyperslab region. /// /// - parameter start: Specifies the offset of the starting element of the specified hyperslab. /// - parameter stride: Chooses array locations from the dataspace with each value in the stride array determining how many elements to move in each dimension. Stride values of 0 are not allowed. If the stride parameter is `nil`, a contiguous hyperslab is selected (as if each value in the stride array were set to 1). /// - parameter count: Determines how many blocks to select from the dataspace, in each dimension. /// - parameter block: Determines the size of the element block selected from the dataspace. If the block parameter is set to `nil`, the block size defaults to a single element in each dimension (as if each value in the block array were set to 1). public func select(start: [Int], stride: [Int]?, count: [Int]?, block: [Int]?) { let start64 = start.map({ hsize_t(bitPattern: hssize_t($0)) }) let stride64 = stride?.map({ hsize_t(bitPattern: hssize_t($0)) }) let count64 = count?.map({ hsize_t(bitPattern: hssize_t($0)) }) let block64 = block?.map({ hsize_t(bitPattern: hssize_t($0)) }) withExtendedLifetime((start64, stride64, count64, block64)) { () -> Void in H5Sselect_hyperslab(id, H5S_SELECT_SET, start64, pointerOrNil(stride64), pointerOrNil(count64), pointerOrNil(block64)) } selectionDims = count ?? dims } /// Select a hyperslab region. public func select(_ slices: HyperslabIndexType...) { select(slices) } /// Select a hyperslab region. public func select(_ slices: [HyperslabIndexType]) { let dims = self.dims let rank = dims.count var start = [Int](repeating: 0, count: rank) var stride = [Int](repeating: 1, count: rank) var count = [Int](repeating: 0, count: rank) var block = [Int](repeating: 1, count: rank) for (index, slice) in slices.enumerated() { start[index] = slice.start stride[index] = slice.stride if slice.blockCount != HyperslabIndex.all { count[index] = slice.blockCount } else { count[index] = dims[index] - slice.start } block[index] = slice.blockSize } select(start: start, stride: stride, count: count, block: block) } /// This function allows the same shaped selection to be moved to different locations within a dataspace without requiring it to be redefined. public func offset(_ offset: [Int]) { let offset64 = offset.map({ hssize_t($0) }) offset64.withUnsafeBufferPointer { (pointer) -> Void in H5Soffset_simple(id, pointer.baseAddress) } } } func pointerOrNil(_ array: [hsize_t]?) -> UnsafePointer<hsize_t>? { if let array = array { return UnsafePointer(array) } return nil }
6a4c5ff8ae93b7eefcec9ffe9ae81042
37.314286
322
0.618792
false
false
false
false
BareFeetWare/BFWControls
refs/heads/develop
BFWControls/Modules/Layout/View/FlowView.swift
mit
1
// // FlowView.swift // BFWControls // // Created by Tom Brodhurst-Hill on 23/3/19. // Copyright © 2019 BareFeetWare. All rights reserved. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit @IBDesignable open class FlowView: UIView { // MARK: - Variables @IBInspectable var gapWidth: CGFloat = 0.0 @IBInspectable var gapHeight: CGFloat = 0.0 private lazy var heightConstraint: NSLayoutConstraint = { NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 100.0) }() // MARK: - Functions private func subviewFramesThatFit(_ size: CGSize) -> [CGRect] { var subviewFrames: [CGRect] = [] var startPoint = CGPoint.zero var maxRowHeight = CGFloat(0.0) for subview in subviews { let subviewSize = subview.sizeThatFits(.noIntrinsicMetric) var leftGap = startPoint.x == 0.0 ? 0.0 : gapWidth let availableWidth = size.width - startPoint.x if availableWidth < subviewSize.width + leftGap { // Move to start of next row startPoint.y += maxRowHeight + gapHeight startPoint.x = 0.0 maxRowHeight = 0.0 leftGap = 0.0 } maxRowHeight = max(maxRowHeight, subviewSize.height) let subviewFrame = CGRect(origin: CGPoint(x: startPoint.x + leftGap, y: startPoint.y), size: subviewSize) subviewFrames.append(subviewFrame) startPoint.x += leftGap + subviewSize.width } return subviewFrames } // MARK: - UIView open override var intrinsicContentSize: CGSize { return subviews.reduce(CGSize.zero) { (size, subview) in let subviewSize = subview.sizeThatFits(.noIntrinsicMetric) let leftGap = size.width == 0.0 ? 0.0 : gapWidth return CGSize(width: size.width + leftGap + subviewSize.width, height: max(size.height, subviewSize.height)) } } open override func layoutSubviews() { let subviewFrames = subviewFramesThatFit(bounds.size) heightConstraint.constant = subviewFrames.last?.maxY ?? 0.0 heightConstraint.isActive = true super.layoutSubviews() zip(subviews, subviewFrames).forEach { $0.frame = $1 } } } fileprivate extension CGSize { static let noIntrinsicMetric = CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric) }
52423fc63677ceceae4e886f4c1df335
34.185185
98
0.567719
false
false
false
false
ReactiveX/RxSwift
refs/heads/develop
RxExample/RxDataSources/RxDataSources/TableViewSectionedDataSource.swift
mit
2
// // TableViewSectionedDataSource.swift // RxDataSources // // Created by Krunoslav Zaher on 6/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit import RxCocoa open class TableViewSectionedDataSource<Section: SectionModelType> : NSObject , UITableViewDataSource , SectionedViewDataSourceType { public typealias Item = Section.Item public typealias ConfigureCell = (TableViewSectionedDataSource<Section>, UITableView, IndexPath, Item) -> UITableViewCell public typealias TitleForHeaderInSection = (TableViewSectionedDataSource<Section>, Int) -> String? public typealias TitleForFooterInSection = (TableViewSectionedDataSource<Section>, Int) -> String? public typealias CanEditRowAtIndexPath = (TableViewSectionedDataSource<Section>, IndexPath) -> Bool public typealias CanMoveRowAtIndexPath = (TableViewSectionedDataSource<Section>, IndexPath) -> Bool #if os(iOS) public typealias SectionIndexTitles = (TableViewSectionedDataSource<Section>) -> [String]? public typealias SectionForSectionIndexTitle = (TableViewSectionedDataSource<Section>, _ title: String, _ index: Int) -> Int #endif #if os(iOS) public init( configureCell: @escaping ConfigureCell, titleForHeaderInSection: @escaping TitleForHeaderInSection = { _, _ in nil }, titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil }, canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false }, canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false }, sectionIndexTitles: @escaping SectionIndexTitles = { _ in nil }, sectionForSectionIndexTitle: @escaping SectionForSectionIndexTitle = { _, _, index in index } ) { self.configureCell = configureCell self.titleForHeaderInSection = titleForHeaderInSection self.titleForFooterInSection = titleForFooterInSection self.canEditRowAtIndexPath = canEditRowAtIndexPath self.canMoveRowAtIndexPath = canMoveRowAtIndexPath self.sectionIndexTitles = sectionIndexTitles self.sectionForSectionIndexTitle = sectionForSectionIndexTitle } #else public init( configureCell: @escaping ConfigureCell, titleForHeaderInSection: @escaping TitleForHeaderInSection = { _, _ in nil }, titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil }, canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false }, canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false } ) { self.configureCell = configureCell self.titleForHeaderInSection = titleForHeaderInSection self.titleForFooterInSection = titleForFooterInSection self.canEditRowAtIndexPath = canEditRowAtIndexPath self.canMoveRowAtIndexPath = canMoveRowAtIndexPath } #endif #if DEBUG // If data source has already been bound, then mutating it // afterwards isn't something desired. // This simulates immutability after binding var _dataSourceBound: Bool = false private func ensureNotMutatedAfterBinding() { assert(!_dataSourceBound, "Data source is already bound. Please write this line before binding call (`bindTo`, `drive`). Data source must first be completely configured, and then bound after that, otherwise there could be runtime bugs, glitches, or partial malfunctions.") } #endif // This structure exists because model can be mutable // In that case current state value should be preserved. // The state that needs to be preserved is ordering of items in section // and their relationship with section. // If particular item is mutable, that is irrelevant for this logic to function // properly. public typealias SectionModelSnapshot = SectionModel<Section, Item> private var _sectionModels: [SectionModelSnapshot] = [] open var sectionModels: [Section] { _sectionModels.map { Section(original: $0.model, items: $0.items) } } open subscript(section: Int) -> Section { let sectionModel = self._sectionModels[section] return Section(original: sectionModel.model, items: sectionModel.items) } open subscript(indexPath: IndexPath) -> Item { get { return self._sectionModels[indexPath.section].items[indexPath.item] } set(item) { var section = self._sectionModels[indexPath.section] section.items[indexPath.item] = item self._sectionModels[indexPath.section] = section } } open func model(at indexPath: IndexPath) throws -> Any { self[indexPath] } open func setSections(_ sections: [Section]) { self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) } } open var configureCell: ConfigureCell { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var titleForHeaderInSection: TitleForHeaderInSection { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var titleForFooterInSection: TitleForFooterInSection { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var canEditRowAtIndexPath: CanEditRowAtIndexPath { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var canMoveRowAtIndexPath: CanMoveRowAtIndexPath { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var rowAnimation: UITableView.RowAnimation = .automatic #if os(iOS) open var sectionIndexTitles: SectionIndexTitles { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } open var sectionForSectionIndexTitle: SectionForSectionIndexTitle { didSet { #if DEBUG ensureNotMutatedAfterBinding() #endif } } #endif // UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { _sectionModels.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard _sectionModels.count > section else { return 0 } return _sectionModels[section].items.count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { precondition(indexPath.item < _sectionModels[indexPath.section].items.count) return configureCell(self, tableView, indexPath, self[indexPath]) } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { titleForHeaderInSection(self, section) } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { titleForFooterInSection(self, section) } open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { canEditRowAtIndexPath(self, indexPath) } open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { canMoveRowAtIndexPath(self, indexPath) } open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath) } #if os(iOS) open func sectionIndexTitles(for tableView: UITableView) -> [String]? { sectionIndexTitles(self) } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { sectionForSectionIndexTitle(self, title, index) } #endif } #endif
05f60631206b977909db510599d73ce8
36.563063
280
0.660151
false
true
false
false
steelwheels/KiwiGraphics
refs/heads/master
Source/Primitives/KGCircle.swift
gpl-2.0
1
/** * @file KGCircule.swift * @brief Define KGCircule data structure * @par Copyright * Copyright (C) 2016 Steel Wheels Project */ import Foundation import CoreGraphics public struct KGCircle { var mCenter: CGPoint var mRadius: CGFloat private var mBounds: CGRect public init(center c: CGPoint, radius r: CGFloat){ mCenter = c mRadius = r mBounds = KGCircle.updateBounds(center: c, radius: r) } public var center: CGPoint { get { return mCenter } } public var radius: CGFloat { get { return mRadius } } public var bounds: CGRect { get { return mBounds } } public var description: String { let cstr = mCenter.description let rstr = NSString(format: "%.2lf", mRadius) return "{center:\(cstr) radius:\(rstr)}" } private static func updateBounds(center c: CGPoint, radius r: CGFloat) -> CGRect { let origin = CGPoint(x: c.x - r, y: c.y - r) let diameter = r * 2 let size = CGSize(width: diameter, height: diameter) return CGRect(origin: origin, size: size) } }
6ed1c2162365190480ad62b88c01e231
20.3125
83
0.678397
false
false
false
false
WalterCreazyBear/Swifter30
refs/heads/master
UIElements/UIElements/ViewController.swift
mit
1
// // ViewController.swift // UIElements // // Created by Bear on 2017/6/20. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class ViewController: UIViewController { let cellIdentify = "cellIdentify" let elements:[String] = { let eles = ["Label","Text","Gesture","Massive"] return eles }() let tableView :UITableView = { let tableView:UITableView = UITableView.init() return tableView }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.title = "UIElements" self.setupTableView() } fileprivate func setupTableView(){ self.tableView.frame = self.view.bounds self.tableView.delegate = self self.tableView.dataSource = self self.tableView.backgroundColor = UIColor.white self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentify) self.view.addSubview(self.tableView) } } extension ViewController:UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.elements.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentify) cell?.textLabel?.text = self.elements[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var vc:UIViewController?; if(elements[indexPath.row] == "Label") { vc = UILabelViewController() } else if(elements[indexPath.row] == "Text") { vc = UITextViewController() } else if(elements[indexPath.row] == "Gesture") { vc = GetureViewController() } else if(elements[indexPath.row] == "Massive") { vc = UIMassiveViewController() } guard vc != nil else { return; } self.navigationController?.pushViewController(vc!, animated: true) } }
65b4d5f06106dabbac0a68d7bc1bf7ff
27.26506
100
0.614237
false
false
false
false
Royal-J/TestKitchen1607
refs/heads/master
TestKitchen1607/TestKitchen1607/classes/ingredient(食材)/material(食材)/view/IngreMaterialCell.swift
mit
1
// // IngreMaterialCell.swift // TestKitchen1607 // // Created by HJY on 2016/11/2. // Copyright © 2016年 HJY. All rights reserved. // import UIKit class IngreMaterialCell: UITableViewCell { //点击事件 var jumpClosure: IngreJumpClosure? var cellModel: IngreMaterialType? { didSet { if cellModel != nil { //删除之前的子视图 for sub in contentView.subviews { sub.removeFromSuperview() } showData() } } } //标题高度 class private var titleH: CGFloat { return 20 } //间距 class private var margin: CGFloat { return 10 } //按钮的高度 class private var btnH: CGFloat { return 44 } //按钮的列数 class private var colum: Int { return 5 } //按钮的宽度 class private var btnW: CGFloat { return (kScreenW-margin*CGFloat(colum+1))/CGFloat(colum) } func showData() { //类型标题 let titleLabel = UILabel.createLabel(cellModel?.text, textAlignment: .Left, font: UIFont.systemFontOfSize(17)) contentView.addSubview(titleLabel) //约束 titleLabel.snp_makeConstraints { (make) in make.left.top.equalTo(IngreMaterialCell.margin) make.right.equalTo(-IngreMaterialCell.margin) make.height.equalTo(IngreMaterialCell.titleH) } //左上角图片 let typeImageView = UIImageView() let url = NSURL(string: (cellModel?.image)!) typeImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) contentView.addSubview(typeImageView) //约束 typeImageView.snp_makeConstraints { (make) in make.left.equalTo(IngreMaterialCell.margin) make.top.equalTo(IngreMaterialCell.margin*2+IngreMaterialCell.titleH) make.width.equalTo(IngreMaterialCell.btnW*2+IngreMaterialCell.margin) make.height.equalTo(IngreMaterialCell.btnH*2+IngreMaterialCell.margin) } //子类型按钮 let cnt = cellModel?.data?.count if cnt > 0 { for i in 0..<cnt! { //显示文字 let model = cellModel?.data![i] let btn = IngreMaterialBtn() btn.model = model //点击事件 btn.addTarget(self, action: #selector(clickBtn(_:)), forControlEvents: .TouchUpInside) contentView.addSubview(btn) if i < 6 { //前面两行的按钮 let row = i/(IngreMaterialCell.colum-2) //行数 let col = i%(IngreMaterialCell.colum-2) //列数 btn.snp_makeConstraints(closure: { (make) in let x = IngreMaterialCell.btnW*2+IngreMaterialCell.margin*3+(IngreMaterialCell.margin+IngreMaterialCell.btnW)*CGFloat(col) make.left.equalTo(x) let top = IngreMaterialCell.titleH+IngreMaterialCell.margin*2+(IngreMaterialCell.btnH+IngreMaterialCell.margin)*CGFloat(row) make.top.equalTo(top) make.width.equalTo(IngreMaterialCell.btnW) make.height.equalTo(IngreMaterialCell.btnH) }) }else{ //后面几行的按钮 let row = (i-6)/IngreMaterialCell.colum //行数 let col = (i-6)%IngreMaterialCell.colum //列数 btn.snp_makeConstraints(closure: { (make) in let x = IngreMaterialCell.margin+(IngreMaterialCell.margin+IngreMaterialCell.btnW)*CGFloat(col) make.left.equalTo(x) make.top.equalTo(typeImageView.snp_bottom).offset(IngreMaterialCell.margin+(IngreMaterialCell.margin+IngreMaterialCell.btnH)*CGFloat(row)) make.width.equalTo(IngreMaterialCell.btnW) make.height.equalTo(IngreMaterialCell.btnH) }) } } } } func clickBtn(btn: IngreMaterialBtn) { let tmpModel = btn.model if tmpModel?.id != nil && jumpClosure != nil { let urlString = "app://material#\((tmpModel?.id)!)#" jumpClosure!(urlString) } } //计算cell高度 class func heightForCellWithModel(typeModel: IngreMaterialType) -> CGFloat { //子类型只有两行内时的高度 var h = IngreMaterialCell.margin*2+IngreMaterialCell.titleH+(IngreMaterialCell.btnH+IngreMaterialCell.margin)*2 //如果超过两行,加上这些高度 if typeModel.data?.count > 6 { //超过的行数 var row = ((typeModel.data?.count)!-6)/IngreMaterialCell.colum let tmpNum = ((typeModel.data?.count)!-6)%IngreMaterialCell.colum if tmpNum > 0 { //除不尽的需要再显示一行 row += 1 } h += (IngreMaterialCell.btnH+IngreMaterialCell.margin)*CGFloat(row) } return h } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } //按钮 class IngreMaterialBtn: UIControl { private var titleLabel: UILabel? //显示数据 var model: IngreMaterialSubType? { didSet { //显示文字 titleLabel?.text = model?.text } } init() { super.init(frame: CGRectZero) titleLabel = UILabel.createLabel(nil, textAlignment: .Center, font: UIFont.systemFontOfSize(18)) titleLabel!.numberOfLines = 0 addSubview(titleLabel!) //约束 titleLabel?.snp_makeConstraints(closure: { (make) in make.edges.equalToSuperview() }) //背景颜色 titleLabel?.backgroundColor = UIColor.init(white: 0.9, alpha: 1.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
4992011a957cf6b3e57e400f3d457076
30.955224
162
0.545157
false
false
false
false
dehesa/Utilities
refs/heads/master
Sources/common/foundation/Calendrical.swift
mit
2
import Foundation public extension Calendar { /// Returns the start of the day (00:00:00) for the given date. /// - parameter date: Date indicating the targeted day. /// - returns: The beginning of the targeted day. public func beginningOfDay(for date: Date) -> Date { var result = self.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date) result.calendar = self result.timeZone = self.timeZone (result.hour, result.minute, result.second, result.nanosecond) = (0, 0, 0, 0) // There are 1_000_000_000 nanoseconds in a second return result.date! } /// Returns the end of the day (23:59:59) for the given date. /// - parameter date: Date indicating the targeted day. /// - returns: The end of the targeted day. public func endOfDay(for date: Date) -> Date { var result = self.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date) result.calendar = self result.timeZone = self.timeZone (result.hour, result.minute, result.second, result.nanosecond) = (23, 59, 59, 500_000_000) // There are 1_000_000_000 nanoseconds in a second return result.date! } /// Returns the next day (tomorrow) of the given date (with the same time). /// - parameter date: Date indicating the targeted day. /// - returns: The day after the targeted day. public func nextDay(for date: Date) -> Date { return self.date(byAdding: .day, value: 1, to: date)! } /// Returns the previous day (yesterday) of the given date (with the same time). /// - parameter date: Date indicating the previous day. /// - returns: The day previous to the targeted day. public func previousDay(for date: Date) -> Date { return self.date(byAdding: .day, value: -1, to: date)! } /// Returns the number of days between the given days. /// - parameter dayA: The first day on the interval. /// - parameter dayB: The last day on the interval. /// - returns: Integer counting the number of days between the first and last day in the range. public func numDaysBetween(_ dayA: Date, _ dayB: Date) -> Int { var result = self.dateComponents([.day], from: dayA, to: dayB) result.calendar = self result.timeZone = self.timeZone return result.day! } }
750c9ef927cf68f3f4979823599aac9a
44.886792
150
0.634046
false
false
false
false
anasmeister/nRF-Coventry-University
refs/heads/master
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUServiceController.swift
bsd-3-clause
2
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth @objc public class DFUServiceController : NSObject { internal var executor:DFUController? private var servicePaused = false private var serviceAborted = false internal override init() { // empty internal constructor } /** Call this method to pause uploading during the transmition process. The transmition can be resumed only when connection remains. If service has already started sending firmware data it will pause after receiving next Packet Receipt Notification. Otherwise it will continue to send Op Codes and pause before sending the first bytes of the firmware. With Packet Receipt Notifications disabled it is the only moment when upload may be paused. */ public func pause() { if executor != nil { if !servicePaused && executor!.pause() { servicePaused = true } } } /** Call this method to resume the paused transffer, otherwise does nothing. */ public func resume() { if executor != nil { if servicePaused && executor!.resume() { servicePaused = false } } } /** Aborts the upload. The phone will disconnect from peripheral. The peripheral will try to recover the last firmware. Might, restart in the Bootloader mode if the application has been removed. Abort (Reset) command will be sent instead of a next Op Code, or after receiving a Packet Receipt Notification. It PRM procedure is disabled it will continue until the whole firmware is sent and then Reset will be sent instead of Verify Firmware op code. */ public func abort() -> Bool { if executor != nil { serviceAborted = true return executor!.abort() } return false } /** Returns true if DFU operation has been paused. */ public var paused:Bool { return servicePaused } /** Returns true if DFU operation has been aborted. */ public var aborted:Bool { return serviceAborted } }
dbba59e31552f7d4ec3bf36ba374b265
39.824176
145
0.696097
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
SignalMessaging/attachments/OWSVideoPlayer.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import AVFoundation @objc public protocol OWSVideoPlayerDelegate: class { func videoPlayerDidPlayToCompletion(_ videoPlayer: OWSVideoPlayer) } @objc public class OWSVideoPlayer: NSObject { @objc public let avPlayer: AVPlayer let audioActivity: AudioActivity let shouldLoop: Bool @objc weak public var delegate: OWSVideoPlayerDelegate? @objc convenience public init(url: URL) { self.init(url: url, shouldLoop: false) } @objc public init(url: URL, shouldLoop: Bool) { self.avPlayer = AVPlayer(url: url) self.audioActivity = AudioActivity(audioDescription: "[OWSVideoPlayer] url:\(url)", behavior: .playback) self.shouldLoop = shouldLoop super.init() NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToCompletion(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem) } // MARK: Dependencies var audioSession: OWSAudioSession { return Environment.shared.audioSession } // MARK: Playback Controls @objc public func pause() { avPlayer.pause() audioSession.endAudioActivity(self.audioActivity) } @objc public func play() { let success = audioSession.startAudioActivity(self.audioActivity) assert(success) guard let item = avPlayer.currentItem else { owsFailDebug("video player item was unexpectedly nil") return } if item.currentTime() == item.duration { // Rewind for repeated plays, but only if it previously played to end. avPlayer.seek(to: CMTime.zero) } avPlayer.play() } @objc public func stop() { avPlayer.pause() avPlayer.seek(to: CMTime.zero) audioSession.endAudioActivity(self.audioActivity) } @objc(seekToTime:) public func seek(to time: CMTime) { avPlayer.seek(to: time) } // MARK: private @objc private func playerItemDidPlayToCompletion(_ notification: Notification) { self.delegate?.videoPlayerDidPlayToCompletion(self) if shouldLoop { avPlayer.seek(to: CMTime.zero) avPlayer.play() } else { audioSession.endAudioActivity(self.audioActivity) } } }
237f6128a5e15d792b0c10e53bd6a409
25.131313
112
0.615385
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
refs/heads/master
04-App Architecture/Swift 2/4-3 Playgrounds/Closures.playground/Pages/Parameters and Basic Syntax.xcplaygroundpage/Contents.swift
mit
1
//: ![Closures - Programming Examples](Banner.jpg) import UIKit //: # Closure Syntax //: ## From the Lecture "Closures" //: //: For Xcode 7 //: //: First created 7th December 2015 //: ## Closure Syntax and Type Inference" //:[The Swift Programming Language (Closures)]: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94 "Open in Browser" //: //:For more information, see the chapter on Automatic Reference Counting in [The Swift Programming Language (Closures)]. //: ### First example - convert a function to a closure func divide(numerator n : Int, denominator d: Int) -> Double? { if (d == 0) { return nil } else { let y = Double(n) / Double(d) return y } } //: Note again, the parameters are all explicitly labelled. let divide_closure = { (n : Int, d: Int) -> Double? in if (d == 0) { return nil } else { let y = Double(n) / Double(d) return y } } //: The `{` now marks the start of the closure. Use `in` to separate the parameters from the code statements //: Evaluate as you would a function (a function is a closure with a name) divide_closure(12, 3) //: The type is the same as the function `(Int,Int)->Double?`. In fact you can interrogate the type (handy tip!) divide_closure.dynamicType //: Where the code is not reused, you can use in-place evaluation. Note how the closures is both defined and invoked in one place. **Useful for initialisation** of variables and constants let y = { (n : Int, d: Int) -> Double? in if (d == 0) { return nil } else { let y = Double(n) / Double(d) return y } }(12, 3) //: (Note also that the type of `y` is inferred, which is the same as the function return type `Double?`) //: ### Example - with explicit internal and external parameter names //: All parameters labelled func cuboidVolume(width w:Double, height h:Double, depth d:Double) -> Double { return w * h * d } //: Now the closure equivalent. Note it has the same *type* as the function, but no function name //: //: Closures do not have default exernal labels. The rule is the same for ALL parameters: you must specify explicitly. let cuboidVolumeClosure = { (w : Double, h: Double, d: Double) -> Double in return w*h*d } cuboidVolumeClosure(2.0,3.0,4.0) //: They have the same type - to prove it, we can add both to a typed array typealias threeDVolume = ((width:Double, height:Double, depth:Double) -> Double) var closureArray : [threeDVolume] = [] closureArray.append(cuboidVolume) closureArray.append(cuboidVolumeClosure) //: Given there are no syntax errors here, they must be the same type. //: One of the reasons to use closures is that it can be written in-place (within some context), such as in a parameter list of a function closureArray.append({ (w : Double, h: Double, d: Double) in return w*h*d} ) //: One of the additional benefits is that closure syntax can often be greatly simplified to keep the code concise. This will be explained later, but for example: //: * As this has a single statement, so we can drop the return closureArray.append({ (w : Double, h: Double, d: Double) in w*h*d} ) //: * Given that we have some typed-context (the typed array), the compiler can inter the types of the parameters closureArray.append({$0*$1*$2}) //: Creating an array of closures might seem strange, but again, we treat closure/function types like any other. To prove it works, we can evaluate as follows: if let c = closureArray.last { c(width:2.0, height:3.0, depth:4.0) } //: More concisely closureArray.last?(width:2.0, height:3.0, depth:4.0) //: ### Example - no external parameter names func cuboidVolumeWHD(width:Double, _ height:Double, _ depth:Double) -> Double { return width * height * depth } //: For the closure, you don't get external parameter labels unless you specify them - *no need to supress parameter labels* let cuboidVolumeWHDClosure = {(width:Double, height:Double, depth:Double) -> Double in return width*height*depth } cuboidVolumeWHD(2.0, 3.0, 4.0) - cuboidVolumeWHDClosure(2.0,3.0,4.0) //: Once again, we can greatly shorten the closure expression //: * There is only one line, so the return can be dropped. The type is inferred let cuboidVolumeWHDClosure2 = {(width:Double, height:Double, depth:Double) -> Double in width*height*depth } cuboidVolumeWHD(2.0, 3.0, 4.0) - cuboidVolumeWHDClosure2(2.0, 3.0, 4.0) //: * If the constant is typed, then the parameter types can be inferred from the context. In this case, we can use shorthand notation: $0 for parameter 0, $1 for parameter 1 etc.. let cuboidVolumeWHDClosure3 : (Double,Double,Double)->Double = { $0*$1*$2 } cuboidVolumeWHD(2.0, 3.0, 4.0) - cuboidVolumeWHDClosure3(2.0,3.0,4.0) //: Again, note the function type is the same closureArray.append(cuboidVolumeWHD) closureArray.append(cuboidVolumeWHDClosure) //: Another way to inspect type cuboidVolume.dynamicType cuboidVolumeWHD.dynamicType //: ## Solution to tasks in lecture //: Convert the following function to a closure func vol(width w:Double, height h:Double, depth d:Double) -> Double { return w * h * d } //: Solution /// *Note that parameter labels in closures are no longer valid* let vol1 = { (w:Double, h:Double, d:Double) -> Double in return w * h * d } //: Test vol(width: 2.0, height: 3.0, depth: 4.0) - vol1(2.0, 3.0, 4.0) //: Convert the following to a closure func cuboidVolumeWithDimensions(w:Double, _ h:Double, _ d:Double) -> Double { return w * h * d } //: Solution let vol2 = { (w:Double, h:Double, d:Double) -> Double in return w * h * d } //: Test vol2(2.0,3.0,4.0) - cuboidVolumeWithDimensions(2.0,3.0,4.0) //: [Next](@next)
e02782a6a41ba9535d35e66a129f9d9b
36.679739
218
0.697138
false
false
false
false
Lollipop95/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/View/Main/NewFeature/WBWelcomeView.swift
mit
1
// // WBWelcomeView.swift // WeiBo // // Created by Ning Li on 2017/5/5. // Copyright © 2017年 Ning Li. All rights reserved. // import UIKit /// 欢迎视图 class WBWelcomeView: UIView { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var topConstraint: NSLayoutConstraint! /// 创建欢迎视图 class func welcomeView() -> WBWelcomeView { let nib = UINib(nibName: "WBWelcomeView", bundle: nil) let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView v.frame = UIScreen.main.bounds return v } override func awakeFromNib() { super.awakeFromNib() guard let urlString = WBNetworkManager.shared.userAccount.avatar_large, let url = URL(string: urlString) else { return } iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big")) iconView.layer.masksToBounds = true iconView.layer.cornerRadius = iconView.bounds.width * 0.5 } override func didMoveToWindow() { super.didMoveToWindow() layoutIfNeeded() topConstraint.constant = 120 UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { self.layoutIfNeeded() }) { (_) in UIView.animate(withDuration: 1, animations: { self.tipLabel.alpha = 1 }, completion: { (_) in self.removeFromSuperview() }) } } }
6385915d87b6dd5c2bd2bb27941c9287
26.768116
95
0.505741
false
false
false
false
ingresse/ios-sdk
refs/heads/dev
IngresseSDK/Model/TransactionSession.swift
mit
1
// // Copyright © 2017 Ingresse. All rights reserved. // public class TransactionSession: NSObject, Codable { @objc public var id: String = "" @objc public var dateTime: DateTime? } public class DateTime: NSObject, Codable { @objc public var date: String = "" @objc public var time: String = "" var tms: String? var dateTime: String = "" @objc public var timestamp: String { return tms ?? dateTime } enum CodingKeys: String, CodingKey { case tms = "timestamp" case date case time case dateTime } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) tms = try container.decodeIfPresent(String.self, forKey: .tms) date = container.decodeKey(.date, ofType: String.self) time = container.decodeKey(.time, ofType: String.self) dateTime = container.decodeKey(.dateTime, ofType: String.self) } }
98270d8108a071c34e5e15b59919877f
27.228571
71
0.643725
false
false
false
false
satorun/MultiSelectionCollectionViewSample
refs/heads/master
MultiSelectionCollectionViewSample/MultiSelectionCell.swift
mit
1
// // MultiSelectionCell.swift // MultiSelectionCollectionViewSample // // Created by satorun on 2/3/15. // Copyright (c) 2015 satorun. All rights reserved. // import UIKit class MultiSelectionCell: UICollectionViewCell { @IBOutlet weak var button: UIButton! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var leadingSpaceConstraint: NSLayoutConstraint! let kAnimationDuration = 0.4 var item : ModelItem? var isEditMode:Bool = false { didSet(oldEditMode) { p_view(true) } } var isSelected:Bool = false { didSet(oldSelected) { item!.isSelected = isSelected p_view(false) } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setData(data: ModelItem) -> Void { item = data titleLabel.text = item!.title isSelected = item!.isSelected! } func didSelect() { if isEditMode { isSelected = !isSelected // invert } else { // 編集モードじゃないときの処理 } } func p_view(animated: Bool) { if isEditMode { if isSelected { p_selectedViewAtEditMode(animated) } else { p_unSelectedViewAtEditMode(animated) } } else { if isSelected { p_selectedViewAtNormalMode(animated) } else { p_unSelectedViewAtNormalMode(animated) } } } func p_selectedViewAtEditMode(animated: Bool) { leadingSpaceConstraint.constant = 34 let duration = animated ? kAnimationDuration : 0 unowned let unownedSelf = self UIView.animateWithDuration(duration, animations: { () -> Void in unownedSelf.layoutIfNeeded() unownedSelf.button.alpha = 1 unownedSelf.backgroundColor = UIColor.blueColor() }) } func p_selectedViewAtNormalMode(animated: Bool) { leadingSpaceConstraint.constant = 0 let duration = animated ? kAnimationDuration : 0 unowned let unownedSelf = self UIView.animateWithDuration(duration, animations: { () -> Void in unownedSelf.layoutIfNeeded() unownedSelf.button.alpha = 0 unownedSelf.backgroundColor = UIColor.yellowColor() }) } func p_unSelectedViewAtEditMode(animated: Bool) { leadingSpaceConstraint.constant = 34 let duration = animated ? kAnimationDuration : 0 unowned let unownedSelf = self UIView.animateWithDuration(duration, animations: { () -> Void in unownedSelf.layoutIfNeeded() unownedSelf.button.alpha = 1 unownedSelf.backgroundColor = UIColor.whiteColor() }) } func p_unSelectedViewAtNormalMode(animated: Bool) { leadingSpaceConstraint.constant = 0 unowned let unownedSelf = self let duration = animated ? kAnimationDuration : 0 UIView.animateWithDuration(duration, animations: { () -> Void in unownedSelf.layoutIfNeeded() unownedSelf.button.alpha = 0 unownedSelf.backgroundColor = UIColor.whiteColor() }) } }
2fa140bf4f6232eef643c9c2c2d02604
29.514019
72
0.599265
false
false
false
false
CoderJackyHuang/SwiftExtensionCodes
refs/heads/master
SwiftExtensionCodes/UIView+HYBExtension.swift
mit
1
// // UIView+HYBExtension.swift // SwiftExtensionCollection // // Created by huangyibiao on 15/9/22. // Copyright © 2015年 huangyibiao. All rights reserved. // import UIKit /// UIView's useful extensions. /// /// Author: huangyibiao /// Github: http://github.com/CoderJackyHuang/ /// Blog: http://www.hybblog.com/ public extension UIView { // MARK: Frame API /// Get/set self.frame.origin var hyb_origin: CGPoint { get { return self.frame.origin } set { self.frame.origin = newValue } } // Get/set self.frame.origin.x var hyb_originX: CGFloat { get { return self.hyb_origin.x } set { self.hyb_origin.x = newValue } } // Get/set self.frame.origin.y var hyb_originY: CGFloat { get { return self.hyb_origin.y } set { self.hyb_origin.y = newValue } } /// Get/set self.frame.size.width var hyb_width: CGFloat { get { return self.frame.size.width } set { self.frame.size.width = newValue } } /// Get/set self.frame.size.height var hyb_height: CGFloat { get { return self.frame.size.height } set { self.frame.size.height = newValue } } /// Get/set self.frame.size var hyb_size: CGSize { get { return self.frame.size } set { self.frame.size = newValue } } /// Get/set self.frame.size.width + self.frame.origin.x var hyb_rightX: CGFloat { get { return self.frame.size.width + self.frame.origin.x } set { self.hyb_originX = newValue - self.hyb_width } } /// Get/set self.frame.size.height + self.frame.origin.y var hyb_bottomX: CGFloat { get { return self.frame.size.height + self.frame.origin.y } set { self.hyb_originY = newValue - self.hyb_height } } /// Get/set self.center.x var hyb_centerX: CGFloat { get { return self.center.x } set { self.center.x = newValue } } /// Get/set self.center.y var hyb_centerY: CGFloat { get { return self.center.y } set { self.center.y = newValue } } /// Get/set self.center var hyb_center: CGPoint { get { return self.center } set { self.center = newValue } } }
6afb9a87485e4d825f86562e9a143d84
23.738095
63
0.636013
false
false
false
false
fleurdeswift/code-editor
refs/heads/master
CodeEditorView/Theme.swift
mit
1
// // Theme.swift // CodeEditorView // // Copyright © 2015 Fleur de Swift. All rights reserved. // import Foundation public class Theme : Hashable, Equatable { public enum Base { case Dark } public let base: Base; public let customized: Bool = false; internal(set) public var backgroundDraw: Bool; internal(set) public var backgroundColor: CGColorRef; internal(set) public var leftSidebarBackgroundColor: CGColorRef; internal(set) public var leftSidebarBorderColor: CGColorRef; internal(set) public var lineNumberColor: CGColorRef; internal(set) public var lineNumberSelectedColor: CGColorRef; internal(set) public var lineNumberFontName: String; internal(set) public var textFontName: String; internal(set) public var textFontSize: CGFloat; internal(set) public var textFontColor: CGColorRef; internal(set) public var breakpointEnabledFillColor: CGColorRef; internal(set) public var breakpointDisabledFillColor: CGColorRef; internal(set) public var breakpointDisabledStrokeColor: CGColorRef; internal(set) public var instructionPointerFillColor: CGColorRef; internal(set) public var instructionPointerStrokeColor: CGColorRef; public init(_ base: Base) { self.base = base; switch (base) { case .Dark: backgroundDraw = true; backgroundColor = CGColorCreateGenericRGB(30.0 / 255.0, 32.0 / 255.0, 40.0 / 255.0, 1.0); leftSidebarBackgroundColor = CGColorCreateGenericRGB(48.0 / 255.0, 49.0 / 255.0, 57.0 / 255.0, 1.0); leftSidebarBorderColor = CGColorCreateGenericRGB(64.0 / 255.0, 66.0 / 255.0, 73.0 / 255.0, 1.0); lineNumberColor = CGColorCreateGenericGray(0.5, 1.0); lineNumberSelectedColor = CGColorCreateGenericGray(1.0, 1.0); lineNumberFontName = "Arial Narrow"; textFontName = "Menlo"; textFontSize = 11.0; textFontColor = CGColorCreateGenericGray(1, 1); breakpointEnabledFillColor = CGColorCreateGenericRGB( 63.0 / 255.0, 112.0 / 255.0, 181.0 / 255.0, 1.0); breakpointDisabledFillColor = CGColorCreateGenericRGB(161.0 / 255.0, 186.0 / 255.0, 328.0 / 255.0, 1.0); breakpointDisabledStrokeColor = CGColorCreateGenericRGB(181.0 / 255.0, 201.0 / 255.0, 224.0 / 255.0, 1.0); instructionPointerFillColor = CGColorCreateGenericRGB(183.0 / 255.0, 216.0 / 255.0, 169.0 / 255.0, 1.0); instructionPointerStrokeColor = CGColorCreateGenericRGB(140.0 / 255.0, 161.0 / 255.0, 126.0 / 255.0, 1.0); } } public var hashValue: Int { get { return backgroundDraw.hashValue ^ backgroundColor.hashValue ^ leftSidebarBackgroundColor.hashValue ^ leftSidebarBorderColor.hashValue ^ lineNumberColor.hashValue ^ lineNumberSelectedColor.hashValue ^ lineNumberFontName.hashValue ^ textFontName.hashValue ^ textFontSize.hashValue ^ breakpointEnabledFillColor.hashValue ^ breakpointDisabledFillColor.hashValue ^ breakpointDisabledStrokeColor.hashValue ^ instructionPointerFillColor.hashValue ^ instructionPointerStrokeColor.hashValue; } } } public func == (left: Theme, right: Theme) -> Bool { return left.backgroundDraw == right.backgroundDraw && left.backgroundColor == right.backgroundColor && left.leftSidebarBackgroundColor == right.leftSidebarBackgroundColor && left.leftSidebarBorderColor == right.leftSidebarBorderColor && left.lineNumberColor == right.lineNumberColor && left.lineNumberSelectedColor == right.lineNumberSelectedColor && left.lineNumberFontName == right.lineNumberFontName && left.textFontName == right.textFontName && left.textFontSize == right.textFontSize && left.breakpointEnabledFillColor == right.breakpointEnabledFillColor && left.breakpointDisabledFillColor == right.breakpointDisabledFillColor && left.breakpointDisabledStrokeColor == right.breakpointDisabledStrokeColor && left.instructionPointerFillColor == right.instructionPointerFillColor && left.instructionPointerStrokeColor == right.instructionPointerStrokeColor; }
1273e2d6aef0adeecfaaba4e1dcc85e3
44.834951
118
0.629528
false
false
false
false
TG908/iOS
refs/heads/master
TUM Campus App/PersistentUserData.swift
gpl-3.0
1
// // PersistentUserData.swift // TUM Campus App // // Created by Mathias Quintero on 12/16/16. // Copyright © 2016 LS1 TUM. All rights reserved. // import Sweeft enum PersistendUserData: StatusSerializable { case no case some(lrzID: String, token: String) var serialized: [String : Any] { switch self { case .no: return [:] case .some(let lrzID, let token): return [ "lrzID": lrzID, "token": token, ] } } init?(from status: [String : Any]) { guard let lrzID = status["lrzID"] as? String, let token = status["token"] as? String else { return nil } self = .some(lrzID: lrzID, token: token) } var user: User? { switch self { case .no: return nil case .some(let lrzID, let token): return User(lrzID: lrzID, token: token) } } } struct PersistentUser: ObjectStatus { static var key: AppDefaults = .login static var defaultValue: PersistendUserData = .no }
666e58c4d3e202ff3fd6b43cc3a274d2
21.86
57
0.524059
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
refs/heads/master
Frameworks/TBAData/Sources/Event/EventStatusQual.swift
mit
1
import CoreData import Foundation import TBAKit extension EventStatusQual { public var numTeams: Int? { return getValue(\EventStatusQual.numTeamsRaw)?.intValue } public var status: String? { return getValue(\EventStatusQual.statusRaw) } public var eventStatus: EventStatus? { return getValue(\EventStatusQual.eventStatusRaw) } public var ranking: EventRanking? { return getValue(\EventStatusQual.rankingRaw) } } @objc(EventStatusQual) public class EventStatusQual: NSManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<EventStatusQual> { return NSFetchRequest<EventStatusQual>(entityName: EventStatusQual.entityName) } @NSManaged var numTeamsRaw: NSNumber? @NSManaged var statusRaw: String? @NSManaged var eventStatusRaw: EventStatus? @NSManaged var rankingRaw: EventRanking? } extension EventStatusQual: Managed { public static func insert(_ model: TBAEventStatusQual, eventKey: String, teamKey: String, in context: NSManagedObjectContext) -> EventStatusQual { let predicate = NSPredicate(format: "(%K == %@ AND %K == %@) OR (%K == %@ AND %K == %@)", #keyPath(EventStatusQual.rankingRaw.eventRaw.keyRaw), eventKey, #keyPath(EventStatusQual.rankingRaw.teamRaw.keyRaw), teamKey, #keyPath(EventStatusQual.eventStatusRaw.eventRaw.keyRaw), eventKey, #keyPath(EventStatusQual.eventStatusRaw.teamRaw.keyRaw), teamKey) return findOrCreate(in: context, matching: predicate, configure: { (eventStatusQual) in if let numTeams = model.numTeams { eventStatusQual.numTeamsRaw = NSNumber(value: numTeams) } else { eventStatusQual.numTeamsRaw = nil } eventStatusQual.statusRaw = model.status eventStatusQual.updateToOneRelationship(relationship: #keyPath(EventStatusQual.rankingRaw), newValue: model.ranking) { return EventRanking.insert($0, sortOrderInfo: model.sortOrder, extraStatsInfo: nil, eventKey: eventKey, in: context) } }) } } extension EventStatusQual: Orphanable { public var isOrphaned: Bool { // EventStatusQual is an orphan if it's not attached to a Ranking or an EventStatus let hasRanking = (rankingRaw != nil) let hasStatus = (eventStatusRaw != nil) return !hasRanking && !hasStatus } }
614d5c56bd980869f22f1b7b2b7ead05
34.597222
150
0.653921
false
false
false
false
brentdax/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSStringAPI.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Important Note // ============== // // This file is shared between two projects: // // 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation // 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation // // If you change this file, you must update it in both places. #if !DEPLOYMENT_RUNTIME_SWIFT @_exported import Foundation // Clang module #endif // Open Issues // =========== // // Property Lists need to be properly bridged // func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.add(f(s)) } return result } #if !DEPLOYMENT_RUNTIME_SWIFT // We only need this for UnsafeMutablePointer, but there's not currently a way // to write that constraint. extension Optional { /// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the /// address of `object` to `body`. /// /// This is intended for use with Foundation APIs that return an Objective-C /// type via out-parameter where it is important to be able to *ignore* that /// parameter by passing `nil`. (For some APIs, this may allow the /// implementation to avoid some work.) /// /// In most cases it would be simpler to just write this code inline, but if /// `body` is complicated than that results in unnecessarily repeated code. internal func _withNilOrAddress<NSType : AnyObject, ResultType>( of object: inout NSType?, _ body: (AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType ) -> ResultType { return self == nil ? body(nil) : body(&object) } } #endif extension String { //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // @property (class) const NSStringEncoding *availableStringEncodings; /// An array of the encodings that strings support in the application's /// environment. public static var availableStringEncodings: [Encoding] { var result = [Encoding]() var p = NSString.availableStringEncodings while p.pointee != 0 { result.append(Encoding(rawValue: p.pointee)) p += 1 } return result } // @property (class) NSStringEncoding defaultCStringEncoding; /// The C-string encoding assumed for any method accepting a C string as an /// argument. public static var defaultCStringEncoding: Encoding { return Encoding(rawValue: NSString.defaultCStringEncoding) } // + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding /// Returns a human-readable string giving the name of the specified encoding. /// /// - Parameter encoding: A string encoding. For possible values, see /// `String.Encoding`. /// - Returns: A human-readable string giving the name of `encoding` in the /// current locale. public static func localizedName( of encoding: Encoding ) -> String { return NSString.localizedName(of: encoding.rawValue) } // + (instancetype)localizedStringWithFormat:(NSString *)format, ... /// Returns a string created by using a given format string as a /// template into which the remaining argument values are substituted /// according to the user's default locale. public static func localizedStringWithFormat( _ format: String, _ arguments: CVarArg... ) -> String { return String(format: format, locale: Locale.current, arguments: arguments) } //===--------------------------------------------------------------------===// // NSString factory functions that have a corresponding constructor // are omitted. // // + (instancetype)string // // + (instancetype) // stringWithCharacters:(const unichar *)chars length:(NSUInteger)length // // + (instancetype)stringWithFormat:(NSString *)format, ... // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithCString:(const char *)cString // encoding:(NSStringEncoding)enc //===--------------------------------------------------------------------===// //===--- Adds nothing for String beyond what String(s) does -------------===// // + (instancetype)stringWithString:(NSString *)aString //===--------------------------------------------------------------------===// // + (instancetype)stringWithUTF8String:(const char *)bytes /// Creates a string by copying the data from a given /// C array of UTF8-encoded bytes. public init?(utf8String bytes: UnsafePointer<CChar>) { if let ns = NSString(utf8String: bytes) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } } extension String { //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Creates a new string equivalent to the given bytes interpreted in the /// specified encoding. /// /// - Parameters: /// - bytes: A sequence of bytes to interpret using `encoding`. /// - encoding: The ecoding to use to interpret `bytes`. public init? <S: Sequence>(bytes: __shared S, encoding: Encoding) where S.Iterator.Element == UInt8 { let byteArray = Array(bytes) if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of bytes from the /// given buffer, interpreted in the specified encoding, and optionally /// frees the buffer. /// /// - Warning: This initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding.rawValue, freeWhenDone: flag) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Creates a new string that contains the specified number of characters /// from the given C array of Unicode characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count)) } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of characters /// from the given C array of UTF-16 code units. public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = String._unconditionallyBridgeFromObjectiveC(NSString( charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag)) } //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // /// Produces a string created by reading data from the file at a /// given path interpreted using a given encoding. public init( contentsOfFile path: __shared String, encoding enc: Encoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from the file at /// a given path and returns by reference the encoding used to /// interpret the file. public init( contentsOfFile path: __shared String, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOfFile: path, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOfFile path: __shared String ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError**)error /// Produces a string created by reading data from a given URL /// interpreted using a given encoding. Errors are written into the /// inout `error` argument. public init( contentsOf url: __shared URL, encoding enc: Encoding ) throws { let ns = try NSString(contentsOf: url, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from a given URL /// and returns by reference the encoding used to interpret the /// data. Errors are written into the inout `error` argument. public init( contentsOf url: __shared URL, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOf url: __shared URL ) throws { let ns = try NSString(contentsOf: url, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithCString:(const char *)nullTerminatedCString // encoding:(NSStringEncoding)encoding /// Produces a string containing the bytes in a given C array, /// interpreted according to a given encoding. public init?( cString: UnsafePointer<CChar>, encoding enc: Encoding ) { if let ns = NSString(cString: cString, encoding: enc.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // FIXME: handle optional locale with default arguments // - (instancetype) // initWithData:(NSData *)data // encoding:(NSStringEncoding)encoding /// Returns a `String` initialized by converting given `data` into /// Unicode characters using a given `encoding`. public init?(data: __shared Data, encoding: Encoding) { guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil } self = String._unconditionallyBridgeFromObjectiveC(s) } // - (instancetype)initWithFormat:(NSString *)format, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted. public init(format: __shared String, _ arguments: CVarArg...) { self = String(format: format, arguments: arguments) } // - (instancetype) // initWithFormat:(NSString *)format // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to the user's default locale. public init(format: __shared String, arguments: __shared [CVarArg]) { self = String(format: format, locale: nil, arguments: arguments) } // - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: __shared String, locale: __shared Locale?, _ args: CVarArg...) { self = String(format: format, locale: locale, arguments: args) } // - (instancetype) // initWithFormat:(NSString *)format // locale:(id)locale // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: __shared String, locale: __shared Locale?, arguments: __shared [CVarArg]) { #if DEPLOYMENT_RUNTIME_SWIFT self = withVaList(arguments) { String._unconditionallyBridgeFromObjectiveC( NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0) ) } #else self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } #endif } } extension StringProtocol where Index == String.Index { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. // FIXME(strings): There is probably a better way to bridge Self to NSString var _ns: NSString { return self._ephemeralString._bridgeToObjectiveC() } // self can be a Substring so we need to subtract/add this offset when // passing _ns to the Foundation APIs. Will be 0 if self is String. @inlinable internal var _substringOffset: Int { return self.startIndex.encodedOffset } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. func _index(_ utf16Index: Int) -> Index { return Index(encodedOffset: utf16Index + _substringOffset) } @inlinable internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange { return NSRange( location: r.lowerBound.encodedOffset - _substringOffset, length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. func _range(_ r: NSRange) -> Range<Index> { return _index(r.location)..<_index(r.location + r.length) } /// Return a `Range<Index>?` corresponding to the given `NSRange` of /// our UTF-16 representation. func _optionalRange(_ r: NSRange) -> Range<Index>? { if r.location == NSNotFound { return nil } return _range(r) } /// Invoke `body` on an `Int` buffer. If `index` was converted from /// non-`nil`, convert the buffer to an `Index` and write it into the /// memory referred to by `index` func _withOptionalOutParameter<Result>( _ index: UnsafeMutablePointer<Index>?, _ body: (UnsafeMutablePointer<Int>?) -> Result ) -> Result { var utf16Index: Int = 0 let result = (index != nil ? body(&utf16Index) : body(nil)) index?.pointee = _index(utf16Index) return result } /// Invoke `body` on an `NSRange` buffer. If `range` was converted /// from non-`nil`, convert the buffer to a `Range<Index>` and write /// it into the memory referred to by `range` func _withOptionalOutParameter<Result>( _ range: UnsafeMutablePointer<Range<Index>>?, _ body: (UnsafeMutablePointer<NSRange>?) -> Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = (range != nil ? body(&nsRange) : body(nil)) range?.pointee = self._range(nsRange) return result } //===--- Instance Methods/Properties-------------------------------------===// //===--------------------------------------------------------------------===// //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // @property BOOL boolValue; // - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding /// Returns a Boolean value that indicates whether the string can be /// converted to the specified encoding without loss of information. /// /// - Parameter encoding: A string encoding. /// - Returns: `true` if the string can be encoded in `encoding` without loss /// of information; otherwise, `false`. public func canBeConverted(to encoding: String.Encoding) -> Bool { return _ns.canBeConverted(to: encoding.rawValue) } // @property NSString* capitalizedString /// A copy of the string with each word changed to its corresponding /// capitalized spelling. /// /// This property performs the canonical (non-localized) mapping. It is /// suitable for programming operations that require stable results not /// depending on the current locale. /// /// A capitalized string is a string with the first character in each word /// changed to its corresponding uppercase value, and all remaining /// characters set to their corresponding lowercase values. A "word" is any /// sequence of characters delimited by spaces, tabs, or line terminators. /// Some common word delimiting punctuation isn't considered, so this /// property may not generally produce the desired results for multiword /// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for /// additional information. /// /// Case transformations aren’t guaranteed to be symmetrical or to produce /// strings of the same lengths as the originals. public var capitalized: String { return _ns.capitalized as String } // @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0); /// A capitalized representation of the string that is produced /// using the current locale. @available(macOS 10.11, iOS 9.0, *) public var localizedCapitalized: String { return _ns.localizedCapitalized } // - (NSString *)capitalizedStringWithLocale:(Locale *)locale /// Returns a capitalized representation of the string /// using the specified locale. public func capitalized(with locale: Locale?) -> String { return _ns.capitalized(with: locale) as String } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. public func caseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.caseInsensitiveCompare(aString._ephemeralString) } //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // - (unichar)characterAtIndex:(NSUInteger)index // // We have a different meaning for "Character" in Swift, and we are // trying not to expose error-prone UTF-16 integer indexes // - (NSString *) // commonPrefixWithString:(NSString *)aString // options:(StringCompareOptions)mask /// Returns a string containing characters this string and the /// given string have in common, starting from the beginning of each /// up to the first characters that aren't equivalent. public func commonPrefix< T : StringProtocol >(with aString: T, options: String.CompareOptions = []) -> String { return _ns.commonPrefix(with: aString._ephemeralString, options: options) } // - (NSComparisonResult) // compare:(NSString *)aString // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range locale:(id)locale /// Compares the string using the specified options and /// returns the lexical ordering for the range. public func compare<T : StringProtocol>( _ aString: T, options mask: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil ) -> ComparisonResult { // According to Ali Ozer, there may be some real advantage to // dispatching to the minimal selector for the supplied options. // So let's do that; the switch should compile away anyhow. let aString = aString._ephemeralString return locale != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange( range ?? startIndex..<endIndex ), locale: locale?._bridgeToObjectiveC() ) : range != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange(range!) ) : !mask.isEmpty ? _ns.compare(aString, options: mask) : _ns.compare(aString) } // - (NSUInteger) // completePathIntoString:(NSString **)outputName // caseSensitive:(BOOL)flag // matchesIntoArray:(NSArray **)outputArray // filterTypes:(NSArray *)filterTypes /// Interprets the string as a path in the file system and /// attempts to perform filename completion, returning a numeric /// value that indicates whether a match was possible, and by /// reference the longest path that matches the string. /// /// - Returns: The actual number of matching paths. public func completePath( into outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { #if DEPLOYMENT_RUNTIME_SWIFT var outputNamePlaceholder: String? var outputArrayPlaceholder = [String]() let res = self._ns.completePath( into: &outputNamePlaceholder, caseSensitive: caseSensitive, matchesInto: &outputArrayPlaceholder, filterTypes: filterTypes ) if let n = outputNamePlaceholder { outputName?.pointee = n } else { outputName?.pointee = "" } outputArray?.pointee = outputArrayPlaceholder return res #else // DEPLOYMENT_RUNTIME_SWIFT var nsMatches: NSArray? var nsOutputName: NSString? let result: Int = outputName._withNilOrAddress(of: &nsOutputName) { outputName in outputArray._withNilOrAddress(of: &nsMatches) { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 let outputNonOptionalName = unsafeBitCast( outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self) let outputNonOptionalArray = unsafeBitCast( outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, matchesInto: outputNonOptionalArray, filterTypes: filterTypes ) } } if let matches = nsMatches { // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion outputArray?.pointee = matches as! [String] } if let n = nsOutputName { outputName?.pointee = n as String } return result #endif // DEPLOYMENT_RUNTIME_SWIFT } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the string /// that have been divided by characters in the given set. public func components(separatedBy separator: CharacterSet) -> [String] { return _ns.components(separatedBy: separator) } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the string that have been /// divided by the given separator. /// /// The substrings in the resulting array appear in the same order as the /// original string. Adjacent occurrences of the separator string produce /// empty strings in the result. Similarly, if the string begins or ends /// with the separator, the first or last substring, respectively, is empty. /// The following example shows this behavior: /// /// let list1 = "Karin, Carrie, David" /// let items1 = list1.components(separatedBy: ", ") /// // ["Karin", "Carrie", "David"] /// /// // Beginning with the separator: /// let list2 = ", Norman, Stanley, Fletcher" /// let items2 = list2.components(separatedBy: ", ") /// // ["", "Norman", "Stanley", "Fletcher" /// /// If the list has no separators, the array contains only the original /// string itself. /// /// let name = "Karin" /// let list = name.components(separatedBy: ", ") /// // ["Karin"] /// /// - Parameter separator: The separator string. /// - Returns: An array containing substrings that have been divided from the /// string using `separator`. // FIXME(strings): now when String conforms to Collection, this can be // replaced by split(separator:maxSplits:omittingEmptySubsequences:) public func components< T : StringProtocol >(separatedBy separator: T) -> [String] { return _ns.components(separatedBy: separator._ephemeralString) } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the string as a C string /// using a given encoding. public func cString(using encoding: String.Encoding) -> [CChar]? { return withExtendedLifetime(_ns) { (s: NSString) -> [CChar]? in _persistCString(s.cString(using: encoding.rawValue)) } } // - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding // // - (NSData *) // dataUsingEncoding:(NSStringEncoding)encoding // allowLossyConversion:(BOOL)flag /// Returns a `Data` containing a representation of /// the `String` encoded using a given encoding. public func data( using encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { return _ns.data( using: encoding.rawValue, allowLossyConversion: allowLossyConversion) } // @property NSString* decomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KD. public var decomposedStringWithCompatibilityMapping: String { return _ns.decomposedStringWithCompatibilityMapping } //===--- Importing Foundation should not affect String printing ---------===// // Therefore, we're not exposing this: // // @property NSString* description //===--- Omitted for consistency with API review results 5/20/2014 -----===// // @property double doubleValue; // - (void) // enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block /// Enumerates all the lines in a string. public func enumerateLines( invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void ) { _ns.enumerateLines { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line, &stop_) if stop_ { stop.pointee = true } } } // @property NSStringEncoding fastestEncoding; /// The fastest encoding to which the string can be converted without loss /// of information. public var fastestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.fastestEncoding) } // - (BOOL) // getCString:(char *)buffer // maxLength:(NSUInteger)maxBufferCount // encoding:(NSStringEncoding)encoding /// Converts the `String`'s content to a given encoding and /// stores them in a buffer. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. public func getCString( _ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding ) -> Bool { return _ns.getCString(&buffer, maxLength: Swift.min(buffer.count, maxLength), encoding: encoding.rawValue) } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. public func lengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.lengthOfBytes(using: encoding.rawValue) } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and the given string using a case-insensitive, /// localized, comparison. public func localizedCaseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and the given string using a localized comparison. public func localizedCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCompare(aString._ephemeralString) } /// Compares the string and the given string as sorted by the Finder. public func localizedStandardCompare< T : StringProtocol >(_ string: T) -> ComparisonResult { return _ns.localizedStandardCompare(string._ephemeralString) } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property long long longLongValue // @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0); /// A lowercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedLowercase: String { return _ns.localizedLowercase } // - (NSString *)lowercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to lowercase, taking into account the specified /// locale. public func lowercased(with locale: Locale?) -> String { return _ns.lowercased(with: locale) } // - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the maximum number of bytes needed to store the /// `String` in a given encoding. public func maximumLengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.maximumLengthOfBytes(using: encoding.rawValue) } // @property NSString* precomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } #if !DEPLOYMENT_RUNTIME_SWIFT // - (id)propertyList /// Parses the `String` as a text representation of a /// property list, returning an NSString, NSData, NSArray, or /// NSDictionary object, according to the topmost element. public func propertyList() -> Any { return _ns.propertyList() } // - (NSDictionary *)propertyListFromStringsFileFormat /// Returns a dictionary object initialized with the keys and /// values found in the `String`. public func propertyListFromStringsFileFormat() -> [String : String] { return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:] } #endif // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns a Boolean value indicating whether the string contains the given /// string, taking the current locale into account. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardContains< T : StringProtocol >(_ string: T) -> Bool { return _ns.localizedStandardContains(string._ephemeralString) } // @property NSStringEncoding smallestEncoding; /// The smallest encoding to which the string can be converted without /// loss of information. public var smallestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.smallestEncoding) } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string created by replacing all characters in the string /// not in the specified set with percent encoded characters. public func addingPercentEncoding( withAllowedCharacters allowedCharacters: CharacterSet ) -> String? { // FIXME: the documentation states that this method can return nil if the // transformation is not possible, without going into further details. The // implementation can only return nil if malloc() returns nil, so in // practice this is not possible. Still, to be consistent with // documentation, we declare the method as returning an optional String. // // <rdar://problem/17901698> Docs for -[NSString // stringByAddingPercentEncodingWithAllowedCharacters] don't precisely // describe when return value is nil return _ns.addingPercentEncoding(withAllowedCharacters: allowedCharacters ) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string created by appending a string constructed from a given /// format string and the following arguments. public func appendingFormat< T : StringProtocol >( _ format: T, _ arguments: CVarArg... ) -> String { return _ns.appending( String(format: format._ephemeralString, arguments: arguments)) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string created by appending the given string. // FIXME(strings): shouldn't it be deprecated in favor of `+`? public func appending< T : StringProtocol >(_ aString: T) -> String { return _ns.appending(aString._ephemeralString) } /// Returns a string with the given character folding options /// applied. public func folding( options: String.CompareOptions = [], locale: Locale? ) -> String { return _ns.folding(options: options, locale: locale) } // - (NSString *)stringByPaddingToLength:(NSUInteger)newLength // withString:(NSString *)padString // startingAtIndex:(NSUInteger)padIndex /// Returns a new string formed from the `String` by either /// removing characters from the end, or by appending as many /// occurrences as necessary of a given pad string. public func padding< T : StringProtocol >( toLength newLength: Int, withPad padString: T, startingAt padIndex: Int ) -> String { return _ns.padding( toLength: newLength, withPad: padString._ephemeralString, startingAt: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// A new string made from the string by replacing all percent encoded /// sequences with the matching UTF-8 characters. public var removingPercentEncoding: String? { return _ns.removingPercentEncoding } // - (NSString *) // stringByReplacingCharactersInRange:(NSRange)range // withString:(NSString *)replacement /// Returns a new string in which the characters in a /// specified range of the `String` are replaced by a given string. public func replacingCharacters< T : StringProtocol, R : RangeExpression >(in range: R, with replacement: T) -> String where R.Bound == Index { return _ns.replacingCharacters( in: _toRelativeNSRange(range.relative(to: self)), with: replacement._ephemeralString) } // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // options:(StringCompareOptions)options // range:(NSRange)searchRange /// Returns a new string in which all occurrences of a target /// string in a specified range of the string are replaced by /// another given string. public func replacingOccurrences< Target : StringProtocol, Replacement : StringProtocol >( of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { let target = target._ephemeralString let replacement = replacement._ephemeralString return (searchRange != nil) || (!options.isEmpty) ? _ns.replacingOccurrences( of: target, with: replacement, options: options, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ) ) : _ns.replacingOccurrences(of: target, with: replacement) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a new string made by replacing in the `String` /// all percent escapes with the matching characters as determined /// by a given encoding. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func replacingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.replacingPercentEscapes(using: encoding.rawValue) } #endif // - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set /// Returns a new string made by removing from both ends of /// the `String` characters contained in a given character set. public func trimmingCharacters(in set: CharacterSet) -> String { return _ns.trimmingCharacters(in: set) } // @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0); /// An uppercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedUppercase: String { return _ns.localizedUppercase as String } // - (NSString *)uppercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to uppercase, taking into account the specified /// locale. public func uppercased(with locale: Locale?) -> String { return _ns.uppercased(with: locale) } //===--- Omitted due to redundancy with "utf8" property -----------------===// // - (const char *)UTF8String // - (BOOL) // writeToFile:(NSString *)path // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to a file at a given /// path using a given encoding. public func write< T : StringProtocol >( toFile path: T, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( toFile: path._ephemeralString, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (BOOL) // writeToURL:(NSURL *)url // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to the URL specified /// by url using the specified encoding. public func write( to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); #if !DEPLOYMENT_RUNTIME_SWIFT /// Perform string transliteration. @available(macOS 10.11, iOS 9.0, *) public func applyingTransform( _ transform: StringTransform, reverse: Bool ) -> String? { return _ns.applyingTransform(transform, reverse: reverse) } // - (void) // enumerateLinguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // usingBlock:( // void (^)( // NSString *tag, NSRange tokenRange, // NSRange sentenceRange, BOOL *stop) // )block /// Performs linguistic analysis on the specified string by /// enumerating the specific range of the string, providing the /// Block with the located tags. public func enumerateLinguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, invoking body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) where R.Bound == Index { let range = range.relative(to: self) _ns.enumerateLinguisticTags( in: _toRelativeNSRange(range), scheme: tagScheme._ephemeralString, options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { $3.pointee = true } } } #endif // - (void) // enumerateSubstringsInRange:(NSRange)range // options:(NSStringEnumerationOptions)opts // usingBlock:( // void (^)( // NSString *substring, // NSRange substringRange, // NSRange enclosingRange, // BOOL *stop) // )block /// Enumerates the substrings of the specified type in the specified range of /// the string. /// /// Mutation of a string value while enumerating its substrings is not /// supported. If you need to mutate a string from within `body`, convert /// your string to an `NSMutableString` instance and then call the /// `enumerateSubstrings(in:options:using:)` method. /// /// - Parameters: /// - range: The range within the string to enumerate substrings. /// - opts: Options specifying types of substrings and enumeration styles. /// If `opts` is omitted or empty, `body` is called a single time with /// the range of the string specified by `range`. /// - body: The closure executed for each substring in the enumeration. The /// closure takes four arguments: /// - The enumerated substring. If `substringNotRequired` is included in /// `opts`, this parameter is `nil` for every execution of the /// closure. /// - The range of the enumerated substring in the string that /// `enumerate(in:options:_:)` was called on. /// - The range that includes the substring as well as any separator or /// filler characters that follow. For instance, for lines, /// `enclosingRange` contains the line terminators. The enclosing /// range for the first string enumerated also contains any characters /// that occur before the string. Consecutive enclosing ranges are /// guaranteed not to overlap, and every single character in the /// enumerated range is included in one and only one enclosing range. /// - An `inout` Boolean value that the closure can use to stop the /// enumeration by setting `stop = true`. public func enumerateSubstrings< R : RangeExpression >( in range: R, options opts: String.EnumerationOptions = [], _ body: @escaping ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) where R.Bound == Index { _ns.enumerateSubstrings( in: _toRelativeNSRange(range.relative(to: self)), options: opts) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property float floatValue; // - (BOOL) // getBytes:(void *)buffer // maxLength:(NSUInteger)maxBufferCount // usedLength:(NSUInteger*)usedBufferCount // encoding:(NSStringEncoding)encoding // options:(StringEncodingConversionOptions)options // range:(NSRange)range // remainingRange:(NSRangePointer)leftover /// Writes the given `range` of characters into `buffer` in a given /// `encoding`, without any allocations. Does not NULL-terminate. /// /// - Parameter buffer: A buffer into which to store the bytes from /// the receiver. The returned bytes are not NUL-terminated. /// /// - Parameter maxBufferCount: The maximum number of bytes to write /// to buffer. /// /// - Parameter usedBufferCount: The number of bytes used from /// buffer. Pass `nil` if you do not need this value. /// /// - Parameter encoding: The encoding to use for the returned bytes. /// /// - Parameter options: A mask to specify options to use for /// converting the receiver's contents to `encoding` (if conversion /// is necessary). /// /// - Parameter range: The range of characters in the receiver to get. /// /// - Parameter leftover: The remaining range. Pass `nil` If you do /// not need this value. /// /// - Returns: `true` iff some characters were converted. /// /// - Note: Conversion stops when the buffer fills or when the /// conversion isn't possible due to the chosen encoding. /// /// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes. public func getBytes< R : RangeExpression >( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: R, remaining leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool where R.Bound == Index { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: Swift.min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding.rawValue, options: options, range: _toRelativeNSRange(range.relative(to: self)), remaining: $0) } } // - (void) // getLineStart:(NSUInteger *)startIndex // end:(NSUInteger *)lineEndIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first line and /// the end of the last line touched by the given range. public func getLineStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } // - (void) // getParagraphStart:(NSUInteger *)startIndex // end:(NSUInteger *)endIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first paragraph /// and the end of the last paragraph touched by the given range. public func getParagraphStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } //===--- Already provided by core Swift ---------------------------------===// // - (instancetype)initWithString:(NSString *)aString //===--- Initializers that can fail dropped for factory functions -------===// // - (instancetype)initWithUTF8String:(const char *)bytes //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property NSInteger integerValue; // @property Int intValue; //===--- Omitted by apparent agreement during API review 5/20/2014 ------===// // @property BOOL absolutePath; // - (BOOL)isEqualToString:(NSString *)aString // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. public func lineRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _range(_ns.lineRange( for: _toRelativeNSRange(aRange.relative(to: self)))) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSArray *) // linguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // tokenRanges:(NSArray**)tokenRanges /// Returns an array of linguistic tags for the specified /// range and requested tags within the receiving string. public func linguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil? ) -> [String] where R.Bound == Index { var nsTokenRanges: NSArray? let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) { self._ns.linguisticTags( in: _toRelativeNSRange(range.relative(to: self)), scheme: tagScheme._ephemeralString, options: opts, orthography: orthography, tokenRanges: $0) as NSArray } if let nsTokenRanges = nsTokenRanges { tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map { self._range($0.rangeValue) } } return result as! [String] } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. public func paragraphRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _range( _ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self)))) } #endif // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // range:(NSRange)aRange /// Finds and returns the range in the `String` of the first /// character from a given character set found in a given range with /// given options. public func rangeOfCharacter( from aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { return _optionalRange( _ns.rangeOfCharacter( from: aSet, options: mask, range: _toRelativeNSRange( aRange ?? startIndex..<endIndex ) ) ) } // - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex /// Returns the range in the `String` of the composed /// character sequence located at a given index. public func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> { return _range( _ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset)) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. public func rangeOfComposedCharacterSequences< R : RangeExpression >( for range: R ) -> Range<Index> where R.Bound == Index { // Theoretically, this will be the identity function. In practice // I think users will be able to observe differences in the input // and output ranges due (if nothing else) to locale changes return _range( _ns.rangeOfComposedCharacterSequences( for: _toRelativeNSRange(range.relative(to: self)))) } // - (NSRange)rangeOfString:(NSString *)aString // // - (NSRange) // rangeOfString:(NSString *)aString options:(StringCompareOptions)mask // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)aRange // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)searchRange // locale:(Locale *)locale /// Finds and returns the range of the first occurrence of a /// given string within a given range of the `String`, subject to /// given options, using the specified locale, if any. public func range< T : StringProtocol >( of aString: T, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { let aString = aString._ephemeralString return _optionalRange( locale != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ), locale: locale ) : searchRange != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange(searchRange!) ) : !mask.isEmpty ? _ns.range(of: aString, options: mask) : _ns.range(of: aString) ) } // - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Finds and returns the range of the first occurrence of a given string, /// taking the current locale into account. Returns `nil` if the string was /// not found. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardRange< T : StringProtocol >(of string: T) -> Range<Index>? { return _optionalRange( _ns.localizedStandardRange(of: string._ephemeralString)) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` using a given /// encoding to determine the percent escapes necessary to convert /// the `String` into a legal URL string. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.") public func addingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.addingPercentEscapes(using: encoding.rawValue) } #endif //===--- From the 10.10 release notes; not in public documentation ------===// // No need to make these unavailable on earlier OSes, since they can // forward trivially to rangeOfString. /// Returns `true` iff `other` is non-empty and contained within /// `self` by case-sensitive, non-literal search. /// /// Equivalent to `self.rangeOfString(other) != nil` public func contains<T : StringProtocol>(_ other: T) -> Bool { let r = self.range(of: other) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.contains(other._ephemeralString)) } return r } /// Returns a Boolean value indicating whether the given string is non-empty /// and contained within this string by case-insensitive, non-literal /// search, taking into account the current locale. /// /// Locale-independent case-insensitive operation, and other needs, can be /// achieved by calling `range(of:options:range:locale:)`. /// /// Equivalent to: /// /// range(of: other, options: .caseInsensitiveSearch, /// locale: Locale.current) != nil public func localizedCaseInsensitiveContains< T : StringProtocol >(_ other: T) -> Bool { let r = self.range( of: other, options: .caseInsensitive, locale: Locale.current ) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.localizedCaseInsensitiveContains(other._ephemeralString)) } return r } } // Deprecated slicing extension StringProtocol where Index == String.Index { // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range from' operator.") public func substring(from index: Index) -> String { return _ns.substring(from: index.encodedOffset) } // - (NSString *)substringToIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` up to, but not including, the one at a given index. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range upto' operator.") public func substring(to index: Index) -> String { return _ns.substring(to: index.encodedOffset) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript.") public func substring(with aRange: Range<Index>) -> String { return _ns.substring(with: _toRelativeNSRange(aRange)) } } extension StringProtocol { // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public var fileSystemRepresentation: [CChar] { fatalError("unavailable function can't be called") } // - (BOOL) // getFileSystemRepresentation:(char *)buffer // maxLength:(NSUInteger)maxLength /// Interprets the `String` as a system-independent path and /// fills a buffer with a C-string in a format and encoding suitable /// for use with file-system calls. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public func getFileSystemRepresentation( _ buffer: inout [CChar], maxLength: Int) -> Bool { fatalError("unavailable function can't be called") } //===--- Kept for consistency with API review results 5/20/2014 ---------===// // We decided to keep pathWithComponents, so keeping this too // @property NSString lastPathComponent; /// Returns the last path component of the `String`. @available(*, unavailable, message: "Use lastPathComponent on URL instead.") public var lastPathComponent: String { fatalError("unavailable function can't be called") } //===--- Renamed by agreement during API review 5/20/2014 ---------------===// // @property NSUInteger length; /// Returns the number of Unicode characters in the `String`. @available(*, unavailable, message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count") public var utf16Count: Int { fatalError("unavailable function can't be called") } // @property NSArray* pathComponents /// Returns an array of NSString objects containing, in /// order, each path component of the `String`. @available(*, unavailable, message: "Use pathComponents on URL instead.") public var pathComponents: [String] { fatalError("unavailable function can't be called") } // @property NSString* pathExtension; /// Interprets the `String` as a path and returns the /// `String`'s extension, if any. @available(*, unavailable, message: "Use pathExtension on URL instead.") public var pathExtension: String { fatalError("unavailable function can't be called") } // @property NSString *stringByAbbreviatingWithTildeInPath; /// Returns a new string that replaces the current home /// directory portion of the current path with a tilde (`~`) /// character. @available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.") public var abbreviatingWithTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathComponent:(NSString *)aString /// Returns a new string made by appending to the `String` a given string. @available(*, unavailable, message: "Use appendingPathComponent on URL instead.") public func appendingPathComponent(_ aString: String) -> String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathExtension:(NSString *)ext /// Returns a new string made by appending to the `String` an /// extension separator followed by a given extension. @available(*, unavailable, message: "Use appendingPathExtension on URL instead.") public func appendingPathExtension(_ ext: String) -> String? { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingLastPathComponent; /// Returns a new string made by deleting the last path /// component from the `String`, along with any final path /// separator. @available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.") public var deletingLastPathComponent: String { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingPathExtension; /// Returns a new string made by deleting the extension (if /// any, and only the last) from the `String`. @available(*, unavailable, message: "Use deletingPathExtension on URL instead.") public var deletingPathExtension: String { fatalError("unavailable function can't be called") } // @property NSString* stringByExpandingTildeInPath; /// Returns a new string made by expanding the initial /// component of the `String` to its full path value. @available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.") public var expandingTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *) // stringByFoldingWithOptions:(StringCompareOptions)options // locale:(Locale *)locale @available(*, unavailable, renamed: "folding(options:locale:)") public func folding( _ options: String.CompareOptions = [], locale: Locale? ) -> String { fatalError("unavailable function can't be called") } // @property NSString* stringByResolvingSymlinksInPath; /// Returns a new string made from the `String` by resolving /// all symbolic links and standardizing path. @available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.") public var resolvingSymlinksInPath: String { fatalError("unavailable property") } // @property NSString* stringByStandardizingPath; /// Returns a new string made by removing extraneous path /// components from the `String`. @available(*, unavailable, message: "Use standardizingPath on URL instead.") public var standardizingPath: String { fatalError("unavailable function can't be called") } // - (NSArray *)stringsByAppendingPaths:(NSArray *)paths /// Returns an array of strings made by separately appending /// to the `String` each string in a given array. @available(*, unavailable, message: "Map over paths with appendingPathComponent instead.") public func strings(byAppendingPaths paths: [String]) -> [String] { fatalError("unavailable function can't be called") } } // Pre-Swift-3 method names extension String { @available(*, unavailable, renamed: "localizedName(of:)") public static func localizedNameOfStringEncoding( _ encoding: String.Encoding ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func pathWithComponents(_ components: [String]) -> String { fatalError("unavailable function can't be called") } // + (NSString *)pathWithComponents:(NSArray *)components /// Returns a string built from the strings in a given array /// by concatenating them with a path separator between each pair. @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func path(withComponents components: [String]) -> String { fatalError("unavailable function can't be called") } } extension StringProtocol { @available(*, unavailable, renamed: "canBeConverted(to:)") public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "capitalizedString(with:)") public func capitalizedStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "commonPrefix(with:options:)") public func commonPrefixWith( _ aString: String, options: String.CompareOptions) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)") public func completePathInto( _ outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedByCharactersIn( _ separator: CharacterSet ) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedBy(_ separator: String) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "cString(usingEncoding:)") public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)") public func dataUsingEncoding( _ encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)") public func enumerateLinguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)") public func enumerateSubstringsIn( _ range: Range<Index>, options opts: String.EnumerationOptions = [], _ body: ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") public func getBytes( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)") public func getLineStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)") public func getParagraphStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lengthOfBytes(using:)") public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lineRange(for:)") public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)") public func linguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil ) -> [String] { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "lowercased(with:)") public func lowercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "maximumLengthOfBytes(using:)") public func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "paragraphRange(for:)") public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)") public func rangeOfCharacterFrom( _ aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)") public func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)") public func rangeOfComposedCharacterSequencesFor( _ range: Range<Index> ) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "range(of:options:range:locale:)") public func rangeOf( _ aString: String, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "localizedStandardRange(of:)") public func localizedStandardRangeOf(_ string: String) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)") public func addingPercentEncodingWithAllowedCharacters( _ allowedCharacters: CharacterSet ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEscapes(using:)") public func addingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "appendingFormat") public func stringByAppendingFormat( _ format: String, _ arguments: CVarArg... ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "padding(toLength:with:startingAt:)") public func byPaddingToLength( _ newLength: Int, withString padString: String, startingAt padIndex: Int ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingCharacters(in:with:)") public func replacingCharactersIn( _ range: Range<Index>, withString replacement: String ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)") public func replacingOccurrencesOf( _ target: String, withString replacement: String, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)") public func replacingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "trimmingCharacters(in:)") public func byTrimmingCharactersIn(_ set: CharacterSet) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "strings(byAppendingPaths:)") public func stringsByAppendingPaths(_ paths: [String]) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(from:)") public func substringFrom(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(to:)") public func substringTo(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(with:)") public func substringWith(_ aRange: Range<Index>) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "uppercased(with:)") public func uppercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(toFile:atomically:encoding:)") public func writeToFile( _ path: String, atomically useAuxiliaryFile:Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(to:atomically:encoding:)") public func writeToURL( _ url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } }
5deb1dd86472aaa0ec34c71dfac1381c
34.508764
279
0.677059
false
false
false
false
iXieYi/Weibo_DemoTest
refs/heads/master
Weibo_DemoTest/Weibo_DemoTest/Common.swift
mit
1
// // Common.swift // Weibo_DemoTest // // Created by 谢毅 on 16/12/13. // Copyright © 2016年 xieyi. All rights reserved. // /// 目的:提供全局共享属性、方法,类似于pch文件 import UIKit /// MARK:- 全局通知定义 //切换根视图控制器通知 - 一定要与系统区别,一定要有前缀 let WBSwitchRootViewControllerNotification = "WBSwitchRootViewControllerNotification" //选中照片的通知 let WBStatusSelectPhotoNotification = "WBStatusSelectPhotoNotification" /// 选中照片的KEY -indexpath let WBStatusSelectPhotoIndexPath = "WBStatusSelectPhotoIndexPath" /// 图片数组 - url数组 let WBStatusSelectPhotoUrlKey = "WBStatusSelectPhotoUrlKey" //全局外观渲染颜色->延展出皮肤的管理类, let WBAppearanceTintColor = UIColor.orangeColor() ///MARK:-全局函数 /// 延迟在主线程执行的函数 /// /// - parameter delta: 延迟时间 /// - parameter callFunc: 要执行的闭包 func delay(delta:Double,callFunc:()->()){ //延迟方法 dispatch_after( dispatch_time(DISPATCH_TIME_NOW, Int64(delta * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { callFunc() } }
8c3d4ae58a9eda6c6f7a88e851d04431
22.170732
85
0.714436
false
false
false
false
inlined/griddle
refs/heads/master
Griddle/ManagedObject.swift
mit
1
// // ManagedObject.swift // Griddle // // Created by Thomas Bouldin on 6/6/15. // Copyright (c) 2015 Inlined. All rights reserved. // import Foundation import Eventful import Firebase protocol UnsafeYielder { func yieldUnsafe(val: AnyObject!) } public class Property<T : AnyObject> : Observable<T>, UnsafeYielder { var target: ManagedObject! let keyPath: String public init(keyPath: String) { self.keyPath = keyPath } public func bind(target: ManagedObject) { assert(self.target == nil) self.target = target } func yieldUnsafe(val: AnyObject!) { yield(val as? T) } func set(val: T!) { target.set(val, forKeyPath:keyPath) } } infix operator <- { assignment } func <-<T : AnyObject>(property: Property<T>, val: T!) { property.set(val) } public class ManagedObject { private var serverData = FDataSnapshot() private var dirtyData = [String:AnyObject]() private var yielders = [String:UnsafeYielder]() private var ref : Firebase! private var eventHandle: UInt = 0 public init(atURL: String) { ref = Firebase(url:atURL) eventHandle = ref.observeEventType(.Value, withBlock: { [unowned self] snapshot in self.updateSnapshot(snapshot) }) } func get(keyPath: String) -> AnyObject? { if let dirtyVal: AnyObject = dirtyData[keyPath] { if dirtyVal is NSNull { return nil } return dirtyVal } return serverData.valueForKeyPath(keyPath) } func set(value: AnyObject!, forKeyPath: String) { dirtyData[forKeyPath] = value ?? NSNull() yielders[forKeyPath]?.yieldUnsafe(value) } // TODO: Make Promise<Void> easier to use; right now it can't even be initialized. public func save() -> Promise<Int> { let done = Promise<Int>() ref.updateChildValues(dirtyData) { err, _ in if err == nil { // TODO: dirtyData needs to be purged, but when will we get the updated snapshot? done.resolve(0) } else { done.fail(err) } } return done } // TODO(Thomas): Don't send events for data which hasn't changed. func updateSnapshot(snapshot: FDataSnapshot!) { serverData = snapshot for child in snapshot.children { let typedChild = child as! FDataSnapshot if let yielder = yielders[typedChild.key] { yielder.yieldUnsafe(typedChild.value) } } } /* public func property<T>(keyPath: String) -> Property<T> { if let existing = yielders[keyPath] { return existing as! Property<T> } let newProp = Property<T>(target:self, keyPath:keyPath) yielders[keyPath] = newProp return newProp }*/ }
ba9863c281140d5d97af61ae4ddb8c3e
23.592593
89
0.651977
false
false
false
false
hejunbinlan/actor-platform
refs/heads/master
actor-apps/app-ios/Actor/Controllers Support/EngineListController.swift
mit
2
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation import UIKit class EngineListController: AAViewController, UITableViewDelegate, UITableViewDataSource, AMDisplayList_AppleChangeListener { private var engineTableView: UITableView! private var displayList: AMBindedDisplayList! private var fade: Bool = false private var contentSection: Int = 0 init(contentSection: Int, nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); self.contentSection = contentSection; } init(contentSection: Int) { super.init(nibName: nil, bundle: nil); self.contentSection = contentSection; } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindTable(table: UITableView, fade: Bool){ self.fade = fade self.engineTableView = table; self.engineTableView!.dataSource = self; self.engineTableView!.delegate = self; } override func viewDidLoad() { super.viewDidLoad() if (self.displayList == nil) { self.displayList = buildDisplayList() self.displayList.addAppleListener(self) self.engineTableView.reloadData() if (displayList.size() == jint(0)) { self.engineTableView.alpha = 0 } else { self.engineTableView.alpha = 1 } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (self.engineTableView != nil) { var selected = self.engineTableView.indexPathForSelectedRow(); if (selected != nil){ self.engineTableView.deselectRowAtIndexPath(selected!, animated: animated); } } } func filter(val: String) { if (val.size() == 0) { self.displayList.initTopWithRefresh(false) } else { self.displayList.initSearchWithQuery(val, withRefresh: false) } } // Table Data Source func onCollectionChangedWithChanges(modification: AMAppleListUpdate!) { if (self.engineTableView == nil) { return } if (modification.isLoadMore()) { UIView.setAnimationsEnabled(false) } // Apply other changes self.engineTableView.beginUpdates() var hasUpdates = false for i in 0..<modification.size() { var change = modification.changeAt(i) switch(UInt(change.getOperationType().ordinal())) { case AMChangeDescription_OperationType.ADD.rawValue: var startIndex = Int(change.getIndex()) var rows: NSMutableArray = [] for ind in 0..<change.getLength() { rows.addObject(NSIndexPath(forRow: Int(startIndex + ind), inSection: contentSection)) } self.engineTableView.insertRowsAtIndexPaths(rows as [AnyObject], withRowAnimation: UITableViewRowAnimation.Automatic) break case AMChangeDescription_OperationType.UPDATE.rawValue: // Execute in separate batch hasUpdates = true break case AMChangeDescription_OperationType.REMOVE.rawValue: var startIndex = Int(change.getIndex()) var rows: NSMutableArray = [] for ind in 0..<change.getLength() { rows.addObject(NSIndexPath(forRow: Int(startIndex + ind), inSection: contentSection)) } self.engineTableView.deleteRowsAtIndexPaths(rows as [AnyObject], withRowAnimation: UITableViewRowAnimation.Automatic) case AMChangeDescription_OperationType.MOVE.rawValue: self.engineTableView.moveRowAtIndexPath(NSIndexPath(forRow: Int(change.getIndex()), inSection: contentSection), toIndexPath: NSIndexPath(forRow: Int(change.getDestIndex()), inSection: contentSection)) break default: break } } self.engineTableView.endUpdates() // Apply cell change if (hasUpdates) { var visibleIndexes = self.engineTableView.indexPathsForVisibleRows() as! [NSIndexPath] for i in 0..<modification.size() { var change = modification.changeAt(i) switch(UInt(change.getOperationType().ordinal())) { case AMChangeDescription_OperationType.UPDATE.rawValue: var startIndex = Int(change.getIndex()) var rows: NSMutableArray = [] for ind in 0..<change.getLength() { for visibleIndex in visibleIndexes { if (visibleIndex.row == Int(startIndex + ind) && visibleIndex.section == contentSection) { // Need to rebind manually because we need to keep cell reference same var item: AnyObject? = objectAtIndexPath(visibleIndex) var cell = self.engineTableView.cellForRowAtIndexPath(visibleIndex) bindCell(self.engineTableView, cellForRowAtIndexPath: visibleIndex, item: item, cell: cell!) } } } break default: break } } } if (displayList.size() == jint(0)) { if (self.engineTableView.alpha != 0) { if (fade) { UIView.animateWithDuration(0.0, animations: { () -> Void in self.engineTableView.alpha = 0 }) } else { self.engineTableView.alpha = 0 } } } else { if (self.engineTableView.alpha == 0){ if (fade) { UIView.animateWithDuration(0.3, animations: { () -> Void in self.engineTableView.alpha = 1 }) } else { self.engineTableView.alpha = 1 } } } if (modification.isLoadMore()) { UIView.setAnimationsEnabled(true) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (displayList == nil) { return 0; } return Int(displayList.size()); } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var item: AnyObject? = objectAtIndexPath(indexPath) var cell = buildCell(tableView, cellForRowAtIndexPath:indexPath, item:item); bindCell(tableView, cellForRowAtIndexPath: indexPath, item: item, cell: cell); displayList.touchWithIndex(jint(indexPath.row)) return cell; } func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? { if (displayList == nil) { return nil } return displayList.itemWithIndex(jint(indexPath.row)); } // Abstract methods func buildDisplayList() -> AMBindedDisplayList { fatalError("Not implemented"); } func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell { fatalError("Not implemented"); } func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) { fatalError("Not implemented"); } }
7bfa6efce51a1922b4f3e4498fbc9d6f
37.360976
216
0.56874
false
false
false
false
niklassaers/Bolt-swift
refs/heads/master
Sources/SSLKeyGeneratorConfig.swift
bsd-3-clause
1
import Foundation public struct SSLKeyGeneratorConfig { public let signingRequestFileName: String public let countryName: String public let stateOrProvinceName: String public let localityName: String public let organizationName: String public let orgUnitName: String public let commonName: String public let emailAddress: String public let companyName: String public init( signingRequestFileName: String, countryName: String, stateOrProvinceName: String, localityName: String, organizationName: String, orgUnitName: String, commonName: String, emailAddress: String, companyName: String) { self.signingRequestFileName = signingRequestFileName self.countryName = countryName self.stateOrProvinceName = stateOrProvinceName self.localityName = localityName self.organizationName = organizationName self.orgUnitName = orgUnitName self.commonName = commonName self.emailAddress = emailAddress self.companyName = companyName } public init(json: [String:Any]) { signingRequestFileName = json["signingRequestFileName"] as? String ?? "csr.csr" countryName = json["countryName"] as? String ?? "DK" stateOrProvinceName = json["stateOrProvinceName"] as? String ?? "Esbjerg" localityName = json["localityName"] as? String ?? "" organizationName = json["organizationName"] as? String ?? "Bolt-swift" orgUnitName = json["orgUnitName"] as? String ?? "" commonName = json["commonName"] as? String ?? "" emailAddress = json["emailAddress"] as? String ?? "" companyName = json["companyName"] as? String ?? "" } }
ed8d1b3fd229ed36568a02efe4e3db0b
35.791667
87
0.669875
false
false
false
false
jakepolatty/HighSchoolScienceBowlPractice
refs/heads/master
High School Science Bowl Practice/AppDelegate.swift
mit
1
// // AppDelegate.swift // High School Science Bowl Practice // // Created by Jake Polatty on 7/11/17. // Copyright © 2017 Jake Polatty. All rights reserved. // import UIKit extension UIImage { class func imageWithColor(color: UIColor) -> UIImage { let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1)) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext()! context.setFillColor(color.cgColor) context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let mainMenuController = MainMenuViewController() window?.rootViewController = mainMenuController window?.makeKeyAndVisible() UIApplication.shared.statusBarStyle = .lightContent let barColorPixel = UIImage.imageWithColor(color: UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.35)) UINavigationBar.appearance().setBackgroundImage(barColorPixel, for: UIBarMetrics.default) UINavigationBar.appearance().shadowImage = barColorPixel UINavigationBar.appearance().isTranslucent = true UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().layer.cornerRadius = 10 UINavigationBar.appearance().titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary([NSAttributedString.Key.foregroundColor.rawValue: UIColor.white]) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
17b19a0f1852983d058fad55b3e8b1a5
49
285
0.73519
false
false
false
false
huonw/swift
refs/heads/master
test/SILGen/dynamic_self_reference_storage.swift
apache-2.0
3
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class Foo { // CHECK-LABEL: sil hidden @$S30dynamic_self_reference_storage3FooC0A4Self{{[_0-9a-zA-Z]*}}F func dynamicSelf() -> Self { // CHECK: debug_value {{%.*}} : $Foo let managedSelf = self // CHECK: alloc_box ${ var @sil_unmanaged Foo } unowned(unsafe) let unmanagedSelf = self // CHECK: alloc_box ${ var @sil_unowned Foo } unowned(safe) let unownedSelf = self // CHECK: alloc_box ${ var @sil_weak Optional<Foo> } weak var weakSelf = self // CHECK: debug_value {{%.*}} : $Optional<Foo> let optionalSelf = Optional(self) // CHECK: alloc_box ${ var @sil_unowned Foo } let f: () -> () = {[unowned self] in ()} // CHECK: alloc_box ${ var @sil_weak Optional<Foo> } let g: () -> () = {[weak self] in ()} } }
424eb21f0dce459679a9540d3401a296
36.454545
94
0.592233
false
false
false
false
adolfrank/Swift_practise
refs/heads/master
25-day/25-day/FifthViewController.swift
mit
1
// // FifthViewController.swift // 25-day // // Created by Hongbo Yu on 16/5/19. // Copyright © 2016年 Frank. All rights reserved. // import UIKit class FifthViewController: UIViewController { @IBOutlet weak var trump1: UIImageView! @IBOutlet weak var trump2: UIImageView! @IBOutlet weak var trump3: UIImageView! @IBOutlet weak var trump4: UIImageView! @IBOutlet weak var trump5: UIImageView! @IBOutlet weak var trump6: UIImageView! @IBOutlet weak var trump7: UIImageView! @IBOutlet weak var trump8: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func spin() { UIView.animateWithDuration(0.8, delay: 0, options: .CurveLinear, animations: { self.trump1.transform = CGAffineTransformRotate(self.trump1.transform, CGFloat(M_PI)) self.trump2.transform = CGAffineTransformRotate(self.trump2.transform, CGFloat(M_PI)) self.trump3.transform = CGAffineTransformRotate(self.trump3.transform, CGFloat(M_PI)) self.trump4.transform = CGAffineTransformRotate(self.trump4.transform, CGFloat(M_PI)) self.trump5.transform = CGAffineTransformRotate(self.trump5.transform, CGFloat(M_PI)) self.trump6.transform = CGAffineTransformRotate(self.trump6.transform, CGFloat(M_PI)) self.trump7.transform = CGAffineTransformRotate(self.trump7.transform, CGFloat(M_PI)) self.trump8.transform = CGAffineTransformRotate(self.trump8.transform, CGFloat(M_PI)) }) { (finished) -> Void in self.spin() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.spin() } }
11cb6e82dcfa47cb4bd0ca4a84b5d5aa
30.793103
97
0.652928
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/Fuzzing/fuzzer_test_simpler.swift
apache-2.0
4
// RUN: %target-build-swift -parse-as-library -sanitize=fuzzer %s -o %t // RUN: not %t -only_ascii=1 -max_len=3 | %FileCheck %s // CHECK: Crash! // REQUIRES: CPU=x86_64 // REQUIRES: executable_test // REQUIRES: fuzzer_runtime // XFAIL: OS=ios // XFAIL: OS=tvos // XFAIL: OS=watchos #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) import Glibc #endif @_cdecl("LLVMFuzzerTestOneInput") public func fuzzOneInput(Data: UnsafePointer<CChar>, Size: CLong) -> CInt { if (Size >= 3) { if (Data[0] == 65) { if (Data[1] == 66) { if (Data[2] == 67) { fputs("Crash!", stdout); fflush(stdout); exit(1); } } } } return 0; }
a6ee298ef12578da78ca1d3d97e8fd5f
23.866667
109
0.576408
false
true
false
false
beanything/BAWebsite
refs/heads/master
Sources/App/main.swift
mit
1
import Foundation import Vapor import HTTP //Create Droplet let app = Droplet() // Middleware // use 404.leaf for notFound status and error.leaf for all other errors // errorPageMiddleware must be added to droplet via availableMiddleware to be called // after file middleware! That avoids throwing 404 errors for files that are served from Public folder let errorPageMiddleware = ErrorPageMiddleware("error", errorViews: [Status.notFound: "404"]) // set cache control for .html files to a short TTL and everything else to a long TTL let cacheControlMiddleware = CacheControlMiddleware(1800, longTTL: 2592000) // allow cross-origin-resources-requests from docs for webfonts and assets let corsMiddleWware = CorsMiddleware("http://docs.swiftybeaver.com", pathPatterns: ["webfonts", ".png", ".jpg", ".less"]) // add middlewares to droplet. FileMiddleWare has to come at the end to make 404 pages work app.middleware.append(cacheControlMiddleware) app.middleware.append(corsMiddleWware) app.middleware.append(errorPageMiddleware) app.middleware.append(FileMiddleware(publicDir: "Public")) // serve static files from Public folder errorPageMiddleware.droplet = app // required for error view rendering //Routes // Home Index app.get { request in return try app.view.make("index") } // Get Invited app.get("invite") { request in return try app.view.make("invite", ["title": "Get Invited"]) } // Redirect Routes app.get("signup") { request in return Response(redirect: "invite") } app.get("getinvited") { request in return Response(redirect: "invite") } // Sign In app.get("signin") { request in return try app.view.make("sign-in", ["title": "Sign In"]) } // Jobs app.get("jobs") { request in return try app.view.make("jobs", ["title": "Jobs"]) } app.get("ui") { request in return try app.view.make("ui-kit.html", ["title": "UI Kit"]) } app.run()
4bf6b605b1237c8e42fbb06a079a14c2
30.213115
122
0.72479
false
false
false
false
inacioferrarini/York
refs/heads/master
Example/Tests/York/Presenter/CollectionViewCellPresenterTests.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2016 Inácio Ferrarini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest import CoreData import York class CollectionViewCellPresenterTests: XCTestCase { // MARK: - Properties static let cellReuseIdBlock: ((_ indexPath: IndexPath) -> String) = { (indexPath: IndexPath) -> String in return "ReuseCellID" } static var blockExecutionTest = "" // MARK: - Supporting Methods func createCollectionViewCellPresenter() -> CollectionViewCellPresenter<UICollectionViewCell, EntityTest> { let presenter = CollectionViewCellPresenter<UICollectionViewCell, EntityTest>( configureCellBlock: { (cell: UICollectionViewCell, entity: EntityTest) -> Void in CollectionViewCellPresenterTests.blockExecutionTest = "testExecuted" }, cellReuseIdentifierBlock: CollectionViewCellPresenterTests.cellReuseIdBlock) return presenter } // MARK: - Tests func test_collectionViewCellPresenterFields_configureCellBlock() { let testAppContext = TestUtil().testAppContext() let context = testAppContext.coreDataStack.managedObjectContext let presenter = self.createCollectionViewCellPresenter() let cell = UICollectionViewCell() let helper = CoreDataUtil(inManagedObjectContext: context) let entity = helper.createTestMass(withSize: 1, usingInitialIndex: 1, inSection: 1, initialOrderValue: 1).first! presenter.configureCellBlock(cell, entity) XCTAssertEqual(CollectionViewCellPresenterTests.blockExecutionTest, "testExecuted") } func test_collectionViewCellPresenterFields_reuseIdentifier() { let presenter = self.createCollectionViewCellPresenter() let presenterReuseId = presenter.cellReuseIdentifierBlock(IndexPath(row: 0, section: 0)) let testReuseId = CollectionViewCellPresenterTests.cellReuseIdBlock(IndexPath(row: 0, section: 0)) XCTAssertEqual(presenterReuseId, testReuseId) } }
43dd7585f750be5ba1b3a6e3f40c2381
41.684932
120
0.731065
false
true
false
false