repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
MrPudin/Skeem
IOS/Prevoir/ScheduleTaskTBC.swift
1
3140
// // ScheduleTaskTBC.swift // Skeem // // Created by Zhu Zhan Yan on 11/11/16. // Copyright © 2016 SSTInc. All rights reserved. // import UIKit class ScheduleTaskTBC: UITableViewCell { //UI Element @IBOutlet weak var label_begin: UILabel! @IBOutlet weak var label_subject: UILabel! @IBOutlet weak var label_duration: UILabel! @IBOutlet weak var label_name: UILabel! @IBOutlet weak var label_description: UILabel! @IBOutlet weak var label_status: UILabel! //Data /* * public func updateUI(name:String,subject:String,description:String,duration:Int,begin:Date,completion:Double) * - Updates UI for data specifed * [Argument] * name - name of the task * subject - subject of the task * description - description of the task * duration - duration of the task * begin - begin date/time of the task * completion - Floating point number 0.0<=x<=1.0, DefinesExtent the task is completed * */ public func updateUI(name:String,subject:String,description:String,duration:Int,begin:Date,completion:Double) { //Init Date Data let date = Date() let cal = Calendar.autoupdatingCurrent var begin_dcmp = cal.dateComponents([Calendar.Component.day, Calendar.Component.month,Calendar.Component.year,Calendar.Component.minute,Calendar.Component.hour], from: begin as Date) var diff_dcmp = cal.dateComponents([Calendar.Component.day], from: date, to: begin as Date ) //Name Label self.label_name.text = name //Begin Label //Adjust Label for Readablity switch diff_dcmp.day! { case 0: label_begin.text = "\(begin_dcmp.hour!) \((begin_dcmp.minute! < 10) ? "0\(begin_dcmp.minute!)": "\(begin_dcmp.minute!)")" case 1: label_begin.text = "Tommorow,\(begin_dcmp.hour!) \((begin_dcmp.minute! < 10) ? "0\(begin_dcmp.minute!)": "\(begin_dcmp.minute!)")" default: label_begin.text = "\(begin_dcmp.day!)/\(begin_dcmp.month!)/\(begin_dcmp.year!), \(begin_dcmp.hour!) \((begin_dcmp.minute! < 10) ? "0\(begin_dcmp.minute!)": "\(begin_dcmp.minute!)")" } //Duration Label var drsn_hour = 0 var drsn_min = 0 var drsn_left = duration drsn_hour = drsn_left / (60 * 60) drsn_left -= drsn_hour * (60 * 60) drsn_min = drsn_left / (60) self.label_duration.text = "\(drsn_hour)h \(drsn_min)m" //Status Label self.label_status.text = "\(completion * 100)%" if completion < 0.50 { self.label_status.textColor = UIColor.red } else if completion < 1.00 { self.label_status.textColor = UIColor.yellow } else { self.label_status.textColor = UIColor.green } } //Events override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
twostraws/HackingWithSwift
SwiftUI/project12/Project12/ContentView.swift
1
4845
// // ContentView.swift // Project12 // // Created by Paul Hudson on 17/02/2020. // Copyright © 2020 Paul Hudson. All rights reserved. // import CoreData import SwiftUI struct OneToManyRelationshipsContentView: View { @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Country.entity(), sortDescriptors: []) var countries: FetchedResults<Country> var body: some View { VStack { List { ForEach(countries, id: \.self) { country in Section(header: Text(country.wrappedFullName)) { ForEach(country.candyArray, id: \.self) { candy in Text(candy.wrappedName) } } } } Button("Add") { let candy1 = Candy(context: self.moc) candy1.name = "Mars" candy1.origin = Country(context: self.moc) candy1.origin?.shortName = "UK" candy1.origin?.fullName = "United Kingdom" let candy2 = Candy(context: self.moc) candy2.name = "KitKat" candy2.origin = Country(context: self.moc) candy2.origin?.shortName = "UK" candy2.origin?.fullName = "United Kingdom" let candy3 = Candy(context: self.moc) candy3.name = "Twix" candy3.origin = Country(context: self.moc) candy3.origin?.shortName = "UK" candy3.origin?.fullName = "United Kingdom" let candy4 = Candy(context: self.moc) candy4.name = "Toblerone" candy4.origin = Country(context: self.moc) candy4.origin?.shortName = "CH" candy4.origin?.fullName = "Switzerland" try? self.moc.save() } } } } struct DynamicFilteringContentView: View { @Environment(\.managedObjectContext) var moc @State private var lastNameFilter = "A" var body: some View { VStack { FilteredList(filterKey: "lastName", filterValue: lastNameFilter) { (singer: Singer) in Text("\(singer.wrappedFirstName) \(singer.wrappedLastName)") } Button("Add Examples") { let taylor = Singer(context: self.moc) taylor.firstName = "Taylor" taylor.lastName = "Swift" let ed = Singer(context: self.moc) ed.firstName = "Ed" ed.lastName = "Sheeran" let adele = Singer(context: self.moc) adele.firstName = "Adele" adele.lastName = "Adkins" try? self.moc.save() } Button("Show A") { self.lastNameFilter = "A" } Button("Show S") { self.lastNameFilter = "S" } } } } struct ShipContentView: View { @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Ship.entity(), sortDescriptors: [], predicate: NSPredicate(format: "universe == 'Star Wars'")) var ships: FetchedResults<Ship> var body: some View { VStack { List(ships, id: \.self) { ship in Text(ship.name ?? "Unknown name") } Button("Add Examples") { let ship1 = Ship(context: self.moc) ship1.name = "Enterprise" ship1.universe = "Star Trek" let ship2 = Ship(context: self.moc) ship2.name = "Defiant" ship2.universe = "Star Trek" let ship3 = Ship(context: self.moc) ship3.name = "Millennium Falcon" ship3.universe = "Star Wars" let ship4 = Ship(context: self.moc) ship4.name = "Executor" ship4.universe = "Star Wars" try? self.moc.save() } } } } struct ContentView: View { @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Wizard.entity(), sortDescriptors: []) var wizards: FetchedResults<Wizard> var body: some View { VStack { List(wizards, id: \.self) { wizard in Text(wizard.name ?? "Unknown") } Button("Add") { let wizard = Wizard(context: self.moc) wizard.name = "Harry Potter" } Button("Save") { do { try self.moc.save() } catch { print(error.localizedDescription) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
unlicense
thomasvl/swift-protobuf
Tests/SwiftProtobufTests/Test_Struct.swift
2
18214
// Tests/SwiftProtobufTests/Test_Struct.swift - Verify Struct well-known type // // Copyright (c) 2014 - 2019 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Struct, Value, ListValue are standard PRoto3 message types that support /// general ad hoc JSON parsing and serialization. /// // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobufCore class Test_Struct: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_Struct func testStruct_pbencode() { assertEncode([10, 12, 10, 3, 102, 111, 111, 18, 5, 26, 3, 98, 97, 114]) {(o: inout MessageTestType) in var v = Google_Protobuf_Value() v.stringValue = "bar" o.fields["foo"] = v } } func testStruct_pbdecode() { assertDecodeSucceeds([10, 7, 10, 1, 97, 18, 2, 32, 1, 10, 7, 10, 1, 98, 18, 2, 8, 0]) { (m) in let vTrue = Google_Protobuf_Value(boolValue: true) let vNull: Google_Protobuf_Value = nil var same = Google_Protobuf_Struct() same.fields = ["a": vTrue, "b": vNull] var different = Google_Protobuf_Struct() different.fields = ["a": vTrue, "b": vNull, "c": vNull] return (m.fields.count == 2 && m.fields["a"] == vTrue && m.fields["a"] != vNull && m.fields["b"] == vNull && m.fields["b"] != vTrue && m == same && m != different) } } func test_JSON() { assertJSONDecodeSucceeds("{}") {$0.fields == [:]} assertJSONDecodeFails("null") assertJSONDecodeFails("false") assertJSONDecodeFails("true") assertJSONDecodeFails("[]") assertJSONDecodeFails("{") assertJSONDecodeFails("}") assertJSONDecodeFails("{}}") assertJSONDecodeFails("{]") assertJSONDecodeFails("1") assertJSONDecodeFails("\"1\"") } func test_JSON_field() throws { // "null" as a field value indicates the field is missing // (Except for Value, where "null" indicates NullValue) do { let c1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString:"{\"optionalStruct\":null}") // null here decodes to an empty field. // See github.com/protocolbuffers/protobuf Issue #1327 XCTAssertEqual(try c1.jsonString(), "{}") } catch let e { XCTFail("Didn't decode c1: \(e)") } do { let c2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString:"{\"optionalStruct\":{}}") XCTAssertNotNil(c2.optionalStruct) XCTAssertEqual(c2.optionalStruct.fields, [:]) } catch let e { XCTFail("Didn't decode c2: \(e)") } } func test_equality() throws { let a1decoded: Google_Protobuf_Struct do { a1decoded = try Google_Protobuf_Struct(jsonString: "{\"a\":1}") } catch { XCTFail("Decode failed for {\"a\":1}") return } let a2decoded = try Google_Protobuf_Struct(jsonString: "{\"a\":2}") var a1literal = Google_Protobuf_Struct() a1literal.fields["a"] = Google_Protobuf_Value(numberValue: 1) XCTAssertEqual(a1literal, a1decoded) XCTAssertEqual(a1literal.hashValue, a1decoded.hashValue) XCTAssertNotEqual(a1decoded, a2decoded) // Hash inequality is not guaranteed, but a collision here would be suspicious let a1literalHash = a1literal.hashValue let a2decodedHash = a2decoded.hashValue XCTAssertNotEqual(a1literalHash, a2decodedHash) } } class Test_JSON_ListValue: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_ListValue // Since ProtobufJSONList is handbuilt rather than generated, // we need to verify all the basic functionality, including // serialization, equality, hash, etc. func testProtobuf() { assertEncode([10, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63, 10, 5, 26, 3, 97, 98, 99, 10, 2, 32, 1]) { (o: inout MessageTestType) in o.values.append(Google_Protobuf_Value(numberValue: 1)) o.values.append(Google_Protobuf_Value(stringValue: "abc")) o.values.append(Google_Protobuf_Value(boolValue: true)) } } func testJSON() { assertJSONEncode("[1.0,\"abc\",true]") { (o: inout MessageTestType) in o.values.append(Google_Protobuf_Value(numberValue: 1)) o.values.append(Google_Protobuf_Value(stringValue: "abc")) o.values.append(Google_Protobuf_Value(boolValue: true)) } assertJSONEncode("[1.0,\"abc\",true,[1.0,null],[]]") { (o: inout MessageTestType) in o.values.append(Google_Protobuf_Value(numberValue: 1)) o.values.append(Google_Protobuf_Value(stringValue: "abc")) o.values.append(Google_Protobuf_Value(boolValue: true)) o.values.append(Google_Protobuf_Value(listValue: [1, nil])) o.values.append(Google_Protobuf_Value(listValue: [])) } assertJSONDecodeSucceeds("[]") {$0.values == []} assertJSONDecodeFails("") assertJSONDecodeFails("true") assertJSONDecodeFails("false") assertJSONDecodeFails("{}") assertJSONDecodeFails("1.0") assertJSONDecodeFails("\"a\"") assertJSONDecodeFails("[}") assertJSONDecodeFails("[,]") assertJSONDecodeFails("[true,]") assertJSONDecodeSucceeds("[true]") {$0.values == [Google_Protobuf_Value(boolValue: true)]} } func test_JSON_nested_list() throws { let limit = JSONDecodingOptions().messageDepthLimit let depths = [ // Small lists 1,2,3,4,5, // Little less than default messageDepthLimit, should succeed limit - 3, limit - 2, limit - 1, limit, // Little bigger than default messageDepthLimit, should fail limit + 1, limit + 2, limit + 3, limit + 4, // Really big, should fail cleanly (not crash) 1000,10000,100000,1000000 ] for depth in depths { var s = "" for _ in 0..<(depth / 10) { s.append("[[[[[[[[[[") } for _ in 0..<(depth % 10) { s.append("[") } for _ in 0..<(depth / 10) { s.append("]]]]]]]]]]") } for _ in 0..<(depth % 10) { s.append("]") } // Recursion limits should cause this to // fail cleanly without crashing if depth <= limit { assertJSONDecodeSucceeds(s) {_ in true} } else { assertJSONDecodeFails(s) } } } func test_equality() throws { let a1decoded = try Google_Protobuf_ListValue(jsonString: "[1]") let a2decoded = try Google_Protobuf_ListValue(jsonString: "[2]") var a1literal = Google_Protobuf_ListValue() a1literal.values.append(Google_Protobuf_Value(numberValue: 1)) XCTAssertEqual(a1literal, a1decoded) XCTAssertEqual(a1literal.hashValue, a1decoded.hashValue) XCTAssertNotEqual(a1decoded, a2decoded) // Hash inequality is not guaranteed, but a collision here would be suspicious XCTAssertNotEqual(a1literal.hashValue, a2decoded.hashValue) XCTAssertNotEqual(a1literal, a2decoded) } } class Test_Value: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_Value func testValue_empty() throws { let empty = Google_Protobuf_Value() // Serializing an empty value (kind not set) in binary or text is ok; // it is only an error in JSON. XCTAssertEqual(try empty.serializedBytes(), []) XCTAssertEqual(empty.textFormatString(), "") // Make sure an empty value is not equal to a nullValue value. let null: Google_Protobuf_Value = nil XCTAssertNotEqual(empty, null) } } // TODO: Should have convenience initializers on Google_Protobuf_Value class Test_JSON_Value: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_Value func testValue_emptyShouldThrow() throws { let empty = Google_Protobuf_Value() do { _ = try empty.jsonString() XCTFail("Encoding should have thrown .missingValue, but it succeeded") } catch JSONEncodingError.missingValue { // Nothing to do here; this is the expected error. } catch { XCTFail("Encoding should have thrown .missingValue, but instead it threw: \(error)") } } func testValue_null() throws { let nullFromLiteral: Google_Protobuf_Value = nil let null: Google_Protobuf_Value = nil XCTAssertEqual("null", try null.jsonString()) XCTAssertEqual([8, 0], try null.serializedBytes()) XCTAssertEqual(nullFromLiteral, null) XCTAssertNotEqual(nullFromLiteral, Google_Protobuf_Value(numberValue: 1)) assertJSONDecodeSucceeds("null") {$0.nullValue == .nullValue} assertJSONDecodeSucceeds(" null ") {$0.nullValue == .nullValue} assertJSONDecodeFails("numb") do { let m1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalValue\": null}") XCTAssertEqual(try m1.jsonString(), "{\"optionalValue\":null}") XCTAssertEqual(try m1.serializedBytes(), [146, 19, 2, 8, 0]) } catch { XCTFail() } assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nnull_value: NULL_VALUE\n", null) } func testValue_number() throws { let oneFromIntegerLiteral: Google_Protobuf_Value = 1 let oneFromFloatLiteral: Google_Protobuf_Value = 1.0 let twoFromFloatLiteral: Google_Protobuf_Value = 2.0 XCTAssertEqual(oneFromIntegerLiteral, oneFromFloatLiteral) XCTAssertNotEqual(oneFromIntegerLiteral, twoFromFloatLiteral) XCTAssertEqual("1.0", try oneFromIntegerLiteral.jsonString()) XCTAssertEqual([17, 0, 0, 0, 0, 0, 0, 240, 63], try oneFromIntegerLiteral.serializedBytes()) assertJSONEncode("3.25") {(o: inout MessageTestType) in o.numberValue = 3.25 } assertJSONDecodeSucceeds("3.25") {$0.numberValue == 3.25} assertJSONDecodeSucceeds(" 3.25 ") {$0.numberValue == 3.25} assertJSONDecodeFails("3.2.5") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nnumber_value: 1.0\n", oneFromIntegerLiteral) } func testValue_string() throws { // Literals and equality testing let fromStringLiteral: Google_Protobuf_Value = "abcd" XCTAssertEqual(fromStringLiteral, Google_Protobuf_Value(stringValue: "abcd")) XCTAssertNotEqual(fromStringLiteral, Google_Protobuf_Value(stringValue: "abc")) XCTAssertNotEqual(fromStringLiteral, Google_Protobuf_Value()) // JSON serialization assertJSONEncode("\"abcd\"") {(o: inout MessageTestType) in o.stringValue = "abcd" } assertJSONEncode("\"\"") {(o: inout MessageTestType) in o.stringValue = "" } assertJSONDecodeSucceeds("\"abcd\"") {$0.stringValue == "abcd"} assertJSONDecodeSucceeds(" \"abcd\" ") {$0.stringValue == "abcd"} assertJSONDecodeFails("\"abcd\" XXX") assertJSONDecodeFails("\"abcd") // JSON serializing special characters XCTAssertEqual("\"a\\\"b\"", try Google_Protobuf_Value(stringValue: "a\"b").jsonString()) let valueWithEscapes = Google_Protobuf_Value(stringValue: "a\u{0008}\u{0009}\u{000a}\u{000c}\u{000d}b") let serializedValueWithEscapes = try valueWithEscapes.jsonString() XCTAssertEqual("\"a\\b\\t\\n\\f\\rb\"", serializedValueWithEscapes) do { let parsedValueWithEscapes = try Google_Protobuf_Value(jsonString: serializedValueWithEscapes) XCTAssertEqual(valueWithEscapes.stringValue, parsedValueWithEscapes.stringValue) } catch { XCTFail("Failed to decode \(serializedValueWithEscapes)") } // PB serialization XCTAssertEqual([26, 3, 97, 34, 98], try Google_Protobuf_Value(stringValue: "a\"b").serializedBytes()) assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nstring_value: \"abcd\"\n", fromStringLiteral) } func testValue_bool() { let trueFromLiteral: Google_Protobuf_Value = true let falseFromLiteral: Google_Protobuf_Value = false XCTAssertEqual(trueFromLiteral, Google_Protobuf_Value(boolValue: true)) XCTAssertEqual(falseFromLiteral, Google_Protobuf_Value(boolValue: false)) XCTAssertNotEqual(falseFromLiteral, trueFromLiteral) assertJSONEncode("true") {(o: inout MessageTestType) in o.boolValue = true } assertJSONEncode("false") {(o: inout MessageTestType) in o.boolValue = false } assertJSONDecodeSucceeds("true") {$0.boolValue == true} assertJSONDecodeSucceeds(" false ") {$0.boolValue == false} assertJSONDecodeFails("yes") assertJSONDecodeFails(" true false ") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nbool_value: true\n", trueFromLiteral) } func testValue_struct() throws { assertJSONEncode("{\"a\":1.0}") {(o: inout MessageTestType) in o.structValue = Google_Protobuf_Struct(fields:["a": Google_Protobuf_Value(numberValue: 1)]) } let structValue = try Google_Protobuf_Value(jsonString: "{\"a\":1.0}") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nstruct_value {\n fields {\n key: \"a\"\n value {\n number_value: 1.0\n }\n }\n}\n", structValue) } func testValue_list() throws { let listValue = try Google_Protobuf_Value(jsonString: "[1, true, \"abc\"]") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nlist_value {\n values {\n number_value: 1.0\n }\n values {\n bool_value: true\n }\n values {\n string_value: \"abc\"\n }\n}\n", listValue) } func testValue_complex() { assertJSONDecodeSucceeds("{\"a\": {\"b\": 1.0}, \"c\": [ 7, true, null, {\"d\": false}]}") { let outer = $0.structValue.fields let a = outer["a"]?.structValue.fields let c = outer["c"]?.listValue.values return (a?["b"]?.numberValue == 1.0 && c?.count == 4 && c?[0].numberValue == 7 && c?[1].boolValue == true && c?[2].nullValue == Google_Protobuf_NullValue() && c?[3].structValue.fields["d"]?.boolValue == false) } } func testStruct_conformance() throws { let json = ("{\n" + " \"optionalStruct\": {\n" + " \"nullValue\": null,\n" + " \"intValue\": 1234,\n" + " \"boolValue\": true,\n" + " \"doubleValue\": 1234.5678,\n" + " \"stringValue\": \"Hello world!\",\n" + " \"listValue\": [1234, \"5678\"],\n" + " \"objectValue\": {\n" + " \"value\": 0\n" + " }\n" + " }\n" + "}\n") let m: ProtobufTestMessages_Proto3_TestAllTypesProto3 do { m = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json) } catch { XCTFail("Decoding failed: \(json)") return } XCTAssertNotNil(m.optionalStruct) let s = m.optionalStruct XCTAssertNotNil(s.fields["nullValue"]) if let nv = s.fields["nullValue"] { XCTAssertEqual(nv.nullValue, Google_Protobuf_NullValue()) } XCTAssertNotNil(s.fields["intValue"]) if let iv = s.fields["intValue"] { XCTAssertEqual(iv, Google_Protobuf_Value(numberValue: 1234)) XCTAssertEqual(iv.numberValue, 1234) } XCTAssertNotNil(s.fields["boolValue"]) if let bv = s.fields["boolValue"] { XCTAssertEqual(bv, Google_Protobuf_Value(boolValue: true)) XCTAssertEqual(bv.boolValue, true) } XCTAssertNotNil(s.fields["doubleValue"]) if let dv = s.fields["doubleValue"] { XCTAssertEqual(dv, Google_Protobuf_Value(numberValue: 1234.5678)) XCTAssertEqual(dv.numberValue, 1234.5678) } XCTAssertNotNil(s.fields["stringValue"]) if let sv = s.fields["stringValue"] { XCTAssertEqual(sv, Google_Protobuf_Value(stringValue: "Hello world!")) XCTAssertEqual(sv.stringValue, "Hello world!") } XCTAssertNotNil(s.fields["listValue"]) if let lv = s.fields["listValue"] { XCTAssertEqual(lv.listValue, [Google_Protobuf_Value(numberValue: 1234), Google_Protobuf_Value(stringValue: "5678")]) } XCTAssertNotNil(s.fields["objectValue"]) if let ov = s.fields["objectValue"] { XCTAssertNotNil(ov.structValue.fields["value"]) if let inner = s.fields["objectValue"]?.structValue.fields["value"] { XCTAssertEqual(inner, Google_Protobuf_Value(numberValue: 0)) XCTAssertEqual(inner.numberValue, 0) } } } func testStruct_null() throws { let json = ("{\n" + " \"optionalStruct\": null\n" + "}\n") do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json) let recoded = try decoded.jsonString() XCTAssertEqual(recoded, "{}") } catch { XCTFail("Should have decoded") } } }
apache-2.0
loudnate/LoopKit
LoopKit/GlucoseEffectVelocity.swift
2
1144
// // GlucoseEffectVelocity.swift // LoopKit // // Copyright © 2017 LoopKit Authors. All rights reserved. // import Foundation import HealthKit /// The first-derivative of GlucoseEffect, blood glucose over time. public struct GlucoseEffectVelocity: SampleValue { public let startDate: Date public let endDate: Date public let quantity: HKQuantity public init(startDate: Date, endDate: Date, quantity: HKQuantity) { self.startDate = startDate self.endDate = endDate self.quantity = quantity } } extension GlucoseEffectVelocity { static let perSecondUnit = HKUnit.milligramsPerDeciliter.unitDivided(by: .second()) /// The integration of the velocity span public var effect: GlucoseEffect { let duration = endDate.timeIntervalSince(startDate) let velocityPerSecond = quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) return GlucoseEffect( startDate: endDate, quantity: HKQuantity( unit: .milligramsPerDeciliter, doubleValue: velocityPerSecond * duration ) ) } }
mit
jane/JanePhotoBrowser
JanePhotoBrowser/PhotoBrowser/PhotoBrowserInfinitePagedView/PhotoBrowserInfinitePagedDelegate.swift
1
394
// // PhotoBrowserInfinitePagedDelegate.swift // PhotoBrowser // // Created by Gordon Tucker on 8/1/19. // Copyright © 2019 Jane. All rights reserved. // import UIKit protocol PhotoBrowserInfinitePagedDelegate: class { func photoBrowserInfinitePhotoViewed(at index: Int) func photoBrowserInfinitePhotoTapped(at index: Int) func photoBrowserInfinitePhotoZoom(at index: Int) }
mit
charvoa/TimberiOS
TimberiOS/Classes/NetworkManager.swift
1
1514
// // NetworkManager.swift // TimberiOS // // Created by Nicolas on 28/09/2017. // import Foundation import Alamofire extension String: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var request = try urlRequest.asURLRequest() request.httpBody = data(using: .utf8, allowLossyConversion: false) return request } } open class NetworkManager { public static let shared = NetworkManager() private init() {} open func request(apiToken: String, sourceIdentification: String, endpoint: String, method: HTTPMethod, params: [String: Any], completionHandler: @escaping (DataResponse<String>) -> ()) { let encodedToken = apiToken.toBase64() let headers: HTTPHeaders = [ "authorization": String(format: "Basic %@", encodedToken), "accept": "content/json", "content-type": "application/json" ] Alamofire.request("https://logs.timber.io/sources/\(sourceIdentification)/\(endpoint)", method: method, parameters: params, encoding: JSONEncoding.default, headers: headers) .validate(contentType: ["text/plain"]) .responseString { (response) in completionHandler(response) } } }
mit
tsolomko/SWCompression
Sources/7-Zip/7zFileInfo.swift
1
5471
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import BitByteData class SevenZipFileInfo { struct File { var isEmptyStream = false var isEmptyFile = false var isAntiFile = false var name: String = "" var cTime: Date? var mTime: Date? var aTime: Date? var winAttributes: UInt32? } let numFiles: Int var files = [File]() var unknownProperties = [SevenZipProperty]() init(_ bitReader: MsbBitReader) throws { numFiles = bitReader.szMbd() for _ in 0..<numFiles { files.append(File()) } var isEmptyStream: [UInt8]? var isEmptyFile: [UInt8]? var isAntiFile: [UInt8]? while true { let propertyType = bitReader.byte() if propertyType == 0 { break } let propertySize = bitReader.szMbd() switch propertyType { case 0x0E: // EmptyStream isEmptyStream = bitReader.bits(count: numFiles) bitReader.align() case 0x0F: // EmptyFile guard let emptyStreamCount = isEmptyStream?.filter({ $0 == 1 }).count else { throw SevenZipError.internalStructureError } isEmptyFile = bitReader.bits(count: emptyStreamCount) bitReader.align() case 0x10: // AntiFile (used in backups to indicate that file was removed) guard let emptyStreamCount = isEmptyStream?.filter({ $0 == 1 }).count else { throw SevenZipError.internalStructureError } isAntiFile = bitReader.bits(count: emptyStreamCount) bitReader.align() case 0x11: // File name let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } guard (propertySize - 1) & 1 == 0, let names = String(bytes: bitReader.bytes(count: propertySize - 1), encoding: .utf16LittleEndian) else { throw SevenZipError.internalStructureError } var nextFile = 0 for name in names.split(separator: "\u{0}") { files[nextFile].name = String(name) nextFile += 1 } guard nextFile == numFiles else { throw SevenZipError.internalStructureError } case 0x12: // Creation time let timesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where timesDefined[i] == 1 { files[i].cTime = Date(bitReader.uint64()) } case 0x13: // Access time let timesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where timesDefined[i] == 1 { files[i].aTime = Date(bitReader.uint64()) } case 0x14: // Modification time let timesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where timesDefined[i] == 1 { files[i].mTime = Date(bitReader.uint64()) } case 0x15: // WinAttributes let attributesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where attributesDefined[i] == 1 { files[i].winAttributes = bitReader.uint32() } case 0x18: // StartPos throw SevenZipError.startPosNotSupported case 0x19: // "Dummy". Used for alignment/padding. guard bitReader.size - bitReader.offset >= propertySize else { throw SevenZipError.internalStructureError } bitReader.offset += propertySize default: // Unknown property guard bitReader.size - bitReader.offset >= propertySize else { throw SevenZipError.internalStructureError } unknownProperties.append(SevenZipProperty(propertyType, propertySize, bitReader.bytes(count: propertySize))) } } var emptyFileIndex = 0 for i in 0..<numFiles { files[i].isEmptyStream = isEmptyStream?[i] == 1 if files[i].isEmptyStream { files[i].isEmptyFile = isEmptyFile?[emptyFileIndex] == 1 files[i].isAntiFile = isAntiFile?[emptyFileIndex] == 1 emptyFileIndex += 1 } } } }
mit
awkward/Tatsi
Tatsi/Views/Assets Grid/Cells/CameraCollectionViewCell.swift
1
1520
// // CameraCollectionViewCell.swift // Tatsi // // Created by Rens Verhoeven on 30-03-16. // Copyright © 2017 Awkward BV. All rights reserved. // import UIKit final internal class CameraCollectionViewCell: UICollectionViewCell { static var reuseIdentifier: String { return "camera-cell" } lazy private var iconView: CameraIconView = { let iconView = CameraIconView() iconView.translatesAutoresizingMaskIntoConstraints = false return iconView }() override init(frame: CGRect) { super.init(frame: frame) self.setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupView() { self.contentView.addSubview(self.iconView) self.contentView.backgroundColor = UIColor.lightGray self.accessibilityIdentifier = "tatsi.cell.camera" self.accessibilityLabel = LocalizableStrings.cameraButtonTitle self.accessibilityTraits = UIAccessibilityTraits.button self.isAccessibilityElement = true self.setupConstraints() } private func setupConstraints() { let constraints = [ self.iconView.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor), self.iconView.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor) ] NSLayoutConstraint.activate(constraints) } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01777-resolvetypedecl.swift
1
221
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class b<T where f: Any func b { func d(B enum B : b
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/00520-getselftypeforcontainer.swift
12
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol d { { } protocol g : e { func e } } extension d
mit
artursDerkintis/Starfly
Starfly/HistoryHit+CoreDataProperties.swift
1
601
// // HistoryHit+CoreDataProperties.swift // Starfly // // Created by Arturs Derkintis on 3/16/16. // Copyright © 2016 Starfly. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension HistoryHit { @NSManaged var date: NSDate? @NSManaged var faviconPath: String? @NSManaged var time: String? @NSManaged var titleOfIt: String? @NSManaged var urlOfIt: String? @NSManaged var arrangeIndex: NSNumber? }
mit
CosmicMind/Samples
Projects/Programmatic/ToolbarController/ToolbarController/SearchViewController.swift
1
2309
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class SearchViewController: UIViewController { let v1 = UIView() open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // v1.depthPreset = .depth3 v1.cornerRadiusPreset = .none v1.motionIdentifier = "v1" v1.backgroundColor = Color.green.base view.layout(v1).centerHorizontally().top().horizontally().height(100) prepareToolbar() } } extension SearchViewController { fileprivate func prepareToolbar() { guard let toolbar = toolbarController?.toolbar else { return } toolbar.title = "Search" } }
bsd-3-clause
AmirDaliri/BaboonProject
Baboon/Baboon/AppDelegate.swift
1
1852
// // AppDelegate.swift // Baboon // // Created by Amir Daliri on 3/21/17. // Copyright © 2017 Baboon. All rights reserved. // import UIKit import XCGLogger import MMDrawerController // TODO: Fix coloring let log: XCGLogger = { let log = XCGLogger.default log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil, fileLevel: .debug) return log }() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? var drawerController: MMDrawerController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = .lightContent let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let centerViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoadingController") as! LoadingController let leftViewController = mainStoryboard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController let leftNav = UINavigationController(rootViewController: leftViewController) let centerNav = UINavigationController(rootViewController: centerViewController) drawerController = MMDrawerController(center: centerNav, leftDrawerViewController: leftNav) drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.all drawerController!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.all; // drawerController!.showsShadow = true drawerController!.setMaximumLeftDrawerWidth(180, animated: true, completion: nil) window!.rootViewController = drawerController window!.makeKeyAndVisible() return true } }
mit
fanyu/EDCCharla
EDCChat/EDCChat/EDCChatMessage.swift
1
2435
// // EDCChatMessage.swift // EDCChat // // Created by FanYu on 11/12/2015. // Copyright © 2015 FanYu. All rights reserved. // import UIKit let EDCChatMessageStatusChangedNotification = "EDCChatMessageStatusChangedNofitication" struct EDCChatMessageOption { // none static var None: Int { return 0x0000 } // 消息静音 static var Mute: Int { return 0x0001 } // 消息隐藏(透明的) static var Hidden: Int { return 0x0010 } // 名片强制显示 static var ContactShow: Int { return 0x0100 } // 名片强制隐藏 static var ContactHidden: Int { return 0x0200 } // 名片根据环境自动显示/隐藏 static var ContactAutomatic: Int { return 0x0400 } } @objc enum EDCChatMessageStatus: Int { case Unknow case Sending case Sent case Unread case Receiving case Received case Read case Played case Destoryed case Error } @objc protocol EDCChatMessageProtocol { var identifier: String { get } var sender: EDCChatUserProtocol? { get } var receiver: EDCChatUserProtocol? { get } var sentTime: NSDate { get } var receiveTime: NSDate { get } var status: EDCChatMessageStatus { get } var content: EDCChatMessageContentProtocol { get } var option: Int { get } var ownership: Bool { get } var height: CGFloat { set get } } class EDCChatMessage: NSObject, EDCChatMessageProtocol { var identifier: String = NSUUID().UUIDString var sender: EDCChatUserProtocol? var receiver: EDCChatUserProtocol? var sentTime: NSDate = .zero var receiveTime: NSDate = .zero var status: EDCChatMessageStatus = .Unknow var content: EDCChatMessageContentProtocol var option: Int = 0 var ownership: Bool = false var height: CGFloat = 0 override init() { self.content = EDCChatMessageContentUnknow() super.init() } init(content: EDCChatMessageContentProtocol) { self.content = content super.init() } } extension EDCChatMessage { func makeDateWithMessage(message: EDCChatMessage) { } } extension EDCChatMessage { func statusChanged() { EDCChatNotificationCenter.postNotificationName(EDCChatMessageStatusChangedNotification, object: self) } } func ==(lhs: EDCChatMessage?, rhs: EDCChatMessage?) -> Bool { return lhs === rhs || lhs?.identifier == rhs?.identifier }
mit
Drusy/auvergne-webcams-ios
Carthage/Checkouts/Siren/Sources/Extensions/SirenLocalizationExtension.swift
1
1935
// // SirenLocalizationExtension.swift // Siren // // Created by Arthur Sabintsev on 9/25/18. // Copyright © 2018 Sabintsev iOS Projects. All rights reserved. // import Foundation // MARK: - Helpers (Localization) extension Siren { func localizedUpdateTitle() -> String { return Bundle.localizedString(forKey: alertMessaging.updateTitle.string, forceLanguageLocalization: forceLanguageLocalization) ?? alertMessaging.updateTitle.string } func localizedNewVersionMessage() -> String { let newVersionMessage = Bundle.localizedString(forKey: alertMessaging.updateMessage.string, forceLanguageLocalization: forceLanguageLocalization) ?? alertMessaging.updateMessage.string guard let currentAppStoreVersion = currentAppStoreVersion else { return String(format: newVersionMessage, appName, "Unknown") } return String(format: newVersionMessage, appName, currentAppStoreVersion) } func localizedUpdateButtonTitle() -> String? { return Bundle.localizedString(forKey: alertMessaging.updateButtonMessage.string, forceLanguageLocalization: forceLanguageLocalization) ?? alertMessaging.updateButtonMessage.string } func localizedNextTimeButtonTitle() -> String? { return Bundle.localizedString(forKey: alertMessaging.nextTimeButtonMessage.string, forceLanguageLocalization: forceLanguageLocalization) ?? alertMessaging.nextTimeButtonMessage.string } func localizedSkipButtonTitle() -> String? { return Bundle.localizedString(forKey: alertMessaging.skipVersionButtonMessage.string, forceLanguageLocalization: forceLanguageLocalization) ?? alertMessaging.skipVersionButtonMessage.string } }
apache-2.0
morizotter/MZRSnappySample
MZRSnappySample/MZRSnappySample/ViewController.swift
1
1713
// // ViewController.swift // MZRSnappySample // // Created by MORITA NAOKI on 2014/11/01. // Copyright (c) 2014年 molabo. All rights reserved. // import UIKit import Snappy class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // FULL SCREEN VIEW [BLUE] let blueView = UIView() blueView.backgroundColor = UIColor.blueColor() self.view.addSubview(blueView) blueView.snp_makeConstraints { make in make.edges.equalTo(self.view) return } // PADDING ALL EDGES [ORANGE] let orangeView = UIView() orangeView.backgroundColor = UIColor.orangeColor() self.view.addSubview(orangeView) let orangeViewPadding = UIEdgeInsetsMake(10, 10, 10, 10) orangeView.snp_makeConstraints { make in make.edges.equalTo(self.view).with.insets(orangeViewPadding) return } // VIEW ON PADDING VIEW [GREEN] let greenView = UIView() greenView.backgroundColor = UIColor.greenColor() orangeView.addSubview(greenView) let greenViewPadding = UIEdgeInsetsMake(0.0, 0.0, 150.0, 10.0) greenView.snp_makeConstraints { make in make.top.equalTo(orangeView.snp_top).with.offset(greenViewPadding.top) make.left.equalTo(orangeView.snp_left).with.offset(greenViewPadding.left) make.bottom.equalTo(orangeView.snp_bottom).with.offset(-greenViewPadding.bottom) make.right.equalTo(orangeView.snp_right).with.offset(-greenViewPadding.right) return } } }
mit
youngsoft/TangramKit
TangramKit/TGFlowLayout.swift
1
105640
// // TGFlowLayout.swift // TangramKit // // Created by apple on 16/3/13. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit /** *流式布局是一种里面的子视图按照添加的顺序依次排列,当遇到某种约束限制后会另起一排再重新排列的多行多列展示的布局视图。这里的约束限制主要有数量约束限制和内容尺寸约束限制两种,排列的方向又分为垂直和水平方向,因此流式布局一共有垂直数量约束流式布局、垂直内容约束流式布局、水平数量约束流式布局、水平内容约束流式布局。流式布局主要应用于那些有规律排列的场景,在某种程度上可以作为UICollectionView的替代品。 1.垂直数量约束流式布局 tg_orientation=.vert,tg_arrangedCount>0 每排数量为3的垂直数量约束流式布局 => +------+---+-----+ | A | B | C | +---+--+-+-+-----+ | D | E | F | | +---+-+--+--+----+ v | G | H | I | +-----+-----+----+ 2.垂直内容约束流式布局. tg_orientation = .vert,tg_arrangedCount = 0 垂直内容约束流式布局 => +-----+-----------+ | A | B | +-----+-----+-----+ | C | D | E | | +-----+-----+-----+ v | F | +-----------------+ 3.水平数量约束流式布局。 tg_orientation = .horz,tg_arrangedCount > 0 每排数量为3的水平数量约束流式布局 => +-----+----+-----+ | A | D | | | |----| G | |-----| | | | | B | E |-----| V |-----| | | | |----| H | | C | |-----| | | F | I | +-----+----+-----+ 4.水平内容约束流式布局 tg_orientation = .horz,arrangedCount = 0 水平内容约束流式布局 => +-----+----+-----+ | A | C | | | |----| | |-----| | | | | | D | | V | | | F | | B |----| | | | | | | | E | | +-----+----+-----+ 流式布局中排的概念是一个通用的称呼,对于垂直方向的流式布局来说一排就是一行,垂直流式布局每排依次从上到下排列,每排内的子视图则是由左往右依次排列;对于水平方向的流式布局来说一排就是一列,水平流式布局每排依次从左到右排列,每排内的子视图则是由上往下依次排列 */ open class TGFlowLayout:TGBaseLayout,TGFlowLayoutViewSizeClass { /** *初始化一个流式布局并指定布局的方向和布局的数量,如果数量为0则表示内容约束流式布局 */ public convenience init(_ orientation:TGOrientation = TGOrientation.vert, arrangedCount:Int = 0) { self.init(frame:CGRect.zero, orientation:orientation, arrangedCount:arrangedCount) } public init(frame: CGRect, orientation:TGOrientation = TGOrientation.vert, arrangedCount:Int = 0) { super.init(frame:frame) let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass lsc.tg_orientation = orientation lsc.tg_arrangedCount = arrangedCount } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** *流式布局的布局方向 *如果是.vert则表示每排先从左到右,再从上到下的垂直布局方式,这个方式是默认方式。 *如果是.horz则表示每排先从上到下,在从左到右的水平布局方式。 */ public var tg_orientation:TGOrientation { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_orientation } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_orientation != newValue) { lsc.tg_orientation = newValue setNeedsLayout() } } } /** *指定方向上的子视图的数量,默认是0表示为内容约束流式布局,当数量不为0时则是数量约束流式布局。当值为0时则表示当子视图在方向上的尺寸超过布局视图时则会新起一排。而如果数量不为0时则: 如果方向为.vert,则表示从左到右的数量,当子视图从左往右满足这个数量后新的子视图将会新起一排 如果方向为.horz,则表示从上到下的数量,当子视图从上往下满足这个数量后新的子视图将会新起一排 */ public var tg_arrangedCount:Int { //get/set方法 get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_arrangedCount } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_arrangedCount != newValue) { lsc.tg_arrangedCount = newValue setNeedsLayout() } } } /** *为流式布局提供分页展示的能力,默认是0表不支持分页展示,当设置为非0时则要求必须是tg_arrangedCount的整数倍数,表示每页的子视图的数量。而tg_arrangedCount则表示每排的子视图的数量。当启用tg_pagedCount时要求将流式布局加入到UIScrollView或者其派生类中才能生效。只有数量约束流式布局才支持分页展示的功能,tg_pagedCount和tg_height.isWrap以及tg_width.isWrap配合使用能实现不同的分页展示能力: 1.垂直数量约束流式布局的tg_height设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的宽度你也可以自定义),整体的分页滚动是从上到下滚动。(每页布局时从左到右再从上到下排列,新页往下滚动继续排列): 1 2 3 4 5 6 ------- ↓ 7 8 9 10 11 12 2.垂直数量约束流式布局的tg_width设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的高度你也可以自定义),整体的分页滚动是从左到右滚动。(每页布局时从左到右再从上到下排列,新页往右滚动继续排列) 1 2 3 | 7 8 9 4 5 6 | 10 11 12 → 1.水平数量约束流式布局的tg_width设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的高度你也可以自定义),整体的分页滚动是从左到右滚动。(每页布局时从上到下再从左到右排列,新页往右滚动继续排列) 1 3 5 | 7 9 11 2 4 6 | 8 10 12 → 2.水平数量约束流式布局的tg_height设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的宽度你也可以自定义),整体的分页滚动是从上到下滚动。(每页布局时从上到下再从左到右排列,新页往下滚动继续排列) 1 3 5 2 4 6 --------- ↓ 7 9 11 8 10 12 */ public var tg_pagedCount:Int { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_pagedCount } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_pagedCount != newValue) { lsc.tg_pagedCount = newValue setNeedsLayout() } } } /** *子视图自动排列,这个属性只有在内容填充约束流式布局下才有用,默认为false.当设置为YES时则根据子视图的内容自动填充,而不是根据加入的顺序来填充,以便保证不会出现多余空隙的情况。 *请在将所有子视图添加完毕并且初始布局完成后再设置这个属性,否则如果预先设置这个属性则在后续添加子视图时非常耗性能。 */ public var tg_autoArrange:Bool { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_autoArrange } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_autoArrange != newValue) { lsc.tg_autoArrange = newValue setNeedsLayout() } } } /** *设置流式布局中每排子视图的对齐方式。 如果布局的方向是.vert则表示每排子视图的上中下对齐方式,这里的对齐基础是以每排中的最高的子视图为基准。这个属性只支持: TGGravity.vert.top 顶部对齐 TGGravity.vert.center 垂直居中对齐 TGGravity.vert.bottom 底部对齐 TGGravity.vert.fill 两端对齐 如果布局的方向是.horz则表示每排子视图的左中右对齐方式,这里的对齐基础是以每排中的最宽的子视图为基准。这个属性只支持: TGGravity.horz.left 左边对齐 TGGravity.horz.center 水平居中对齐 TGGravity.horz.right 右边对齐 TGGravity.horz.fill 两端对齐 */ public var tg_arrangedGravity:TGGravity { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_arrangedGravity } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_arrangedGravity != newValue) { lsc.tg_arrangedGravity = newValue setNeedsLayout() } } } /** * 指定流式布局最后一行的尺寸或间距的拉伸策略。默认值是TGGravityPolicy.no表示最后一行的尺寸或间接拉伸策略不生效。 在流式布局中我们可以通过tg_gravity属性来对每一行的尺寸或间距进行拉伸处理。但是在实际情况中最后一行的子视图数量可能会小于等于前面行的数量。 在这种情况下如果对最后一行进行相同的尺寸或间距的拉伸处理则有可能会影响整体的布局效果。因此我们可通过这个属性来指定最后一行的尺寸或间距的生效策略。 这个策略在不同的流式布局中效果不一样: 1.在数量约束布局中如果最后一行的子视图数量小于tg_arrangedCount的值时,那么当我们使用tg_gravity来对行内视图进间距拉伸时(between,around,among) 可以指定三种策略:no表示最后一行不进行任何间距拉伸处理,always表示最后一行总是进行间距拉伸处理,auto表示最后一行的每个子视图都和上一行对应位置视图左对齐。 2.在内容约束布局中因为每行的子视图数量不固定,所以只有no和always两种策略有效,并且这两种策略不仅影响子视图的尺寸的拉伸(fill)还影响间距的拉伸效果(between,around,among)。 */ public var tg_lastlineGravityPolicy:TGGravityPolicy { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_lastlineGravityPolicy } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_lastlineGravityPolicy != newValue) { lsc.tg_lastlineGravityPolicy = newValue setNeedsLayout() } } } /** *在流式布局的一些应用场景中我们有时候希望某些子视图的宽度或者高度是固定的情况下,子视图的间距是浮动的而不是固定的。比如每个子视图的宽度是固定80,那么在小屏幕下每行只能放3个,而我们希望大屏幕每行能放4个或者5个子视图。 因此您可以通过如下方法来设置浮动间距,这个方法会根据您当前布局的orientation方向不同而意义不同: 1.如果您的布局方向是.vert表示设置的是子视图的水平间距,其中的size指定的是子视图的宽度,minSpace指定的是最小的水平间距,maxSpace指定的是最大的水平间距,如果指定的subviewSize计算出的间距大于这个值则会调整subviewSize的宽度。 2.如果您的布局方向是.horz表示设置的是子视图的垂直间距,其中的size指定的是子视图的高度,minSpace指定的是最小的垂直间距,maxSpace指定的是最大的垂直间距,如果指定的subviewSize计算出的间距大于这个值则会调整subviewSize的高度。 3.如果您不想使用浮动间距则请将subviewSize设置为0就可以了。 4.对于数量约束流式布局来说,因为每行和每列的数量的固定的,因此不存在根据屏幕的大小自动换行的能力以及进行最佳数量的排列,但是可以使用这个方法来实现所有子视图尺寸固定但是间距是浮动的功能需求。 5. centered属性指定这个浮动间距是否包括最左边和最右边两个区域,也就是说当设置为true时视图之间以及视图与父视图之间的间距都是相等的,而设置为false时则只有视图之间的间距相等而视图与父视图之间的间距则为0。 */ public func tg_setSubviews(size:CGFloat, minSpace:CGFloat, maxSpace:CGFloat = CGFloat.greatestFiniteMagnitude, centered:Bool = false, inSizeClass type:TGSizeClassType = TGSizeClassType.default) { let lsc = self.tg_fetchSizeClass(with: type) as! TGFlowLayoutViewSizeClassImpl if size == 0.0 { lsc.tgFlexSpace = nil } else { if lsc.tgFlexSpace == nil { lsc.tgFlexSpace = TGSequentLayoutFlexSpace() } lsc.tgFlexSpace.subviewSize = size lsc.tgFlexSpace.minSpace = minSpace lsc.tgFlexSpace.maxSpace = maxSpace lsc.tgFlexSpace.centered = centered } self.setNeedsLayout() } override internal func tgCalcLayoutRect(_ size:CGSize, isEstimate:Bool, hasSubLayout:inout Bool!, sbs:[UIView]!, type :TGSizeClassType) -> CGSize { var selfSize = super.tgCalcLayoutRect(size, isEstimate:isEstimate, hasSubLayout:&hasSubLayout, sbs:sbs, type:type) var sbs:[UIView]! = sbs if sbs == nil { sbs = self.tgGetLayoutSubviews() } let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClassImpl for sbv:UIView in sbs { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate { sbvtgFrame.frame = sbv.bounds self.tgCalcSizeFromSizeWrapSubview(sbv, sbvsc:sbvsc, sbvtgFrame: sbvtgFrame) } if let sbvl:TGBaseLayout = sbv as? TGBaseLayout { if sbvsc.width.isWrap { if (lsc.tg_pagedCount > 0 || (lsc.tg_orientation == TGOrientation.horz && (lsc.tg_arrangedGravity & TGGravity.vert.mask) == TGGravity.horz.fill) || (lsc.tg_orientation == TGOrientation.vert && ((lsc.tg_gravity & TGGravity.vert.mask) == TGGravity.horz.fill))) { sbvsc.width.resetValue() } } if sbvsc.height.isWrap { if (lsc.tg_pagedCount > 0 || (lsc.tg_orientation == TGOrientation.vert && (lsc.tg_arrangedGravity & TGGravity.horz.mask) == TGGravity.vert.fill) || (lsc.tg_orientation == TGOrientation.horz && ((lsc.tg_gravity & TGGravity.horz.mask) == TGGravity.vert.fill))) { sbvsc.height.resetValue() } } if hasSubLayout != nil && sbvsc.isSomeSizeWrap { hasSubLayout = true } if isEstimate && sbvsc.isSomeSizeWrap { _ = sbvl.tg_sizeThatFits(sbvtgFrame.frame.size,inSizeClass:type) if sbvtgFrame.multiple { sbvtgFrame.sizeClass = sbv.tgMatchBestSizeClass(type) //因为tg_sizeThatFits执行后会还原,所以这里要重新设置 } } } } if lsc.tg_orientation == TGOrientation.vert { if lsc.tg_arrangedCount == 0 { if (lsc.tg_autoArrange) { //计算出每个子视图的宽度。 for sbv in sbs { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame rect.size.width = sbvsc.width.numberSize(rect.size.width) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) //暂时把宽度存放sbvtgFrame.trailing上。因为浮动布局来说这个属性无用。 sbvtgFrame.trailing = leadingSpace + rect.size.width + trailingSpace; if _tgCGFloatGreat(sbvtgFrame.trailing , selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) { sbvtgFrame.trailing = selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding; } } let tempSbs:NSMutableArray = NSMutableArray(array: sbs) sbs = self.tgGetAutoArrangeSubviews(tempSbs, selfSize:selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding, space: lsc.tg_hspace) as? [UIView] } selfSize = self.tgLayoutSubviewsForVertContent(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } else { selfSize = self.tgLayoutSubviewsForVert(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } } else { if lsc.tg_arrangedCount == 0 { if (lsc.tg_autoArrange) { //计算出每个子视图的宽度。 for sbv in sbs { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let topSpace = sbvsc.top.absPos let bottomSpace = sbvsc.bottom.absPos var rect = sbvtgFrame.frame; rect.size.width = sbvsc.width.numberSize(rect.size.width) rect.size.height = sbvsc.height.numberSize(rect.size.height) rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize,sbvsc:sbvsc,lsc:lsc, rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) //如果高度是浮动的则需要调整高度。 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } //暂时把宽度存放sbvtgFrame.trailing上。因为浮动布局来说这个属性无用。 sbvtgFrame.trailing = topSpace + rect.size.height + bottomSpace; if _tgCGFloatGreat(sbvtgFrame.trailing, selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) { sbvtgFrame.trailing = selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding } } let tempSbs:NSMutableArray = NSMutableArray(array: sbs) sbs = self.tgGetAutoArrangeSubviews(tempSbs, selfSize:selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding, space: lsc.tg_vspace) as? [UIView] } selfSize = self.tgLayoutSubviewsForHorzContent(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } else { selfSize = self.tgLayoutSubviewsForHorz(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } } tgAdjustLayoutSelfSize(selfSize: &selfSize, lsc: lsc) tgAdjustSubviewsLayoutTransform(sbs: sbs, lsc: lsc, selfSize: selfSize) tgAdjustSubviewsRTLPos(sbs: sbs, selfWidth: selfSize.width) return self.tgAdjustSizeWhenNoSubviews(size: selfSize, sbs: sbs, lsc:lsc) } internal override func tgCreateInstance() -> AnyObject { return TGFlowLayoutViewSizeClassImpl(view:self) } } extension TGFlowLayout { fileprivate func tgCalcSinglelineSize(_ sbs:NSArray, space:CGFloat) ->CGFloat { var size:CGFloat = 0; for i in 0..<sbs.count { let sbv = sbs[i] as! UIView size += sbv.tgFrame.trailing; if (sbv != sbs.lastObject as! UIView) { size += space } } return size; } fileprivate func tgGetAutoArrangeSubviews(_ sbs:NSMutableArray, selfSize:CGFloat, space:CGFloat) ->NSArray { let retArray:NSMutableArray = NSMutableArray(capacity: sbs.count) let bestSinglelineArray:NSMutableArray = NSMutableArray(capacity: sbs.count / 2) while (sbs.count > 0) { self.tgGetAutoArrangeSinglelineSubviews(sbs, index:0, calcArray:NSArray(), selfSize:selfSize, space:space, bestSinglelineArray:bestSinglelineArray) retArray.addObjects(from: bestSinglelineArray as [AnyObject]) bestSinglelineArray.forEach({ (obj) -> () in sbs.remove(obj) }) bestSinglelineArray.removeAllObjects() } return retArray; } fileprivate func tgGetAutoArrangeSinglelineSubviews(_ sbs:NSMutableArray,index:Int,calcArray:NSArray,selfSize:CGFloat,space:CGFloat,bestSinglelineArray:NSMutableArray) { if (index >= sbs.count) { let s1 = self.tgCalcSinglelineSize(calcArray, space:space) let s2 = self.tgCalcSinglelineSize(bestSinglelineArray, space:space) if _tgCGFloatLess(abs(selfSize - s1) , abs(selfSize - s2)) && _tgCGFloatLessOrEqual(s1, selfSize) { bestSinglelineArray.setArray(calcArray as [AnyObject]) } return; } for i in index ..< sbs.count { let calcArray2 = NSMutableArray(array: calcArray) calcArray2.add(sbs[i]) let s1 = self.tgCalcSinglelineSize(calcArray2,space:space) if ( _tgCGFloatLessOrEqual(s1, selfSize)) { let s2 = self.tgCalcSinglelineSize(bestSinglelineArray,space:space) if _tgCGFloatLess(abs(selfSize - s1) , abs(selfSize - s2)) { bestSinglelineArray.setArray(calcArray2 as [AnyObject]) } if ( _tgCGFloatEqual(s1, selfSize)) { break; } self.tgGetAutoArrangeSinglelineSubviews(sbs, index:i + 1, calcArray:calcArray2, selfSize:selfSize, space:space, bestSinglelineArray:bestSinglelineArray) } else { break; } } } //计算Vert下每行的对齐方式 fileprivate func tgCalcVertLayoutSinglelineAlignment(_ selfSize:CGSize, rowMaxHeight:CGFloat, rowMaxWidth:CGFloat, horzGravity:TGGravity, vertAlignment:TGGravity, sbs:[UIView], startIndex:Int, count:Int,vertSpace:CGFloat, horzSpace:CGFloat, horzPadding:CGFloat, isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl) { var addXPos:CGFloat = 0 var addXPosInc:CGFloat = 0 var addXFill:CGFloat = 0 let averageArrange = (horzGravity == TGGravity.horz.fill) //只有最后一行,并且数量小于tg_arrangedCount,并且不是第一行才应用策略。 let applyLastlineGravityPolicy:Bool = (startIndex == sbs.count && count != lsc.tg_arrangedCount && (horzGravity == TGGravity.horz.between || horzGravity == TGGravity.horz.around || horzGravity == TGGravity.horz.among || horzGravity == TGGravity.horz.fill)) //处理 对其方式 if !averageArrange || lsc.tg_arrangedCount == 0 { switch horzGravity { case TGGravity.horz.center: addXPos = (selfSize.width - horzPadding - rowMaxWidth)/2 break case TGGravity.horz.trailing: //不用考虑左边距,而原来的位置增加了左边距 因此不用考虑 addXPos = selfSize.width - horzPadding - rowMaxWidth break case TGGravity.horz.between: if count > 1 && (!applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always) { addXPosInc = (selfSize.width - horzPadding - rowMaxWidth)/(CGFloat(count) - 1) } break case TGGravity.horz.around: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addXPosInc = (selfSize.width - horzPadding - rowMaxWidth)/CGFloat(count) addXPos = addXPosInc / 2.0 } else { addXPos = (selfSize.width - horzPadding - rowMaxWidth) / 2.0 } } break case TGGravity.horz.among: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addXPosInc = (selfSize.width - horzPadding - rowMaxWidth)/CGFloat(count + 1) addXPos = addXPosInc } else { addXPos = (selfSize.width - horzPadding - rowMaxWidth) / 2.0 } } break default: break } //处理内容拉伸的情况 if lsc.tg_arrangedCount == 0 && averageArrange && count > 0 { if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { addXFill = (selfSize.width - horzPadding - rowMaxWidth)/CGFloat(count) } } } //调整 整行子控件的位置 for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate && self.tg_intelligentBorderline != nil { if let sbvl = sbv as? TGBaseLayout { if !sbvl.tg_notUseIntelligentBorderline { sbvl.tg_leadingBorderline = nil sbvl.tg_topBorderline = nil sbvl.tg_trailingBorderline = nil sbvl.tg_bottomBorderline = nil //如果不是最后一行就画下面, if (startIndex != sbs.count) { sbvl.tg_bottomBorderline = self.tg_intelligentBorderline; } //如果不是最后一列就画右边, if (j < startIndex - 1) { sbvl.tg_trailingBorderline = self.tg_intelligentBorderline; } //如果最后一行的最后一个没有满列数时 if (j == sbs.count - 1 && lsc.tg_arrangedCount != count ) { sbvl.tg_trailingBorderline = self.tg_intelligentBorderline; } //如果有垂直间距则不是第一行就画上 if (vertSpace != 0 && startIndex - count != 0) { sbvl.tg_topBorderline = self.tg_intelligentBorderline; } //如果有水平间距则不是第一列就画左 if (horzSpace != 0 && j != startIndex - count) { sbvl.tg_leadingBorderline = self.tg_intelligentBorderline; } } } } //为子视图设置单独的对齐方式 var sbvVertAlignment = sbvsc.tg_alignment & TGGravity.horz.mask if sbvVertAlignment == TGGravity.none { sbvVertAlignment = vertAlignment } if vertAlignment == TGGravity.vert.between { sbvVertAlignment = vertAlignment } if (sbvVertAlignment != TGGravity.none && sbvVertAlignment != TGGravity.vert.top) || _tgCGFloatNotEqual(addXPos, 0) || _tgCGFloatNotEqual(addXFill, 0) || _tgCGFloatNotEqual(addXPosInc, 0) || applyLastlineGravityPolicy { sbvtgFrame.leading += addXPos if lsc.tg_arrangedCount == 0 && averageArrange { //只拉伸宽度 不拉伸间距 sbvtgFrame.width += addXFill if j != startIndex - count { sbvtgFrame.leading += addXFill * CGFloat(j - (startIndex - count)) } } else { //只拉伸间距 sbvtgFrame.leading += addXPosInc * CGFloat(j - (startIndex - count)) if (startIndex - count) > 0 && applyLastlineGravityPolicy && lsc.tg_lastlineGravityPolicy == TGGravityPolicy.auto { //对齐前一行对应位置的 sbvtgFrame.leading = sbs[j - lsc.tg_arrangedCount].tgFrame.leading } } let topSpace = sbvsc.top.absPos let bottomSpace = sbvsc.bottom.absPos switch sbvVertAlignment { case TGGravity.vert.center: sbvtgFrame.top += (rowMaxHeight - topSpace - bottomSpace - sbvtgFrame.height) / 2 break case TGGravity.vert.bottom: sbvtgFrame.top += rowMaxHeight - topSpace - bottomSpace - sbvtgFrame.height break case TGGravity.vert.fill: sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rowMaxHeight - topSpace - bottomSpace, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) break default: break } } } } //计算Horz下每行的水平对齐方式。 fileprivate func tgCalcHorzLayoutSinglelineAlignment(_ selfSize:CGSize, colMaxHeight:CGFloat, colMaxWidth:CGFloat, vertGravity:TGGravity, horzAlignment:TGGravity, sbs:[UIView], startIndex:Int, count:Int, vertSpace:CGFloat, horzSpace:CGFloat, vertPadding:CGFloat, isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl) { var addYPos:CGFloat = 0 var addYPosInc:CGFloat = 0 var addYFill:CGFloat = 0 let averageArrange = (vertGravity == TGGravity.vert.fill) //只有最后一行,并且数量小于tg_arrangedCount,并且不是第一行才应用策略。 let applyLastlineGravityPolicy:Bool = (startIndex == sbs.count && count != lsc.tg_arrangedCount && (vertGravity == TGGravity.vert.between || vertGravity == TGGravity.vert.around || vertGravity == TGGravity.vert.among || vertGravity == TGGravity.vert.fill)) if !averageArrange || lsc.tg_arrangedCount == 0 { switch vertGravity { case TGGravity.vert.center: addYPos = (selfSize.height - vertPadding - colMaxHeight)/2 break case TGGravity.vert.bottom: addYPos = selfSize.height - vertPadding - colMaxHeight break case TGGravity.vert.between: if count > 1 && (!applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always) { addYPosInc = (selfSize.height - vertPadding - colMaxHeight)/(CGFloat(count) - 1) } break case TGGravity.vert.around: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addYPosInc = (selfSize.height - vertPadding - colMaxHeight)/CGFloat(count) addYPos = addYPosInc / 2.0 } else { addYPos = (selfSize.height - vertPadding - colMaxHeight) / 2.0 } } break case TGGravity.vert.among: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addYPosInc = (selfSize.height - vertPadding - colMaxHeight)/CGFloat(count + 1) addYPos = addYPosInc } else { addYPos = (selfSize.height - vertPadding - colMaxHeight) / 2.0 } } break default: break } //处理内容拉伸的情况 if lsc.tg_arrangedCount == 0 && averageArrange && count > 0 { if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { addYFill = (selfSize.height - vertPadding - colMaxHeight)/CGFloat(count) } } } //调整位置 for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate && self.tg_intelligentBorderline != nil { if let sbvl = sbv as? TGBaseLayout { if !sbvl.tg_notUseIntelligentBorderline { sbvl.tg_leadingBorderline = nil sbvl.tg_topBorderline = nil sbvl.tg_trailingBorderline = nil sbvl.tg_bottomBorderline = nil //如果不是最后一行就画下面, if (j < startIndex - 1) { sbvl.tg_bottomBorderline = self.tg_intelligentBorderline; } //如果不是最后一列就画右边, if (startIndex != sbs.count ) { sbvl.tg_trailingBorderline = self.tg_intelligentBorderline; } //如果最后一行的最后一个没有满列数时 if (j == sbs.count - 1 && lsc.tg_arrangedCount != count ) { sbvl.tg_bottomBorderline = self.tg_intelligentBorderline; } //如果有垂直间距则不是第一行就画上 if (vertSpace != 0 && j != startIndex - count) { sbvl.tg_topBorderline = self.tg_intelligentBorderline } //如果有水平间距则不是第一列就画左 if (horzSpace != 0 && startIndex - count != 0 ) { sbvl.tg_leadingBorderline = self.tg_intelligentBorderline; } } } } //为子视图设置单独的对齐方式 var sbvHorzAlignment = self.tgConvertLeftRightGravityToLeadingTrailing(sbvsc.tg_alignment & TGGravity.vert.mask) if sbvHorzAlignment == TGGravity.none { sbvHorzAlignment = horzAlignment } if horzAlignment == TGGravity.vert.between { sbvHorzAlignment = horzAlignment } if (sbvHorzAlignment != TGGravity.none && sbvHorzAlignment != TGGravity.horz.leading) || _tgCGFloatNotEqual(addYPos, 0) || _tgCGFloatNotEqual(addYFill, 0) || _tgCGFloatNotEqual(addYPosInc, 0) || applyLastlineGravityPolicy { sbvtgFrame.top += addYPos if lsc.tg_arrangedCount == 0 && averageArrange { //只拉伸宽度不拉伸间距 sbvtgFrame.height += addYFill if j != startIndex - count { sbvtgFrame.top += addYFill * CGFloat(j - (startIndex - count)) } } else { //只拉伸间距 sbvtgFrame.top += addYPosInc * CGFloat(j - (startIndex - count)) if (startIndex - count) > 0 && applyLastlineGravityPolicy && lsc.tg_lastlineGravityPolicy == TGGravityPolicy.auto { //对齐前一行对应位置的 sbvtgFrame.top = sbs[j - lsc.tg_arrangedCount].tgFrame.top } } let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos switch sbvHorzAlignment { case TGGravity.horz.center: sbvtgFrame.leading += (colMaxWidth - leadingSpace - trailingSpace - sbvtgFrame.width)/2 break case TGGravity.horz.trailing: sbvtgFrame.leading += colMaxWidth - leadingSpace - trailingSpace - sbvtgFrame.width break case TGGravity.horz.fill: sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: colMaxWidth - leadingSpace - trailingSpace, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) break default: break } } } } fileprivate func tgCalcVertLayoutSinglelineWeight(selfSize:CGSize, totalFloatWidth:CGFloat, totalWeight:CGFloat,sbs:[UIView],startIndex:NSInteger, count:NSInteger) { var totalFloatWidth = totalFloatWidth var totalWeight = totalWeight for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if sbvsc.width.weightVal != nil || sbvsc.width.isFill { var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal { widthWeight = t.rawValue/100 } let tempWidth = sbvsc.width.measure(_tgRoundNumber(totalFloatWidth * ( widthWeight / totalWeight))) totalFloatWidth -= tempWidth totalWeight -= widthWeight sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv:sbv,calcSize:tempWidth,sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width; } } } fileprivate func tgCalcHorzLayoutSinglelineWeight(selfSize:CGSize, totalFloatHeight:CGFloat, totalWeight:CGFloat,sbs:[UIView],startIndex:NSInteger, count:NSInteger) { var totalFloatHeight = totalFloatHeight var totalWeight = totalWeight for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal { heightWeight = t.rawValue / 100 } let tempHeight = sbvsc.height.measure(_tgRoundNumber(totalFloatHeight * ( heightWeight / totalWeight))) totalFloatHeight -= tempHeight totalWeight -= heightWeight sbvtgFrame.height = self.tgValidMeasure(sbvsc.height,sbv:sbv,calcSize:tempHeight,sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height; if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { sbvtgFrame.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:sbvsc.width.measure(sbvtgFrame.height),sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) } } } } fileprivate func tgLayoutSubviewsForVert(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize let autoArrange:Bool = lsc.tg_autoArrange let arrangedCount:Int = lsc.tg_arrangedCount var leadingPadding:CGFloat = lsc.tgLeadingPadding var trailingPadding:CGFloat = lsc.tgTrailingPadding let topPadding:CGFloat = lsc.tgTopPadding let bottomPadding:CGFloat = lsc.tgBottomPadding var vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask let horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let vertAlignment:TGGravity = lsc.tg_arrangedGravity & TGGravity.horz.mask var horzSpace = lsc.tg_hspace let vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,leadingPadding,trailingPadding,horzSpace) = t.calcMaxMinSubviewSize(selfSize.width, arrangedCount: arrangedCount, startPadding: leadingPadding, endPadding: trailingPadding, space: horzSpace) } var rowMaxHeight:CGFloat = 0 var rowMaxWidth:CGFloat = 0 var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var maxWidth = leadingPadding var maxHeight = topPadding //判断父滚动视图是否分页滚动 var isPagingScroll = false if let scrolv = self.superview as? UIScrollView, scrolv.isPagingEnabled { isPagingScroll = true } var pagingItemHeight:CGFloat = 0 var pagingItemWidth:CGFloat = 0 var isVertPaging = false var isHorzPaging = false if lsc.tg_pagedCount > 0 && self.superview != nil { let rows = CGFloat(lsc.tg_pagedCount / arrangedCount) //每页的行数。 //对于垂直流式布局来说,要求要有明确的宽度。因此如果我们启用了分页又设置了宽度包裹时则我们的分页是从左到右的排列。否则分页是从上到下的排列。 if lsc.width.isWrap { isHorzPaging = true if isPagingScroll { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - trailingPadding - CGFloat(arrangedCount - 1) * horzSpace ) / CGFloat(arrangedCount) } else { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - CGFloat(arrangedCount) * horzSpace ) / CGFloat(arrangedCount) } pagingItemHeight = (selfSize.height - topPadding - bottomPadding - (rows - 1) * vertSpace) / rows } else { isVertPaging = true pagingItemWidth = (selfSize.width - leadingPadding - trailingPadding - CGFloat(arrangedCount - 1) * horzSpace) / CGFloat(arrangedCount) //分页滚动时和非分页滚动时的高度计算是不一样的。 if (isPagingScroll) { pagingItemHeight = (self.superview!.bounds.height - topPadding - bottomPadding - (rows - 1) * vertSpace) / CGFloat(rows) } else { pagingItemHeight = (self.superview!.bounds.height - topPadding - rows * vertSpace) / rows } } } let averageArrange = (horzGravity == TGGravity.horz.fill) var arrangedIndex:Int = 0 var rowTotalWeight:CGFloat = 0 var rowTotalFixedWidth:CGFloat = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if (arrangedIndex >= arrangedCount) { arrangedIndex = 0; if (rowTotalWeight != 0 && !averageArrange) { self.tgCalcVertLayoutSinglelineWeight(selfSize:selfSize,totalFloatWidth:selfSize.width - leadingPadding - trailingPadding - rowTotalFixedWidth,totalWeight:rowTotalWeight,sbs:sbs,startIndex:i,count:arrangedCount) } rowTotalWeight = 0; rowTotalFixedWidth = 0; } let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame if sbvsc.width.weightVal != nil || sbvsc.width.isFill { if sbvsc.width.isFill { rowTotalWeight += 1.0 } else { rowTotalWeight += sbvsc.width.weightVal.rawValue / 100 } } else { if subviewSize != 0 { rect.size.width = subviewSize - leadingSpace - trailingSpace } if pagingItemWidth != 0 { rect.size.width = pagingItemWidth - leadingSpace - trailingSpace } if sbvsc.width.numberVal != nil && !averageArrange { rect.size.width = sbvsc.width.measure; } rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc,rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:rect.size.width,sbvSize:rect.size,selfLayoutSize:selfSize) rowTotalFixedWidth += rect.size.width; } rowTotalFixedWidth += leadingSpace + trailingSpace; if (arrangedIndex != (arrangedCount - 1)) { rowTotalFixedWidth += horzSpace } sbvtgFrame.frame = rect; arrangedIndex += 1 } //最后一行。 if (rowTotalWeight != 0 && !averageArrange) { //如果最后一行没有填满则应该减去一个间距的值。 if arrangedIndex < arrangedCount { rowTotalFixedWidth -= horzSpace } self.tgCalcVertLayoutSinglelineWeight(selfSize:selfSize,totalFloatWidth:selfSize.width - leadingPadding - trailingPadding - rowTotalFixedWidth,totalWeight:rowTotalWeight,sbs:sbs,startIndex:sbs.count, count:arrangedIndex) } var nextPointOfRows:[CGPoint]! = nil if autoArrange { nextPointOfRows = [CGPoint]() for _ in 0 ..< arrangedCount { nextPointOfRows.append(CGPoint(x:leadingPadding, y: topPadding)) } } var pageWidth:CGFloat = 0; //页宽 let averageWidth:CGFloat = (selfSize.width - leadingPadding - trailingPadding - (CGFloat(arrangedCount) - 1) * horzSpace) / CGFloat(arrangedCount) arrangedIndex = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) //换行 if arrangedIndex >= arrangedCount { arrangedIndex = 0 yPos += rowMaxHeight yPos += vertSpace //分别处理水平分页和垂直分页。 if (isHorzPaging) { if (i % lsc.tg_pagedCount == 0) { pageWidth += self.superview!.bounds.width if (!isPagingScroll) { pageWidth -= leadingPadding } yPos = topPadding } } if (isVertPaging) { //如果是分页滚动则要多添加垂直间距。 if (i % lsc.tg_pagedCount == 0) { if (isPagingScroll) { yPos -= vertSpace yPos += bottomPadding yPos += topPadding } } } xPos = leadingPadding + pageWidth //计算每行的gravity情况 self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex: i, count: arrangedCount, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding: leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) rowMaxHeight = 0 rowMaxWidth = 0 } let topSpace = sbvsc.top.absPos let leadingSpace = sbvsc.leading.absPos let bottomSpace = sbvsc.bottom.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame if (pagingItemHeight != 0) { rect.size.height = pagingItemHeight - topSpace - bottomSpace } rect.size.height = sbvsc.height.numberSize(rect.size.height) if averageArrange { rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: averageWidth - leadingSpace - trailingSpace, sbvSize: rect.size, selfLayoutSize:selfSize) } rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize,sbvsc:sbvsc,lsc:lsc, rect: rect) //如果高度是浮动的 则需要调整陶都 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } if sbvsc.height.weightVal != nil || sbvsc.height.isFill { var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal { heightWeight = t.rawValue/100 } rect.size.height = sbvsc.height.measure((selfSize.height - yPos - bottomPadding)*heightWeight - topSpace - bottomSpace) } rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) if _tgCGFloatLess(rowMaxHeight , topSpace + bottomSpace + rect.size.height) { rowMaxHeight = topSpace + bottomSpace + rect.size.height } if autoArrange { var minPt:CGPoint = CGPoint(x:CGFloat.greatestFiniteMagnitude, y:CGFloat.greatestFiniteMagnitude) var minNextPointIndex:Int = 0 for idx in 0 ..< arrangedCount { let pt = nextPointOfRows[idx] if minPt.y > pt.y { minPt = pt minNextPointIndex = idx } } xPos = minPt.x yPos = minPt.y minPt.y = minPt.y + topSpace + rect.size.height + bottomSpace + vertSpace nextPointOfRows[minNextPointIndex] = minPt if minNextPointIndex + 1 <= arrangedCount - 1 { minPt = nextPointOfRows[minNextPointIndex + 1] minPt.x = xPos + leadingSpace + rect.size.width + trailingSpace + horzSpace nextPointOfRows[minNextPointIndex + 1] = minPt } if _tgCGFloatLess(maxHeight, yPos + topSpace + rect.size.height + bottomSpace) { maxHeight = yPos + topSpace + rect.size.height + bottomSpace } } else if vertAlignment == TGGravity.vert.between { //当行是紧凑排行时需要特殊处理当前的垂直位置。 //第0行特殊处理。 if (i - arrangedCount < 0) { yPos = topPadding } else { //取前一行的对应的列的子视图。 let (prevSbvtgFrame, prevSbvsc) = self.tgGetSubviewFrameAndSizeClass(sbs[i - arrangedCount]) //当前子视图的位置等于前一行对应列的最大y的值 + 前面对应列的尾部间距 + 子视图之间的行间距。 yPos = prevSbvtgFrame.frame.maxY + prevSbvsc.bottom.absPos + vertSpace } if _tgCGFloatLess(maxHeight, yPos + topSpace + rect.size.height + bottomSpace) { maxHeight = yPos + topSpace + rect.size.height + bottomSpace } } else { maxHeight = yPos + rowMaxHeight } rect.origin.x = (xPos + leadingSpace) rect.origin.y = (yPos + topSpace) xPos += (leadingSpace + rect.size.width + trailingSpace) if _tgCGFloatLess(rowMaxWidth , xPos - leadingPadding) { rowMaxWidth = xPos - leadingPadding } if _tgCGFloatLess(maxWidth , xPos) { maxWidth = xPos } if arrangedIndex != (arrangedCount - 1) && !autoArrange { xPos += horzSpace } sbvtgFrame.frame = rect arrangedIndex += 1 } //最后一行 布局 self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex: sbs.count, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding: leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) maxHeight = maxHeight + bottomPadding if lsc.height.isWrap { selfSize.height = maxHeight //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isVertPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.height , totalPages * self.superview!.bounds.height) { selfSize.height = totalPages * self.superview!.bounds.height } } } else { var addYPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 let arranges = floor(CGFloat(sbs.count + arrangedCount - 1) / CGFloat(arrangedCount)) if arranges <= 1 && vertGravity == TGGravity.vert.around { vertGravity = TGGravity.vert.center } if vertGravity == TGGravity.vert.center { addYPos = (selfSize.height - maxHeight)/2 } else if vertGravity == TGGravity.vert.bottom { addYPos = selfSize.height - maxHeight } else if (vertGravity == TGGravity.vert.fill) { if (arranges > 0) { fill = (selfSize.height - maxHeight) / arranges } } else if (vertGravity == TGGravity.vert.between) { if (arranges > 1) { between = (selfSize.height - maxHeight) / (arranges - 1) } } else if (vertGravity == TGGravity.vert.around) { between = (selfSize.height - maxHeight) / arranges } else if (vertGravity == TGGravity.vert.among) { between = (selfSize.height - maxHeight) / (arranges + 1) } if addYPos != 0 || between != 0 || fill != 0 { for i in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame let line = i / arrangedCount sbvtgFrame.height += fill sbvtgFrame.top += fill * CGFloat(line) sbvtgFrame.top += addYPos sbvtgFrame.top += between * CGFloat(line) //如果是vert_around那么所有行都应该添加一半的between值。 if (vertGravity == TGGravity.vert.around) { sbvtgFrame.top += (between / 2.0) } if (vertGravity == TGGravity.vert.among) { sbvtgFrame.top += between } } } } if lsc.width.isWrap && !averageArrange { selfSize.width = maxWidth + trailingPadding //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isHorzPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.width , totalPages * self.superview!.bounds.width) { selfSize.width = totalPages * self.superview!.bounds.width } } } return selfSize } fileprivate func tgLayoutSubviewsForVertContent(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize var leadingPadding:CGFloat = lsc.tgLeadingPadding var trailingPadding:CGFloat = lsc.tgTrailingPadding let topPadding:CGFloat = lsc.tgTopPadding let bottomPadding:CGFloat = lsc.tgBottomPadding var vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask let horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let vertAlignment:TGGravity = lsc.tg_arrangedGravity & TGGravity.horz.mask var horzSpace = lsc.tg_hspace let vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,leadingPadding,trailingPadding,horzSpace) = t.calcMaxMinSubviewSizeForContent(selfSize.width, startPadding: leadingPadding, endPadding: trailingPadding, space: horzSpace) } var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var rowMaxHeight:CGFloat = 0 var rowMaxWidth:CGFloat = 0 var arrangeIndexSet = IndexSet() var arrangeIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let topSpace:CGFloat = sbvsc.top.absPos let leadingSpace:CGFloat = sbvsc.leading.absPos let bottomSpace:CGFloat = sbvsc.bottom.absPos let trailingSpace:CGFloat = sbvsc.trailing.absPos var rect:CGRect = sbvtgFrame.frame if subviewSize != 0 { rect.size.width = subviewSize - leadingSpace - trailingSpace } rect.size.width = sbvsc.width.numberSize(rect.size.width) rect.size.height = sbvsc.height.numberSize(rect.size.height) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal { heightWeight = t.rawValue/100 } rect.size.height = sbv.tg_height.measure((selfSize.height - yPos - bottomPadding)*heightWeight - topSpace - bottomSpace) } if sbvsc.width.weightVal != nil || sbvsc.width.isFill { //如果过了,则表示当前的剩余空间为0了,所以就按新的一行来算。。 var floatWidth = selfSize.width - trailingPadding - xPos - leadingSpace - trailingSpace; if arrangeIndex != 0 { floatWidth -= horzSpace } if _tgCGFloatLessOrEqual(floatWidth, 0){ floatWidth = selfSize.width - leadingPadding - trailingPadding } var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal{ widthWeight = t.rawValue/100 } rect.size.width = (floatWidth + sbvsc.width.increment) * widthWeight - leadingSpace - trailingSpace; } rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) if sbvsc.height.isRelaSizeEqualTo(sbvsc.width) { rect.size.height = sbvsc.height.measure(rect.size.width) } //如果高度是浮动则需要调整 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) //计算xPos的值加上leadingSpace + rect.size.width + trailingSpace + lsc.tg_hspace 的值要小于整体的宽度。 var place:CGFloat = xPos + leadingSpace + rect.size.width + trailingSpace if arrangeIndex != 0 { place += horzSpace } place += trailingPadding //sbv所占据的宽度要超过了视图的整体宽度,因此需要换行。但是如果arrangedIndex为0的话表示这个控件的整行的宽度和布局视图保持一致。 if place - selfSize.width > 0.0001 { xPos = leadingPadding yPos += vertSpace yPos += rowMaxHeight arrangeIndexSet.insert(i - arrangeIndex) //计算每行Gravity情况 self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex: i, count: arrangeIndex, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding: leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) //计算单独的sbv的宽度是否大于整体的宽度。如果大于则缩小宽度。 if _tgCGFloatGreat(leadingSpace + trailingSpace + rect.size.width , selfSize.width - leadingPadding - trailingPadding) { rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: selfSize.width - leadingPadding - trailingPadding - leadingSpace - trailingSpace, sbvSize: rect.size, selfLayoutSize: selfSize) if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } } rowMaxHeight = 0 rowMaxWidth = 0 arrangeIndex = 0 } if arrangeIndex != 0 { xPos += horzSpace } rect.origin.x = xPos + leadingSpace rect.origin.y = yPos + topSpace xPos += leadingSpace + rect.size.width + trailingSpace if _tgCGFloatLess(rowMaxHeight , topSpace + bottomSpace + rect.size.height) { rowMaxHeight = topSpace + bottomSpace + rect.size.height; } if _tgCGFloatLess(rowMaxWidth , xPos - leadingPadding) { rowMaxWidth = xPos - leadingPadding } sbvtgFrame.frame = rect; arrangeIndex += 1 } //设置最后一行 arrangeIndexSet.insert(sbs.count - arrangeIndex) self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex:sbs.count, count: arrangeIndex, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding:leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) if lsc.height.isWrap { selfSize.height = yPos + bottomPadding + rowMaxHeight; } else { var addYPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 if arrangeIndexSet.count <= 1 && vertGravity == TGGravity.vert.around { vertGravity = TGGravity.vert.center } if vertGravity == TGGravity.vert.center { addYPos = (selfSize.height - bottomPadding - rowMaxHeight - yPos)/2 } else if vertGravity == TGGravity.vert.bottom { addYPos = selfSize.height - bottomPadding - rowMaxHeight - yPos } else if vertGravity == TGGravity.vert.fill { if arrangeIndexSet.count > 0 { fill = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count) } } else if (vertGravity == TGGravity.vert.between) { if arrangeIndexSet.count > 1 { between = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count - 1) } } else if (vertGravity == TGGravity.vert.around) { between = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count) } else if (vertGravity == TGGravity.vert.among) { between = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count + 1) } if addYPos != 0 || between != 0 || fill != 0 { var line:CGFloat = 0 var lastIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame sbvtgFrame.top += addYPos let index = arrangeIndexSet.integerLessThanOrEqualTo(i) if lastIndex != index { lastIndex = index! line += 1 } sbvtgFrame.height += fill sbvtgFrame.top += fill * line sbvtgFrame.top += between * line //如果是vert_around那么所有行都应该添加一半的between值。 if (vertGravity == TGGravity.vert.around) { sbvtgFrame.top += (between / 2.0) } if (vertGravity == TGGravity.vert.among) { sbvtgFrame.top += between } } } } return selfSize } fileprivate func tgLayoutSubviewsForHorz(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize let autoArrange:Bool = lsc.tg_autoArrange let arrangedCount:Int = lsc.tg_arrangedCount let leadingPadding:CGFloat = lsc.tgLeadingPadding let trailingPadding:CGFloat = lsc.tgTrailingPadding var topPadding:CGFloat = lsc.tgTopPadding var bottomPadding:CGFloat = lsc.tgBottomPadding let vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask var horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let horzAlignment:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_arrangedGravity & TGGravity.vert.mask) let horzSpace = lsc.tg_hspace var vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,topPadding,bottomPadding,vertSpace) = t.calcMaxMinSubviewSize(selfSize.height, arrangedCount: arrangedCount, startPadding: topPadding, endPadding: bottomPadding, space: vertSpace) } var colMaxWidth:CGFloat = 0 var colMaxHeight:CGFloat = 0 var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var maxHeight:CGFloat = topPadding var maxWidth:CGFloat = leadingPadding //判断父滚动视图是否分页滚动 var isPagingScroll = false if let scrolv = self.superview as? UIScrollView, scrolv.isPagingEnabled { isPagingScroll = true } var pagingItemHeight:CGFloat = 0 var pagingItemWidth:CGFloat = 0 var isVertPaging = false var isHorzPaging = false if lsc.tg_pagedCount > 0 && self.superview != nil { let cols = CGFloat(lsc.tg_pagedCount / arrangedCount) //每页的列数。 //对于水平流式布局来说,要求要有明确的高度。因此如果我们启用了分页又设置了高度包裹时则我们的分页是从上到下的排列。否则分页是从左到右的排列。 if lsc.height.isWrap { isVertPaging = true if isPagingScroll { pagingItemHeight = (self.superview!.bounds.height - topPadding - bottomPadding - CGFloat(arrangedCount - 1) * vertSpace ) / CGFloat(arrangedCount) } else { pagingItemHeight = (self.superview!.bounds.height - topPadding - CGFloat(arrangedCount) * vertSpace ) / CGFloat(arrangedCount) } pagingItemWidth = (selfSize.width - leadingPadding - trailingPadding - (cols - 1) * horzSpace) / cols } else { isHorzPaging = true pagingItemHeight = (selfSize.height - topPadding - bottomPadding - CGFloat(arrangedCount - 1) * vertSpace) / CGFloat(arrangedCount) //分页滚动时和非分页滚动时的高度计算是不一样的。 if (isPagingScroll) { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - trailingPadding - (cols - 1) * horzSpace) / cols } else { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - cols * horzSpace) / cols } } } let averageArrange = (vertGravity == TGGravity.vert.fill) var arrangedIndex:Int = 0 var rowTotalWeight:CGFloat = 0 var rowTotalFixedHeight:CGFloat = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if (arrangedIndex >= arrangedCount) { arrangedIndex = 0; if (rowTotalWeight != 0 && !averageArrange) { self.tgCalcHorzLayoutSinglelineWeight(selfSize:selfSize,totalFloatHeight:selfSize.height - topPadding - bottomPadding - rowTotalFixedHeight,totalWeight:rowTotalWeight,sbs:sbs,startIndex:i,count:arrangedCount) } rowTotalWeight = 0; rowTotalFixedHeight = 0; } let topSpace = sbvsc.top.absPos let bottomSpace = sbvsc.bottom.absPos let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame if (pagingItemWidth != 0) { rect.size.width = pagingItemWidth - leadingSpace - trailingSpace } rect.size.width = sbvsc.width.numberSize(rect.size.width) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize,sbvsc:sbvsc,lsc:lsc, rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:rect.size.width,sbvSize:rect.size,selfLayoutSize:selfSize) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { if sbvsc.height.isFill { rowTotalWeight += 1.0 } else { rowTotalWeight += sbvsc.height.weightVal.rawValue/100 } } else { if subviewSize != 0 { rect.size.height = subviewSize - topSpace - bottomSpace } if (pagingItemHeight != 0) { rect.size.height = pagingItemHeight - topSpace - bottomSpace } if (sbvsc.height.numberVal != nil && !averageArrange) { rect.size.height = sbvsc.height.measure; } rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) //如果高度是浮动的则需要调整高度。 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } rect.size.height = self.tgValidMeasure(sbvsc.height,sbv:sbv,calcSize:rect.size.height,sbvSize:rect.size,selfLayoutSize:selfSize) if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { rect.size.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:sbvsc.width.measure(rect.size.height),sbvSize:rect.size,selfLayoutSize:selfSize) } rowTotalFixedHeight += rect.size.height; } rowTotalFixedHeight += topSpace + bottomSpace if (arrangedIndex != (arrangedCount - 1)) { rowTotalFixedHeight += vertSpace } sbvtgFrame.frame = rect; arrangedIndex += 1 } //最后一行。 if (rowTotalWeight != 0 && !averageArrange) { if arrangedIndex < arrangedCount { rowTotalFixedHeight -= vertSpace } self.tgCalcHorzLayoutSinglelineWeight(selfSize:selfSize,totalFloatHeight:selfSize.height - topPadding - bottomPadding - rowTotalFixedHeight,totalWeight:rowTotalWeight,sbs:sbs,startIndex:sbs.count,count:arrangedIndex) } var nextPointOfRows:[CGPoint]! = nil if autoArrange { nextPointOfRows = [CGPoint]() for _ in 0 ..< arrangedCount { nextPointOfRows.append(CGPoint(x:leadingPadding, y: topPadding)) } } var pageHeight:CGFloat = 0 let averageHeight:CGFloat = (selfSize.height - topPadding - bottomPadding - (CGFloat(arrangedCount) - 1) * vertSpace) / CGFloat(arrangedCount) arrangedIndex = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if arrangedIndex >= arrangedCount { arrangedIndex = 0 xPos += colMaxWidth xPos += horzSpace //分别处理水平分页和垂直分页。 if (isVertPaging) { if (i % lsc.tg_pagedCount == 0) { pageHeight += self.superview!.bounds.height if (!isPagingScroll) { pageHeight -= topPadding } xPos = leadingPadding; } } if (isHorzPaging) { //如果是分页滚动则要多添加垂直间距。 if (i % lsc.tg_pagedCount == 0) { if (isPagingScroll) { xPos -= horzSpace xPos += trailingPadding xPos += leadingPadding } } } yPos = topPadding + pageHeight; //计算每行Gravity情况 self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: i, count: arrangedCount, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding+bottomPadding, isEstimate: isEstimate, lsc:lsc) colMaxWidth = 0 colMaxHeight = 0 } let topSpace:CGFloat = sbvsc.top.absPos let leadingSpace:CGFloat = sbvsc.leading.absPos let bottomSpace:CGFloat = sbvsc.bottom.absPos let trailingSpace:CGFloat = sbvsc.trailing.absPos var rect:CGRect = sbvtgFrame.frame if averageArrange { rect.size.height = (averageHeight - topSpace - bottomSpace) if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { rect.size.width = sbvsc.width.measure(rect.size.height) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) } } if sbvsc.width.weightVal != nil || sbvsc.width.isFill { var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal { widthWeight = t.rawValue/100 } rect.size.width = sbvsc.width.measure((selfSize.width - xPos - trailingPadding)*widthWeight - leadingSpace - trailingSpace) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) } if _tgCGFloatLess(colMaxWidth , leadingSpace + trailingSpace + rect.size.width) { colMaxWidth = leadingSpace + trailingSpace + rect.size.width } if autoArrange { var minPt:CGPoint = CGPoint(x:CGFloat.greatestFiniteMagnitude, y:CGFloat.greatestFiniteMagnitude) var minNextPointIndex:Int = 0 for idx in 0 ..< arrangedCount { let pt = nextPointOfRows[idx] if minPt.x > pt.x { minPt = pt minNextPointIndex = idx } } xPos = minPt.x yPos = minPt.y minPt.x = minPt.x + leadingSpace + rect.size.width + trailingSpace + horzSpace; nextPointOfRows[minNextPointIndex] = minPt if minNextPointIndex + 1 <= arrangedCount - 1 { minPt = nextPointOfRows[minNextPointIndex + 1] minPt.y = yPos + topSpace + rect.size.height + bottomSpace + vertSpace nextPointOfRows[minNextPointIndex + 1] = minPt } if _tgCGFloatLess(maxWidth, xPos + leadingSpace + rect.size.width + trailingSpace) { maxWidth = xPos + leadingSpace + rect.size.width + trailingSpace } } else if horzAlignment == TGGravity.horz.between { //当列是紧凑排列时需要特殊处理当前的水平位置。 //第0列特殊处理。 if (i - arrangedCount < 0) { xPos = leadingPadding } else { //取前一列的对应的行的子视图。 let (prevSbvtgFrame, prevSbvsc) = self.tgGetSubviewFrameAndSizeClass(sbs[i - arrangedCount]) //当前子视图的位置等于前一列对应行的最大x的值 + 前面对应行的尾部间距 + 子视图之间的列间距。 xPos = prevSbvtgFrame.frame.maxX + prevSbvsc.trailing.absPos + horzSpace } if _tgCGFloatLess(maxWidth, xPos + leadingSpace + rect.size.width + trailingSpace) { maxWidth = xPos + leadingSpace + rect.size.width + trailingSpace } } else { maxWidth = xPos + colMaxWidth } rect.origin.y = yPos + topSpace rect.origin.x = xPos + leadingSpace yPos += topSpace + rect.size.height + bottomSpace if _tgCGFloatLess(colMaxHeight , (yPos - topPadding)) { colMaxHeight = yPos - topPadding } if _tgCGFloatLess(maxHeight , yPos) { maxHeight = yPos } if arrangedIndex != (arrangedCount - 1) && !autoArrange { yPos += vertSpace } sbvtgFrame.frame = rect arrangedIndex += 1 } //最后一列 self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: sbs.count, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding+bottomPadding, isEstimate: isEstimate, lsc:lsc) if lsc.height.isWrap && !averageArrange { selfSize.height = maxHeight + bottomPadding //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isVertPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.height , totalPages * self.superview!.bounds.height) { selfSize.height = totalPages * self.superview!.bounds.height } } } maxWidth = maxWidth + trailingPadding if lsc.width.isWrap { selfSize.width = maxWidth //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isHorzPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.width , totalPages * self.superview!.bounds.width) { selfSize.width = totalPages * self.superview!.bounds.width } } } else { var addXPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 let arranges = floor(CGFloat(sbs.count + arrangedCount - 1) / CGFloat(arrangedCount)) if arranges <= 1 && horzGravity == TGGravity.horz.around { horzGravity = TGGravity.horz.center } if horzGravity == TGGravity.horz.center { addXPos = (selfSize.width - maxWidth) / 2 } else if horzGravity == TGGravity.horz.trailing { addXPos = selfSize.width - maxWidth } else if (horzGravity == TGGravity.horz.fill) { if (arranges > 0) { fill = (selfSize.width - maxWidth) / arranges } } else if (horzGravity == TGGravity.horz.between) { if (arranges > 1) { between = (selfSize.width - maxWidth) / (arranges - 1) } } else if (horzGravity == TGGravity.horz.around) { between = (selfSize.width - maxWidth) / arranges } else if (horzGravity == TGGravity.horz.among) { between = (selfSize.width - maxWidth) / (arranges + 1) } if addXPos != 0 || between != 0 || fill != 0 { for i:Int in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame let line = i / arrangedCount sbvtgFrame.width += fill sbvtgFrame.leading += fill * CGFloat(line) sbvtgFrame.leading += addXPos sbvtgFrame.leading += between * CGFloat(line) //如果是vert_around那么所有行都应该添加一半的between值。 if (horzGravity == TGGravity.horz.around) { sbvtgFrame.leading += (between / 2.0) } if (horzGravity == TGGravity.horz.among) { sbvtgFrame.leading += between } } } } return selfSize } fileprivate func tgLayoutSubviewsForHorzContent(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize let leadingPadding:CGFloat = lsc.tgLeadingPadding let trailingPadding:CGFloat = lsc.tgTrailingPadding var topPadding:CGFloat = lsc.tgTopPadding var bottomPadding:CGFloat = lsc.tgBottomPadding let vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask var horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let horzAlignment:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_arrangedGravity & TGGravity.vert.mask) //支持浮动垂直间距。 let horzSpace = lsc.tg_hspace var vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,topPadding,bottomPadding,vertSpace) = t.calcMaxMinSubviewSizeForContent(selfSize.height, startPadding: topPadding, endPadding: bottomPadding, space: vertSpace) } var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var colMaxWidth:CGFloat = 0 var colMaxHeight:CGFloat = 0 var arrangeIndexSet = IndexSet() var arrangedIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let topSpace:CGFloat = sbvsc.top.absPos let leadingSpace:CGFloat = sbvsc.leading.absPos let bottomSpace:CGFloat = sbvsc.bottom.absPos let trailingSpace:CGFloat = sbvsc.trailing.absPos var rect:CGRect = sbvtgFrame.frame rect.size.width = sbvsc.width.numberSize(rect.size.width) if subviewSize != 0 { rect.size.height = subviewSize - topSpace - bottomSpace } rect.size.height = sbvsc.height.numberSize(rect.size.height) rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { //如果过了,则表示当前的剩余空间为0了,所以就按新的一行来算。。 var floatHeight = selfSize.height - bottomPadding - yPos - topSpace - bottomSpace if arrangedIndex != 0 { floatHeight -= vertSpace } if (_tgCGFloatLessOrEqual(floatHeight, 0)){ floatHeight = selfSize.height - topPadding - bottomPadding } var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal{ heightWeight = t.rawValue/100 } rect.size.height = (floatHeight + sbvsc.height.increment) * heightWeight - topSpace - bottomSpace; } rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { rect.size.width = sbvsc.width.measure(rect.size.height) } if sbvsc.width.weightVal != nil || sbvsc.width.isFill { var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal { widthWeight = t.rawValue / 100 } rect.size.width = sbvsc.width.measure((selfSize.width - xPos - trailingPadding)*widthWeight - leadingSpace - trailingSpace) } rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) //如果高度是浮动则调整 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } //计算yPos的值加上topSpace + rect.size.height + bottomSpace + lsc.tg_vspace 的值要小于整体的宽度。 var place:CGFloat = yPos + topSpace + rect.size.height + bottomSpace if arrangedIndex != 0 { place += vertSpace } place += bottomPadding //sbv所占据的宽度要超过了视图的整体宽度,因此需要换行。但是如果arrangedIndex为0的话表示这个控件的整行的宽度和布局视图保持一致。 if place - selfSize.height > 0.0001 { yPos = topPadding xPos += horzSpace xPos += colMaxWidth //计算每行Gravity情况 arrangeIndexSet.insert(i - arrangedIndex) self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: i, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding+bottomPadding, isEstimate: isEstimate, lsc:lsc) //计算单独的sbv的高度是否大于整体的高度。如果大于则缩小高度。 if _tgCGFloatGreat(topSpace + bottomSpace + rect.size.height , selfSize.height - topPadding - bottomPadding) { rect.size.height = selfSize.height - topPadding - bottomPadding - topSpace - bottomSpace rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } colMaxWidth = 0; colMaxHeight = 0; arrangedIndex = 0; } if arrangedIndex != 0 { yPos += vertSpace } rect.origin.x = xPos + leadingSpace rect.origin.y = yPos + topSpace yPos += topSpace + rect.size.height + bottomSpace if _tgCGFloatLess(colMaxWidth , leadingSpace + trailingSpace + rect.size.width) { colMaxWidth = leadingSpace + trailingSpace + rect.size.width } if _tgCGFloatLess(colMaxHeight , (yPos - topPadding)) { colMaxHeight = (yPos - topPadding); } sbvtgFrame.frame = rect; arrangedIndex += 1; } //最后一行 arrangeIndexSet.insert(sbs.count - arrangedIndex) self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: sbs.count, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding + bottomPadding, isEstimate: isEstimate, lsc:lsc) if lsc.width.isWrap { selfSize.width = xPos + trailingPadding + colMaxWidth } else { var addXPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 if arrangeIndexSet.count <= 1 && horzGravity == TGGravity.horz.around { horzGravity = TGGravity.horz.center } if (horzGravity == TGGravity.horz.center) { addXPos = (selfSize.width - trailingPadding - colMaxWidth - xPos) / 2; } else if (horzGravity == TGGravity.horz.trailing) { addXPos = selfSize.width - trailingPadding - colMaxWidth - xPos; } else if (horzGravity == TGGravity.horz.fill) { if (arrangeIndexSet.count > 0) { fill = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count) } } else if (horzGravity == TGGravity.horz.between) { if (arrangeIndexSet.count > 1) { between = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count - 1) } } else if (horzGravity == TGGravity.horz.around) { between = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count) } else if (horzGravity == TGGravity.horz.among) { between = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count + 1) } if (addXPos != 0 || between != 0 || fill != 0) { var line:CGFloat = 0 var lastIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame sbvtgFrame.leading += addXPos let index = arrangeIndexSet.integerLessThanOrEqualTo(i) if lastIndex != index { lastIndex = index! line += 1 } sbvtgFrame.width += fill sbvtgFrame.leading += fill * line sbvtgFrame.leading += between * line if (horzGravity == TGGravity.horz.around) { sbvtgFrame.leading += (between / 2.0) } if (horzGravity == TGGravity.horz.among) { sbvtgFrame.leading += between } } } } return selfSize } }
mit
Luavis/Kasa
Kasa.swift/ShadowLabel.swift
1
1497
// // ShadowLabel.swift // Kasa.swift // // Created by Luavis Kang on 12/2/15. // Copyright © 2015 Luavis. All rights reserved. // import Cocoa class VerticallyCenteredTextFieldCell:NSTextFieldCell { override func titleRectForBounds(theRect: NSRect) -> NSRect { let stringHeight = self.attributedStringValue.size().height var titleRect = super.titleRectForBounds(theRect) let oldOriginY = theRect.origin.y titleRect.origin.y = theRect.origin.y + (theRect.size.height - stringHeight) / 2.0 titleRect.size.height = titleRect.size.height - (titleRect.origin.y - oldOriginY) return titleRect } override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) { super.drawInteriorWithFrame(self.titleRectForBounds(cellFrame), inView: controlView) } } class ShadowLabel: NSTextField { var shadowColor = NSColor.blackColor(); var shadowOffset = CGSize(width: 1.0, height: 1.0) var shadowRadius:Float = 2.0 var shadowOpacity:Float = 1.0 override func awakeFromNib() { self.drawShadow() } func drawShadow() { self.wantsLayer = true; let layer:CALayer! = self.layer!; layer.backgroundColor = NSColor.clearColor().CGColor; layer.shadowColor = self.shadowColor.CGColor; layer.shadowOffset = self.shadowOffset layer.shadowOpacity = self.shadowOpacity layer.shadowRadius = CGFloat(self.shadowRadius) } }
mit
clooth/HanekeSwift
Haneke/Data.swift
1
3235
// // Data.swift // Haneke // // Created by Hermes Pique on 9/19/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit // See: http://stackoverflow.com/questions/25922152/not-identical-to-self public protocol DataConvertible { typealias Result static func convertFromData(data:NSData) -> Result? } public protocol DataRepresentable { func asData() -> NSData! } private let imageSync = NSLock() extension UIImage : DataConvertible, DataRepresentable { public typealias Result = UIImage static func safeImageWithData(data:NSData) -> Result? { imageSync.lock() let image = UIImage(data:data) imageSync.unlock() return image } public class func convertFromData(data:NSData) -> Result? { let image = UIImage.safeImageWithData(data) return image } public func asData() -> NSData! { return self.hnk_data() } } extension String : DataConvertible, DataRepresentable { public typealias Result = String public static func convertFromData(data:NSData) -> Result? { var string = NSString(data: data, encoding: NSUTF8StringEncoding) return string as? Result } public func asData() -> NSData! { return self.dataUsingEncoding(NSUTF8StringEncoding) } } extension NSData : DataConvertible, DataRepresentable { public typealias Result = NSData public class func convertFromData(data:NSData) -> Result? { return data } public func asData() -> NSData! { return self } } public enum JSON : DataConvertible, DataRepresentable { public typealias Result = JSON case Dictionary([String:AnyObject]) case Array([AnyObject]) public static func convertFromData(data:NSData) -> Result? { var error : NSError? if let object : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) { switch (object) { case let dictionary as [String:AnyObject]: return JSON.Dictionary(dictionary) case let array as [AnyObject]: return JSON.Array(array) default: return nil } } else { Log.error("Invalid JSON data", error) return nil } } public func asData() -> NSData! { switch (self) { case .Dictionary(let dictionary): return NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.allZeros, error: nil) case .Array(let array): return NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions.allZeros, error: nil) } } public var array : [AnyObject]! { switch (self) { case .Dictionary(let _): return nil case .Array(let array): return array } } public var dictionary : [String:AnyObject]! { switch (self) { case .Dictionary(let dictionary): return dictionary case .Array(let _): return nil } } }
apache-2.0
frodoking/GithubIOSClient
Github/Core/Module/Users/UserDetailViewController.swift
1
9167
// // UserDetailViewController.swift // Github // // Created by frodo on 15/10/25. // Copyright © 2015年 frodo. All rights reserved. // import UIKit import Alamofire class UserDetailViewController: UIViewController, ViewPagerIndicatorDelegate, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var titleImageView: UIImageView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var emaiButton: UIButton! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var blogButton: UIButton! @IBOutlet weak var companyLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var createLabel: UILabel! @IBOutlet weak var viewPagerIndicator: ViewPagerIndicator! @IBOutlet weak var tableView: UITableView! private lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshAction:", forControlEvents: UIControlEvents.ValueChanged) return refreshControl }() var viewModule: UserDetailViewModule? var tabIndex: Int = 0 var array: NSArray? { didSet { self.tableView.reloadData() } } var user: User? { didSet { self.title = user?.login } } private func updateUserInfo () { if let _ = user { if let avatar_url = user!.avatar_url { Alamofire.request(.GET, avatar_url) .responseData { response in NSLog("Fetch: Image: \(avatar_url)") let imageData = UIImage(data: response.data!) self.titleImageView?.image = imageData } } if let login = user!.login { loginButton.setTitle(login, forState:UIControlState.Normal) } if let email = user!.email { emaiButton.setTitle(email, forState:UIControlState.Normal) } if let name = user!.name { nameLabel.text = name } if let blog = user!.blog { blogButton.setTitle(blog, forState:UIControlState.Normal) } if let company = user!.company { companyLabel.text = company } if let location = user!.location { locationLabel.text = location } if let created_at = user!.created_at { createLabel.text = created_at } } } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge.None self.automaticallyAdjustsScrollViewInsets=false self.view.backgroundColor = Theme.WhiteColor self.navigationController?.navigationBar.backgroundColor = Theme.Color titleImageView.layer.cornerRadius = 10 titleImageView.layer.borderColor = Theme.GrayColor.CGColor titleImageView.layer.borderWidth = 0.3 titleImageView.layer.masksToBounds=true viewModule = UserDetailViewModule() if self.user != nil { viewModule?.loadUserFromApi((self.user!.login)!, handler: { user in if user != nil { self.user = user self.updateUserInfo() } }) } updateUserInfo() viewPagerIndicator.titles = UserDetailViewModule.Indicator //监听ViewPagerIndicator选中项变化 viewPagerIndicator.delegate = self viewPagerIndicator.setTitleColorForState(Theme.Color, state: UIControlState.Selected) //选中文字的颜色 viewPagerIndicator.setTitleColorForState(UIColor.blackColor(), state: UIControlState.Normal) //正常文字颜色 viewPagerIndicator.tintColor = Theme.Color //指示器和基线的颜色 viewPagerIndicator.showBottomLine = true //基线是否显示 viewPagerIndicator.autoAdjustSelectionIndicatorWidth = true//指示器宽度是按照文字内容大小还是按照count数量平分屏幕 viewPagerIndicator.indicatorDirection = .Bottom//指示器位置 viewPagerIndicator.titleFont = UIFont.systemFontOfSize(14) self.tableView.addSubview(self.refreshControl) self.tableView.estimatedRowHeight = tableView.rowHeight self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.dataSource = self self.tableView.delegate = self viewPagerIndicator.setSelectedIndex(tabIndex) refreshAction(refreshControl) } func refreshAction(sender: UIRefreshControl) { self.refreshControl.beginRefreshing() if let _ = user { viewModule?.loadDataFromApiWithIsFirst(true, currentIndex: tabIndex, userName: (user?.login)!, handler: { array in self.refreshControl.endRefreshing() if array.count > 0 { self.array = array } }) } } @IBAction func backAction(sender: UIBarButtonItem) { if let prevViewController = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)! - 2] { self.navigationController?.popToViewController(prevViewController, animated: true) } else { self.navigationController?.popToRootViewControllerAnimated(true) } } } // MARK: - ViewPagerIndicator extension UserDetailViewController { // 点击顶部选中后回调 func indicatorChange(indicatorIndex: Int) { self.tabIndex = indicatorIndex switch indicatorIndex { case 0: self.array = viewModule!.userRepositoriesDataSource.dsArray break case 1: self.array = viewModule!.userFollowingDataSource.dsArray break case 2: self.array = viewModule!.userFollowersDataSource.dsArray break default:break } self.refreshAction(self.refreshControl) } } // MARK: - UITableViewDataSource extension UserDetailViewController { func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections if array == nil { return 0 } return self.array!.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tabIndex == 0 { let cell = tableView.dequeueReusableCellWithIdentifier(Key.CellReuseIdentifier.RepositoryCell, forIndexPath: indexPath) as! RepositoryTableViewCell cell.repository = self.array![indexPath.section] as? Repository return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier(Key.CellReuseIdentifier.UserCell, forIndexPath: indexPath) as! UserTableViewCell cell.user = self.array![indexPath.section] as? User return cell } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if tabIndex == 0 { return Theme.RepositoryTableViewCellheight } return Theme.UserTableViewCellHeight } } // MARK: - Navigation extension UserDetailViewController { // 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. let viewController = segue.destinationViewController if let userDetailViewController = viewController as? UserDetailViewController { if let cell = sender as? UserTableViewCell { let selectedIndex = tableView.indexPathForCell(cell)?.section if let index = selectedIndex { userDetailViewController.user = self.array![index] as? User } } } else if let repositoryDetailViewController = viewController as? RepositoryDetailViewController { if let cell = sender as? RepositoryTableViewCell { let selectedIndex = tableView.indexPathForCell(cell)?.section if let index = selectedIndex { repositoryDetailViewController.repository = self.array![index] as? Repository } } } } }
apache-2.0
PlutoMa/SwiftProjects
025.CustomTransition/CustomTransition/CustomTransition/FirstViewController/CustomCollectionViewCell.swift
1
645
// // CustomCollectionViewCell.swift // CustomTransition // // Created by Dareway on 2017/11/6. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(imageView) } public func configCell(model: CustomModel) -> Void { imageView.image = model.image imageView.frame = contentView.bounds } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ios-ximen/DYZB
斗鱼直播/斗鱼直播/Classes/Home/Controllers/AmuseController.swift
1
1411
// // AmuseController.swift // 斗鱼直播 // // Created by niujinfeng on 2017/7/10. // Copyright © 2017年 niujinfeng. All rights reserved. // import UIKit fileprivate let KmenuViewH : CGFloat = 200 class AmuseController: BaseAnchorController { //mark: -模型数据 fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel() //mark: -懒加载 fileprivate lazy var amuseMenuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMendView() menuView.frame = CGRect(x: 0, y: -KmenuViewH, width: KscreenWidth, height: KmenuViewH) return menuView }() } //设置ui extension AmuseController{ override func setUpUI() { //调用父类 super.setUpUI() //添加menuview collectionView.addSubview(amuseMenuView) //设置内边距 collectionView.contentInset = UIEdgeInsetsMake(KmenuViewH, 0, 0, 0) } } //mark: -加载数据 extension AmuseController{ override func loadData(){ //传递模型数据 baseVM = amuseVM amuseVM.loadAmuseData{ self.collectionView.reloadData() var tempGroups = self.amuseVM.anchorsGroup tempGroups.removeFirst() //传递数据 self.amuseMenuView.anchorGroup = tempGroups; //加载数据完成 self.loadDataFinished() } } }
mit
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Mapping/MSOverhead+Convertible.swift
1
1119
// // MSOverhead+Convertible.swift // MoyskladiOSRemapSDK // // Created by Vladislav on 31.08.17. // Copyright © 2017 Andrey Parshakov. All rights reserved. // import Foundation extension MSOverhead { public static func from(dict: Dictionary<String, Any>) -> MSOverhead? { guard let distr = MSOverheadDistribution(rawValue: dict.value("distribution") ?? "") else { return nil } return MSOverhead(sum: (dict.value("sum") ?? 0.0).toMoney(), distribution: distr) } public func dictionary() -> Dictionary<String, Any> { return ["sum": sum.minorUnits, "distribution":distribution.rawValue] } } extension MSBundleOverhead { public static func from(dict: Dictionary<String, Any>) -> MSBundleOverhead? { guard let currency = MSCurrency.from(dict: dict.msValue("currency")) else { return nil } return MSBundleOverhead(value: (dict.value("value") ?? 0.0).toMoney(), currency: currency) } public func dictionary() -> Dictionary<String, Any> { return ["value": value.minorUnits, "currency": serialize(entity: currency)] } }
mit
ahoppen/swift
test/expr/print/protocol.swift
9
691
// RUN: %target-swift-frontend -print-ast %s 2>&1 | %FileCheck %s protocol Archivable { func archive(version: String) } // CHECK: internal protocol Archivable { // CHECK: func archive(version: String) // CHECK: } func archive(_ a: Archivable) { a.archive(version: "1") } // CHECK: internal func archive(_ a: Archivable) { // CHECK: a.archive(version: "1") // CHECK: } func cast(_ a: Any) { let conditional = a as? Archivable let forced = a as! Archivable } // CHECK: internal func cast(_ a: Any) { // CHECK: @_hasInitialValue private let conditional: Archivable? = a as? Archivable // CHECK: @_hasInitialValue private let forced: Archivable = a as! Archivable // CHECK: }
apache-2.0
evan-liu/CommandArguments
Tests/CommandArgumentsTests/FlagTests.swift
1
1484
import XCTest import CommandArguments class FlagTests: XCTestCase { static let allTests = [ ("testFlag", testFlag), ] func testFlag() { struct TestArgs: CommandArguments { var a = Flag(longName: "aa") var b = Flag(longName: "bb") var c = Flag(longName: "cc") var d = Flag(longName: "dd") var e = Flag(longName: "ee") var f = Flag(longName: "ff") var g = Flag(longName: "gg") } var shortNames = TestArgs() try! shortNames.parse([ "-a", "-b", "true", "-c", "false", "-d=true", "-e=false", "-f=" ]) XCTAssertTrue(shortNames.a.value) XCTAssertTrue(shortNames.b.value) XCTAssertFalse(shortNames.c.value) XCTAssertTrue(shortNames.d.value) XCTAssertFalse(shortNames.e.value) XCTAssertFalse(shortNames.f.value) XCTAssertFalse(shortNames.g.value) var longNames = TestArgs() try! longNames.parse([ "--aa", "--bb", "true", "--cc", "false", "--dd=true", "--ee=false", "--ff=" ]) XCTAssertTrue(longNames.a.value) XCTAssertTrue(longNames.b.value) XCTAssertFalse(longNames.c.value) XCTAssertTrue(longNames.d.value) XCTAssertFalse(longNames.e.value) XCTAssertFalse(longNames.f.value) XCTAssertFalse(longNames.g.value) } }
mit
2794129697/-----mx
CoolXuePlayer/NetWorkHelper.swift
1
6432
// // NetWorkHelper.swift // CoolXuePlayer // // Created by lion-mac on 15/7/24. // Copyright (c) 2015年 lion-mac. All rights reserved. // import Foundation public class NetWorkHelper:NSObject{ //网络状态 public static var networkStatus:Int = 0 //网络是否正常 public static var is_network_ok:Bool = false //是否已经注册网络监测 private static var is_register_network_monitor:Bool = false private static var hostReachability:Reachability! private static var internetReachability:Reachability! private static var wifiReachability:Reachability! private static var observer:NetWorkHelper = NetWorkHelper() private override init(){ println("init") } //监测设备网络 public class func registerNetWorkMonitor(){ if !self.is_register_network_monitor { self.is_register_network_monitor = true NSNotificationCenter.defaultCenter().addObserver(observer, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil) self.hostReachability = Reachability(hostName: "www.apple.com") self.hostReachability.startNotifier() self.internetReachability = Reachability.reachabilityForInternetConnection() self.internetReachability.startNotifier() self.wifiReachability = Reachability.reachabilityForLocalWiFi() self.wifiReachability.startNotifier() println(self.hostReachability.currentReachabilityStatus().value) println(self.internetReachability.currentReachabilityStatus().value) println(self.wifiReachability.currentReachabilityStatus().value) if self.hostReachability.currentReachabilityStatus().value != 0 || self.internetReachability.currentReachabilityStatus().value != 0 || self.wifiReachability.currentReachabilityStatus().value != 0{ NetWorkHelper.is_network_ok = true } } } //设备网络环境发生变化时通知(不能写成私有方法) func reachabilityChanged(note:NSNotification){ println("reachabilityChanged") var curReach:Reachability = note.object as! Reachability var netStatus:NetworkStatus = curReach.currentReachabilityStatus() var connectionRequired = curReach.connectionRequired() var statusString = ""; println(netStatus.value) if netStatus.value == 0 { NetWorkHelper.is_network_ok = false println("没有可用网络!\(netStatus.value)") D3Notice.showText("没有可用网络!",time:D3Notice.longTime,autoClear:true) }else{ NetWorkHelper.is_network_ok = true println("网络已连接!\(netStatus.value)") //D3Notice.showText("网络已连接!\(netStatus.value)",time:D3Notice.longTime,autoClear:true) } switch netStatus.value { case 0: break; case 1: break; case 2: break; default: break; } if (connectionRequired){ println("%@, Connection Required"+"Concatenation of status string with connection requirement") } } } public enum IJReachabilityType { case WWAN, WiFi, NotConnected } public class IJReachability { /** :see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/ */ public class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } public class func isConnectedToNetworkOfType() -> IJReachabilityType { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return .NotConnected } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let isWWAN = (flags & UInt32(kSCNetworkReachabilityFlagsIsWWAN)) != 0 //let isWifI = (flags & UInt32(kSCNetworkReachabilityFlagsReachable)) != 0 if(isReachable && isWWAN){ return .WWAN } if(isReachable && !isWWAN){ return .WiFi } return .NotConnected //let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 //return (isReachable && !needsConnection) ? true : false } public class func test(){ if IJReachability.isConnectedToNetwork() { println("Network Connection: Available") } else { println("Network Connection: Unavailable") } let statusType = IJReachability.isConnectedToNetworkOfType() switch statusType { case .WWAN: println("Connection Type: Mobile\n") case .WiFi: println("Connection Type: WiFi\n") case .NotConnected: println("Connection Type: Not connected to the Internet\n") } } }
lgpl-3.0
CoderJackyHuang/SwiftExtensionCodes
SwiftExtensionCollection/ViewController.swift
1
2244
// // ViewController.swift // SwiftExtensionCollection // // Created by huangyibiao on 15/9/22. // Copyright © 2015年 huangyibiao. All rights reserved. // import UIKit class ViewController: UIViewController { var timer: NSTimer? override func viewDidLoad() { super.viewDidLoad() let string = " 就要去" print(string.hyb_length() == 5) print(string.hyb_trimLeft() == "就要去") let str = " \n 测试" print(str.hyb_trimLeft()) print(str.hyb_trimLeft(true)) print(" ".hyb_trim().hyb_length() == 0) print(" \n ".hyb_trimLeft(true).hyb_length() == 0) print("right ----------") print(" 去掉右边的空格 ".hyb_trimRight().hyb_length() == " 去掉右边的空格 ".hyb_length() - 4) print(" ".hyb_trimRight().hyb_length() == 0) print(" \n ".hyb_trimRight().hasSuffix("\n")) print(" \n ".hyb_trimRight(true).hyb_length() == 0) print("".hyb_trimRight().hyb_length() == 0) // print("after delay 4") // NSObject.hyb_delay(4) { () -> Void in //NSTimer.hyb_schedule(NSTimeInterval(0.1), repeats: true) { () -> Void in // print("111") // print("hyb_schdule(1, count: 2)") // } // // NSTimer.hyb_schdule(count: nil) { () -> Void in // print("nil count") // } // // // 可以省略 // NSTimer.hyb_schdule(count: 2) { // print("hehe") // } // self.hyb_showAlert("Thanks") // self.hyb_showOkAlert("Thanks") { () -> Void in // print("hehe") // } // self.hyb_showOkAlert("Thanks") { () -> Void in // print("hehe") // } // self.hyb_showAlert("Thanks", message: "hehe", buttonTitles: ["Left", "Right"]) { (index) -> Void in // print("\(index)") // } // self.hyb_okCancelDirection = .CancelOk // self.hyb_showAlert("cancel, ok") // self.hyb_showActionSheet("Thanks", message: "How to call with hyb_showActionSheet", cancel: "Cancel", destructive: "Destructive", otherTitles: "Beijing", "ShenZhen") { (index) -> Void in // print(index) // } self.hyb_showActionSheet("Thanks", message: "How to use", cancel: "Cancel", otherTitles: "First", "Second") { (index) -> Void in print(index) } } }
mit
dreamsxin/swift
validation-test/compiler_crashers_fixed/25433-swift-archetypebuilder-finalize.swift
11
468
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A{ func c:A protocol A{typealias h:B class B{ struct Q<d where h:A
apache-2.0
2794129697/-----mx
CoolXuePlayer/HTTPRequestSerializer.swift
1
11868
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPRequestSerializer.swift // // Created by Dalton Cherry on 6/3/14. // Copyright (c) 2014 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation extension String { /** A simple extension to the String object to encode it for web request. :returns: Encoded version of of string it was called as. */ var escaped: String { return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,self,"[].",":/?&=;+!@#$()',*",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as! String } } /// Default Serializer for serializing an object to an HTTP request. This applies to form serialization, parameter encoding, etc. public class HTTPRequestSerializer: NSObject { let contentTypeKey = "Content-Type" /// headers for the request. public var headers = Dictionary<String,String>() /// encoding for the request. public var stringEncoding: UInt = NSUTF8StringEncoding /// Send request if using cellular network or not. Defaults to true. public var allowsCellularAccess = true /// If the request should handle cookies of not. Defaults to true. public var HTTPShouldHandleCookies = true /// If the request should use piplining or not. Defaults to false. public var HTTPShouldUsePipelining = false /// How long the timeout interval is. Defaults to 60 seconds. public var timeoutInterval: NSTimeInterval = 60 /// Set the request cache policy. Defaults to UseProtocolCachePolicy. public var cachePolicy: NSURLRequestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy /// Set the network service. Defaults to NetworkServiceTypeDefault. public var networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeDefault /// Initializes a new HTTPRequestSerializer Object. public override init() { super.init() } /** Creates a new NSMutableURLRequest object with configured options. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :returns: A new NSMutableURLRequest with said options. */ public func newRequest(url: NSURL, method: HTTPMethod) -> NSMutableURLRequest { var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval) request.HTTPMethod = method.rawValue request.cachePolicy = self.cachePolicy request.timeoutInterval = self.timeoutInterval request.allowsCellularAccess = self.allowsCellularAccess request.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies request.HTTPShouldUsePipelining = self.HTTPShouldUsePipelining request.networkServiceType = self.networkServiceType for (key,val) in self.headers { request.addValue(val, forHTTPHeaderField: key) } return request } /** Creates a new NSMutableURLRequest object with configured options. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A new NSMutableURLRequest with said options or an error. */ public func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) { var request = newRequest(url, method: method) var isMulti = false //do a check for upload objects to see if we are multi form if let params = parameters { isMulti = isMultiForm(params) } // if isMulti { // if(method != .POST && method != .PUT && method != .PATCH) { // request.HTTPMethod = HTTPMethod.POST.rawValue // you probably wanted a post // } // var boundary = "Boundary+\(arc4random())\(arc4random())" // if parameters != nil { // request.HTTPBody = dataFromParameters(parameters!,boundary: boundary) // } // if request.valueForHTTPHeaderField(contentTypeKey) == nil { // request.setValue("multipart/form-data; boundary=\(boundary)", // forHTTPHeaderField:contentTypeKey) // } // return (request,nil) // } var queryString = "" if parameters != nil { queryString = self.stringFromParameters(parameters!) } println("queryString=\(queryString)") if isURIParam(method) { var para = (request.URL!.query != nil) ? "&" : "?" var newUrl = "\(request.URL!.absoluteString!)" if count(queryString) > 0 { newUrl += "\(para)\(queryString)" } request.URL = NSURL(string: newUrl) } else { var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); if request.valueForHTTPHeaderField(contentTypeKey) == nil { request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField:contentTypeKey) } request.HTTPBody = queryString.dataUsingEncoding(self.stringEncoding) } return (request,nil) } ///check for multi form objects public func isMultiForm(params: Dictionary<String,AnyObject>) -> Bool { for (name,object: AnyObject) in params { if object is HTTPUpload { return true } else if let subParams = object as? Dictionary<String,AnyObject> { if isMultiForm(subParams) { return true } } } return false } ///check if enum is a HTTPMethod that requires the params in the URL public func isURIParam(method: HTTPMethod) -> Bool { if(method == .GET || method == .HEAD || method == .DELETE) { return true } return false } ///convert the parameter dict to its HTTP string representation func stringFromParameters(parameters: Dictionary<String,AnyObject>) -> String { return join("&", map(serializeObject(parameters, key: nil), {(pair) in return pair.stringValue() })) } ///the method to serialized all the objects func serializeObject(object: AnyObject,key: String?) -> Array<HTTPPair> { var collect = Array<HTTPPair>() if let array = object as? Array<AnyObject> { for nestedValue : AnyObject in array { collect.extend(self.serializeObject(nestedValue,key: "\(key!)[]")) } } else if let dict = object as? Dictionary<String,AnyObject> { for (nestedKey, nestedObject: AnyObject) in dict { var newKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey collect.extend(self.serializeObject(nestedObject,key: newKey)) } } else { collect.append(HTTPPair(value: object, key: key)) } return collect } //create a multi form data object of the parameters func dataFromParameters(parameters: Dictionary<String,AnyObject>,boundary: String) -> NSData { var mutData = NSMutableData() var multiCRLF = "\r\n" var boundSplit = "\(multiCRLF)--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)! var lastBound = "\(multiCRLF)--\(boundary)--\(multiCRLF)".dataUsingEncoding(self.stringEncoding)! mutData.appendData("--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!) let pairs = serializeObject(parameters, key: nil) let count = pairs.count-1 var i = 0 for pair in pairs { var append = true if let upload = pair.getUpload() { if let data = upload.data { mutData.appendData(multiFormHeader(pair.k, fileName: upload.fileName, type: upload.mimeType, multiCRLF: multiCRLF).dataUsingEncoding(self.stringEncoding)!) mutData.appendData(data) } else { append = false } } else { let str = "\(multiFormHeader(pair.k, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.getValue())" mutData.appendData(str.dataUsingEncoding(self.stringEncoding)!) } if append { if i == count { mutData.appendData(lastBound) } else { mutData.appendData(boundSplit) } } i++ } return mutData } ///helper method to create the multi form headers func multiFormHeader(name: String, fileName: String?, type: String?, multiCRLF: String) -> String { var str = "Content-Disposition: form-data; name=\"\(name.escaped)\"" if fileName != nil { str += "; filename=\"\(fileName!)\"" } str += multiCRLF if type != nil { str += "Content-Type: \(type!)\(multiCRLF)" } str += multiCRLF return str } /// Creates key/pair of the parameters. class HTTPPair: NSObject { var val: AnyObject var k: String! init(value: AnyObject, key: String?) { self.val = value self.k = key } func getUpload() -> HTTPUpload? { return self.val as? HTTPUpload } func getValue() -> String { var val = "" if let str = self.val as? String { val = str } else if self.val.description != nil { val = self.val.description } return val } func stringValue() -> String { var v = getValue() if self.k == nil { return v.escaped } return "\(self.k.escaped)=\(v.escaped)" } } } /// JSON Serializer for serializing an object to an HTTP request. Same as HTTPRequestSerializer, expect instead of HTTP form encoding it does JSON. public class JSONRequestSerializer: HTTPRequestSerializer { /** Creates a new NSMutableURLRequest object with configured options. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A new NSMutableURLRequest with said options or an error. */ public override func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) { if self.isURIParam(method) { return super.createRequest(url, method: method, parameters: parameters) } var request = newRequest(url, method: method) var error: NSError? if parameters != nil { var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: self.contentTypeKey) request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions(), error:&error) } return (request, error) } }
lgpl-3.0
Shun87/Adios
Adios/Regex.swift
6
646
// // Regex.swift // Parser // // Created by Armand Grillet on 30/08/2015. // Copyright © 2015 Armand Grillet. All rights reserved. // import Foundation class Regex { let internalExpression: NSRegularExpression let pattern: String init(pattern: String) { self.pattern = pattern self.internalExpression = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive) } func test(input: String) -> Bool { let matches = self.internalExpression.matchesInString(input, options: .ReportCompletion, range:NSMakeRange(0, input.characters.count)) return matches.count > 0 } }
gpl-3.0
romankisil/eqMac2
native/app/Source/UI/UI.swift
1
11772
// // UI.swift // eqMac // // Created by Roman Kisil on 24/12/2018. // Copyright © 2018 Roman Kisil. All rights reserved. // import Foundation import ReSwift import Cocoa import EmitterKit import SwiftyUserDefaults import WebKit import Zip import SwiftHTTP import Shared enum UIMode: String, Codable { case window = "window" case popover = "popover" } extension UIMode { static let allValues = [ window.rawValue, popover.rawValue ] } class UI: StoreSubscriber { static var state: UIState { return Application.store.state.ui } static var minHeight: Double { return state.minHeight * scale } static var minWidth: Double { return state.minWidth * scale } static var maxHeight: Double { var maxHeight = (state.maxHeight ?? 4000) * scale if (maxHeight < minHeight) { maxHeight = minHeight } return maxHeight } static var maxWidth: Double { var maxWidth = (state.maxWidth ?? 4000) * scale if (maxWidth < minWidth) { maxWidth = minWidth } return maxWidth } static var height: Double { get { return window.height } set { window.height = newValue } } static var width: Double { get { return window.width } set { window.width = newValue } } static var scale: Double { return state.scale } static var minSize: NSSize { return NSSize( width: minWidth, height: minHeight ) } static var maxSize: NSSize { if isResizable { return NSSize( width: maxWidth, height: maxHeight ) } else { return minSize } } static var isResizable: Bool { return state.resizable } static var domain = Constants.UI_ENDPOINT_URL.host! static func unarchiveZip () { // Unpack Archive let fs = FileManager.default if fs.fileExists(atPath: remoteZipPath.path) { try! Zip.unzipFile(remoteZipPath, destination: localPath, overwrite: true, password: nil) // Unzip } else { if !fs.fileExists(atPath: localZipPath.path) { Console.log("\(localZipPath.path) doesnt exist") let bundleUIZipPath = Bundle.main.url(forResource: "ui", withExtension: "zip", subdirectory: "Embedded")! try! fs.copyItem(at: bundleUIZipPath, to: localZipPath) } try! Zip.unzipFile(localZipPath, destination: localPath, overwrite: true, password: nil) // Unzip } } static var localZipPath: URL { return Application.supportPath.appendingPathComponent( "ui-\(Application.version) (Local).zip", isDirectory: false ) } static var remoteZipPath: URL { return Application.supportPath.appendingPathComponent( "ui-\(Application.version) (Remote).zip", isDirectory: false ) } static var localPath: URL { return Application.supportPath.appendingPathComponent("ui") } static let statusItem = StatusItem() static let storyboard = NSStoryboard(name: "Main", bundle: Bundle.main) static var windowController: NSWindowController = ( storyboard.instantiateController( withIdentifier: "EQMWindowController" ) as! NSWindowController) static var window: Window = (windowController.window! as! Window) static var viewController = ( storyboard.instantiateController( withIdentifier: "EQMViewController" ) as! ViewController) static var cachedIsShown: Bool = false static var isShownChanged = Event<Bool>() static var isShown: Bool { return window.isShown } static var mode: UIMode = .window { willSet { DispatchQueue.main.async { window.becomeFirstResponder() if (!duringInit) { show() } } } } static var alwaysOnTop = false { didSet { DispatchQueue.main.async { if alwaysOnTop { window.level = .floating } else { window.level = .normal } } } } static var canHide: Bool { get { return window.canHide } set { window.canHide = newValue } } static func toggle () { DispatchQueue.main.async { if isShown { close() } else { show() } } } static func show () { DispatchQueue.main.async { if mode == .popover { // If mode is Popover move the window to where the Popover would be if let frame = statusItem.item.button?.window?.frame { var point = frame.origin point.x = point.x - window.frame.width / 2 + frame.width / 2 point.y -= 10 window.setFrameOrigin(point) } } window.show() NSApp.activate(ignoringOtherApps: true) } } static func close () { DispatchQueue.main.async { window.close() NSApp.hide(self) } } static func hide () { DispatchQueue.main.async { if mode == .popover { close() } else { window.performMiniaturize(nil) } } } // Instance static var statusItemClickedListener: EventListener<Void>! static var bridge: Bridge! static var duringInit = true init (_ completion: @escaping () -> Void) { DispatchQueue.main.async { func setup () { ({ UI.mode = Application.store.state.ui.mode UI.alwaysOnTop = Application.store.state.ui.alwaysOnTop UI.width = Application.store.state.ui.width UI.height = Application.store.state.ui.height UI.statusItem.iconType = Application.store.state.ui.statusItemIconType })() UI.window.contentViewController = UI.viewController // Set window position to where it was last time, in case that position is not available anymore - reset. if var windowPosition = Application.store.state.ui.windowPosition { var withinBounds = false for screen in NSScreen.screens { if NSPointInRect(windowPosition, screen.frame) { withinBounds = true break } } if (!withinBounds) { if let mainScreen = NSScreen.screens.first { let screenSize = mainScreen.frame.size windowPosition.x = screenSize.width / 2 - CGFloat(UI.width / 2) windowPosition.y = screenSize.height / 2 - CGFloat(UI.height / 2) } else { windowPosition.x = 0 windowPosition.y = 0 } } UI.window.position = windowPosition Application.dispatchAction(UIAction.setWindowPosition(windowPosition)) } UI.close() self.setupStateListener() UI.setupBridge() UI.setupListeners() UI.load() func checkIfVisible () { let shown = UI.isShown if (UI.cachedIsShown != shown) { UI.cachedIsShown = shown UI.isShownChanged.emit(shown) } Async.delay(1000) { checkIfVisible() } } checkIfVisible() completion() Async.delay(1000) { UI.duringInit = false } } if (!UI.viewController.isViewLoaded) { UI.viewController.loaded.once { setup() } let _ = UI.viewController.view } else { setup() } } } static func reload () { viewController.webView.reload() } static func setupBridge () { bridge = Bridge(webView: viewController.webView) } // MARK: - State public typealias StoreSubscriberStateType = UIState private func setupStateListener () { Application.store.subscribe(self) { subscription in subscription.select { state in state.ui } } } func newState(state: UIState) { DispatchQueue.main.async { if (state.mode != UI.mode) { UI.mode = state.mode } if (state.alwaysOnTop != UI.alwaysOnTop) { UI.alwaysOnTop = state.alwaysOnTop } if (state.statusItemIconType != UI.statusItem.iconType) { UI.statusItem.iconType = state.statusItemIconType } if (state.height != UI.height && state.fromUI) { UI.height = state.height } if (state.width != UI.width && state.fromUI) { UI.width = state.width } UI.checkFixWindowSize() } } private static func checkFixWindowSize () { if (UI.height < Double(UI.minSize.height)) { UI.height = Double(UI.minSize.height) } if (UI.height > Double(UI.maxSize.height)) { UI.height = Double(UI.maxSize.height) } if (UI.width < Double(UI.minSize.width)) { UI.width = Double(UI.minSize.width) } if (UI.width > Double(UI.maxSize.width)) { UI.width = Double(UI.maxSize.width) } } private static func setupListeners () { statusItemClickedListener = statusItem.clicked.on {_ in toggle() } } static var hasLoaded = false static var loaded = Event<Void>() static func whenLoaded (_ completion: @escaping () -> Void) { if hasLoaded { return completion() } loaded.once { completion() } } private static func load () { hasLoaded = false func startUILoad (_ url: URL) { DispatchQueue.main.async { viewController.load(url) } } func loadRemote () { Console.log("Loading Remote UI") startUILoad(Constants.UI_ENDPOINT_URL) self.getRemoteVersion { remoteVersion in if remoteVersion != nil { let fs = FileManager.default if fs.fileExists(atPath: remoteZipPath.path) { unarchiveZip() let currentVersion = try? String(contentsOf: localPath.appendingPathComponent("version.txt")) if (currentVersion?.trim() != remoteVersion?.trim()) { self.cacheRemote() } } else { self.cacheRemote() } } } } func loadLocal () { Console.log("Loading Local UI") unarchiveZip() let url = URL(string: "\(localPath)/index.html")! startUILoad(url) } if (Application.store.state.settings.doOTAUpdates) { remoteIsReachable() { reachable in if reachable { loadRemote() } else { loadLocal() } } } else { loadLocal() } } private static func getRemoteVersion (_ completion: @escaping (String?) -> Void) { HTTP.GET("\(Constants.UI_ENDPOINT_URL)/version.txt") { resp in completion(resp.error != nil ? nil : resp.text?.trim()) } } private static func remoteIsReachable (_ completion: @escaping (Bool) -> Void) { var returned = false Networking.checkConnected { reachable in if (!reachable) { returned = true return completion(false) } HTTP.GET(Constants.UI_ENDPOINT_URL.absoluteString) { response in returned = true completion(response.error == nil) } } Async.delay(1000) { if (!returned) { returned = true completion(false) } } } private static func cacheRemote () { // Only download ui.zip when UI endpoint is remote if Constants.UI_ENDPOINT_URL.absoluteString.contains(Constants.DOMAIN) { let remoteZipUrl = "\(Constants.UI_ENDPOINT_URL)/ui.zip" Console.log("Caching Remote UI from \(remoteZipUrl)") let download = HTTP(URLRequest(urlString: remoteZipUrl)!) download.run() { resp in Console.log("Finished caching Remote UI") if resp.error == nil { do { try resp.data.write(to: remoteZipPath, options: .atomic) } catch { print(error) } } } } } deinit { Application.store.unsubscribe(self) } }
mit
adamkaplan/swifter
SwifterTests/LinkedListTests.swift
1
2301
// // LinkedListTests.swift // Swifter // // Created by Daniel Hanggi on 6/26/14. // Copyright (c) 2014 Yahoo!. All rights reserved. // import XCTest class LinkedListTests: XCTestCase { func testInit() { let l1 = LinkedList(this: 10) XCTAssertEqual(l1.this!, 10) XCTAssertNil(l1.next) XCTAssertNil(l1.prev) } func testPush() { let l1 = LinkedList(this: "Cat") l1.push("Kitten") XCTAssertEqual(l1.this!, "Kitten") XCTAssertEqual(l1.next!.this!, "Cat") XCTAssertEqual(l1.next!.prev!.this!, "Kitten") XCTAssertNil(l1.next!.next) XCTAssertNil(l1.prev) } func testPop() { let l1 = LinkedList(this: "Cat") l1.push("Kitten") l1.push("Kitty") XCTAssertEqual(l1.pop()!, "Kitty") XCTAssertEqual(l1.next!.prev!.this!, "Kitten") XCTAssertEqual(l1.this!, "Kitten") XCTAssertEqual(l1.next!.this!, "Cat") XCTAssertNil(l1.next!.next) XCTAssertNil(l1.prev) } func testAppend1() -> () { let l1 = LinkedList(this: "Cat") let l2 = LinkedList(this: "Kitty") l2.append("Kitten") XCTAssertEqual(l2.this!, "Kitty") XCTAssertEqual(l2.next!.this!, "Kitten") XCTAssertEqual(l2.next!.prev!.this!, "Kitty") l1.append(l2) XCTAssertEqual(l1.this!, "Cat") XCTAssertEqual(l1.next!.this!, "Kitty") XCTAssertEqual(l1.next!.prev!.this!, "Cat") XCTAssertEqual(l1.next!.next!.this!, "Kitten") XCTAssertNil(l1.next!.next!.next) } func testIsEmpty() { let l1 = LinkedList<Int>() XCTAssertTrue(l1.isEmpty()) let l2 = LinkedList(this: 10) XCTAssertFalse(l2.isEmpty()) l2.pop() XCTAssertTrue(l2.isEmpty()) } func testSequence() { let l1 = LinkedList<Int>() l1.push(3) l1.push(2) l1.push(1) l1.push(0) var counter = 0 // for i in l1 { // XCTAssertEqual(i, counter++) // } XCTAssertEqual(l1.pop()!, 0) XCTAssertEqual(l1.pop()!, 1) XCTAssertEqual(l1.pop()!, 2) XCTAssertEqual(l1.pop()!, 3) XCTAssertTrue(l1.isEmpty()) } }
apache-2.0
AaronMT/firefox-ios
XCUITests/WebPagesForTesting.swift
6
2111
import Foundation import Shared import GCDWebServers // XCUITests that require custom localhost pages can add handlers here. // This file is compiled as part of Client target, but it is in the XCUITest directory // because it is for XCUITest purposes. func registerHandlersForTestMethods(server: GCDWebServer) { // Add tracking protection check page server.addHandler(forMethod: "GET", path: "/test-fixture/find-in-page-test.html", request: GCDWebServerRequest.self) { (request: GCDWebServerRequest?) in let node = "<span> And the beast shall come forth surrounded by a roiling cloud of vengeance. The house of the unbelievers shall be razed and they shall be scorched to the earth. Their tags shall blink until the end of days. from The Book of Mozilla, 12:10 And the beast shall be made legion. Its numbers shall be increased a thousand thousand fold. The din of a million keyboards like unto a great storm shall cover the earth, and the followers of Mammon shall tremble. from The Book of Mozilla, 3:31 (Red Letter Edition) </span>" let repeatCount = 1000 let textNodes = [String](repeating: node, count: repeatCount).reduce("", +) return GCDWebServerDataResponse(html: "<html><body>\(textNodes)</body></html>") } ["test-indexeddb-private", "test-window-opener", "test-password", "test-password-submit", "test-password-2", "test-password-submit-2", "empty-login-form", "empty-login-form-submit", "test-example", "test-example-link", "test-mozilla-book", "test-mozilla-org", "test-popup-blocker", "manifesto-en", "manifesto-es", "manifesto-zh-CN", "manifesto-ar", "test-user-agent"].forEach { addHTMLFixture(name: $0, server: server) } } // Make sure to add files to '/test-fixtures' directory in the source tree fileprivate func addHTMLFixture(name: String, server: GCDWebServer) { if let path = Bundle.main.path(forResource: "test-fixtures/\(name)", ofType: "html") { server.addGETHandler(forPath: "/test-fixture/\(name).html", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } }
mpl-2.0
AaronMT/firefox-ios
Client/Frontend/Widgets/OneLineCell.swift
8
2163
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit struct OneLineCellUX { static let ImageSize: CGFloat = 29 static let ImageCornerRadius: CGFloat = 6 static let HorizontalMargin: CGFloat = 16 } class OneLineTableViewCell: UITableViewCell, Themeable { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.separatorInset = .zero self.applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let indentation = CGFloat(indentationLevel) * indentationWidth imageView?.translatesAutoresizingMaskIntoConstraints = true imageView?.contentMode = .scaleAspectFill imageView?.layer.cornerRadius = OneLineCellUX.ImageCornerRadius imageView?.layer.masksToBounds = true imageView?.snp.remakeConstraints { make in guard let _ = imageView?.superview else { return } make.width.height.equalTo(OneLineCellUX.ImageSize) make.leading.equalTo(indentation + OneLineCellUX.HorizontalMargin) make.centerY.equalToSuperview() } textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel textLabel?.snp.remakeConstraints { make in guard let _ = textLabel?.superview else { return } make.leading.equalTo(indentation + OneLineCellUX.ImageSize + OneLineCellUX.HorizontalMargin*2) make.trailing.equalTo(isEditing ? 0 : -OneLineCellUX.HorizontalMargin) make.centerY.equalToSuperview() } } override func prepareForReuse() { super.prepareForReuse() self.applyTheme() } func applyTheme() { backgroundColor = UIColor.theme.tableView.rowBackground textLabel?.textColor = UIColor.theme.tableView.rowText } }
mpl-2.0
rnystrom/GitHawk
Classes/Search/SearchRecentHeaderSectionController.swift
1
1389
// // SearchRecentHeaderSectionController.swift // Freetime // // Created by Ryan Nystrom on 9/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit protocol SearchRecentHeaderSectionControllerDelegate: class { func didTapClear(sectionController: SearchRecentHeaderSectionController) } final class SearchRecentHeaderSectionController: ListSectionController, ClearAllHeaderCellDelegate { weak var delegate: SearchRecentHeaderSectionControllerDelegate? init(delegate: SearchRecentHeaderSectionControllerDelegate) { self.delegate = delegate super.init() } override func sizeForItem(at index: Int) -> CGSize { return collectionContext.cellSize(with: Styles.Sizes.tableCellHeight) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: ClearAllHeaderCell.self, for: self, at: index) as? ClearAllHeaderCell else { fatalError("Missing context or wrong cell type") } cell.delegate = self cell.configure(title: NSLocalizedString("Recent Searches", comment: "").uppercased(with: Locale.current)) return cell } // MARK: ClearAllHeaderCellDelegate func didSelectClear(cell: ClearAllHeaderCell) { delegate?.didTapClear(sectionController: self) } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/01709-vtable.swift
1
557
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck }(AnyObject> () { struct c() { class A : A.e = c: B.join(.f = b(2, end: d { A, Any, ()("A> (self.init((self) case C<T) -> { } } } protocol b : C { typealias C
apache-2.0
PrashntS/sleepygeeks
Sleepy/Sleepy/ModelController.swift
1
3243
// // ModelController.swift // Sleepy // // Created by Prashant Sinha on 18/01/15. // Copyright (c) 2015 Prashant Sinha. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData = NSArray() override init() { super.init() // Create the data model. let dateFormatter = NSDateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. if let dataObject: AnyObject = viewController.dataObject { return self.pageData.indexOfObject(dataObject) } else { return NSNotFound } } // MARK: - Page View Controller Data Source func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as DataViewController) if (index == 0) || (index == NSNotFound) { return nil } index-- return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as DataViewController) if index == NSNotFound { return nil } index++ if index == self.pageData.count { return nil } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
mit
micchyboy1023/Today
Today Watch App/Today Watch Extension/ExtensionDelegate.swift
1
881
// // ExtensionDelegate.swift // TodayWatch Extension // // Created by UetaMasamichi on 2016/01/20. // Copyright © 2016年 Masamichi Ueta. All rights reserved. // import WatchKit import WatchConnectivity import TodayWatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { private var session: WCSession! func applicationDidFinishLaunching() { if WCSession.isSupported() { session = WCSession.default() session.delegate = self session.activate() } } func applicationDidBecomeActive() { } func applicationWillResignActive() { } } //MARK: - WCSessionDelegate extension ExtensionDelegate: WCSessionDelegate { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/27787-swift-typechecker-overapproximateosversionsatlocation.swift
3
256
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {@objc protocol P{subscript(t:String)->S
apache-2.0
1aurabrown/eidolon
Kiosk/Bid Fulfillment/Models/BidDetails.swift
1
542
@objc class BidDetails: NSObject { dynamic var newUser: NewUser = NewUser() dynamic var saleArtwork: SaleArtwork? dynamic var bidderNumber: String? dynamic var bidderPIN: String? dynamic var bidAmountCents: NSNumber? dynamic var bidderID: String? init(saleArtwork: SaleArtwork?, bidderNumber: String?, bidderPIN: String?, bidAmountCents:Int?) { self.saleArtwork = saleArtwork self.bidderNumber = bidderNumber self.bidderPIN = bidderPIN self.bidAmountCents = bidAmountCents } }
mit
dangthaison91/SwagGen
Specs/petstore_full/generated/Swift/Sources/API/Models/ArrayOfArrayOfNumberOnly.swift
1
953
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation import JSONUtilities public class ArrayOfArrayOfNumberOnly: JSONDecodable, JSONEncodable, PrettyPrintable { public var arrayArrayNumber: [[Double]]? public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } public required init(jsonDictionary: JSONDictionary) throws { arrayArrayNumber = jsonDictionary.json(atKeyPath: "ArrayArrayNumber") } public func encode() -> JSONDictionary { var dictionary: JSONDictionary = [:] if let arrayArrayNumber = arrayArrayNumber?.encode() { dictionary["ArrayArrayNumber"] = arrayArrayNumber } return dictionary } /// pretty prints all properties including nested models public var prettyPrinted: String { return "\(type(of: self)):\n\(encode().recursivePrint(indentIndex: 1))" } }
mit
KnockSoftware/RCounter
RCounterExample/ViewController.swift
1
526
// // ViewController.swift // RCounter Example // // Created by William Henderson on 10/21/15. // Copyright © 2015 William Henderson. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
chanhx/Octogit
iGithub/Models/Event.swift
2
8305
// // Event.swift // iGithub // // Created by Chan Hocheung on 7/21/16. // Copyright © 2016 Hocheung. All rights reserved. // import Foundation import ObjectMapper import SwiftDate enum EventType: String { case commitCommentEvent = "CommitCommentEvent" case createEvent = "CreateEvent" case deleteEvent = "DeleteEvent" case deploymentEvent = "DeploymentEvent" // not visible case deploymentStatusEvent = "DeploymentStatusEvent" // not visible case downloadEvent = "DownloadEvent" // no longer created case followEvent = "FollowEvent" // no longer created case forkEvent = "ForkEvent" case forkApplyEvent = "ForkApplyEvent" // no longer created case gistEvent = "GistEvent" // no longer created case gollumEvent = "GollumEvent" case issueCommentEvent = "IssueCommentEvent" case issuesEvent = "IssuesEvent" case memberEvent = "MemberEvent" case membershipEvent = "MembershipEvent" // not visible case pageBuildEvent = "PageBuildEvent" // not visible case publicEvent = "PublicEvent" case pullRequestEvent = "PullRequestEvent" case pullRequestReviewCommentEvent = "PullRequestReviewCommentEvent" case pushEvent = "PushEvent" case releaseEvent = "ReleaseEvent" case repositoryEvent = "RepositoryEvent" // not visible case statusEvent = "StatusEvent" // not visible case teamAddEvent = "TeamAddEvent" case watchEvent = "WatchEvent" } class Event: Mappable, StaticMappable { var id: Int? var type: EventType? var repository: String? var actor: User? var org: User? var createdAt: Date? static func objectForMapping(map: ObjectMapper.Map) -> BaseMappable? { if let type: EventType = EventType(rawValue: map["type"].value()!) { switch type { case .commitCommentEvent: return CommitCommentEvent(map: map) case .createEvent: return CreateEvent(map: map) case .deleteEvent: return DeleteEvent(map: map) case .forkEvent: return ForkEvent(map: map) case .gollumEvent: return GollumEvent(map: map) case .issueCommentEvent: return IssueCommentEvent(map: map) case .issuesEvent: return IssueEvent(map: map) case .memberEvent: return MemberEvent(map: map) case .publicEvent: return PublicEvent(map: map) case .pullRequestEvent: return PullRequestEvent(map: map) case .pullRequestReviewCommentEvent: return PullRequestReviewCommentEvent(map: map) case .pushEvent: return PushEvent(map: map) case .releaseEvent: return ReleaseEvent(map: map) case .watchEvent: return WatchEvent(map: map) default: return nil } } return nil } required init?(map: Map) { mapping(map: map) } func mapping(map: Map) { id <- (map["id"], IntTransform()) type <- map["type"] repository <- map["repo.name"] actor <- map["actor"] org <- map["org"] createdAt <- (map["created_at"], ISO8601DateTransform()) } } // MARK: CommitCommentEvent class CommitCommentEvent : Event { var comment: CommitComment? override func mapping(map: Map) { super.mapping(map: map) comment <- map["payload.comment"] } } enum RefType : String { case branch = "branch" case tag = "tag" case repository = "repository" } // MARK: CreateEvent class CreateEvent: Event { var refType: RefType? var ref: String? var repoDescription: String? override func mapping(map: Map) { super.mapping(map: map) refType <- map["payload.ref_type"] ref <- map["payload.ref"] repoDescription <- map["payload.description"] } } // MARK: DeleteEvent class DeleteEvent: Event { var refType: RefType? var ref: String? override func mapping(map: Map) { super.mapping(map: map) refType <- map["payload.ref_type"] ref <- map["payload.ref"] } } // MARK: ForkEvent class ForkEvent: Event { var forkee: String? var forkeeDescription: String? override func mapping(map: Map) { super.mapping(map: map) forkee <- map["payload.forkee.full_name"] forkeeDescription <- map["payload.forkee.description"] } } // MARK: GollumEvent class GollumEvent: Event { var pageName: String? var action: String? var summary: String? override func mapping(map: Map) { super.mapping(map: map) pageName <- map["payload.pages.0.page_name"] action <- map["payload.pages.0.action"] summary <- map["payload.pages.0.summary"] } } // MARK: IssueCommentEvent class IssueCommentEvent : Event { var action: String? var issue: Issue? var comment: String? override func mapping(map: Map) { super.mapping(map: map) action <- map["payload.action"] issue <- map["payload.issue"] comment <- map["payload.comment.body"] } } // MARK: IssueEvent enum IssueAction: String { case assigned = "assigned" case unassigned = "unassigned" case labeled = "labeled" case unlabeled = "unlabeled" case opened = "opened" case edited = "edited" case closed = "closed" case reopened = "reopened" } class IssueEvent: Event { var issue: Issue? var action: IssueAction? override func mapping(map: Map) { super.mapping(map: map) issue <- map["payload.issue"] action <- map["payload.action"] } } // MARK: MemberEvent class MemberEvent: Event { var member: User? override func mapping(map: Map) { super.mapping(map: map) member <- map["payload.member"] } } // MARK: PublicEvent class PublicEvent: Event { var repositoryDescription: String? override func mapping(map: Map) { super.mapping(map: map) repositoryDescription <- map["payload.repository.description"] } } // MARK: PullRequestEvent class PullRequestEvent : Event { var pullRequest: PullRequest? var action: IssueAction? override func mapping(map: Map) { super.mapping(map: map) pullRequest <- map["payload.pull_request"] action <- map["payload.action"] } } // MARK: PullRequestCommentEvent class PullRequestReviewCommentEvent : Event { var action: String? var pullRequest : PullRequest? var comment: String? override func mapping(map: Map) { super.mapping(map: map) action <- map["payload.action"] pullRequest <- map["payload.pull_request"] comment <- map["payload.comment.body"] } } // MARK: PushEvent class PushEvent : Event { var ref: String? var commitCount: Int? var distinctCommitCount: Int? var previousHeadSHA: String? var currentHeadSHA: String? var branchName: String? var commits: [EventCommit]? override func mapping(map: Map) { super.mapping(map: map) ref <- map["payload.ref"] commitCount <- map["payload.size"] distinctCommitCount <- map["payload.distinct_size"] previousHeadSHA <- map["payload.before"] currentHeadSHA <- map["payload.head"] branchName <- map["payload.ref"] commits <- map["payload.commits"] } } // MARK: ReleaseEvent class ReleaseEvent: Event { var releaseTagName: String? override func mapping(map: Map) { super.mapping(map: map) releaseTagName <- map["payload.release.tag_name"] } } // MARK: WatchEvent class WatchEvent : Event { var action: String? override func mapping(map: Map) { super.mapping(map: map) action <- map["payload.action"] } }
gpl-3.0
ptankTwilio/video-quickstart-swift
VideoCallKitQuickStart/ViewController.swift
1
14186
// // ViewController.swift // VideoCallKitQuickStart // // Copyright © 2016-2017 Twilio, Inc. All rights reserved. // import UIKit import TwilioVideo import CallKit class ViewController: UIViewController { // MARK: View Controller Members // Configure access token manually for testing, if desired! Create one manually in the console // at https://www.twilio.com/user/account/video/dev-tools/testing-tools var accessToken = "TWILIO_ACCESS_TOKEN" // Configure remote URL to fetch token from var tokenUrl = "http://localhost:8000/token.php" // Video SDK components var room: TVIRoom? var camera: TVICameraCapturer? var localVideoTrack: TVILocalVideoTrack? var localAudioTrack: TVILocalAudioTrack? var participant: TVIParticipant? var remoteView: TVIVideoView? // CallKit components let callKitProvider:CXProvider let callKitCallController:CXCallController var callKitCompletionHandler: ((Bool)->Swift.Void?)? = nil // MARK: UI Element Outlets and handles @IBOutlet weak var connectButton: UIButton! @IBOutlet weak var simulateIncomingButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var roomTextField: UITextField! @IBOutlet weak var roomLine: UIView! @IBOutlet weak var roomLabel: UILabel! @IBOutlet weak var micButton: UIButton! // `TVIVideoView` created from a storyboard @IBOutlet weak var previewView: TVIVideoView! required init?(coder aDecoder: NSCoder) { let configuration = CXProviderConfiguration(localizedName: "CallKit Quickstart") configuration.maximumCallGroups = 1 configuration.maximumCallsPerCallGroup = 1 configuration.supportsVideo = true if let callKitIcon = UIImage(named: "iconMask80") { configuration.iconTemplateImageData = UIImagePNGRepresentation(callKitIcon) } callKitProvider = CXProvider(configuration: configuration) callKitCallController = CXCallController() super.init(coder: aDecoder) callKitProvider.setDelegate(self, queue: nil) } deinit { // CallKit has an odd API contract where the developer must call invalidate or the CXProvider is leaked. callKitProvider.invalidate() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() if PlatformUtils.isSimulator { self.previewView.removeFromSuperview() } else { // Preview our local camera track in the local video preview view. self.startPreview() } // Disconnect and mic button will be displayed when the Client is connected to a Room. self.disconnectButton.isHidden = true self.micButton.isHidden = true self.roomTextField.delegate = self let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) self.view.addGestureRecognizer(tap) } func setupRemoteVideoView() { // Creating `TVIVideoView` programmatically self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate: self) self.view.insertSubview(self.remoteView!, at: 0) // `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit // scaleAspectFit is the default mode when you create `TVIVideoView` programmatically. self.remoteView!.contentMode = .scaleAspectFit; let centerX = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0); self.view.addConstraint(centerX) let centerY = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0); self.view.addConstraint(centerY) let width = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0); self.view.addConstraint(width) let height = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0); self.view.addConstraint(height) } // MARK: IBActions @IBAction func connect(sender: AnyObject) { performStartCallAction(uuid: UUID.init(), roomName: self.roomTextField.text) self.dismissKeyboard() } @IBAction func disconnect(sender: AnyObject) { if let room = room, let uuid = room.uuid { logMessage(messageText: "Attempting to disconnect from room \(room.name)") performEndCallAction(uuid: uuid) } } @IBAction func toggleMic(sender: AnyObject) { if (self.localAudioTrack != nil) { self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)! // Update the button title if (self.localAudioTrack?.isEnabled == true) { self.micButton.setTitle("Mute", for: .normal) } else { self.micButton.setTitle("Unmute", for: .normal) } } } // MARK: Private func startPreview() { if PlatformUtils.isSimulator { return } // Preview our local camera track in the local video preview view. camera = TVICameraCapturer(source: .frontCamera, delegate: self) localVideoTrack = TVILocalVideoTrack.init(capturer: camera!) if (localVideoTrack == nil) { logMessage(messageText: "Failed to create video track") } else { // Add renderer to video track for local preview localVideoTrack!.addRenderer(self.previewView) logMessage(messageText: "Video track created") // We will flip camera on tap. let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.flipCamera)) self.previewView.addGestureRecognizer(tap) } } func flipCamera() { if (self.camera?.source == .frontCamera) { self.camera?.selectSource(.backCameraWide) } else { self.camera?.selectSource(.frontCamera) } } func prepareLocalMedia() { // We will share local audio and video when we connect to the Room. // Create an audio track. if (localAudioTrack == nil) { localAudioTrack = TVILocalAudioTrack.init() if (localAudioTrack == nil) { logMessage(messageText: "Failed to create audio track") } } // Create a video track which captures from the camera. if (localVideoTrack == nil) { self.startPreview() } } // Update our UI based upon if we are in a Room or not func showRoomUI(inRoom: Bool) { self.connectButton.isHidden = inRoom self.simulateIncomingButton.isHidden = inRoom self.roomTextField.isHidden = inRoom self.roomLine.isHidden = inRoom self.roomLabel.isHidden = inRoom self.micButton.isHidden = !inRoom self.disconnectButton.isHidden = !inRoom UIApplication.shared.isIdleTimerDisabled = inRoom } func dismissKeyboard() { if (self.roomTextField.isFirstResponder) { self.roomTextField.resignFirstResponder() } } func cleanupRemoteParticipant() { if ((self.participant) != nil) { if ((self.participant?.videoTracks.count)! > 0) { self.participant?.videoTracks[0].removeRenderer(self.remoteView!) self.remoteView?.removeFromSuperview() self.remoteView = nil } } self.participant = nil } func logMessage(messageText: String) { NSLog(messageText) messageLabel.text = messageText } func holdCall(onHold: Bool) { localAudioTrack?.isEnabled = !onHold localVideoTrack?.isEnabled = !onHold } } // MARK: UITextFieldDelegate extension ViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.connect(sender: textField) return true } } // MARK: TVIRoomDelegate extension ViewController : TVIRoomDelegate { func didConnect(to room: TVIRoom) { // At the moment, this example only supports rendering one Participant at a time. logMessage(messageText: "Connected to room \(room.name) as \(String(describing: room.localParticipant?.identity))") if (room.participants.count > 0) { self.participant = room.participants[0] self.participant?.delegate = self } let cxObserver = callKitCallController.callObserver let calls = cxObserver.calls // Let the call provider know that the outgoing call has connected if let uuid = room.uuid, let call = calls.first(where:{$0.uuid == uuid}) { if call.isOutgoing { callKitProvider.reportOutgoingCall(with: uuid, connectedAt: nil) } } self.callKitCompletionHandler!(true) } func room(_ room: TVIRoom, didDisconnectWithError error: Error?) { logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))") self.cleanupRemoteParticipant() self.room = nil self.showRoomUI(inRoom: false) self.callKitCompletionHandler = nil } func room(_ room: TVIRoom, didFailToConnectWithError error: Error) { logMessage(messageText: "Failed to connect to room with error: \(error.localizedDescription)") self.callKitCompletionHandler!(false) self.room = nil self.showRoomUI(inRoom: false) } func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) { if (self.participant == nil) { self.participant = participant self.participant?.delegate = self } logMessage(messageText: "Room \(room.name), Participant \(participant.identity) connected") } func room(_ room: TVIRoom, participantDidDisconnect participant: TVIParticipant) { if (self.participant == participant) { cleanupRemoteParticipant() } logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected") } } // MARK: TVIParticipantDelegate extension ViewController : TVIParticipantDelegate { func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) { logMessage(messageText: "Participant \(participant.identity) added video track") if (self.participant == participant) { setupRemoteVideoView() videoTrack.addRenderer(self.remoteView!) } } func participant(_ participant: TVIParticipant, removedVideoTrack videoTrack: TVIVideoTrack) { logMessage(messageText: "Participant \(participant.identity) removed video track") if (self.participant == participant) { videoTrack.removeRenderer(self.remoteView!) self.remoteView?.removeFromSuperview() self.remoteView = nil } } func participant(_ participant: TVIParticipant, addedAudioTrack audioTrack: TVIAudioTrack) { logMessage(messageText: "Participant \(participant.identity) added audio track") } func participant(_ participant: TVIParticipant, removedAudioTrack audioTrack: TVIAudioTrack) { logMessage(messageText: "Participant \(participant.identity) removed audio track") } func participant(_ participant: TVIParticipant, enabledTrack track: TVITrack) { var type = "" if (track is TVIVideoTrack) { type = "video" } else { type = "audio" } logMessage(messageText: "Participant \(participant.identity) enabled \(type) track") } func participant(_ participant: TVIParticipant, disabledTrack track: TVITrack) { var type = "" if (track is TVIVideoTrack) { type = "video" } else { type = "audio" } logMessage(messageText: "Participant \(participant.identity) disabled \(type) track") } } // MARK: TVIVideoViewDelegate extension ViewController : TVIVideoViewDelegate { func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) { self.view.setNeedsLayout() } } // MARK: TVICameraCapturerDelegate extension ViewController : TVICameraCapturerDelegate { func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) { self.previewView.shouldMirror = (source == .frontCamera) } }
mit
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Playgrounds/Functions 2.playground/Pages/Section 3 - Generic Functions.xcplaygroundpage/Contents.swift
2
1415
//: [Previous](@previous) import UIKit import PlaygroundSupport //: ![Functions Part 2](banner.png) //: # Functions Part 2 - Section 3 //: Version 3 - updated for Swift 3 //: //: 24-11-2016 //: //: This playground is designed to support the materials of the lecure "Functions 2". //: ## Generic Functions //: Consider the following function func swapInt( _ tupleValue : (Int, Int) ) -> (Int, Int) { let y = (tupleValue.1, tupleValue.0) return y } let u2 = (2,3) let v2 = swapInt( u2 ) //: This function only works with type Int. It cannot be used for other types. This is where Generics come in. The compiler will generate alternative versions using the required types (where appropriate). //: ### Generic Functions without constraints func swap<U,V>( _ tupleValue : (U, V) ) -> (V, U) { let y = (tupleValue.1, tupleValue.0) return y } swap( (1, "Fred") ) //: ### Generic Functions with constraints func compareAnything<U:Equatable>(_ a : U, b : U) -> Bool { return a == b } compareAnything(10, b: 10) //: ### Generic Functions with custom constraints protocol CanMultiply { static func *(left: Self, right: Self) -> Self } extension Double : CanMultiply {} extension Int : CanMultiply {} extension Float : CanMultiply {} func cuboidVolume<T:CanMultiply>(_ width:T, _ height:T, _ depth:T) -> T { return (width*height*depth) } cuboidVolume(2.1, 3.1, 4.1) cuboidVolume(2.1, 3, 4)
mit
khizkhiz/swift
validation-test/compiler_crashers_fixed/28161-swift-constraints-constraintsystem-solvesingle.swift
1
348
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { class B{ class p{ { } enum S{ var d=a{ } struct B:Collection}}} enum E<T where B:a{struct B{{}struct B<g{class B{class d{var _=B a
apache-2.0
sinoru/STwitter
Sources/StatusSessionTask.swift
1
801
// // StatusSessionTask.swift // STwitter // // Created by Sinoru on 2016. 12. 4.. // Copyright © 2016 Sinoru. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @objc(STWStatusSessionTask) public class StatusSessionTask: SessionTask { }
apache-2.0
2345Team/Design-Pattern-For-Swift
1.SimpleFactoryPattern/SimpleFactory/Factory/CalculateMinus.swift
1
312
// // CalculateMinus.swift // SimpleFactory // // Created by luzhiyong on 16/5/8. // Copyright © 2016年 2345. All rights reserved. // import UIKit class CalculateMinus: Calculate { override func calculate() -> Float { super.calculate() return firstNumber - secondNumber } }
mit
mqshen/SwiftForms
SwiftForms/cells/FormSegmentedControlCell.swift
1
3529
// // FormSegmentedControlCell.swift // SwiftForms // // Created by Miguel Angel Ortuno on 21/08/14. // Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormSegmentedControlCell: FormBaseCell { // MARK: Cell views public let titleLabel = UILabel() public let segmentedControl = UISegmentedControl() // MARK: Properties private var customConstraints: [AnyObject] = [] // MARK: FormBaseCell public override func configure() { super.configure() selectionStyle = .None titleLabel.translatesAutoresizingMaskIntoConstraints = false segmentedControl.translatesAutoresizingMaskIntoConstraints = false titleLabel.setContentCompressionResistancePriority(500, forAxis: .Horizontal) segmentedControl.setContentCompressionResistancePriority(500, forAxis: .Horizontal) titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) contentView.addSubview(titleLabel) contentView.addSubview(segmentedControl) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) segmentedControl.addTarget(self, action: #selector(FormSegmentedControlCell.valueChanged(_:)), forControlEvents: .ValueChanged) } public override func update() { super.update() titleLabel.text = rowDescriptor?.title updateSegmentedControl() guard let value = rowDescriptor?.value else { return } guard let options = rowDescriptor?.configuration.selection.options where !options.isEmpty else { return } var idx = 0 for optionValue in options { if optionValue === value { segmentedControl.selectedSegmentIndex = idx break } idx += 1 } } public override func constraintsViews() -> [String : UIView] { return ["titleLabel" : titleLabel, "segmentedControl" : segmentedControl] } public override func defaultVisualConstraints() -> [String] { if let text = titleLabel.text where text.characters.count > 0 { return ["H:|-16-[titleLabel]-16-[segmentedControl]-16-|"] } else { return ["H:|-16-[segmentedControl]-16-|"] } } // MARK: Actions internal func valueChanged(sender: UISegmentedControl) { guard let options = rowDescriptor?.configuration.selection.options where !options.isEmpty else { return } let value = options[sender.selectedSegmentIndex] rowDescriptor?.value = value } // MARK: Private private func updateSegmentedControl() { segmentedControl.removeAllSegments() guard let options = rowDescriptor?.configuration.selection.options where !options.isEmpty else { return } var idx = 0 for value in options { let title = rowDescriptor?.configuration.selection.optionTitleClosure?(value) segmentedControl.insertSegmentWithTitle(title, atIndex: idx, animated: false) idx += 1 } } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/21475-swift-constraints-constraint-createbindoverload.swift
11
252
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a { var f = [ ] struct Q<T { class a { deinit { { } class a { let end = a( )
mit
wuleijun/Zeus
Zeus/ZeusAlert.swift
1
3362
// // ZeusAlert.swift // Zeus // // Created by 吴蕾君 on 16/4/11. // Copyright © 2016年 rayjuneWu. All rights reserved. // import UIKit class ZeusAlert { class func alert(title title: String, message: String?, dismissTitle: String, inViewController viewController: UIViewController?, withDismissAction dismissAction: (() -> Void)?) { dispatch_async(dispatch_get_main_queue()) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action: UIAlertAction = UIAlertAction(title: dismissTitle, style: .Default) { action -> Void in if let dismissAction = dismissAction { dismissAction() } } alertController.addAction(action) viewController?.presentViewController(alertController, animated: true, completion: nil) } } class func alertConfirmOrCancel(title title: String, message: String, confirmTitle: String, cancelTitle: String, inViewController viewController: UIViewController?, withConfirmAction confirmAction: () -> Void, cancelAction: () -> Void) { dispatch_async(dispatch_get_main_queue()) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction: UIAlertAction = UIAlertAction(title: cancelTitle, style: .Cancel) { action -> Void in cancelAction() } alertController.addAction(cancelAction) let confirmAction: UIAlertAction = UIAlertAction(title: confirmTitle, style: .Default) { action -> Void in confirmAction() } alertController.addAction(confirmAction) viewController?.presentViewController(alertController, animated: true, completion: nil) } } class func alertSorry(message message: String?, inViewController viewController: UIViewController?) { alert(title: "抱歉", message: message, dismissTitle: "确定", inViewController: viewController, withDismissAction: nil) } } extension UIViewController { func alertCanNotAccessCameraRoll() { dispatch_async(dispatch_get_main_queue()) { ZeusAlert.alertConfirmOrCancel(title: "抱歉", message:"EMM不能访问您的相册!\n但您可以在iOS设置里修改设定。", confirmTitle: "现在就改", cancelTitle: "取消", inViewController: self, withConfirmAction: { UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) }, cancelAction: { }) } } func alertCanNotOpenCamera() { dispatch_async(dispatch_get_main_queue()) { ZeusAlert.alertConfirmOrCancel(title: "抱歉", message:"EMM不能打开您的相机!\n但您可以在iOS设置里修改设定。", confirmTitle: "现在就改", cancelTitle: "取消", inViewController: self, withConfirmAction: { UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) }, cancelAction: { }) } } }
mit
radex/swift-compiler-crashes
crashes-duplicates/10104-swift-constraints-constraintsystem-solve.swift
11
246
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var : { if true { func a( ) -> { let : A protocol A { func p typealias e : e
mit
lkzhao/MCollectionView
Sources/UIScrollView+Addtion.swift
1
1679
// // UIScrollView+Addtion.swift // MCollectionView // // Created by Luke on 4/16/17. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit import YetAnotherAnimationLibrary extension UIScrollView { public var visibleFrame: CGRect { return bounds } public var visibleFrameLessInset: CGRect { return UIEdgeInsetsInsetRect(visibleFrame, contentInset) } public var absoluteFrameLessInset: CGRect { return UIEdgeInsetsInsetRect(CGRect(origin:.zero, size:bounds.size), contentInset) } public var innerSize: CGSize { return absoluteFrameLessInset.size } public var offsetFrame: CGRect { return CGRect(x: -contentInset.left, y: -contentInset.top, width: max(0, contentSize.width - bounds.width + contentInset.right + contentInset.left), height: max(0, contentSize.height - bounds.height + contentInset.bottom + contentInset.top)) } public func absoluteLocation(for point: CGPoint) -> CGPoint { return point - contentOffset } public func scrollTo(edge: UIRectEdge, animated: Bool) { let target:CGPoint switch edge { case UIRectEdge.top: target = CGPoint(x: contentOffset.x, y: offsetFrame.minY) case UIRectEdge.bottom: target = CGPoint(x: contentOffset.x, y: offsetFrame.maxY) case UIRectEdge.left: target = CGPoint(x: offsetFrame.minX, y: contentOffset.y) case UIRectEdge.right: target = CGPoint(x: offsetFrame.maxY, y: contentOffset.y) default: return } if animated { yaal.contentOffset.animateTo(target) } else { contentOffset = target yaal.contentOffset.updateWithCurrentState() } } }
mit
txaidw/TWControls
TWSpriteKitUtils/TWLayout/TWCollectionNode.swift
1
3132
// // File.swift // Repel // // Created by Txai Wieser on 7/22/15. // // import SpriteKit open class TWCollectionNode: SKSpriteNode { open fileprivate(set) var fillMode: FillMode open fileprivate(set) var subNodes: [SKNode] = [] open var reloadCompletion: (()->())? = nil required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(fillMode: FillMode) { self.fillMode = fillMode super.init(texture: nil, color: SKColor.clear, size: CGSize(width: fillMode.width, height: 0)) } open func reloadCollection() { let elements = subNodes.count let columns = fillMode.columns let xDiv = (fillMode.width - CGFloat(fillMode.columns)*fillMode.objectSize.width) / CGFloat(fillMode.columns-1) let lines = Int(ceil(CGFloat(elements)/CGFloat(columns))) var accumulatedHeight = CGFloat(0) for lineIndex in 0..<lines { let resta = elements - lineIndex*columns let distance = fillMode.objectSize.height + fillMode.verticalMargin for columnIdex in 0..<min(columns, resta) { var xPos = (-size.width/2 + fillMode.objectSize.width/2) xPos += CGFloat(columnIdex)*(fillMode.objectSize.width+xDiv) let yPos = -CGFloat(lineIndex)*distance - fillMode.objectSize.height/2 subNodes[lineIndex*columns + columnIdex].position = CGPoint(x: xPos, y: yPos) } accumulatedHeight += distance } subNodes.forEach { $0.position.y += accumulatedHeight/2 - self.fillMode.verticalMargin/2 } self.size.height = accumulatedHeight - self.fillMode.verticalMargin reloadCompletion?() } open func add(node: SKNode, reload: Bool = false) { subNodes.append(node) self.addChild(node) if reload { self.reloadCollection() } } open func remove(node: SKNode?, reload: Bool = false) { if let n = node { n.removeFromParent() if let ind = subNodes.index(of: n) { subNodes.remove(at: ind) } if reload { self.reloadCollection() } } } public struct FillMode { let columns: Int let width: CGFloat let verticalMargin: CGFloat let objectSize: CGSize public init(columns: Int, width: CGFloat, verticalMargin: CGFloat, objectSize: CGSize) { self.columns = columns self.width = width self.verticalMargin = verticalMargin self.objectSize = objectSize } } } public extension SKNode { public func removeNodeFromCollection(_ withRefresh: Bool = true) { if let collection = self.parent as? TWCollectionNode { collection.remove(node: self, reload: withRefresh) } else { let message = "TWSKUtils ERROR: Node is not in a TWCollectionNode" assertionFailure(message) } } }
mit
rokuz/omim
iphone/Maps/Classes/CustomAlert/CreateBookmarkCategory/BCCreateCategoryAlert.swift
1
4313
@objc(MWMBCCreateCategoryAlert) final class BCCreateCategoryAlert: MWMAlert { private enum State { case valid case tooFewSymbols case tooManySymbols case nameAlreadyExists } @IBOutlet private(set) weak var textField: UITextField! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var textFieldContainer: UIView! @IBOutlet private weak var centerHorizontaly: NSLayoutConstraint! @IBOutlet private weak var errorLabel: UILabel! @IBOutlet private weak var charactersCountLabel: UILabel! @IBOutlet private weak var rightButton: UIButton! { didSet { rightButton.setTitleColor(UIColor.blackHintText(), for: .disabled) } } private var maxCharactersNum: UInt? private var minCharactersNum: UInt? private var callback: MWMCheckStringBlock? @objc static func alert(maxCharachersNum: UInt, minCharactersNum: UInt, callback: @escaping MWMCheckStringBlock) -> BCCreateCategoryAlert? { guard let alert = Bundle.main.loadNibNamed(className(), owner: nil, options: nil)?.first as? BCCreateCategoryAlert else { assertionFailure() return nil } alert.titleLabel.text = L("bookmarks_create_new_group") let text = L("create").capitalized for s in [.normal, .highlighted, .disabled] as [UIControl.State] { alert.rightButton.setTitle(text, for: s) } alert.maxCharactersNum = maxCharachersNum alert.minCharactersNum = minCharactersNum alert.callback = callback alert.process(state: .tooFewSymbols) alert.formatCharactersCountText() MWMKeyboard.add(alert) return alert } @IBAction private func leftButtonTap() { MWMKeyboard.remove(self) close(nil) } @IBAction private func rightButtonTap() { guard let callback = callback, let text = textField.text else { assertionFailure() return } if callback(text) { MWMKeyboard.remove(self) close(nil) } else { process(state: .nameAlreadyExists) } } @IBAction private func editingChanged(sender: UITextField) { formatCharactersCountText() process(state: checkState()) } private func checkState() -> State { let count = textField.text!.count if count <= minCharactersNum! { return .tooFewSymbols } if count > maxCharactersNum! { return .tooManySymbols } return .valid } private func process(state: State) { let color: UIColor switch state { case .valid: color = UIColor.blackHintText() rightButton.isEnabled = true errorLabel.isHidden = true case .tooFewSymbols: color = UIColor.blackHintText() errorLabel.isHidden = true rightButton.isEnabled = false case .tooManySymbols: color = UIColor.buttonRed() errorLabel.isHidden = false errorLabel.text = L("bookmarks_error_title_list_name_too_long") rightButton.isEnabled = false case .nameAlreadyExists: color = UIColor.buttonRed() errorLabel.isHidden = false errorLabel.text = L("bookmarks_error_title_list_name_already_taken") rightButton.isEnabled = false } charactersCountLabel.textColor = color textFieldContainer.layer.borderColor = color.cgColor } private func formatCharactersCountText() { let count = textField.text!.count charactersCountLabel.text = String(count) + " / " + String(maxCharactersNum!) } } extension BCCreateCategoryAlert: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if checkState() == .valid { rightButtonTap() } return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let str = textField.text as NSString? let newStr = str?.replacingCharacters(in: range, with: string) guard let count = newStr?.count else { return true } if count > maxCharactersNum! + 1 { return false } return true } } extension BCCreateCategoryAlert: MWMKeyboardObserver { func onKeyboardAnimation() { centerHorizontaly.constant = -MWMKeyboard.keyboardHeight() / 2 layoutIfNeeded() } func onKeyboardWillAnimate() { setNeedsLayout() } }
apache-2.0
richeterre/jumu-nordost-ios
JumuNordost/Application/SeparatorView.swift
1
595
// // SeparatorView.swift // JumuNordost // // Created by Martin Richter on 27/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import UIKit class SeparatorView: UIView { // MARK: - Lifecycle init() { super.init(frame: CGRectZero) self.backgroundColor = Color.separatorColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override func intrinsicContentSize() -> CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: 1) } }
mit
rokuz/omim
iphone/Maps/Core/Subscriptions/SubscriptionManager.swift
1
8290
@objc protocol ISubscriptionManager: class{ typealias SuscriptionsCompletion = ([ISubscription]?, Error?) -> Void typealias ValidationCompletion = (MWMValidationResult) -> Void @objc static func canMakePayments() -> Bool @objc func getAvailableSubscriptions(_ completion: @escaping SuscriptionsCompletion) @objc func subscribe(to subscription: ISubscription) @objc func addListener(_ listener: SubscriptionManagerListener) @objc func removeListener(_ listener: SubscriptionManagerListener) @objc func validate(completion: ValidationCompletion?) @objc func restore(_ callback: @escaping ValidationCompletion) } @objc protocol SubscriptionManagerListener: AnyObject { func didFailToSubscribe(_ subscription: ISubscription, error: Error?) func didSubscribe(_ subscription: ISubscription) func didDefer(_ subscription: ISubscription) func didFailToValidate() func didValidate(_ isValid: Bool) } class SubscriptionManager: NSObject, ISubscriptionManager { private let paymentQueue = SKPaymentQueue.default() private var productsRequest: SKProductsRequest? private var subscriptionsComplection: SuscriptionsCompletion? private var products: [String: SKProduct]? private var pendingSubscription: ISubscription? private var listeners = NSHashTable<SubscriptionManagerListener>.weakObjects() private var restorationCallback: ValidationCompletion? private var productIds: [String] = [] private var serverId: String = "" private var vendorId: String = "" private var purchaseManager: MWMPurchaseManager? convenience init(productIds: [String], serverId: String, vendorId: String) { self.init() self.productIds = productIds self.serverId = serverId self.vendorId = vendorId self.purchaseManager = MWMPurchaseManager(vendorId: vendorId) } override private init() { super.init() paymentQueue.add(self) } deinit { paymentQueue.remove(self) } @objc static func canMakePayments() -> Bool { return SKPaymentQueue.canMakePayments() } @objc func getAvailableSubscriptions(_ completion: @escaping SuscriptionsCompletion){ subscriptionsComplection = completion productsRequest = SKProductsRequest(productIdentifiers: Set(productIds)) productsRequest!.delegate = self productsRequest!.start() } @objc func subscribe(to subscription: ISubscription) { pendingSubscription = subscription guard let product = products?[subscription.productId] else { return } paymentQueue.add(SKPayment(product: product)) } @objc func addListener(_ listener: SubscriptionManagerListener) { listeners.add(listener) } @objc func removeListener(_ listener: SubscriptionManagerListener) { listeners.remove(listener) } @objc func validate(completion: ValidationCompletion? = nil) { validate(false, completion: completion) } @objc func restore(_ callback: @escaping ValidationCompletion) { validate(true) { callback($0) } } private func validate(_ refreshReceipt: Bool, completion: ValidationCompletion? = nil) { purchaseManager?.validateReceipt(serverId, refreshReceipt: refreshReceipt) { [weak self] (_, validationResult) in self?.logEvents(validationResult) if validationResult == .valid || validationResult == .notValid { self?.listeners.allObjects.forEach { $0.didValidate(validationResult == .valid) } self?.paymentQueue.transactions .filter { self?.productIds.contains($0.payment.productIdentifier) ?? false && ($0.transactionState == .purchased || $0.transactionState == .restored) } .forEach { self?.paymentQueue.finishTransaction($0) } } else { self?.listeners.allObjects.forEach { $0.didFailToValidate() } } completion?(validationResult) } } private func logEvents(_ validationResult: MWMValidationResult) { switch validationResult { case .valid: Statistics.logEvent(kStatInappValidationSuccess, withParameters: [kStatPurchase : serverId]) Statistics.logEvent(kStatInappProductDelivered, withParameters: [kStatVendor : vendorId, kStatPurchase : serverId], with: .realtime) case .notValid: Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 0, kStatPurchase : serverId]) case .serverError: Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 2, kStatPurchase : serverId]) case .authError: Statistics.logEvent(kStatInappValidationError, withParameters: [kStatErrorCode : 1, kStatPurchase : serverId]) } } } extension SubscriptionManager: SKProductsRequestDelegate { func request(_ request: SKRequest, didFailWithError error: Error) { Statistics.logEvent(kStatInappPaymentError, withParameters: [kStatError : error.localizedDescription, kStatPurchase : serverId]) DispatchQueue.main.async { [weak self] in self?.subscriptionsComplection?(nil, error) self?.subscriptionsComplection = nil self?.productsRequest = nil } } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { guard response.products.count == productIds.count else { DispatchQueue.main.async { [weak self] in self?.subscriptionsComplection?(nil, NSError(domain: "mapsme.subscriptions", code: -1, userInfo: nil)) self?.subscriptionsComplection = nil self?.productsRequest = nil } return } let subscriptions = response.products.map { Subscription($0) } .sorted { $0.period.rawValue < $1.period.rawValue } DispatchQueue.main.async { [weak self] in self?.products = Dictionary(uniqueKeysWithValues: response.products.map { ($0.productIdentifier, $0) }) self?.subscriptionsComplection?(subscriptions, nil) self?.subscriptionsComplection = nil self?.productsRequest = nil } } } extension SubscriptionManager: SKPaymentTransactionObserver { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { let subscriptionTransactions = transactions.filter { productIds.contains($0.payment.productIdentifier) } subscriptionTransactions .filter { $0.transactionState == .failed } .forEach { processFailed($0, error: $0.error) } if subscriptionTransactions.contains(where: { $0.transactionState == .purchased || $0.transactionState == .restored }) { subscriptionTransactions .filter { $0.transactionState == .purchased } .forEach { processPurchased($0) } subscriptionTransactions .filter { $0.transactionState == .restored } .forEach { processRestored($0) } validate(false) } subscriptionTransactions .filter { $0.transactionState == .deferred } .forEach { processDeferred($0) } } private func processDeferred(_ transaction: SKPaymentTransaction) { if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { listeners.allObjects.forEach { $0.didDefer(ps) } } } private func processPurchased(_ transaction: SKPaymentTransaction) { paymentQueue.finishTransaction(transaction) if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { Statistics.logEvent(kStatInappPaymentSuccess, withParameters: [kStatPurchase : serverId]) listeners.allObjects.forEach { $0.didSubscribe(ps) } } } private func processRestored(_ transaction: SKPaymentTransaction) { paymentQueue.finishTransaction(transaction) if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { listeners.allObjects.forEach { $0.didSubscribe(ps) } } } private func processFailed(_ transaction: SKPaymentTransaction, error: Error?) { paymentQueue.finishTransaction(transaction) if let ps = pendingSubscription, transaction.payment.productIdentifier == ps.productId { let errorText = error?.localizedDescription ?? "" Statistics.logEvent(kStatInappPaymentError, withParameters: [kStatPurchase : serverId, kStatError : errorText]) listeners.allObjects.forEach { $0.didFailToSubscribe(ps, error: error) } } } }
apache-2.0
soxjke/Redux-ReactiveSwift
Example/Simple-Weather-App/Simple-Weather-App/Services/WeatherService.swift
1
7143
// // WeatherService.swift // Simple-Weather-App // // Created by Petro Korienev on 10/30/17. // Copyright © 2017 Sigma Software. All rights reserved. // import Foundation import Alamofire import ReactiveSwift import ObjectMapper class WeatherService { private struct Constants { static let apiKey = "7yLb1UKneALEl7pON1ryH4qAtkCz1eGG" } static let shared: WeatherService = WeatherService() fileprivate lazy var sessionManager: SessionManager = self.setupSessionManager() fileprivate let appStore: AppStore = AppStore.shared private init() { setupObserving() } private func setupObserving() { let locationProducer = self.appStore.producer .map { $0.location.locationRequestState } .filter { $0.isSuccess } .skipRepeats() .observe(on: QueueScheduler.main) locationProducer.startWithValues { [weak self] _ in self?.appStore.consume(event: .geopositionRequest )} let geopositionProducer = self.appStore.producer .map { $0.weather.geopositionRequestState } .skipRepeats() // To use skipRepeats we have to implement equatable for GeopositionRequestState .observe(on: QueueScheduler.main) geopositionProducer .filter { $0 == .updating } .startWithValues { [weak self] _ in self?.performGeopositionRequest() } geopositionProducer .filter { $0.isSuccess } .startWithValues { [weak self] _ in self?.appStore.consume(event: .weatherRequest )} let weatherProducer = self.appStore.producer .map { $0.weather.weatherRequestState } .skipRepeats() // To use skipRepeats we have to implement equatable for WeatherRequestState .filter { $0 == .updating } .observe(on: QueueScheduler.main) weatherProducer.startWithValues { [weak self] _ in self?.performWeatherRequest() } } private func setupSessionManager() -> SessionManager { return SessionManager.default // let's use very default for simplicity } } extension WeatherService { fileprivate func performGeopositionRequest() { guard case .success(let latitude, let longitude, _) = self.appStore.value.location.locationRequestState else { // There should be assertion thrown here, but for safety let's error the request self.appStore.consume(event: .geopositionResult(geoposition: nil, error: AppError.inconsistentStateGeoposition)) return } sessionManager .request( "https://dataservice.accuweather.com/locations/v1/cities/geoposition/search", method: .get, parameters: ["q": "\(latitude),\(longitude)", "apikey": Constants.apiKey]) .responseJSON { [weak self] (dataResponse) in switch (dataResponse.result) { case .failure(let error): self?.appStore.consume(event: .geopositionResult(geoposition: nil, error: error)) case .success(let value): guard let json = value as? [String: Any] else { self?.appStore.consume(event: .geopositionResult(geoposition: nil, error: AppError.inconsistentAlamofireBehaviour)) return } do { let geoposition = try Geoposition(JSON: json) self?.appStore.consume(event: .geopositionResult(geoposition: geoposition, error: nil)) } catch (let error) { self?.appStore.consume(event: .geopositionResult(geoposition: nil, error: error)) } } } } fileprivate func performWeatherRequest() { guard case .success(let geoposition) = self.appStore.value.weather.geopositionRequestState else { // There should be assertion thrown here, but for safety let's error the request self.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: AppError.inconsistentStateWeather)) return } performCurrentConditionsRequest(for: geoposition.key) } private func performCurrentConditionsRequest(for key: String) { sessionManager .request( "https://dataservice.accuweather.com/currentconditions/v1/\(key)", method: .get, parameters: ["details": "true", "apikey": Constants.apiKey]) .responseJSON { [weak self] (dataResponse) in switch (dataResponse.result) { case .failure(let error): self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error)) case .success(let value): guard let responseJson = value as? [[String: Any]], let weatherJson = responseJson.first else { self?.appStore.consume(event: .weatherResult(current: nil, forecast:nil, error: AppError.inconsistentAlamofireBehaviour)) return } do { let weather = try CurrentWeather(JSON: weatherJson) self?.performForecastRequest(for: key, currentConditions: weather) } catch (let error) { self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error)) } } } } private func performForecastRequest(for key: String, currentConditions: CurrentWeather) { sessionManager .request( "https://dataservice.accuweather.com/forecasts/v1/daily/5day/\(key)", method: .get, parameters: ["details": "true", "apikey": Constants.apiKey]) .responseJSON { [weak self] (dataResponse) in switch (dataResponse.result) { case .failure(let error): self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error)) case .success(let value): guard let rootJson = value as? [String: Any], let forecastsJson = rootJson["DailyForecasts"] as? [[String:Any]] else { self?.appStore.consume(event: .weatherResult(current: nil, forecast:nil, error: AppError.inconsistentAlamofireBehaviour)) return } do { let forecasts = try Mapper<Weather>().mapArray(JSONArray: forecastsJson) self?.appStore.consume(event: .weatherResult(current: currentConditions, forecast: forecasts, error: nil)) } catch (let error) { self?.appStore.consume(event: .weatherResult(current: nil, forecast: nil, error: error)) } } } } }
mit
ReactiveX/RxSwift
Tests/RxCocoaTests/KVOObservableTests.swift
1
41070
// // KVOObservableTests.swift // Tests // // Created by Krunoslav Zaher on 5/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxCocoa #if os(iOS) import UIKit #elseif os(macOS) import Cocoa #endif final class KVOObservableTests : RxTest { var parent: Parent! var parentWithChild: ParentWithChild! var hasStrongProperty: HasStrongProperty! var hasWeakProperty: HasWeakProperty! fileprivate var testClass: TestClass! } private final class TestClass : NSObject { @objc dynamic var pr: String? = "0" } final class Parent : NSObject { var disposeBag: DisposeBag! = DisposeBag() @objc dynamic var val: String = "" init(callback: @escaping (String?) -> Void) { super.init() self.rx.observe(String.self, "val", options: [.initial, .new], retainSelf: false) .subscribe(onNext: callback) .disposed(by: disposeBag) } deinit { disposeBag = nil } } final class Child : NSObject { let disposeBag = DisposeBag() init(parent: ParentWithChild, callback: @escaping (String?) -> Void) { super.init() parent.rx.observe(String.self, "val", options: [.initial, .new], retainSelf: false) .subscribe(onNext: callback) .disposed(by: disposeBag) } deinit { } } final class ParentWithChild : NSObject { @objc dynamic var val: String = "" var child: Child? = nil init(callback: @escaping (String?) -> Void) { super.init() child = Child(parent: self, callback: callback) } } @objc enum IntEnum: Int { typealias RawValue = Int case one case two } @objc enum UIntEnum: UInt { case one case two } @objc enum Int32Enum: Int32 { case one case two } @objc enum UInt32Enum: UInt32 { case one case two } @objc enum Int64Enum: Int64 { case one case two } @objc enum UInt64Enum: UInt64 { case one case two } final class HasStrongProperty : NSObject { @objc dynamic var property: NSObject? = nil @objc dynamic var frame: CGRect @objc dynamic var point: CGPoint @objc dynamic var size: CGSize @objc dynamic var intEnum: IntEnum = .one @objc dynamic var uintEnum: UIntEnum = .one @objc dynamic var int32Enum: Int32Enum = .one @objc dynamic var uint32Enum: UInt32Enum = .one @objc dynamic var int64Enum: Int64Enum = .one @objc dynamic var uint64Enum: UInt64Enum = .one @objc dynamic var integer: Int @objc dynamic var uinteger: UInt override init() { self.frame = CGRect(x: 0, y: 0, width: 100, height: 100) self.point = CGPoint(x: 3, y: 5) self.size = CGSize(width: 1, height: 2) self.integer = 1 self.uinteger = 1 super.init() } } final class HasWeakProperty : NSObject { @objc dynamic weak var property: NSObject? = nil override init() { super.init() } } // MARK: Test key path observation extension KVOObservableTests { func testKeyPathObservation_DefaultOptions() { testClass = TestClass() let os = testClass.rx.observe(\.pr) var latest: String? var completed = false _ = os.subscribe(onNext: { latest = $0 }, onCompleted: { completed = true }) testClass.pr = "1" XCTAssertEqual(latest!, "1") testClass.pr = "2" XCTAssertEqual(latest!, "2") testClass.pr = nil XCTAssertTrue(latest == nil) testClass.pr = "3" XCTAssertEqual(latest!, "3") XCTAssertFalse(completed) testClass = nil XCTAssertTrue(completed) XCTAssertEqual(latest!, "3") } func testKeyPathObservation_NewAndInitialOptions() { let testClass = TestClass() let os = testClass.rx.observe(\.pr, options: [.new, .initial]) var latest: String? let d = os.subscribe(onNext: { latest = $0 }) testClass.pr = "1" XCTAssertEqual(latest!, "1") testClass.pr = "2" XCTAssertEqual(latest!, "2") testClass.pr = nil XCTAssertTrue(latest == nil) testClass.pr = "3" XCTAssertEqual(latest!, "3") d.dispose() testClass.pr = "4" XCTAssertEqual(latest!, "3") } func testKeyPathObservation_NewOptions() { testClass = TestClass() let os = testClass.rx.observe(\.pr, options: [.new]) var latest: String? var completed = false _ = os.subscribe(onNext: { latest = $0 }, onCompleted: { completed = true }) XCTAssertNil(latest) testClass.pr = "1" XCTAssertEqual(latest!, "1") testClass.pr = "2" XCTAssertEqual(latest!, "2") testClass.pr = nil XCTAssertTrue(latest == nil) testClass.pr = "3" XCTAssertEqual(latest!, "3") XCTAssertFalse(completed) testClass = nil XCTAssertTrue(completed) XCTAssertEqual(latest!, "3") } } // MARK: Test fast observe extension KVOObservableTests { func test_New() { let testClass = TestClass() let os = testClass.rx.observe(String.self, "pr", options: .new) var latest: String? let d = os.subscribe(onNext: { latest = $0 }) XCTAssertTrue(latest == nil) testClass.pr = "1" XCTAssertEqual(latest!, "1") testClass.pr = "2" XCTAssertEqual(latest!, "2") testClass.pr = nil XCTAssertTrue(latest == nil) testClass.pr = "3" XCTAssertEqual(latest!, "3") d.dispose() testClass.pr = "4" XCTAssertEqual(latest!, "3") } func test_New_And_Initial() { let testClass = TestClass() let os = testClass.rx.observe(String.self, "pr", options: [.initial, .new]) var latest: String? let d = os.subscribe(onNext: { latest = $0 }) XCTAssertTrue(latest == "0") testClass.pr = "1" XCTAssertEqual(latest ?? "", "1") testClass.pr = "2" XCTAssertEqual(latest ?? "", "2") testClass.pr = nil XCTAssertTrue(latest == nil) testClass.pr = "3" XCTAssertEqual(latest ?? "", "3") d.dispose() testClass.pr = "4" XCTAssertEqual(latest ?? "", "3") } func test_Default() { let testClass = TestClass() let os = testClass.rx.observe(String.self, "pr") var latest: String? let d = os.subscribe(onNext: { latest = $0 }) XCTAssertTrue(latest == "0") testClass.pr = "1" XCTAssertEqual(latest!, "1") testClass.pr = "2" XCTAssertEqual(latest!, "2") testClass.pr = nil XCTAssertTrue(latest == nil) testClass.pr = "3" XCTAssertEqual(latest!, "3") d.dispose() testClass.pr = "4" XCTAssertEqual(latest!, "3") } func test_ObserveAndDontRetainWorks() { var latest: String? var isDisposed = false parent = Parent { n in latest = n } _ = parent.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == "") XCTAssertTrue(isDisposed == false) parent.val = "1" XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == false) parent = nil XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == true) } func test_ObserveAndDontRetainWorks2() { var latest: String? var isDisposed = false parentWithChild = ParentWithChild { n in latest = n } _ = parentWithChild.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == "") XCTAssertTrue(isDisposed == false) parentWithChild.val = "1" XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == false) parentWithChild = nil XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == true) } } #if !DISABLE_SWIZZLING // test weak observe extension KVOObservableTests { func testObserveWeak_SimpleStrongProperty() { var latest: String? var isDisposed = false hasStrongProperty = HasStrongProperty() _ = hasStrongProperty.rx.observeWeakly(String.self, "property") .subscribe(onNext: { n in latest = n }) _ = hasStrongProperty.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == nil) XCTAssertTrue(!isDisposed) hasStrongProperty.property = "a".duplicate() XCTAssertTrue(latest == "a") XCTAssertTrue(!isDisposed) hasStrongProperty = nil XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed) } func testObserveWeak_SimpleWeakProperty() { var latest: String? var isDisposed = false hasWeakProperty = HasWeakProperty() _ = hasWeakProperty.rx.observeWeakly(String.self, "property") .subscribe(onNext: { n in latest = n }) _ = hasWeakProperty.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == nil) XCTAssertTrue(!isDisposed) let a: NSString! = "a".duplicate() hasWeakProperty.property = a XCTAssertTrue(latest == "a") XCTAssertTrue(!isDisposed) hasWeakProperty = nil XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed) } func testObserveWeak_ObserveFirst_Weak_Strong_Basic() { var latest: String? var isDisposed = false hasStrongProperty = HasStrongProperty() hasWeakProperty = HasWeakProperty() _ = hasWeakProperty.rx.observeWeakly(String.self, "property.property") .subscribe(onNext: { n in latest = n }) _ = hasWeakProperty.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == false) hasWeakProperty.property = hasStrongProperty XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == false) let one: NSString! = "1".duplicate() hasStrongProperty.property = one XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == false) hasWeakProperty = nil hasStrongProperty = nil XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == true) } func testObserveWeak_Weak_Strong_Observe_Basic() { var latest: String? var isDisposed = false hasStrongProperty = HasStrongProperty() hasWeakProperty = HasWeakProperty() hasWeakProperty.property = hasStrongProperty let one: NSString! = "1".duplicate() hasStrongProperty.property = one XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == false) _ = hasWeakProperty.rx.observeWeakly(String.self, "property.property") .subscribe(onNext: { n in latest = n }) _ = hasWeakProperty.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == false) hasWeakProperty = nil hasStrongProperty = nil XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == true) } func testObserveWeak_ObserveFirst_Strong_Weak_Basic() { var latest: String? var isDisposed = false hasWeakProperty = HasWeakProperty() hasStrongProperty = HasStrongProperty() _ = hasStrongProperty.rx.observeWeakly(String.self, "property.property") .subscribe(onNext: { n in latest = n }) _ = hasStrongProperty.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == false) hasStrongProperty.property = hasWeakProperty XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == false) let one: NSString! = "1".duplicate() hasWeakProperty.property = one XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == false) hasStrongProperty = nil hasWeakProperty = nil XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == true) } func testObserveWeak_Strong_Weak_Observe_Basic() { var latest: String? var isDisposed = false hasWeakProperty = HasWeakProperty() hasStrongProperty = HasStrongProperty() hasStrongProperty.property = hasWeakProperty let one: NSString! = "1".duplicate() hasWeakProperty.property = one XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == false) _ = hasStrongProperty.rx.observeWeakly(String.self, "property.property") .subscribe(onNext: { n in latest = n }) _ = hasStrongProperty.rx.deallocated .subscribe(onCompleted: { isDisposed = true }) XCTAssertTrue(latest == "1") XCTAssertTrue(isDisposed == false) hasStrongProperty = nil hasWeakProperty = nil XCTAssertTrue(latest == nil) XCTAssertTrue(isDisposed == true) } // compiler won't release weak references otherwise :( func _testObserveWeak_Strong_Weak_Observe_NilLastPropertyBecauseOfWeak() -> (HasWeakProperty, NSObject?, Observable<Void>) { var dealloc: Observable<Void>! = nil let child: HasWeakProperty! = HasWeakProperty() var latest: NSObject? = nil autoreleasepool { let root: HasStrongProperty! = HasStrongProperty() root.property = child var one: NSObject! = nil one = NSObject() child.property = one XCTAssertTrue(latest == nil) let observable = root.rx.observeWeakly(NSObject.self, "property.property") _ = observable .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest! === one) dealloc = one.rx.deallocating one = nil } return (child, latest, dealloc) } func testObserveWeak_Strong_Weak_Observe_NilLastPropertyBecauseOfWeak() { var gone = false let (child, latest, dealloc) = _testObserveWeak_Strong_Weak_Observe_NilLastPropertyBecauseOfWeak() _ = dealloc .subscribe(onNext: { n in gone = true }) XCTAssertTrue(gone) XCTAssertTrue(child.property == nil) XCTAssertTrue(latest == nil) } func _testObserveWeak_Weak_Weak_Weak_middle_NilifyCorrectly() -> (HasWeakProperty, NSObject?, Observable<Void>) { var dealloc: Observable<Void>! = nil var middle: HasWeakProperty! = HasWeakProperty() var latest: NSObject? = nil let root: HasWeakProperty! = HasWeakProperty() autoreleasepool { middle = HasWeakProperty() let leaf = HasWeakProperty() root.property = middle middle.property = leaf XCTAssertTrue(latest == nil) let observable = root.rx.observeWeakly(NSObject.self, "property.property.property") _ = observable .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == nil) let one = NSObject() leaf.property = one XCTAssertTrue(latest === one) dealloc = middle.rx.deallocating } return (root!, latest, dealloc) } func testObserveWeak_Weak_Weak_Weak_middle_NilifyCorrectly() { let (root, latest, deallocatedMiddle) = _testObserveWeak_Weak_Weak_Weak_middle_NilifyCorrectly() var gone = false _ = deallocatedMiddle .subscribe(onCompleted: { gone = true }) XCTAssertTrue(gone) XCTAssertTrue(root.property == nil) XCTAssertTrue(latest == nil) } func testObserveWeak_TargetDeallocated() { var root: HasStrongProperty! = HasStrongProperty() var latest: String? = nil root.property = "a".duplicate() XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(String.self, "property") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == "a") var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeakWithOptions_ObserveNotInitialValue() { var root: HasStrongProperty! = HasStrongProperty() var latest: String? = nil root.property = "a".duplicate() XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(String.self, "property", options: .new) .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == nil) root.property = "b".duplicate() XCTAssertTrue(latest == "b") var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } #if os(macOS) // just making sure it's all the same for NS extensions func testObserve_ObserveNSRect() { var root: HasStrongProperty! = HasStrongProperty() var latest: NSRect? = nil XCTAssertTrue(latest == nil) let disposable = root.rx.observe(NSRect.self, "frame") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == root.frame) root.frame = NSRect(x: -2, y: 0, width: 0, height: 1) XCTAssertTrue(latest == NSRect(x: -2, y: 0, width: 0, height: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == NSRect(x: -2, y: 0, width: 0, height: 1)) XCTAssertTrue(!rootDeallocated) disposable.dispose() } #endif // let's just check for one, other ones should have the same check func testObserve_ObserveCGRectForBiggerStructureDoesntCrashPropertyTypeReturnsNil() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGSize? = nil XCTAssertTrue(latest == nil) let d = root.rx.observe(CGSize.self, "frame") .subscribe(onNext: { n in latest = n }) defer { d.dispose() } XCTAssertTrue(latest == nil) root.size = CGSize(width: 56, height: 1) XCTAssertTrue(latest == nil) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(!rootDeallocated) } func testObserve_ObserveCGRect() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGRect? = nil XCTAssertTrue(latest == nil) let d = root.rx.observe(CGRect.self, "frame") .subscribe(onNext: { n in latest = n }) defer { d.dispose() } XCTAssertTrue(latest == root.frame) root.frame = CGRect(x: -2, y: 0, width: 0, height: 1) XCTAssertTrue(latest == CGRect(x: -2, y: 0, width: 0, height: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == CGRect(x: -2, y: 0, width: 0, height: 1)) XCTAssertTrue(!rootDeallocated) } func testObserve_ObserveCGSize() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGSize? = nil XCTAssertTrue(latest == nil) let d = root.rx.observe(CGSize.self, "size") .subscribe(onNext: { n in latest = n }) defer { d.dispose() } XCTAssertTrue(latest == root.size) root.size = CGSize(width: 56, height: 1) XCTAssertTrue(latest == CGSize(width: 56, height: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == CGSize(width: 56, height: 1)) XCTAssertTrue(!rootDeallocated) } func testObserve_ObserveCGPoint() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGPoint? = nil XCTAssertTrue(latest == nil) let d = root.rx.observe(CGPoint.self, "point") .subscribe(onNext: { n in latest = n }) defer { d.dispose() } XCTAssertTrue(latest == root.point) root.point = CGPoint(x: -100, y: 1) XCTAssertTrue(latest == CGPoint(x: -100, y: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == CGPoint(x: -100, y: 1)) XCTAssertTrue(!rootDeallocated) } func testObserveWeak_ObserveCGRect() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGRect? = nil XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(CGRect.self, "frame") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == root.frame) root.frame = CGRect(x: -2, y: 0, width: 0, height: 1) XCTAssertTrue(latest == CGRect(x: -2, y: 0, width: 0, height: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveCGSize() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGSize? = nil XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(CGSize.self, "size") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == root.size) root.size = CGSize(width: 56, height: 1) XCTAssertTrue(latest == CGSize(width: 56, height: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveCGPoint() { var root: HasStrongProperty! = HasStrongProperty() var latest: CGPoint? = nil XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(CGPoint.self, "point") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == root.point) root.point = CGPoint(x: -100, y: 1) XCTAssertTrue(latest == CGPoint(x: -100, y: 1)) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveInt() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int? = nil XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(NSNumber.self, "integer") .subscribe(onNext: { n in latest = n?.intValue }) XCTAssertTrue(latest == root.integer) root.integer = 10 XCTAssertTrue(latest == 10) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_PropertyDoesntExist() { var root: HasStrongProperty! = HasStrongProperty() var lastError: Swift.Error? = nil _ = root.rx.observeWeakly(NSNumber.self, "notExist") .subscribe(onError: { error in lastError = error }) XCTAssertTrue(lastError != nil) lastError = nil var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(rootDeallocated) } func testObserveWeak_HierarchyPropertyDoesntExist() { var root: HasStrongProperty! = HasStrongProperty() var lastError: Swift.Error? = nil _ = root.rx.observeWeakly(NSNumber.self, "property.notExist") .subscribe(onError: { error in lastError = error }) XCTAssertTrue(lastError == nil) root.property = HasStrongProperty() XCTAssertTrue(lastError != nil) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(rootDeallocated) } } #endif // MARK: KVORepresentable extension KVOObservableTests { func testObserve_ObserveIntegerRepresentable() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(Int.self, "integer") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == 1) root.integer = 2 XCTAssertTrue(latest == 2) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == 2) XCTAssertTrue(!rootDeallocated) disposable.dispose() } func testObserve_ObserveUIntegerRepresentable() { var root: HasStrongProperty! = HasStrongProperty() var latest: UInt? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(UInt.self, "uinteger") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == 1) root.uinteger = 2 XCTAssertTrue(latest == 2) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == 2) XCTAssertTrue(!rootDeallocated) disposable.dispose() } } #if !DISABLE_SWIZZLING extension KVOObservableTests { func testObserveWeak_ObserveIntegerRepresentable() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(Int.self, "integer") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == 1) root.integer = 2 XCTAssertTrue(latest == 2) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveUIntegerRepresentable() { var root: HasStrongProperty! = HasStrongProperty() var latest: UInt? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(UInt.self, "uinteger") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == 1) root.uinteger = 2 XCTAssertTrue(latest == 2) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } } #endif // MARK: RawRepresentable extension KVOObservableTests { func testObserve_ObserveIntEnum() { var root: HasStrongProperty! = HasStrongProperty() var latest: IntEnum? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(IntEnum.self, "intEnum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.intEnum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == .two) XCTAssertTrue(!rootDeallocated) disposable.dispose() } func testObserve_ObserveInt32Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int32Enum? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(Int32Enum.self, "int32Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.int32Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == .two) XCTAssertTrue(!rootDeallocated) disposable.dispose() } func testObserve_ObserveInt64Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int64Enum? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(Int64Enum.self, "int64Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.int64Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == .two) XCTAssertTrue(!rootDeallocated) disposable.dispose() } func testObserve_ObserveUIntEnum() { var root: HasStrongProperty! = HasStrongProperty() var latest: UIntEnum? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(UIntEnum.self, "uintEnum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.uintEnum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == .two) XCTAssertTrue(!rootDeallocated) disposable.dispose() } func testObserve_ObserveUInt32Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: UInt32Enum? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(UInt32Enum.self, "uint32Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.uint32Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == .two) XCTAssertTrue(!rootDeallocated) disposable.dispose() } func testObserve_ObserveUInt64Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: UInt64Enum? XCTAssertTrue(latest == nil) let disposable = root.rx.observe(UInt64Enum.self, "uint64Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.uint64Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == .two) XCTAssertTrue(!rootDeallocated) disposable.dispose() } } #if !DISABLE_SWIZZLING extension KVOObservableTests { func testObserveWeak_ObserveIntEnum() { var root: HasStrongProperty! = HasStrongProperty() var latest: IntEnum? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(IntEnum.self, "intEnum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.intEnum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveInt32Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int32Enum? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(Int32Enum.self, "int32Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.int32Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveInt64Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: Int64Enum? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(Int64Enum.self, "int64Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.int64Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveUIntEnum() { var root: HasStrongProperty! = HasStrongProperty() var latest: UIntEnum? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(UIntEnum.self, "uintEnum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.uintEnum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveUInt32Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: UInt32Enum? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(UInt32Enum.self, "uint32Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.uint32Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } func testObserveWeak_ObserveUInt64Enum() { var root: HasStrongProperty! = HasStrongProperty() var latest: UInt32Enum? XCTAssertTrue(latest == nil) _ = root .rx.observeWeakly(UInt32Enum.self, "uint64Enum") .subscribe(onNext: { n in latest = n }) XCTAssertTrue(latest == .one) root.uint64Enum = .two XCTAssertTrue(latest == .two) var rootDeallocated = false _ = root .rx.deallocated .subscribe(onCompleted: { rootDeallocated = true }) root = nil XCTAssertTrue(latest == nil) XCTAssertTrue(rootDeallocated) } } #endif extension NSString { func duplicate() -> NSString { NSMutableString(string: self) } }
mit
mcconkiee/poyntsdk
Example/SwiftExample/src/AppDelegate.swift
1
2169
// // AppDelegate.swift // TCPTest // // Created by Eric McConkie on 2/18/16. // Copyright © 2016 poynt.co. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
mindvalley/Mobile_iOS_Library_MVMedia
MVMedia/Classes/Protocols/MVMediaTrackingDelegate.swift
1
582
// // MVMediaTrackingDelegate.swift // Pods // // Created by Evandro Harrison Hoffmann on 17/11/2016. // // import UIKit public enum MVMediaType: String{ case video = "Video" case audio = "Audio" } public protocol MVMediaTrackingDelegate { func media(withType: MVMediaType, didChangeSpeedTo: Float) func media(withType: MVMediaType, didStopPlaying: Bool) func media(withType: MVMediaType, didStartPlaying: Bool) func media(withType: MVMediaType, didDownloadMedia: Bool) func media(withType: MVMediaType, didSelectMarker: MVMediaMarker) }
mit
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/Protocols/ActivityIndicator/ActivityIndicatorAnimating.swift
3
534
// // Created by Tom Baranes on 21/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit /// Protocol for all activity indicator classes. public protocol ActivityIndicatorAnimating: class { /** Define the animation for the activity indicator. - Parameter layer: The layer to execute the animation - Parameter size: The size of the activity indicator. - Parameter color: The color of the activity indicator. */ func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) }
mit
whipsterCZ/WeatherTest
WeatherTest/Classes/Models/Forecast.swift
1
878
// // Forecast.swift // WeatherTest // // Created by Daniel Kouba on 20/02/15. // Copyright (c) 2015 Daniel Kouba. All rights reserved. // import Foundation class Forecast : NSObject { var tempreatureC = WEATHER_NA var tempreatureF = WEATHER_NA var iconImage = UIImage() var iconCode : Int { set(code) { iconImage = UIImage(named: DI.context.weatherService.iconNameByCode(code))! } get { return 0 } } var type = "Now available" var date = NSDate() var weekday = WEATHER_NA func tempreature(short:Bool) -> String { if ( DI.context.settings.tempreatureUnit == .Celsius ) { return tempreatureC + ( short ? "°" :"°C" ) } else { return tempreatureF + ( short ? "°" :"°F" ) } } }
apache-2.0
emvakar/EKBlurAlert
Sources/EKBlurAlert/EKBlurAlert.swift
1
6971
// // EKBlurAlert.swift // EKBlurAlert // // Created by Emil Karimov on 13/08/2020. // Copyright © 2020 Emil Karimov. All rights reserved. // import UIKit import SnapKit public enum EKShowType { case noTexts case withTitle case withSubtitle } public class EKBlurAlertView: UIView { private var alertImage: UIImageView! private var titleLabel: UILabel! private var subtitleLabel: UILabel! private var blurView: UIVisualEffectView! private var contentView: UIView = UIView() private var viewCornerRadius: CGFloat = 8 private var timer: Timer? private var autoFade: Bool = true private var timeAfter: Double = 0.7 public init( frame: CGRect, titleFont: UIFont = UIFont.systemFont(ofSize: 17, weight: .regular), subTitleFont: UIFont = UIFont.systemFont(ofSize: 14, weight: .regular), image: UIImage = UIImage(), title: String? = nil, subtitle: String? = nil, autoFade: Bool = true, after: Double = 0.7, radius: CGFloat = 8, blurEffect: UIBlurEffect.Style = .dark) { super.init(frame: frame) createUI(with: image, blurEffect: blurEffect) setup(title: title, subtitle: subtitle, autoFade: autoFade, after: after, radius: radius, titleFont: titleFont, subTitleFont: subTitleFont) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) createUI(with: UIImage(), blurEffect: UIBlurEffect.Style.dark) } public override func layoutSubviews() { layoutIfNeeded() cornerRadius(viewCornerRadius) } public override func didMoveToSuperview() { contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) UIView.animate(withDuration: 0.15, animations: { self.contentView.alpha = 1.0 self.contentView.transform = CGAffineTransform.identity }) { _ in if self.autoFade { self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(self.timeAfter), target: self, selector: #selector(self.removeSelf), userInfo: nil, repeats: false) } else { self.removeSelf() } } } public func setup(title: String? = nil, subtitle: String? = nil, autoFade: Bool = true, after: Double = 3.0, radius: CGFloat = 8, titleFont: UIFont = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.regular), subTitleFont: UIFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)) { viewCornerRadius = radius titleLabel.text = title titleLabel.font = titleFont subtitleLabel.text = subtitle subtitleLabel.font = subTitleFont self.autoFade = autoFade timeAfter = after setupConstraints() } } // MARK: - Private extension EKBlurAlertView { @objc private func removeSelf() { UIView.animate(withDuration: 0.15, animations: { self.contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) self.contentView.alpha = 0.0 }) { _ in self.removeFromSuperview() } } private func cornerRadius(_ radius: CGFloat = 0.0) { contentView.layer.cornerRadius = radius contentView.layer.masksToBounds = contentView.layer.cornerRadius > 0 contentView.clipsToBounds = contentView.layer.cornerRadius > 0 } private func setupContetViewContraints(type: EKShowType) { contentView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.equalTo(frame.width / 2) // switch type { // case .noTexts: // make.height.equalTo(self.frame.width / 2) // case .withTitle: // make.height.equalTo((self.frame.width / 3) * 2) // case .withSubtitle: // make.height.equalTo((self.frame.width / 5) * 3) // } } blurView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } private func setupConstraints() { contentView.center = center contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] contentView.translatesAutoresizingMaskIntoConstraints = true addSubview(contentView) if titleLabel.text != nil { alertImage.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(30) make.left.equalToSuperview().offset(30) make.right.equalToSuperview().offset(-30) make.height.equalTo(contentView.snp.width).offset(-60) } titleLabel.snp.makeConstraints { (make) in make.top.equalTo(alertImage.snp.bottom).offset(15) make.left.equalToSuperview().offset(15) make.right.equalToSuperview().offset(-15) make.height.greaterThanOrEqualTo(21) } if subtitleLabel.text != nil { setupContetViewContraints(type: EKShowType.withSubtitle) subtitleLabel.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom).offset(8) make.left.equalToSuperview().offset(15) make.right.equalToSuperview().offset(-15) make.height.greaterThanOrEqualTo(21) make.bottom.equalToSuperview().offset(-15) } } else { setupContetViewContraints(type: EKShowType.withTitle) } } else { setupContetViewContraints(type: EKShowType.noTexts) alertImage.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(30) make.left.equalToSuperview().offset(30) make.right.equalToSuperview().offset(-30) make.bottom.equalToSuperview().offset(-30) make.width.equalTo(contentView.snp.width).offset(-60) make.height.equalTo(contentView.snp.width).offset(-60) } } } private func createUI(with image: UIImage, blurEffect: UIBlurEffect.Style = .dark) { alertImage = UIImageView(image: image) titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.textAlignment = .center titleLabel.textColor = UIColor.lightText subtitleLabel = UILabel() subtitleLabel.numberOfLines = 0 subtitleLabel.textAlignment = .center subtitleLabel.textColor = UIColor.lightText blurView = UIVisualEffectView(effect: UIBlurEffect(style: blurEffect)) contentView.alpha = 0.0 contentView.addSubview(blurView) contentView.addSubview(alertImage) contentView.addSubview(titleLabel) contentView.addSubview(subtitleLabel) } }
mit
mamouneyya/Fusuma
Sources/FSVideoCameraView.swift
3
12489
// // FSVideoCameraView.swift // Fusuma // // Created by Brendan Kirchner on 3/18/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import AVFoundation @objc protocol FSVideoCameraViewDelegate: class { func videoFinished(withFileURL fileURL: URL) } final class FSVideoCameraView: UIView { @IBOutlet weak var previewViewContainer: UIView! @IBOutlet weak var shotButton: UIButton! @IBOutlet weak var flashButton: UIButton! @IBOutlet weak var flipButton: UIButton! weak var delegate: FSVideoCameraViewDelegate? = nil var session: AVCaptureSession? var device: AVCaptureDevice? var videoInput: AVCaptureDeviceInput? var videoOutput: AVCaptureMovieFileOutput? var focusView: UIView? var flashOffImage: UIImage? var flashOnImage: UIImage? var videoStartImage: UIImage? var videoStopImage: UIImage? fileprivate var isRecording = false static func instance() -> FSVideoCameraView { return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView } func initialize() { if session != nil { return } self.backgroundColor = fusumaBackgroundColor self.isHidden = false // AVCapture session = AVCaptureSession() for device in AVCaptureDevice.devices() { if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back { self.device = device } } do { if let session = session { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) videoOutput = AVCaptureMovieFileOutput() let totalSeconds = 60.0 //Total Seconds of capture time let timeScale: Int32 = 30 //FPS let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale) videoOutput?.maxRecordedDuration = maxDuration videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME if session.canAddOutput(videoOutput) { session.addOutput(videoOutput) } let videoLayer = AVCaptureVideoPreviewLayer(session: session) videoLayer?.frame = self.previewViewContainer.bounds videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill self.previewViewContainer.layer.addSublayer(videoLayer!) session.startRunning() } // Focus View self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:))) self.previewViewContainer.addGestureRecognizer(tapRecognizer) } catch { } let bundle = Bundle(for: self.classForCoder) flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil) flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil) let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil) videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil) videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil) if(fusumaTintIcons) { flashButton.tintColor = fusumaBaseTintColor flipButton.tintColor = fusumaBaseTintColor shotButton.tintColor = fusumaBaseTintColor flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) shotButton.setImage(videoStartImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) } else { flashButton.setImage(flashOffImage, for: UIControlState()) flipButton.setImage(flipImage, for: UIControlState()) shotButton.setImage(videoStartImage, for: UIControlState()) } flashConfiguration() self.startCamera() } deinit { NotificationCenter.default.removeObserver(self) } func startCamera() { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.authorized { session?.startRunning() } else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted { session?.stopRunning() } } func stopCamera() { if self.isRecording { self.toggleRecording() } session?.stopRunning() } @IBAction func shotButtonPressed(_ sender: UIButton) { self.toggleRecording() } fileprivate func toggleRecording() { guard let videoOutput = videoOutput else { return } self.isRecording = !self.isRecording let shotImage: UIImage? if self.isRecording { shotImage = videoStopImage } else { shotImage = videoStartImage } self.shotButton.setImage(shotImage, for: UIControlState()) if self.isRecording { let outputPath = "\(NSTemporaryDirectory())output.mov" let outputURL = URL(fileURLWithPath: outputPath) let fileManager = FileManager.default if fileManager.fileExists(atPath: outputPath) { do { try fileManager.removeItem(atPath: outputPath) } catch { print("error removing item at path: \(outputPath)") self.isRecording = false return } } self.flipButton.isEnabled = false self.flashButton.isEnabled = false videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self) } else { videoOutput.stopRecording() self.flipButton.isEnabled = true self.flashButton.isEnabled = true } return } @IBAction func flipButtonPressed(_ sender: UIButton) { session?.stopRunning() do { session?.beginConfiguration() if let session = session { for input in session.inputs { session.removeInput(input as! AVCaptureInput) } let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) { if let device = device as? AVCaptureDevice , device.position == position { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) } } } session?.commitConfiguration() } catch { } session?.startRunning() } @IBAction func flashButtonPressed(_ sender: UIButton) { do { if let device = device { try device.lockForConfiguration() let mode = device.flashMode if mode == AVCaptureFlashMode.off { device.flashMode = AVCaptureFlashMode.on flashButton.setImage(flashOnImage, for: UIControlState()) } else if mode == AVCaptureFlashMode.on { device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) } device.unlockForConfiguration() } } catch _ { flashButton.setImage(flashOffImage, for: UIControlState()) return } } } extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate { func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) { print("started recording to: \(fileURL)") } func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { print("finished recording to: \(outputFileURL)") self.delegate?.videoFinished(withFileURL: outputFileURL) } } extension FSVideoCameraView { func focus(_ recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) let viewsize = self.bounds.size let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width) let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { try device?.lockForConfiguration() } catch _ { return } if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true { device?.focusMode = AVCaptureFocusMode.autoFocus device?.focusPointOfInterest = newPoint } if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true { device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure device?.exposurePointOfInterest = newPoint } device?.unlockForConfiguration() self.focusView?.alpha = 0.0 self.focusView?.center = point self.focusView?.backgroundColor = UIColor.clear self.focusView?.layer.borderColor = UIColor.white.cgColor self.focusView?.layer.borderWidth = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.addSubview(self.focusView!) UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState animations: { self.focusView!.alpha = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) }, completion: {(finished) in self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.focusView!.removeFromSuperview() }) } func flashConfiguration() { do { if let device = device { try device.lockForConfiguration() device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) device.unlockForConfiguration() } } catch _ { return } } }
mit
wireapp/wire-ios-data-model
Source/Model/Message/ZMOTRMessage+Unarchive.swift
1
2200
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation extension ZMConversation { fileprivate func unarchive(with message: ZMOTRMessage) { self.internalIsArchived = false if self.lastServerTimeStamp != nil, let serverTimestamp = message.serverTimestamp { self.updateArchived(serverTimestamp, synchronize: false) } } } extension ZMOTRMessage { @objc(unarchiveIfNeeded:) func unarchiveIfNeeded(_ conversation: ZMConversation) { if let clearedTimestamp = conversation.clearedTimeStamp, let serverTimestamp = self.serverTimestamp, serverTimestamp.compare(clearedTimestamp) == ComparisonResult.orderedAscending { return } unarchiveIfCurrentUserIsMentionedOrQuoted(conversation) unarchiveIfNotSilenced(conversation) } private func unarchiveIfCurrentUserIsMentionedOrQuoted(_ conversation: ZMConversation) { if conversation.isArchived, let sender = self.sender, !sender.isSelfUser, let textMessageData = self.textMessageData, !conversation.mutedMessageTypes.contains(.mentionsAndReplies), textMessageData.isMentioningSelf || textMessageData.isQuotingSelf { conversation.unarchive(with: self) } } private func unarchiveIfNotSilenced(_ conversation: ZMConversation) { if conversation.isArchived, conversation.mutedMessageTypes == .none { conversation.unarchive(with: self) } } }
gpl-3.0
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/Home(首页)/Model/KYSlideModel.swift
1
1258
// // KYSlide.swift // KYHandMade // // Created by Kerain on 2017/6/13. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // 轮播图 import UIKit class KYSlideModel: NSObject { /* "hand_daren" = 0; "hand_id" = "http://www.shougongke.com/index.php?m=Topic&a=topicDetail&topic_id=1593&topic_type=shiji&funding_id=44"; "host_pic" = "http://imgs.shougongker.com/Public/data/lunbo/1497334789_y45a8kkesy.jpg@!home_page"; itemtype = "topic_detail_h5"; "step_count" = ""; subject = "\U4f17\U7b79\Uff5c\U62fe\U827a\U5b66\U5802\U5468\U5e74\U5e86\Uff0c\U5168\U7f51\U6700\U4f4e\U4ef7\U9080\U4f60\U505a\U624b\U5de5"; template = 4; type = 2; "user_name" = "\U624b\U5de5\U5ba2\U5b98\U65b9"; */ var hand_daren : String? var hand_id : String? var host_pic : String? var itemtype : String? var step_count : String? var subject : String? var template : String? var type : String? var user_name : String? // var is_expired : String? init(dict:[String : AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
apache-2.0
KentaKudo/Smeargle
Demo/Demo/ViewController.swift
1
504
// // ViewController.swift // Demo // // Created by Kenta Kudo on 2016/06/05. // Copyright © 2016年 KentaKudo. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
puyanLiu/LPYFramework
第三方框架改造/pull-to-refresh-master/ESPullToRefreshExample/ESPullToRefreshExample/Custom/Meituan/UIView+Extension.swift
1
2980
// // UIView+Extension.swift // QQMProjectSwift // // Created by liupuyan on 2017/5/12. // Copyright © 2017年 liupuyan. All rights reserved. // import Foundation import UIKit extension UIView { /** * 高度 */ var height_: CGFloat { get { return frame.size.height } set(newValue) { var frame: CGRect = self.frame frame.size.height = newValue self.frame = frame } } /** * 宽度 */ var width_: CGFloat { get { return frame.size.width } set(newValue) { var frame: CGRect = self.frame frame.size.width = newValue self.frame = frame } } var x_: CGFloat { get { return frame.origin.x } set(newValue) { var frame: CGRect = self.frame frame.origin.x = newValue self.frame = frame } } var y_: CGFloat { get { return frame.origin.y } set(newValue) { var frame: CGRect = self.frame frame.origin.y = newValue self.frame = frame } } var centerX_: CGFloat { get { return center.x } set(newValue) { var center: CGPoint = self.center center.x = newValue self.center = center } } var centerY_: CGFloat { get { return center.y } set(newValue) { var center: CGPoint = self.center center.y = newValue self.center = center } } var size_: CGSize { get { return frame.size } set(newValue) { var frame: CGRect = self.frame frame.size = newValue self.frame = frame } } } // MARK: - layer extension UIView { class func createGradientLayer(frame: CGRect, startColor: UIColor, endColor: UIColor, gradientAngle: CGFloat) -> CAGradientLayer { return createGradientLayer(frame: frame, startColor: startColor, endColor: endColor, gradientAngle: gradientAngle, startPoint: CGPoint(x: 1, y: 1), endPoint: CGPoint(x: 0, y: tan(gradientAngle))) } class func createGradientLayer(frame: CGRect, startColor: UIColor, endColor: UIColor, gradientAngle: CGFloat, startPoint: CGPoint, endPoint: CGPoint) -> CAGradientLayer { let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.frame = frame gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint if gradientAngle > 0 { let l: NSNumber = NSNumber(value: Float(tan(gradientAngle))) gradientLayer.locations = [l] } let startColor = startColor.cgColor let endColor = endColor.cgColor gradientLayer.colors = [startColor, endColor] return gradientLayer } }
apache-2.0
Mozharovsky/XMLParser
XMLParser Demo/XMLParser Demo/AppDelegate.swift
4
1500
// // AppDelegate.swift // XMLParser Demo // // Created by Eugene Mozharovsky on 8/29/15. // Copyright © 2015 DotMyWay LCC. All rights reserved. // import UIKit import XMLParser @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { /// Parsing an XML string from a Dictionary let body = [ "request" : [ "meta" : [ "type" : "getOrder", "date" : "2015-08-29 12:00:00", "device_name" : "iPhone 6 Plus", "device_os_version" : "iOS 9" ] ], "encryption" : [ "type" : "RSA" ] ] let header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" let result = XMLParser.sharedParser.encode(body, header: header) print(result) /// Extracting data from an XML converted string let convertedString = "<request><meta><type>getOrder</type><date>2015-08-29 12:00:00</date><device_name>iPhone 6 Plus</device_name><device_os_version>iOS 9</device_os_version></meta></request><encryption><type>RSA</type></encryption>" let result1 = XMLParser.sharedParser.decode(convertedString) print(result1) return true } }
mit
alreadyRight/Swift-algorithm
自定义cell编辑状态/自定义cell编辑状态/AppDelegate.swift
1
2191
// // AppDelegate.swift // 自定义cell编辑状态 // // Created by 周冰烽 on 2017/12/12. // Copyright © 2017年 周冰烽. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
justinhester/SmokeOrFire
SmokeOrFire/SmokeOrFire/Enums/PlayerChoices.swift
1
512
// // PlayerChoices.swift // SmokeOrFire // // Created by Justin Lawrence Hester on 8/14/16. // Copyright © 2016 Justin Lawrence Hester. All rights reserved. // enum PlayerChoices: Int { // Suit? case CLUB = 1, DIAMOND, HEART, SPADE // Smoke or fire? case RED case BLACK // Higher or lower? case HIGHER case LOWER // Inside or outside? case INSIDE case OUTSIDE // Misc choice case SAME // Pyramid, no actual choice. case PYRAMID case GUESS }
gpl-3.0
karwa/swift
test/Constraints/closures.swift
1
31827
// RUN: %target-typecheck-verify-swift func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {} var intArray : [Int] _ = myMap(intArray, { String($0) }) _ = myMap(intArray, { x -> String in String(x) } ) // Closures with too few parameters. func foo(_ x: (Int, Int) -> Int) {} foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} struct X {} func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {} func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {} var strings : [String] _ = mySort(strings, { x, y in x < y }) // Closures with inout arguments. func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U { var t2 = t return f(&t2) } struct X2 { func g() -> Float { return 0 } } _ = f0(X2(), {$0.g()}) // Closures with inout arguments and '__shared' conversions. func inoutToSharedConversions() { func fooOW<T, U>(_ f : (__owned T) -> U) {} fooOW({ (x : Int) in return Int(5) }) // defaut-to-'__owned' allowed fooOW({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__owned' allowed fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__owned Int) -> Int'}} func fooIO<T, U>(_ f : (inout T) -> U) {} fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(inout Int) -> Int'}} fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout Int) -> Int'}} fooIO({ (x : __owned Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__owned Int) -> Int' to expected argument type '(inout Int) -> Int'}} func fooSH<T, U>(_ f : (__shared T) -> U) {} fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed fooSH({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__shared' allowed fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared Int) -> Int'}} fooSH({ (x : Int) in return Int(5) }) // default-to-'__shared' allowed } // Autoclosure func f1(f: @autoclosure () -> Int) { } func f2() -> Int { } f1(f: f2) // expected-error{{add () to forward @autoclosure parameter}}{{9-9=()}} f1(f: 5) // Ternary in closure var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"} // <rdar://problem/15367882> func foo() { not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}} } // <rdar://problem/15536725> struct X3<T> { init(_: (T) -> ()) {} } func testX3(_ x: Int) { var x = x _ = X3({ x = $0 }) _ = x } // <rdar://problem/13811882> func test13811882() { var _ : (Int) -> (Int, Int) = {($0, $0)} var x = 1 var _ : (Int) -> (Int, Int) = {($0, x)} x = 2 } // <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement // <https://bugs.swift.org/browse/SR-3671> func r21544303() { var inSubcall = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false // This is a problem, but isn't clear what was intended. var somethingElse = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false var v2 : Bool = false v2 = inSubcall // expected-error {{cannot call value of non-function type 'Bool'}} { } } // <https://bugs.swift.org/browse/SR-3671> func SR3671() { let n = 42 func consume(_ x: Int) {} { consume($0) }(42) ; ({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} ; ({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} ; ({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} ; ({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} ; ({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // This is technically a valid call, so nothing goes wrong until (42) { $0(3) } // expected-error {{cannot call value of non-function type '()'}} { consume($0) }(42) ; ({ $0(42) }) // expected-error {{cannot call value of non-function type '()'}} { consume($0) }(42) ; { $0(3) } // expected-error {{cannot call value of non-function type '()'}} { [n] in consume($0) }(42) ; ({ $0(42) }) // expected-error {{cannot call value of non-function type '()'}} { [n] in consume($0) }(42) ; // Equivalent but more obviously unintended. { $0(3) } // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { consume($0) }(42) // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ({ $0(3) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}} { consume($0) }(42) // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // Also a valid call (!!) { $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}} consume(111) } // <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure func r22162441(_ lines: [String]) { _ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} _ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} } func testMap() { let a = 42 [1,a].map { $0 + 1.0 } // expected-error {{cannot convert value of type 'Int' to expected element type 'Double'}} } // <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier [].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '(@escaping (_, _) -> _)'}} // <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments var _: () -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }} var _: (Int) -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}} var _: (Int) -> Int = { 0 } // expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }} var _: (Int, Int) -> Int = {0} // expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {$0+$1} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}} var _: (Int) -> Int = {a,b in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}} var _: (Int) -> Int = {a,b,c in 0} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {a, b in a+b} // <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument func r15998821() { func take_closure(_ x : (inout Int) -> ()) { } func test1() { take_closure { (a : inout Int) in a = 42 } } func test2() { take_closure { a in a = 42 } } func withPtr(_ body: (inout Int) -> Int) {} func f() { withPtr { p in return p } } let g = { x in x = 3 } take_closure(g) } // <rdar://problem/22602657> better diagnostics for closures w/o "in" clause var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} // Crash when re-typechecking bodies of non-single expression closures struct CC {} func callCC<U>(_ f: (CC) -> U) -> () {} func typeCheckMultiStmtClosureCrash() { callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}} _ = $0 return 1 } } // SR-832 - both these should be ok func someFunc(_ foo: ((String) -> String)?, bar: @escaping (String) -> String) { let _: (String) -> String = foo != nil ? foo! : bar let _: (String) -> String = foo ?? bar } func verify_NotAC_to_AC_failure(_ arg: () -> ()) { func takesAC(_ arg: @autoclosure () -> ()) {} takesAC(arg) // expected-error {{add () to forward @autoclosure parameter}} {{14-14=()}} } // SR-1069 - Error diagnostic refers to wrong argument class SR1069_W<T> { func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {} // expected-note@-1 {{where 'Key' = 'Object?'}} } class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() } struct S<T> { let cs: [SR1069_C<T>] = [] func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable { let wrappedMethod = { (object: AnyObject, value: T) in } // expected-error @+2 {{instance method 'append(value:forKey:)' requires that 'Object?' be a class type}} // expected-note @+1 {{wrapped type 'Object' satisfies this requirement}} cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) } } } // Similar to SR1069 but with multiple generic arguments func simplified1069() { class C {} struct S { func genericallyNonOptional<T: AnyObject>(_ a: T, _ b: T, _ c: T) { } // expected-note@-1 {{where 'T' = 'Optional<C>'}} func f(_ a: C?, _ b: C?, _ c: C) { genericallyNonOptional(a, b, c) // expected-error {{instance method 'genericallyNonOptional' requires that 'Optional<C>' be a class type}} // expected-note @-1 {{wrapped type 'C' satisfies this requirement}} } } } // Make sure we cannot infer an () argument from an empty parameter list. func acceptNothingToInt (_: () -> Int) {} func testAcceptNothingToInt(ac1: @autoclosure () -> Int) { acceptNothingToInt({ac1($0)}) // expected-error@:27 {{argument passed to call that takes no arguments}} // expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} } // <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference) struct Thing { init?() {} } // This throws a compiler error let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> <#Result#> }} // Commenting out this makes it compile _ = thing return thing } // <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches func r21675896(file : String) { let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> <#Result#> in }} if true { return "foo" } else { return file } }().pathExtension } // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} // expected-note {{candidate expects value of type 'String' for parameter #1}} func f19997471(_ x: Int) {} // expected-note {{candidate expects value of type 'Int' for parameter #1}} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{no exact matches in call to global function 'f19997471'}} } } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } [0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> <#Result#> }} _ in let r = (1,2).0 return r } // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) throws -> U' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} {{17-17=UInt8(}} {{25-25=)}} } } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} // expected-error@-1:11 {{cannot call value of non-function type '()'}} let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> <#Result#> }} print("a") return "hi" } } // In the example below, SR-2505 started preferring C_SR_2505.test(_:) over // test(it:). Prior to Swift 5.1, we emulated the old behavior. However, // that behavior is inconsistent with the typical approach of preferring // overloads from the concrete type over one from a protocol, so we removed // the hack. protocol SR_2505_Initable { init() } struct SR_2505_II : SR_2505_Initable {} protocol P_SR_2505 { associatedtype T: SR_2505_Initable } extension P_SR_2505 { func test(it o: (T) -> Bool) -> Bool { return o(T.self()) } } class C_SR_2505 : P_SR_2505 { typealias T = SR_2505_II func test(_ o: Any) -> Bool { return false } func call(_ c: C_SR_2505) -> Bool { // Note: the diagnostic about capturing 'self', indicates that we have // selected test(_) rather than test(it:) return c.test { o in test(o) } // expected-error{{call to method 'test' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} expected-note{{reference 'self.' explicitly}} } } let _ = C_SR_2505().call(C_SR_2505()) // <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic extension Collection { func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index { return startIndex } } func fn_r28909024(n: Int) { return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} _ in true } } // SR-2994: Unexpected ambiguous expression in closure with generics struct S_2994 { var dataOffset: Int } class C_2994<R> { init(arg: (R) -> Void) {} } func f_2994(arg: String) {} func g_2994(arg: Int) -> Double { return 2 } C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}} let _ = { $0[$1] }(1, 1) // expected-error {{value of type 'Int' has no subscripts}} let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}} let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}} // https://bugs.swift.org/browse/SR-403 // The () -> T => () -> () implicit conversion was kicking in anywhere // inside a closure result, not just at the top-level. let mismatchInClosureResultType : (String) -> ((Int) -> Void) = { (String) -> ((Int) -> Void) in return { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{13-13= _ in}} } // SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS func sr3520_1<T>(_ g: (inout T) -> Int) {} sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} // This test makes sure that having closure with inout argument doesn't crash with member lookup struct S_3520 { var number1: Int } func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} // expected-note {{in call to function 'sr3520_set_via_closure'}} sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error@-1 {{generic parameter 'S' could not be inferred}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} // SR-3073: UnresolvedDotExpr in single expression closure struct SR3073Lense<Whole, Part> { let set: (inout Whole, Part) -> () } struct SR3073 { var number1: Int func lenses() { let _: SR3073Lense<SR3073, Int> = SR3073Lense( set: { $0.number1 = $1 } // ok ) } } // SR-3479: Segmentation fault and other error for closure with inout parameter func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {} func sr3497() { let _ = sr3497_unfold((0, 0)) { s in 0 } // ok } // SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs let _: ((Any?) -> Void) = { (arg: Any!) in } // This example was rejected in 3.0 as well, but accepting it is correct. let _: ((Int?) -> Void) = { (arg: Int!) in } // rdar://30429709 - We should not attempt an implicit conversion from // () -> T to () -> Optional<()>. func returnsArray() -> [Int] { return [] } returnsArray().compactMap { $0 }.compactMap { } // expected-warning@-1 {{expression of type 'Int' is unused}} // expected-warning@-2 {{result of call to 'compactMap' is unused}} // rdar://problem/30271695 _ = ["hi"].compactMap { $0.isEmpty ? nil : $0 } // rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected func r32432145(_ a: () -> ()) {} r32432145 { _ in let _ = 42 } // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}} r32432145 { _ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}} print("answer is 42") } r32432145 { _,_ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}} print("answer is 42") } // rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller [1, 2].first { $0.foo = 3 } // expected-error@-1 {{value of type 'Int' has no member 'foo'}} // expected-error@-2 {{cannot convert value of type '()' to closure result type 'Bool'}} // rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem protocol A_SR_5030 { associatedtype Value func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U> } struct B_SR_5030<T> : A_SR_5030 { typealias Value = T func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() } } func sr5030_exFalso<T>() -> T { fatalError() } extension A_SR_5030 { func foo() -> B_SR_5030<Int> { let tt : B_SR_5030<Int> = sr5030_exFalso() return tt.map { x in (idx: x) } // expected-error@-1 {{cannot convert value of type '(idx: Int)' to closure result type 'Int'}} } } // rdar://problem/33296619 let u = rdar33296619().element //expected-error {{use of unresolved identifier 'rdar33296619'}} [1].forEach { _ in _ = "\(u)" _ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } class SR5666 { var property: String? } func testSR5666(cs: [SR5666?]) -> [String?] { return cs.map({ c in let a = c.propertyWithTypo ?? "default" // expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}} let b = "\(a)" return b }) } // Ensure that we still do the appropriate pointer conversion here. _ = "".withCString { UnsafeMutableRawPointer(mutating: $0) } // rdar://problem/34077439 - Crash when pre-checking bails out and // leaves us with unfolded SequenceExprs inside closure body. _ = { (offset) -> T in // expected-error {{use of undeclared type 'T'}} return offset ? 0 : 0 } struct SR5202<T> { func map<R>(fn: (T) -> R) {} } SR5202<()>().map{ return 0 } SR5202<()>().map{ _ in return 0 } SR5202<Void>().map{ return 0 } SR5202<Void>().map{ _ in return 0 } func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) { var x = item update(&x) } var sr3250_arg = 42 sr3520_2(sr3250_arg) { $0 += 3 } // ok // SR-1976/SR-3073: Inference of inout func sr1976<T>(_ closure: (inout T) -> Void) {} sr1976({ $0 += 2 }) // ok // rdar://problem/33429010 struct I_33429010 : IteratorProtocol { func next() -> Int? { fatalError() } } extension Sequence { public func rdar33429010<Result>(into initialResult: Result, _ nextPartialResult: (_ partialResult: inout Result, Iterator.Element) throws -> () ) rethrows -> Result { return initialResult } } extension Int { public mutating func rdar33429010_incr(_ inc: Int) { self += inc } } func rdar33429010_2() { let iter = I_33429010() var acc: Int = 0 // expected-warning {{}} let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0 + $1 }) // expected-warning@-1 {{result of operator '+' is unused}} let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0.rdar33429010_incr($1) }) } class P_33429010 { var name: String = "foo" } class C_33429010 : P_33429010 { } func rdar33429010_3() { let arr = [C_33429010()] let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok } func rdar36054961() { func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {} bar(dict: ["abc": { str, range, _ in str.replaceSubrange(range, with: str[range].reversed()) }]) } protocol P_37790062 { associatedtype T var elt: T { get } } func rdar37790062() { struct S<T> { init(_ a: () -> T, _ b: () -> T) {} } class C1 : P_37790062 { typealias T = Int var elt: T { return 42 } } class C2 : P_37790062 { typealias T = (String, Int, Void) var elt: T { return ("question", 42, ()) } } func foo() -> Int { return 42 } func bar() -> Void {} func baz() -> (String, Int) { return ("question", 42) } func bzz<T>(_ a: T) -> T { return a } func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt } _ = S({ foo() }, { bar() }) // expected-warning {{result of call to 'foo()' is unused}} _ = S({ baz() }, { bar() }) // expected-warning {{result of call to 'baz()' is unused}} _ = S({ bzz(("question", 42)) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ bzz(String.self) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ bzz(((), (()))) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ bzz(C1()) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ faz(C2()) }, { bar() }) // expected-warning {{result of call to 'faz' is unused}} } // <rdar://problem/39489003> typealias KeyedItem<K, T> = (key: K, value: T) protocol Node { associatedtype T associatedtype E associatedtype K var item: E {get set} var children: [(key: K, value: T)] {get set} } extension Node { func getChild(for key:K)->(key: K, value: T) { return children.first(where: { (item:KeyedItem) -> Bool in return item.key == key // expected-error@-1 {{binary operator '==' cannot be applied to two 'Self.K' operands}} })! } } // Make sure we don't allow this anymore func takesTwo(_: (Int, Int) -> ()) {} func takesTwoInOut(_: (Int, inout Int) -> ()) {} takesTwo { _ in } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} takesTwoInOut { _ in } // expected-error {{contextual closure type '(Int, inout Int) -> ()' expects 2 arguments, but 1 was used in closure body}} // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 _ = x.filter { ($0 + y) > 42 } // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} } // rdar://problem/42337247 func overloaded(_ handler: () -> Int) {} // expected-note {{found this candidate}} func overloaded(_ handler: () -> Void) {} // expected-note {{found this candidate}} overloaded { } // empty body => inferred as returning () overloaded { print("hi") } // single-expression closure => typechecked with body overloaded { print("hi"); print("bye") } // multiple expression closure without explicit returns; can default to any return type // expected-error@-1 {{ambiguous use of 'overloaded'}} func not_overloaded(_ handler: () -> Int) {} // expected-note@-1 {{'not_overloaded' declared here}} not_overloaded { } // empty body // expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}} not_overloaded { print("hi") } // single-expression closure // expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}} // no error in -typecheck, but dataflow diagnostics will complain about missing return not_overloaded { print("hi"); print("bye") } // multiple expression closure func apply(_ fn: (Int) throws -> Int) rethrows -> Int { return try fn(0) } enum E : Error { case E } func test() -> Int? { return try? apply({ _ in throw E.E }) } var fn: () -> [Int] = {} // expected-error@-1 {{cannot convert value of type '()' to closure result type '[Int]'}} fn = {} // expected-error@-1 {{cannot assign value of type '() -> ()' to type '() -> [Int]'}} func test<Instances : Collection>( _ instances: Instances, _ fn: (Instances.Index, Instances.Index) -> Bool ) { fatalError() } test([1]) { _, _ in fatalError(); () } // rdar://problem/40537960 - Misleading diagnostic when using closure with wrong type protocol P_40537960 {} func rdar_40537960() { struct S { var v: String } struct L : P_40537960 { init(_: String) {} } struct R<T : P_40537960> { init(_: P_40537960) {} } struct A<T: Collection, P: P_40537960> { // expected-note {{'P' declared as parameter to type 'A'}} typealias Data = T.Element init(_: T, fn: (Data) -> R<P>) {} } var arr: [S] = [] _ = A(arr, fn: { L($0.v) }) // expected-error {{cannot convert value of type 'L' to closure result type 'R<P>'}} // expected-error@-1 {{generic parameter 'P' could not be inferred}} // expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<[S], <#P: P_40537960#>>}} } // rdar://problem/45659733 func rdar_45659733() { func foo<T : BinaryInteger>(_: AnyHashable, _: T) {} func bar(_ a: Int, _ b: Int) { _ = (a ..< b).map { i in foo(i, i) } // Ok } struct S<V> { func map<T>( get: @escaping (V) -> T, set: @escaping (inout V, T) -> Void ) -> S<T> { fatalError() } subscript<T>( keyPath: WritableKeyPath<V, T?>, default defaultValue: T ) -> S<T> { return map( get: { $0[keyPath: keyPath] ?? defaultValue }, set: { $0[keyPath: keyPath] = $1 } ) // Ok, make sure that we deduce result to be S<T> } } } func rdar45771997() { struct S { mutating func foo() {} } let _: Int = { (s: inout S) in s.foo() } // expected-error@-1 {{cannot convert value of type '(inout S) -> ()' to specified type 'Int'}} } struct rdar30347997 { func withUnsafeMutableBufferPointer(body : (inout Int) -> ()) {} func foo() { withUnsafeMutableBufferPointer { // expected-error {{cannot convert value of type '(Int) -> ()' to expected argument type '(inout Int) -> ()'}} (b : Int) in } } } struct rdar43866352<Options> { func foo() { let callback: (inout Options) -> Void callback = { (options: Options) in } // expected-error {{cannot assign value of type '(Options) -> ()' to type '(inout Options) -> Void'}} } } extension Hashable { var self_: Self { return self } } do { struct S< C : Collection, I : Hashable, R : Numeric > { init(_ arr: C, id: KeyPath<C.Element, I>, content: @escaping (C.Element) -> R) {} } func foo(_ arr: [Int]) { _ = S(arr, id: \.self_) { // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{30-30=_ in }} return 42 } } } // Don't allow result type of a closure to end up as a noescape type // The funny error is because we infer the type of badResult as () -> () // via the 'T -> U => T -> ()' implicit conversion. let badResult = { (fn: () -> ()) in fn } // expected-error@-1 {{expression resolves to an unused function}} // rdar://problem/55102498 - closure's result type can't be inferred if the last parameter has a default value func test_trailing_closure_with_defaulted_last() { func foo<T>(fn: () -> T, value: Int = 0) {} foo { 42 } // Ok foo(fn: { 42 }) // Ok }
apache-2.0
24/ios-o2o-c
gxc/Common/GXTableViewCell.swift
1
6754
// // TableViewCell.swift // gx // // Created by gx on 14/11/9. // Copyright (c) 2014年 gx. All rights reserved. // // // ProgramNoteTableViewCell.swift // NotesSwift // // Created by Samuel Susla on 9/12/14. // Copyright (c) 2014 Samuel Susla. All rights reserved. // import UIKit protocol GXTableViewCellDelegate { // func didLongPressCell(cell: GXTableViewCell, recognizer: UILongPressGestureRecognizer) // func didTapCell(cell: GXTableViewCell, recognizer: UITapGestureRecognizer) // func didDoubleTapCell(cell: GXTableViewCell, recognizer: UITapGestureRecognizer) } class GXTableViewCell: UITableViewCell { var delegate: GXTableViewCellDelegate? var titleLabel = UILabel() var addressLabel = UILabel() var shopImageView = UIImageView(image: UIImage(named: "ddd")) var shopInfoView = UIView() var shopStatueView = UIImageView(image: UIImage(named: "ddd")) //info var locationImageView = UIImageView(image: UIImage(named: "shop_location.png")) var locationLengthLabel = UILabel() // locationLengthLabel.textColor = UIColor(fromHexString: "#2F9BD4") // locationLengthLabel.backgroundColor = UIColor(fromHexString: "#F1F1F1") var carImageView = UIImageView(image: UIImage(named: "shop_car.png")) var carLabel = UILabel() var discountImageView = UIImageView(image: UIImage(named: "shop_dazhe.png")) var discountLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } func setupViews() { // self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator titleLabel.font = UIFont (name: "Heiti SC", size: 16) addressLabel.font = UIFont (name: "Heiti SC", size: 12) locationLengthLabel.font = UIFont(name: "Heiti SC", size: 10) carLabel.font = UIFont(name: "Heiti SC", size: 10) discountLabel.font = UIFont(name: "Heiti SC", size: 10) contentView.addSubview(titleLabel) contentView.addSubview(addressLabel) contentView.addSubview(shopImageView) contentView.addSubview(shopInfoView) contentView.addSubview(shopStatueView) shopInfoView.addSubview(locationImageView) shopInfoView.addSubview(locationLengthLabel) shopInfoView.addSubview(carImageView) shopInfoView.addSubview(carLabel) shopInfoView.addSubview(discountImageView) shopInfoView.addSubview(discountLabel) let padding = 10 shopImageView.snp_makeConstraints { make in make.centerY.equalTo(self.contentView.snp_centerY) make.left.equalTo(self.contentView.snp_left).offset(5) make.width.equalTo(48) make.height.equalTo(40) } titleLabel.snp_makeConstraints { make in make.top.equalTo(self.contentView.snp_top).offset(8) make.left.equalTo(self.shopImageView.snp_right).offset(15) make.width.equalTo(200) make.height.equalTo(20) } addressLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping addressLabel.numberOfLines = 2 addressLabel.snp_makeConstraints { make in make.top.equalTo(self.titleLabel.snp_bottom) make.left.equalTo(self.shopImageView.snp_right).offset(15) make.width.equalTo(200) make.height.equalTo(30) } shopInfoView.snp_makeConstraints { make in make.bottom.equalTo(self.snp_bottom).offset(-5) make.left.equalTo(self.shopImageView.snp_right).offset(15) make.width.equalTo(200) make.height.equalTo(15) } locationImageView.snp_makeConstraints { make in // make.top.equalTo(self.shopInfoView.snp_top) make.centerY.equalTo(self.shopInfoView.snp_centerY) make.left.equalTo(self.shopInfoView.snp_left) make.width.equalTo(13) make.height.equalTo(13) } locationLengthLabel.snp_makeConstraints { make in make.centerY.equalTo(self.shopInfoView.snp_centerY) // make.top.equalTo(self.shopInfoView.snp_top) make.left.equalTo(self.locationImageView.snp_right) make.width.equalTo(40) make.height.equalTo(15) } carImageView.snp_makeConstraints { make in make.centerY.equalTo(self.shopInfoView.snp_centerY) // make.top.equalTo(self.shopInfoView.snp_top) make.left.equalTo(self.locationLengthLabel.snp_right) make.width.equalTo(13) make.height.equalTo(10) } carLabel.snp_makeConstraints { make in make.centerY.equalTo(self.shopInfoView.snp_centerY) // make.top.equalTo(self.shopInfoView.snp_top) make.left.equalTo(self.carImageView.snp_right) make.width.equalTo(50) make.height.equalTo(15) } discountImageView.snp_makeConstraints { make in make.centerY.equalTo(self.shopInfoView.snp_centerY) // make.top.equalTo(self.shopInfoView.snp_top) make.left.equalTo(self.carLabel.snp_right) make.width.equalTo(13) make.height.equalTo(13) } discountLabel.snp_makeConstraints { make in make.centerY.equalTo(self.shopInfoView.snp_centerY) // make.top.equalTo(self.shopInfoView.snp_top) make.left.equalTo(self.discountImageView.snp_right) make.width.equalTo(30) make.height.equalTo(15) } //右边图片 shopStatueView.snp_makeConstraints { make in make.centerY.equalTo(self.contentView.snp_centerY) make.right.equalTo(self.contentView.snp_right).offset(-13) make.width.equalTo(23) make.height.equalTo(23) } } //MARK: Actions // internal func didLongPress(recognizer: UILongPressGestureRecognizer){ // delegate?.didLongPressCell(self, recognizer: recognizer) // } // // internal func didTap(recognizer: UITapGestureRecognizer) { // delegate?.didTapCell(self, recognizer: recognizer) // } // // internal func didDoubleTap(recognizer: UITapGestureRecognizer) { // delegate?.didDoubleTapCell(self, recognizer: recognizer) // } }
mit
mohamede1945/quran-ios
Quran/QariAudioFileListRetrievalCreator.swift
2
1007
// // QariAudioFileListRetrievalCreator.swift // Quran // // Created by Mohamed Afifi on 4/17/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // struct QariAudioFileListRetrievalCreator: Creator { func create(_ qari: Qari) -> QariAudioFileListRetrieval { switch qari.audioType { case .gapped: return GappedQariAudioFileListRetrieval() case .gapless: return GaplessQariAudioFileListRetrieval() } } }
gpl-3.0
edwinbosire/A-SwiftProgress
EBProgressView/ViewController.swift
1
1705
// // ViewController.swift // EBProgressView // // Created by edwin bosire on 06/11/2015. // Copyright © 2015 Edwin Bosire. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var progressLabel: UILabel! override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "refresh") self.navigationController?.navigationItem.leftBarButtonItem = refresh; /** To set the progress bar, assuming change is your progress change var change = 10; let navigationBar = self.navigationController as! EBNavigationController if let navgationBarProgress = navigationBar.lineProgressView { navgationBarProgress.progress = progress + change } */ self.progressLabel.text = "\(0.0) %" simulateProgress() } func refresh () { NSLog("Refresh the data here") } func simulateProgress() { let delay: Double = 2.0 let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( delay * Double(NSEC_PER_SEC))) dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in let increment = Double(arc4random() % 5) / Double(10.0) + 0.1 let navigationBar = self.navigationController as! EBNavigationController let progress = navigationBar.lineProgressView.progress + increment navigationBar.lineProgressView.progress = progress self.progressLabel.text = "\(progress*100) %" if (progress < 1){ self.simulateProgress() }else { // Using a callback function here would be ideal // navigationBar.lineProgressView.stopAnimating() NSLog("Finished animating progress bar") } } } }
mit
barteljan/RocketChatAdapter
Pod/Classes/Commands/GetChannelsCommand.swift
1
231
// // GetChannelsCommand.swift // Pods // // Created by Jan Bartel on 12.03.16. // // import Foundation public protocol GetChannelsCommandProtocol{ } public struct GetChannelsCommand : GetChannelsCommandProtocol{ }
mit
ScoutHarris/WordPress-iOS
WordPressKit/WordPressKit/WordPressOrgXMLRPCApi.swift
1
14737
import Foundation import wpxmlrpc open class WordPressOrgXMLRPCApi: NSObject { public typealias SuccessResponseBlock = (AnyObject, HTTPURLResponse?) -> () public typealias FailureReponseBlock = (_ error: NSError, _ httpResponse: HTTPURLResponse?) -> () fileprivate let endpoint: URL fileprivate let userAgent: String? fileprivate var ongoingProgress = [URLSessionTask: Progress]() fileprivate lazy var session: Foundation.URLSession = { let sessionConfiguration = URLSessionConfiguration.default var additionalHeaders: [String : AnyObject] = ["Accept-Encoding": "gzip, deflate" as AnyObject] if let userAgent = self.userAgent { additionalHeaders["User-Agent"] = userAgent as AnyObject? } sessionConfiguration.httpAdditionalHeaders = additionalHeaders let session = Foundation.URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) return session }() fileprivate var uploadSession: Foundation.URLSession { get { return self.session } } public init(endpoint: URL, userAgent: String? = nil) { self.endpoint = endpoint self.userAgent = userAgent super.init() } deinit { session.finishTasksAndInvalidate() } /** Cancels all ongoing and makes the session so the object will not fullfil any more request */ open func invalidateAndCancelTasks() { session.invalidateAndCancel() } // MARK: - Network requests /** Check if username and password are valid credentials for the xmlrpc endpoint. - parameter username: username to check - parameter password: password to check - parameter success: callback block to be invoked if credentials are valid, the object returned in the block is the options dictionary for the site. - parameter failure: callback block to be invoked is credentials fail */ open func checkCredentials(_ username: String, password: String, success: @escaping SuccessResponseBlock, failure: @escaping FailureReponseBlock) { let parameters: [AnyObject] = [0 as AnyObject, username as AnyObject, password as AnyObject] callMethod("wp.getOptions", parameters: parameters, success: success, failure: failure) } /** Executes a XMLRPC call for the method specificied with the arguments provided. - parameter method: the xmlrpc method to be invoked - parameter parameters: the parameters to be encoded on the request - parameter success: callback to be called on successful request - parameter failure: callback to be called on failed request - returns: a NSProgress object that can be used to track the progress of the request and to cancel the request. If the method returns nil it's because something happened on the request serialization and the network request was not started, but the failure callback will be invoked with the error specificing the serialization issues. */ @discardableResult open func callMethod(_ method: String, parameters: [AnyObject]?, success: @escaping SuccessResponseBlock, failure: @escaping FailureReponseBlock) -> Progress? { //Encode request let request: URLRequest do { request = try requestWithMethod(method, parameters: parameters) } catch let encodingError as NSError { failure(encodingError, nil) return nil } var progress: Progress? // Create task let task = session.dataTask(with: request, completionHandler: { (data, urlResponse, error) in if let uploadProgress = progress { uploadProgress.completedUnitCount = uploadProgress.totalUnitCount } do { let responseObject = try self.handleResponseWithData(data, urlResponse: urlResponse, error: error as NSError?) DispatchQueue.main.async { success(responseObject, urlResponse as? HTTPURLResponse) } } catch let error as NSError { DispatchQueue.main.async { failure(error, urlResponse as? HTTPURLResponse) } return } }) progress = createProgressForTask(task) task.resume() return progress } /** Executes a XMLRPC call for the method specificied with the arguments provided, by streaming the request from a file. This allows to do requests that can use a lot of memory, like media uploads. - parameter method: the xmlrpc method to be invoked - parameter parameters: the parameters to be encoded on the request - parameter success: callback to be called on successful request - parameter failure: callback to be called on failed request - returns: a NSProgress object that can be used to track the progress of the request and to cancel the request. If the method returns nil it's because something happened on the request serialization and the network request was not started, but the failure callback will be invoked with the error specificing the serialization issues. */ @discardableResult open func streamCallMethod(_ method: String, parameters: [AnyObject]?, success: @escaping SuccessResponseBlock, failure: @escaping FailureReponseBlock) -> Progress? { let fileURL = URLForTemporaryFile() //Encode request let request: URLRequest do { request = try streamingRequestWithMethod(method, parameters: parameters, usingFileURLForCache: fileURL) } catch let encodingError as NSError { failure(encodingError, nil) return nil } // Create task let session = uploadSession var progress: Progress? let task = session.uploadTask(with: request, fromFile: fileURL, completionHandler: { (data, urlResponse, error) in if session != self.session { session.finishTasksAndInvalidate() } let _ = try? FileManager.default.removeItem(at: fileURL) do { let responseObject = try self.handleResponseWithData(data, urlResponse: urlResponse, error: error as NSError?) success(responseObject, urlResponse as? HTTPURLResponse) } catch let error as NSError { failure(error, urlResponse as? HTTPURLResponse) } if let uploadProgress = progress { uploadProgress.completedUnitCount = uploadProgress.totalUnitCount } }) task.resume() progress = createProgressForTask(task) return progress } // MARK: - Request Building fileprivate func requestWithMethod(_ method: String, parameters: [AnyObject]?) throws -> URLRequest { let mutableRequest = NSMutableURLRequest(url: endpoint) mutableRequest.httpMethod = "POST" mutableRequest.setValue("text/xml", forHTTPHeaderField: "Content-Type") let encoder = WPXMLRPCEncoder(method: method, andParameters: parameters) mutableRequest.httpBody = try encoder.dataEncoded() return mutableRequest as URLRequest } fileprivate func streamingRequestWithMethod(_ method: String, parameters: [AnyObject]?, usingFileURLForCache fileURL: URL) throws -> URLRequest { let mutableRequest = NSMutableURLRequest(url: endpoint) mutableRequest.httpMethod = "POST" mutableRequest.setValue("text/xml", forHTTPHeaderField: "Content-Type") let encoder = WPXMLRPCEncoder(method: method, andParameters: parameters) try encoder.encode(toFile: fileURL.path) var optionalFileSize: AnyObject? try (fileURL as NSURL).getResourceValue(&optionalFileSize, forKey: URLResourceKey.fileSizeKey) if let fileSize = optionalFileSize as? NSNumber { mutableRequest.setValue(fileSize.stringValue, forHTTPHeaderField: "Content-Length") } return mutableRequest as URLRequest } fileprivate func URLForTemporaryFile() -> URL { let fileName = "\(ProcessInfo.processInfo.globallyUniqueString)_file.xmlrpc" let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName) return fileURL } // MARK: - Progress reporting fileprivate func createProgressForTask(_ task: URLSessionTask) -> Progress { // Progress report let progress = Progress(parent: Progress.current(), userInfo: nil) progress.totalUnitCount = 1 if let contentLengthString = task.originalRequest?.allHTTPHeaderFields?["Content-Length"], let contentLength = Int64(contentLengthString) { // Sergio Estevao: Add an extra 1 unit to the progress to take in account the upload response and not only the uploading of data progress.totalUnitCount = contentLength + 1 } progress.cancellationHandler = { task.cancel() } ongoingProgress[task] = progress return progress } // MARK: - Handling of data fileprivate func handleResponseWithData(_ originalData: Data?, urlResponse: URLResponse?, error: NSError?) throws -> AnyObject { guard let data = originalData, let httpResponse = urlResponse as? HTTPURLResponse, let contentType = httpResponse.allHeaderFields["Content-Type"] as? String, error == nil else { if let unwrappedError = error { throw convertError(unwrappedError, data: originalData) } else { throw convertError(WordPressOrgXMLRPCApiError.unknown as NSError, data: originalData) } } if ["application/xml", "text/xml"].filter({ (type) -> Bool in return contentType.hasPrefix(type)}).count == 0 { throw convertError(WordPressOrgXMLRPCApiError.responseSerializationFailed as NSError, data: originalData) } guard let decoder = WPXMLRPCDecoder(data: data) else { throw WordPressOrgXMLRPCApiError.responseSerializationFailed } guard !(decoder.isFault()), let responseXML = decoder.object() else { if let decoderError = decoder.error() { throw convertError(decoderError as NSError, data: data) } else { throw WordPressOrgXMLRPCApiError.responseSerializationFailed } } return responseXML as AnyObject } open static let WordPressOrgXMLRPCApiErrorKeyData = "WordPressOrgXMLRPCApiErrorKeyData" open static let WordPressOrgXMLRPCApiErrorKeyDataString = "WordPressOrgXMLRPCApiErrorKeyDataString" fileprivate func convertError(_ error: NSError, data: Data?) -> NSError { if let data = data { var userInfo: [AnyHashable: Any] = error.userInfo userInfo[type(of: self).WordPressOrgXMLRPCApiErrorKeyData] = data userInfo[type(of: self).WordPressOrgXMLRPCApiErrorKeyDataString] = NSString(data: data, encoding: String.Encoding.utf8.rawValue) return NSError(domain: error.domain, code: error.code, userInfo: userInfo) } return error } } extension WordPressOrgXMLRPCApi: URLSessionTaskDelegate, URLSessionDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { guard let progress = ongoingProgress[task] else { return } progress.completedUnitCount = totalBytesSent if (totalBytesSent == totalBytesExpectedToSend) { ongoingProgress.removeValue(forKey: task) } } public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodServerTrust: if let credential = URLCredentialStorage.shared.defaultCredential(for: challenge.protectionSpace), challenge.previousFailureCount == 0 { completionHandler(.useCredential, credential) return } var result = SecTrustResultType.invalid if let serverTrust = challenge.protectionSpace.serverTrust { let certificateStatus = SecTrustEvaluate(serverTrust, &result) if certificateStatus == 0 && result == SecTrustResultType.recoverableTrustFailure { DispatchQueue.main.async(execute: { () in HTTPAuthenticationAlertController.presentWithChallenge(challenge, handler: completionHandler) }) } else { completionHandler(.performDefaultHandling, nil) } } default: completionHandler(.performDefaultHandling, nil) } } public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodHTTPBasic: if let credential = URLCredentialStorage.shared.defaultCredential(for: challenge.protectionSpace), challenge.previousFailureCount == 0 { completionHandler(.useCredential, credential) } else { DispatchQueue.main.async(execute: { () in HTTPAuthenticationAlertController.presentWithChallenge(challenge, handler: completionHandler) }) } default: completionHandler(.performDefaultHandling, nil) } } } /** Error constants for the WordPress XMLRPC API - RequestSerializationFailed: The serialization of the request failed - ResponseSerializationFailed: The serialization of the response failed - Unknown: Unknow error happen */ @objc public enum WordPressOrgXMLRPCApiError: Int, Error { case requestSerializationFailed case responseSerializationFailed case unknown }
gpl-2.0
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift
81
2178
// // UINavigationController+Rx.swift // RxCocoa // // Created by Diogo on 13/04/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UINavigationController { /// Factory method that enables subclasses to implement their own `delegate`. /// /// - returns: Instance of delegate proxy that wraps `delegate`. public func createRxDelegateProxy() -> RxNavigationControllerDelegateProxy { return RxNavigationControllerDelegateProxy(parentObject: self) } } extension Reactive where Base: UINavigationController { public typealias ShowEvent = (viewController: UIViewController, animated: Bool) /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy { return RxNavigationControllerDelegateProxy.proxyForObject(base) } /// Reactive wrapper for delegate method `navigationController(:willShow:animated:)`. public var willShow: ControlEvent<ShowEvent> { let source: Observable<ShowEvent> = delegate .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:))) .map { arg in let viewController = try castOrThrow(UIViewController.self, arg[1]) let animated = try castOrThrow(Bool.self, arg[2]) return (viewController, animated) } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `navigationController(:didShow:animated:)`. public var didShow: ControlEvent<ShowEvent> { let source: Observable<ShowEvent> = delegate .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:))) .map { arg in let viewController = try castOrThrow(UIViewController.self, arg[1]) let animated = try castOrThrow(Bool.self, arg[2]) return (viewController, animated) } return ControlEvent(events: source) } } #endif
mit
Peekazoo/Peekazoo-iOS
Peekazoo/PeekazooTests/Test Doubles/CapturingHomepageServiceLoadingDelegate.swift
1
908
// // CapturingHomepageServiceLoadingDelegate.swift // Peekazoo // // Created by Thomas Sherwood on 16/05/2017. // Copyright © 2017 Peekazoo. All rights reserved. // import Peekazoo class CapturingHomepageServiceLoadingDelegate: HomepageServiceLoadingDelegate { private(set) var didFinishLoadingInvoked = false private(set) var capturedHomepageItems: [HomepageItem]? func homepageServiceDidLoadSuccessfully(content: [HomepageItem]) { didFinishLoadingInvoked = true capturedHomepageItems = content } private(set) var didFailToLoadInvoked = false func homepageServiceDidFailToLoad() { didFailToLoadInvoked = true } func capturedItemsEqual<T>(to items: [T]) -> Bool where T: HomepageItem, T: Equatable { guard let castedItems = capturedHomepageItems as? [T] else { return false } return items.elementsEqual(castedItems) } }
apache-2.0
groue/GRDB.swift
Tests/GRDBTests/AssociationHasManySQLTests.swift
1
56575
import XCTest import GRDB /// Test SQL generation class AssociationHasManySQLTests: GRDBTestCase { func testSingleColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var id: Int? var rowid: Int? func encode(to container: inout PersistenceContainer) { container["id"] = id container["rowid"] = rowid } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("id", .integer) } try db.create(table: "children") { t in t.column("parentId", .integer) } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentId")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."rowid" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."rowid" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."rowid" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."rowid" """) try assertEqualSQL(db, Parent(id: 1, rowid: 2).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 2 """) try assertEqualSQL(db, Parent(id: 1, rowid: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentId")], to: [Column("id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1, rowid: 2).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil, rowid: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testSingleColumnNoForeignKey() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var id: Int? func encode(to container: inout PersistenceContainer) { container["id"] = id } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("id", .integer).primaryKey() } try db.create(table: "children") { t in t.column("parentId", .integer) } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentId")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentId")], to: [Column("id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testSingleColumnSingleForeignKey() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var id: Int? func encode(to container: inout PersistenceContainer) { container["id"] = id } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("id", .integer).primaryKey() } try db.create(table: "children") { t in t.column("parentId", .integer).references("parents") } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self), Parent.hasMany(Table(Child.databaseTableName)), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentId")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentId")], to: [Column("id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parentId" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testSingleColumnSeveralForeignKeys() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var id: Int? func encode(to container: inout PersistenceContainer) { container["id"] = id } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("id", .integer).primaryKey() } try db.create(table: "children") { t in t.column("parent1Id", .integer).references("parents") t.column("parent2Id", .integer).references("parents") } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent1Id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent1Id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parent1Id" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent1Id")], to: [Column("id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent1Id" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parent1Id" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent2Id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent2Id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parent2Id" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent2Id")], to: [Column("id")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON "children"."parent2Id" = "parents"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT * FROM "children" WHERE "parent2Id" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var a: Int? var b: Int? func encode(to container: inout PersistenceContainer) { container["a"] = a container["b"] = b } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("a", .integer) t.column("b", .integer) } try db.create(table: "children") { t in t.column("parentA", .integer) t.column("parentB", .integer) } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testCompoundColumnNoForeignKey() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var a: Int? var b: Int? func encode(to container: inout PersistenceContainer) { container["a"] = a container["b"] = b } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("a", .integer) t.column("b", .integer) t.primaryKey(["a", "b"]) } try db.create(table: "children") { t in t.column("parentA", .integer) t.column("parentB", .integer) } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentA"), Column("parentB")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testCompoundColumnSingleForeignKey() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var a: Int? var b: Int? func encode(to container: inout PersistenceContainer) { container["a"] = a container["b"] = b } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("a", .integer) t.column("b", .integer) t.primaryKey(["a", "b"]) } try db.create(table: "children") { t in t.column("parentA", .integer) t.column("parentB", .integer) t.foreignKey(["parentA", "parentB"], references: "parents") } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self), Parent.hasMany(Table(Child.databaseTableName)), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentA"), Column("parentB")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parentA" = 1) AND ("parentB" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testCompoundColumnSeveralForeignKeys() throws { struct Child : TableRecord { static let databaseTableName = "children" } struct Parent : TableRecord, EncodableRecord { static let databaseTableName = "parents" var a: Int? var b: Int? func encode(to container: inout PersistenceContainer) { container["a"] = a container["b"] = b } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { t in t.column("a", .integer) t.column("b", .integer) t.primaryKey(["a", "b"]) } try db.create(table: "children") { t in t.column("parent1A", .integer) t.column("parent1B", .integer) t.column("parent2A", .integer) t.column("parent2B", .integer) t.foreignKey(["parent1A", "parent1B"], references: "parents") t.foreignKey(["parent2A", "parent2B"], references: "parents") } } try dbQueue.inDatabase { db in for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent1A"), Column("parent1B")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parent1A" = 1) AND ("parent1B" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parent1A" = 1) AND ("parent1B" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent2A"), Column("parent2B")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parent2A" = 1) AND ("parent2B" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } for association in [ Parent.hasMany(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), Parent.hasMany(Table(Child.databaseTableName), using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().including(optional: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parents".* \ FROM "parents" \ JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent.all().joining(optional: association), """ SELECT "parents".* \ FROM "parents" \ LEFT JOIN "children" ON ("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b") """) try assertEqualSQL(db, Parent(a: 1, b: 2).request(for: association), """ SELECT * FROM "children" WHERE ("parent2A" = 1) AND ("parent2B" = 2) """) try assertEqualSQL(db, Parent(a: 1, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: 2).request(for: association), """ SELECT * FROM "children" WHERE 0 """) try assertEqualSQL(db, Parent(a: nil, b: nil).request(for: association), """ SELECT * FROM "children" WHERE 0 """) } } } func testForeignKeyDefinitionFromColumn() { // This test pass if code compiles struct Parent : TableRecord { static let databaseTableName = "parents" enum Columns { static let id = Column("id") } static let child1 = hasMany(Child.self, using: Child.ForeignKeys.parent1) static let child2 = hasMany(Child.self, using: Child.ForeignKeys.parent2) } struct Child : TableRecord { static let databaseTableName = "children" enum Columns { static let parentId = Column("parentId") } enum ForeignKeys { static let parent1 = ForeignKey([Columns.parentId]) static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) } } } func testAssociationFilteredByOtherAssociation() throws { struct Toy: TableRecord { } struct Child: TableRecord { static let toy = hasOne(Toy.self) static let parent = belongsTo(Parent.self) } struct Parent: TableRecord, EncodableRecord { static let children = hasMany(Child.self) var id: Int? func encode(to container: inout PersistenceContainer) { container["id"] = id } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parent") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") t.column("parentId", .integer).references("parent") } try db.create(table: "toy") { t in t.column("childId", .integer).references("child") } } try dbQueue.inDatabase { db in do { let association = Parent.children.joining(required: Child.toy) try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parent".*, "child".* \ FROM "parent" JOIN "child" ON "child"."parentId" = "parent"."id" \ JOIN "toy" ON "toy"."childId" = "child"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parent".* FROM "parent" \ JOIN "child" ON "child"."parentId" = "parent"."id" \ JOIN "toy" ON "toy"."childId" = "child"."id" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT "child".* \ FROM "child" \ JOIN "toy" ON "toy"."childId" = "child"."id" \ WHERE "child"."parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT "child".* \ FROM "child" \ JOIN "toy" ON "toy"."childId" = "child"."id" \ WHERE 0 """) } do { // not a realistic use case, but testable anyway let association = Parent.children.joining(required: Child.parent) try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parent1".*, "child".* \ FROM "parent" "parent1" \ JOIN "child" ON "child"."parentId" = "parent1"."id" \ JOIN "parent" "parent2" ON "parent2"."id" = "child"."parentId" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parent1".* \ FROM "parent" "parent1" \ JOIN "child" ON "child"."parentId" = "parent1"."id" \ JOIN "parent" "parent2" ON "parent2"."id" = "child"."parentId" """) try assertEqualSQL(db, Parent(id: 1).request(for: association), """ SELECT "child".* \ FROM "child" \ JOIN "parent" ON "parent"."id" = "child"."parentId" \ WHERE "child"."parentId" = 1 """) try assertEqualSQL(db, Parent(id: nil).request(for: association), """ SELECT "child".* \ FROM "child" \ JOIN "parent" ON "parent"."id" = "child"."parentId" \ WHERE 0 """) } } } }
mit
tiusender/JVToolkit
Example/Pods/PKHUD/PKHUD/Window.swift
1
2640
// // HUDWindow.swift // PKHUD // // Created by Philip Kluz on 6/16/14. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit /// The window used to display the PKHUD within. Placed atop the applications main window. internal class ContainerView: UIView { internal let frameView: FrameView internal init(frameView: FrameView = FrameView()) { self.frameView = frameView super.init(frame: CGRect.zero) commonInit() } required init?(coder aDecoder: NSCoder) { frameView = FrameView() super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { backgroundColor = UIColor.clear isHidden = true addSubview(backgroundView) addSubview(frameView) } internal override func layoutSubviews() { super.layoutSubviews() frameView.center = center backgroundView.frame = bounds } internal func showFrameView() { layer.removeAllAnimations() frameView.center = center frameView.alpha = 1.0 isHidden = false } fileprivate var willHide = false internal func hideFrameView(animated anim: Bool, completion: ((Bool) -> Void)? = nil) { let finalize: (_ finished: Bool) -> Void = { finished in self.isHidden = true self.removeFromSuperview() self.willHide = false completion?(finished) } if isHidden { return } willHide = true if anim { UIView.animate(withDuration: 0.8, animations: { self.frameView.alpha = 0.0 self.hideBackground(animated: false) }, completion: { _ in finalize(true) }) } else { self.frameView.alpha = 0.0 finalize(true) } } fileprivate let backgroundView: UIView = { let view = UIView() view.backgroundColor = UIColor(white:0.0, alpha:0.25) view.alpha = 0.0 return view }() internal func showBackground(animated anim: Bool) { if anim { UIView.animate(withDuration: 0.175, animations: { self.backgroundView.alpha = 1.0 }) } else { backgroundView.alpha = 1.0 } } internal func hideBackground(animated anim: Bool) { if anim { UIView.animate(withDuration: 0.65, animations: { self.backgroundView.alpha = 0.0 }) } else { backgroundView.alpha = 0.0 } } }
mit
SwiftGen/SwiftGen
Sources/SwiftGenCLI/Config/Config.swift
1
3741
// // SwiftGen // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import PathKit import SwiftGenKit // MARK: - Config public struct Config { enum Keys: String { case inputDir = "input_dir" case outputDir = "output_dir" } public let inputDir: Path? public let outputDir: Path? public let commands: [(command: ParserCLI, entry: ConfigEntry)] public let sourcePath: Path } extension Config { public init( file: Path, env: [String: String] = ProcessInfo.processInfo.environment, logger: (LogLevel, String) -> Void = logMessage ) throws { if !file.exists { throw Config.Error.pathNotFound(path: file) } let anyConfig = try YAML.read(path: file, env: env) try self.init(yaml: anyConfig, sourcePath: file.parent(), logger: logger) } public init( content: String, env: [String: String], sourcePath: Path, logger: (LogLevel, String) -> Void ) throws { let anyConfig = try YAML.decode(string: content, env: env) try self.init(yaml: anyConfig, sourcePath: sourcePath, logger: logger) } private init( yaml: Any?, sourcePath: Path, logger: (LogLevel, String) -> Void ) throws { self.sourcePath = sourcePath guard let config = yaml as? [String: Any] else { throw Config.Error.wrongType(key: nil, expected: "Dictionary", got: type(of: yaml)) } self.inputDir = (config[Keys.inputDir.rawValue] as? String).map { Path($0) } self.outputDir = (config[Keys.outputDir.rawValue] as? String).map { Path($0) } var cmds: [(ParserCLI, ConfigEntry)] = [] var errors: [Error] = [] for (cmdName, cmdEntry) in config.filter({ Keys(rawValue: $0.0) == nil }).sorted(by: { $0.0 < $1.0 }) { if let parserCmd = ParserCLI.command(named: cmdName) { do { cmds += try ConfigEntry.parseCommandEntry( yaml: cmdEntry, cmd: parserCmd.name, logger: logger ) .map { (parserCmd, $0) } } catch let error as Config.Error { // Prefix the name of the command for a better error message errors.append(error.withKeyPrefixed(by: parserCmd.name)) } } else { errors.append(Config.Error.unknownParser(name: cmdName)) } } if errors.isEmpty { self.commands = cmds } else { throw Error.multipleErrors(errors) } } } // MARK: - Config.Error extension Config { public enum Error: Swift.Error, CustomStringConvertible { case missingEntry(key: String) case multipleErrors([Swift.Error]) case pathNotFound(path: Path) case unknownParser(name: String) case wrongType(key: String?, expected: String, got: Any.Type) public var description: String { switch self { case .missingEntry(let key): return "Missing entry for key \(key)." case .multipleErrors(let errors): return errors.map { String(describing: $0) }.joined(separator: "\n") case .pathNotFound(let path): return "File \(path) not found." case .unknownParser(let name): return "Parser `\(name)` does not exist." case .wrongType(let key, let expected, let got): return "Wrong type for key \(key ?? "root"): expected \(expected), got \(got)." } } func withKeyPrefixed(by prefix: String) -> Config.Error { switch self { case .missingEntry(let key): return Config.Error.missingEntry(key: "\(prefix).\(key)") case .wrongType(let key, let expected, let got): let fullKey = [prefix, key].compactMap({ $0 }).joined(separator: ".") return Config.Error.wrongType(key: fullKey, expected: expected, got: got) default: return self } } } }
mit
feiin/GesturePassword4Swift
GesturePassword4SwiftTests/GesturePassword4SwiftTests.swift
1
930
// // GesturePassword4SwiftTests.swift // GesturePassword4SwiftTests // // Created by feiin on 14/11/9. // Copyright (c) 2014年 swiftmi. All rights reserved. // import UIKit import XCTest class GesturePassword4SwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
Brightify/ReactantUI
Sources/Tokenizer/Properties/Types/Implementation/Font.swift
1
2390
// // Font.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation public enum Font: AttributeSupportedPropertyType { case system(weight: SystemFontWeight, size: Float) case named(String, size: Float) case themed(String) public var requiresTheme: Bool { switch self { case .system, .named: return false case .themed: return true } } public func generate(context: SupportedPropertyTypeContext) -> String { switch self { case .system(let weight, let size): return "UIFont.systemFont(ofSize: \(size), weight: \(weight.name))" case .named(let name, let size): return "UIFont(\"\(name)\", \(size))" case .themed(let name): return "theme.fonts.\(name)" } } #if SanAndreas public func dematerialize(context: SupportedPropertyTypeContext) -> String { switch self { case .system(let weight, let size): return ":\(weight.rawValue)@\(size)" case .named(let name, let size): return "\(name)@\(size)" } } #endif public static func materialize(from value: String) throws -> Font { if let themedName = ApplicationDescription.themedValueName(value: value) { return .themed(themedName) } else { let tokens = Lexer.tokenize(input: value, keepWhitespace: true) return try FontParser(tokens: tokens).parseSingle() } } public static var runtimeType: String = "UIFont" public static var xsdType: XSDType { return .builtin(.string) } } #if canImport(UIKit) import UIKit extension Font { public func runtimeValue(context: SupportedPropertyTypeContext) -> Any? { switch self { case .system(let weight, let size): return UIFont.systemFont(ofSize: CGFloat(size), weight: UIFont.Weight(rawValue: weight.value)) case .named(let name, let size): return UIFont(name, CGFloat(size)) case .themed(let name): guard let themedFont = context.themed(font: name) else { return nil } return themedFont.runtimeValue(context: context.child(for: themedFont)) } } } #endif
mit
svdo/ReRxSwift
ReRxSwiftTests/ConnectionSpec.swift
1
13770
// Copyright © 2017 Stefan van den Oord. All rights reserved. import Quick import Nimble import ReSwift import ReRxSwift import UIKit import RxCocoa import RxDataSources let initialState = TestState(someString: "initial string", someFloat: 0.42, numbers: []) struct ViewControllerProps { let str: String let optStr: String? let flt: Float let sections: [TestSectionModel] let optInt: Int? } struct ViewControllerActions { let setNewString: (String) -> Void } struct DummyAction: Action {} class ConnectionSpec: QuickSpec { override func spec() { describe("sub - unsub") { var testStore: Store<TestState>! var mapStateToPropsCalled: Bool? = nil var connection: Connection<TestState, SimpleProps, SimpleActions>! beforeEach { testStore = Store<TestState>( reducer: {(_,state) in return state!}, state: initialState) connection = Connection( store: testStore, mapStateToProps: { _ in mapStateToPropsCalled = true return SimpleProps(str: "") }, mapDispatchToActions: mapDispatchToActions ) mapStateToPropsCalled = nil } it("subscribes to the store when connecting") { connection.connect() testStore.dispatch(DummyAction()) expect(mapStateToPropsCalled).to(beTrue()) } context("when it is subscribed") { beforeEach { connection.connect() mapStateToPropsCalled = nil } it("unsubscribes from the store when disconnecting") { connection.disconnect() testStore.dispatch(DummyAction()) expect(mapStateToPropsCalled).to(beNil()) } } } context("given a connection") { var testStore : Store<TestState>! = nil var connection: Connection<TestState, ViewControllerProps, ViewControllerActions>! let mapStateToProps = { (state: TestState) in return ViewControllerProps( str: state.someString, optStr: state.someString, flt: state.someFloat, sections: state.sections, optInt: state.maybeInt ) } let mapDispatchToActions = { (dispatch: @escaping DispatchFunction) in return ViewControllerActions( setNewString: { str in dispatch(TestAction(newString: str)) } ) } beforeEach { testStore = Store<TestState>( reducer: {(_,state) in return state!}, state: initialState) connection = Connection( store:testStore, mapStateToProps: mapStateToProps, mapDispatchToActions: mapDispatchToActions ) } it("uses store's initial state for initial props value") { expect(connection.props.value.str) == initialState.someString } it("can set and get props") { connection.props.accept( ViewControllerProps(str: "some props", optStr: nil, flt: 0, sections: [], optInt: nil) ) expect(connection.props.value.str) == "some props" } it("sets new props when receiving new state from ReSwift") { let newState = TestState(someString: "new string", someFloat: 0, numbers: []) connection.newState(state: newState) expect(connection.props.value.str) == newState.someString } it("maps actions using the store's dispatch function") { var dispatchedAction: Action? = nil testStore.dispatchFunction = { (action:Action) in dispatchedAction = action } connection.actions.setNewString("new string") expect(dispatchedAction as? TestAction) == TestAction(newString: "new string") } it("can subscribe to a props entry") { var next: String? = nil connection.subscribe(\ViewControllerProps.str) { nextStr in next = nextStr } let newState = TestState(someString: "new string", someFloat: 0, numbers: []) connection.newState(state: newState) expect(next) == "new string" } it("can subscribe to an optional props entry") { var next: Int? = nil connection.subscribe(\ViewControllerProps.optInt) { nextInt in next = nextInt } let newState = TestState(someString: "", someFloat: 0, numbers: [], maybeInt: 42) connection.newState(state: newState) expect(next) == 42 } it("can subscribe to an array-typed props entry") { var next: [TestSectionModel] = [] connection.subscribe(\ViewControllerProps.sections) { nextSections in next = nextSections } let newSection = TestSectionModel(header: "", items: []) let newState = TestState(someString: "", someFloat: 0, numbers: [], sections: [newSection]) connection.newState(state: newState) expect(next) == [newSection] } describe("binding") { it("can bind an optional observer") { let textField = UITextField() connection.bind(\ViewControllerProps.str, to: textField.rx.text) connection.newState(state: TestState(someString: "textField.text", someFloat: 0.0, numbers: [])) expect(textField.text) == "textField.text" } it("can bind an optional observer using additional mapping") { let textField = UITextField() connection.bind(\ViewControllerProps.flt, to: textField.rx.text, mapping: { String($0) }) connection.newState(state: TestState(someString: "", someFloat: 42.42, numbers: [])) expect(textField.text) == "42.42" } it("it can bind to an optional prop") { let textField = UITextField() connection.bind(\ViewControllerProps.optInt, to: textField.rx.isHidden) { $0 == nil } connection.newState(state: TestState(someString: "", someFloat: 0, numbers: [], maybeInt: nil)) expect(textField.isHidden).to(beTrue()) connection.newState(state: TestState(someString: "", someFloat: 0, numbers: [], maybeInt: 42)) expect(textField.isHidden).to(beFalse()) } it("can bind a non-optional observer") { let progressView = UIProgressView() connection.bind(\ViewControllerProps.flt, to: progressView.rx.progress) connection.newState(state: TestState(someString: "", someFloat: 0.42, numbers: [])) expect(progressView.progress) ≈ 0.42 } it("can bind a non-optional observer using additional mapping") { let progressView = UIProgressView() connection.bind(\ViewControllerProps.str, to: progressView.rx.progress, mapping: { Float($0) ?? 0 }) connection.newState(state: TestState(someString: "0.42", someFloat: 0, numbers: [])) expect(progressView.progress) ≈ 0.42 } it("can bind colletion view items") { let collectionView = UICollectionView( frame: CGRect(), collectionViewLayout: UICollectionViewFlowLayout()) let dataSource = RxCollectionViewSectionedReloadDataSource<TestSectionModel>( configureCell: { _,_,_,_ in return UICollectionViewCell() }, configureSupplementaryView: { _,_,_,_ in return UICollectionReusableView() }) connection.bind(\ViewControllerProps.sections, to: collectionView.rx.items(dataSource: dataSource)) expect(collectionView.dataSource).toNot(beNil()) connection.newState(state: TestState(someString: "", someFloat: 0, numbers: [12, 34], sections: [TestSectionModel(header: "section", items: [12,34])])) expect(dataSource.numberOfSections(in: collectionView)) == 1 expect(dataSource.collectionView(collectionView, numberOfItemsInSection: 0)) == 2 } it("can bind table view items") { let tableView = UITableView(frame: CGRect(), style: .plain) let dataSource = RxTableViewSectionedReloadDataSource<TestSectionModel>( configureCell: { _,_,_,item in let cell = UITableViewCell() cell.tag = item return cell } ) connection.bind(\ViewControllerProps.sections, to: tableView.rx.items(dataSource: dataSource)) expect(tableView.dataSource).toNot(beNil()) connection.newState(state: TestState(someString: "", someFloat: 0, numbers: [12, 34], sections: [TestSectionModel(header: "section", items: [12, 34])])) expect(dataSource.numberOfSections(in: tableView)) == 1 expect(dataSource.tableView(tableView, numberOfRowsInSection: 0)) == 2 expect(tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0)).tag) == 12 expect(tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 1, section: 0)).tag) == 34 } it("can bind table view items with a mapping function") { let tableView = UITableView(frame: CGRect(), style: .plain) let dataSource = RxTableViewSectionedReloadDataSource<TestSectionModel>( configureCell: { _,_,_,item in let cell = UITableViewCell() cell.tag = item return cell } ) connection.bind(\ViewControllerProps.sections, to: tableView.rx.items(dataSource: dataSource)) { sections in return sections.map { $0.sorted() } } expect(tableView.dataSource).toNot(beNil()) connection.newState(state: TestState(someString: "", someFloat: 0, numbers: [12, 34], sections: [TestSectionModel(header: "section", items: [34, 12])])) expect(dataSource.numberOfSections(in: tableView)) == 1 expect(dataSource.tableView(tableView, numberOfRowsInSection: 0)) == 2 expect(tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0)).tag) == 12 expect(tableView.dataSource?.tableView(tableView, cellForRowAt: IndexPath(row: 1, section: 0)).tag) == 34 } } describe("binding optional and non-optionals") { it("binds non-optional to non-optional") { let barButtonItem = UIBarButtonItem() connection.bind(\ViewControllerProps.str, to: barButtonItem.rx.title) connection.newState(state: TestState(someString: "test string", someFloat: 0.0, numbers: [])) expect(barButtonItem.title) == "test string" } it("binds non-optional to optional") { let label = UILabel() connection.bind(\ViewControllerProps.str, to: label.rx.text) connection.newState(state: TestState(someString: "test string", someFloat: 0.0, numbers: [])) expect(label.text) == "test string" } it("binds optional to non-optional") { let barButtonItem = UIBarButtonItem() connection.bind(\ViewControllerProps.optStr, to: barButtonItem.rx.title) { $0! } connection.newState(state: TestState(someString: "test string", someFloat: 0.0, numbers: [])) expect(barButtonItem.title) == "test string" } it("binds optional to optional") { let label = UILabel() connection.bind(\ViewControllerProps.optStr, to: label.rx.text) connection.newState(state: TestState(someString: "test string", someFloat: 0.0, numbers: [])) expect(label.text) == "test string" } } } } }
mit
practicalswift/swift
validation-test/Evolution/test_class_fixed_layout_add_virtual_method_subclass.swift
33
802
// RUN: %target-resilience-test // REQUIRES: executable_test import StdlibUnittest import class_fixed_layout_add_virtual_method_subclass var ClassAddVirtualMethodSubclassTest = TestSuite("ClassAddVirtualMethodSubclass") class AddVirtualMethodSubclass : AddVirtualMethod { func f3() -> Int { return f1() + 1 } } ClassAddVirtualMethodSubclassTest.test("AddVirtualMethod") { let t = AddVirtualMethodSubclass() expectEqual(1, t.f1()) expectEqual(2, t.f3()) } class AddVirtualMethodGenericSubclass<T> : AddVirtualMethod { func f3(_ t: T) -> [Int : T] { return [f1() : t] } } ClassAddVirtualMethodSubclassTest.test("AddVirtualMethodGeneric") { let t = AddVirtualMethodGenericSubclass<String>() expectEqual(1, t.f1()) expectEqual([1 : "hi"], t.f3("hi")) } runAllTests()
apache-2.0
citysite102/kapi-kaffeine
kapi-kaffeine/KPGetRatingRequest.swift
1
751
// // KPGetRatingRequest.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/7/9. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit import ObjectMapper import PromiseKit import Alamofire class KPGetRatingRequest: NetworkRequest { typealias ResponseType = RawJsonResult private var cafeID: String? var endpoint: String { return "/rates" } var parameters: [String : Any]? { var parameters = [String : Any]() parameters["cafe_id"] = cafeID return parameters } public func perform(_ cafeID: String) -> Promise<(ResponseType)> { self.cafeID = cafeID return networkClient.performRequest(self).then(execute: responseHandler) } }
mit
studyYF/SingleSugar
SingleSugar/SingleSugar/Classes/Tool(工具)/YFHTTPRequestTool.swift
1
6961
// // YFHTTPRequestTool.swift // SingleSugar // // Created by YangFan on 2017/4/14. // Copyright © 2017年 YangFan. All rights reserved. // 网络请求工具 import Foundation import Alamofire import SwiftyJSON import SVProgressHUD class YFHTTPRequestTool { ///单例 static let shareNetTool = YFHTTPRequestTool() /// 网络请求基本方法 /// /// - Parameters: /// - method: 请求方式 /// - url: 网址 /// - param: 参数 /// - finished: 成功返回 func baseRequest(_ url: String, param: [String:Any]? = nil, finished: @escaping(Any) -> ()) { Alamofire.request(url, parameters: param).responseJSON { (response) in //判断是否请求成功 guard response.result.isSuccess else { SVProgressHUD.showError(withStatus: "加载失败") return } //请求成功后,如果有数据,将数据返回 if let value = response.result.value { finished(value) } } } /// 获取单糖数据 /// /// - Parameters: /// - id: 标题栏id /// - finished: 成功返回 func momosacchrideData(id: Int, finished: @escaping (_ monoItems: [YFMonosacchrideItem]) -> ()) { let url = baseURL + "v1/channels/\(id)/items" let param = ["gender": 1, "generation": 1, "limit": 20, "offset": 0] baseRequest(url, param: param) { (response) in //判断返回的数据是否正确 let dict = JSON(response) let code = dict["code"].intValue let message = dict["message"].stringValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: message) return } let data = dict["data"].dictionary if let items = data?["items"]?.arrayObject { var monosacchrideItems = [YFMonosacchrideItem]() for item in items { let monoItem = YFMonosacchrideItem(dict: item as! [String : AnyObject]) monosacchrideItems.append(monoItem) } finished(monosacchrideItems) } } } /// 获取单糖标题数据 /// /// - Parameter finished: 完成回调 func monosacchrideTitleData(_ finished: @escaping(_ titleItems: [YFMonoTitleItem]) -> ()) { let url = baseURL + "v2/channels/preset" let param = ["gender": 1, "generation": 1] baseRequest(url, param: param) { (response) in let dict = JSON(response) let code = dict["code"].intValue let message = dict["message"].stringValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: message) return } let data = dict["data"].dictionary if let titles = data?["channels"]?.arrayObject { var titleItems = [YFMonoTitleItem]() for item in titles { titleItems.append(YFMonoTitleItem(dict: item as! [String : Any])) } finished(titleItems) } } } /// 请求单品数据 /// /// - Parameter finished: 数据回调 func singleProductItem(finished: @escaping([YFSinglePItem]) -> ()) { let url = baseURL + "v2/items" let param = ["gender" : 1, "generation" : 1, "limit" : 20, "offset" : 0 ] baseRequest(url, param: param) { (response) in let dict = JSON(response) let code = dict["code"].intValue let message = dict["message"].stringValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: message) return } let data = dict["data"].dictionary if let items = data?["items"]?.arrayObject { var products = [YFSinglePItem]() for item in items { let itemDict = item as! [String : Any] if let itemData = itemDict["data"] { products.append(YFSinglePItem(dict: itemData as! [String : Any])) } } finished(products) } } } /// 获取单品详情数据 /// /// - Parameters: /// - id: 商品id /// - finished: 返回数组 func singleProductDetail(id: Int, finished: @escaping(YFSingleProductDetailItem) -> ()) { let url = baseURL + "v2/items/\(id)" baseRequest(url) { (response) in let data = JSON(response) let message = data["message"].stringValue let code = data["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: message) return } if let items = data["data"].dictionaryObject { let item = YFSingleProductDetailItem(dict: items as [String : AnyObject]) finished(item) } } } /// 请求评论数据 /// /// - Parameters: /// - id: 商品id /// - finished: func loadComment(id: Int, finished: @escaping([YFCommentItem]) -> ()) { let url = baseURL + "v2/items/\(id)/comments" let params = ["limit": 20, "offset": 0] baseRequest(url, param: params) { (response) in let dict = JSON(response) let message = dict["message"].stringValue let code = dict["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: message) return } if let data = dict["data"].dictionary { if let commentData = data["comments"]?.arrayObject { var commentItems = [YFCommentItem]() for item in commentData { commentItems.append(YFCommentItem(dict: item as! [String : AnyObject])) } finished(commentItems) } } } } func classifyData(_ limit: Int, finished: @escaping([YFClassifyItem]) -> ()) { let url = baseURL + "v1/collections" let params = ["limit": limit, "offset": 0] baseRequest(url, param: params) { (response) in let dict = JSON(response) let message = dict["message"].stringValue let code = dict["code"].intValue guard code == kSuccessCode else { SVProgressHUD.showInfo(withStatus: message) return } } } }
apache-2.0
CorlaOnline/ACPaginatorViewController
ACPaginatorViewController/Classes/ACPaginatorViewControllerDelegate.swift
1
1011
// // ACPaginatorViewControllerDelegate.swift // Pods // // Created by Alex Corlatti on 16/06/16. // // @objc public protocol ACPaginatorViewControllerDelegate { weak var pageControl: UIPageControl? { get set } weak var containerView: UIView! { get set } var orderedViewControllers: [UIViewController] { get set } /** Called when the number of pages is updated. - parameter paginatorViewController: the ACPaginatorViewController instance - parameter count: the total number of pages. */ @objc optional func paginatorViewController(_ paginatorViewController: ACPaginatorViewController, didUpdatePageCount count: Int) /** Called when the current index is updated. - parameter paginatorViewController: the ACPaginatorViewController instance - parameter index: the index of the currently visible page. */ @objc optional func paginatorViewController(_ paginatorViewController: ACPaginatorViewController, didUpdatePageIndex index: Int) }
mit
heartfly/DropdownMenu
Example/DropdownMenu/AppDelegate.swift
2
2147
// // AppDelegate.swift // DropdownMenu // // Created by 邱星豪 on 02/02/2016. // Copyright (c) 2016 邱星豪. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
Jnosh/swift
test/APINotes/basic.swift
8
1082
// RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules -F %S/Inputs/custom-frameworks import APINotesTest import APINotesFrameworkTest #if _runtime(_ObjC) extension A { func implicitlyObjC() { } } func testSelectors(a: AnyObject) { a.implicitlyObjC?() // okay: would complain without SwiftObjCMembers } #endif func testSwiftName() { moveTo(x: 0, y: 0, z: 0) moveTo(0, 0, 0) // expected-error{{missing argument labels 'x:y:z:' in call}} _ = global _ = ANTGlobalValue // expected-error{{'ANTGlobalValue' has been renamed to 'global'}} let ps = Point(x: 0.0, y: 0.0) let ps2 = PointStruct(x: 0.0, y: 0.0) // expected-error{{'PointStruct' has been renamed to 'Point'}} let r: Real = 0.0 let r2: real_t = 0.0 // expected-error{{'real_t' has been renamed to 'Real'}} let rect: Rect let rect2: RectStruct // expected-error{{'RectStruct' has been renamed to 'Rect'}} let d: Double = __will_be_private // From APINotesFrameworkTest. jumpTo(x: 0, y: 0, z: 0) jumpTo(0, 0, 0) // expected-error{{missing argument labels 'x:y:z:' in call}} }
apache-2.0
ozgur/AutoLayoutAnimation
String+Additions.swift
1
249
// // String+Additions.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 11/2/15. // Copyright © 2015 Techshed. All rights reserved. // import Foundation extension String { var length: Int { return characters.count } }
mit
otakisan/SmartToDo
SmartToDo/Views/Cells/ToDoEditorTagV2TableViewCell.swift
1
1079
// // ToDoEditorTagV2TableViewCell.swift // SmartToDo // // Created by takashi on 2014/12/31. // Copyright (c) 2014年 ti. All rights reserved. // import UIKit class ToDoEditorTagV2TableViewCell: ToDoEditorTextBaseTableViewCell { @IBOutlet weak var tagLabel: UILabel! 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 } override func bindingString() -> String { return "tag" } override func didFinishTextView(textView: UITextView) { self.tagLabel.text = textView.text } override func setTextValueOfCell(textValue: String) { self.tagLabel.text = textValue } override func textValueOfCell() -> String { return self.tagLabel.text ?? "" } override func detailViewInitValue() -> AnyObject? { return self.tagLabel.text ?? "" } }
mit
achernoprudov/PagedViewContainer
Source/PageMenuCoordinator.swift
1
1863
// // PagingMenuCoordinator.swift // PagingMenuView // // Created by Андрей Чернопрудов on 03/03/2017. // Copyright © 2017 Naumen. All rights reserved. // import UIKit protocol PageCoordinatorProtocol: class { var currentPage: Int { get } var enabledItems: [PageItem] { get } func select(page index: Int) func select(pageInMenu index: Int) func select(pageInContainer index: Int) func set(page index: Int, isEnabled: Bool) func isEnabled(page: Int) -> Bool } class PageCoordinator: PageCoordinatorProtocol { var items: [PageItem] = [] var currentPage: Int = 0 weak var menu: PageMenu? weak var container: PageContainer? var enabledItems: [PageItem] { return items.filter { $0.isEnabled } } func setup(with items: [PageItem]) { self.items = items correctCurrentPageIndex() } func select(page index: Int) { currentPage = index select(pageInMenu: index) select(pageInContainer: index) } func select(pageInMenu index: Int) { menu?.setActive(page: index) } func select(pageInContainer index: Int) { container?.setActive(page: index) } func set(page index: Int, isEnabled: Bool) { items[index].isEnabled = isEnabled correctCurrentPageIndex() let enabledItems = self.enabledItems UIView.animate(withDuration: 0.3) { self.menu?.setup(withItems: enabledItems) self.container?.setup(with: enabledItems) } } func isEnabled(page: Int) -> Bool { return items[page].isEnabled } private func correctCurrentPageIndex() { if currentPage >= enabledItems.count { currentPage = 0 } } }
mit
iOS-mamu/SS
P/Pods/PSOperations/PSOperations/ReachabilityCondition.swift
1
3293
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if !os(watchOS) import Foundation import SystemConfiguration /** This is a condition that performs a very high-level reachability check. It does *not* perform a long-running reachability check, nor does it respond to changes in reachability. Reachability is evaluated once when the operation to which this is attached is asked about its readiness. */ public struct ReachabilityCondition: OperationCondition { public static let hostKey = "Host" public static let name = "Reachability" public static let isMutuallyExclusive = false let host: URL public init(host: URL) { self.host = host } public func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? { return nil } public func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) { ReachabilityController.requestReachability(host) { reachable in if reachable { completion(.satisfied) } else { let error = NSError(code: .conditionFailed, userInfo: [ OperationConditionKey: type(of: self).name, type(of: self).hostKey: self.host ]) completion(.failed(error)) } } } } /// A private singleton that maintains a basic cache of `SCNetworkReachability` objects. private class ReachabilityController { static var reachabilityRefs = [String: SCNetworkReachability]() static let reachabilityQueue = DispatchQueue(label: "Operations.Reachability", attributes: []) static func requestReachability(_ url: URL, completionHandler: @escaping (Bool) -> Void) { if let host = url.host { reachabilityQueue.async { var ref = self.reachabilityRefs[host] if ref == nil { let hostString = host as NSString ref = SCNetworkReachabilityCreateWithName(nil, hostString.utf8String!) } if let ref = ref { self.reachabilityRefs[host] = ref var reachable = false var flags: SCNetworkReachabilityFlags = [] if SCNetworkReachabilityGetFlags(ref, &flags) { /* Note that this is a very basic "is reachable" check. Your app may choose to allow for other considerations, such as whether or not the connection would require VPN, a cellular connection, etc. */ reachable = flags.contains(.reachable) } completionHandler(reachable) } else { completionHandler(false) } } } else { completionHandler(false) } } } #endif
mit
biboran/dao
DAO/Classes/Persistable.swift
1
166
// // Persistable.swift // Pods // // Created by Timofey on 3/22/17. // // import Foundation public protocol Persistable { associatedtype PrimaryKeyType }
mit
KYawn/myiOS
MyPicker/MyPickerTests/MyPickerTests.swift
1
903
// // MyPickerTests.swift // MyPickerTests // // Created by K.Yawn Xoan on 3/27/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit import XCTest class MyPickerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
apache-2.0
tache/SwifterSwift
Sources/Extensions/Foundation/URLExtensions.swift
1
1323
// // URLExtensions.swift // SwifterSwift // // Created by Omar Albeik on 03/02/2017. // Copyright © 2017 SwifterSwift // import Foundation // MARK: - Methods public extension URL { /// SwifterSwift: URL with appending query parameters. /// /// let url = URL(string: "https://google.com")! /// let param = ["q": "Swifter Swift"] /// url.appendingQueryParameters(params) -> "https://google.com?q=Swifter%20Swift" /// /// - Parameter parameters: parameters dictionary. /// - Returns: URL with appending given query parameters. public func appendingQueryParameters(_ parameters: [String: String]) -> URL { var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)! var items = urlComponents.queryItems ?? [] items += parameters.map({ URLQueryItem(name: $0, value: $1) }) urlComponents.queryItems = items return urlComponents.url! } /// SwifterSwift: Append query parameters to URL. /// /// var url = URL(string: "https://google.com")! /// let param = ["q": "Swifter Swift"] /// url.appendQueryParameters(params) /// print(url) // prints "https://google.com?q=Swifter%20Swift" /// /// - Parameter parameters: parameters dictionary. public mutating func appendQueryParameters(_ parameters: [String: String]) { self = appendingQueryParameters(parameters) } }
mit
Composed/TagListView
TagListView/TagListView.swift
1
7391
// // TagListView.swift // TagListViewDemo // // Created by Dongyuan Liu on 2015-05-09. // Copyright (c) 2015 Ela. All rights reserved. // import UIKit @objc public protocol TagListViewDelegate { optional func tagPressed(title: String, tagView: TagView, sender: TagListView) -> Void } @IBDesignable public class TagListView: UIView { @IBInspectable public var textColor: UIColor = UIColor.whiteColor() { didSet { for tagView in tagViews { tagView.textColor = textColor } } } @IBInspectable public var highlightedTextColor: UIColor = UIColor.whiteColor() { didSet { for tagView in tagViews { tagView.highlightedTextColor = highlightedTextColor } } } @IBInspectable public var tagBackgroundColor: UIColor = UIColor.grayColor() { didSet { for tagView in tagViews { tagView.tagBackgroundColor = tagBackgroundColor } } } @IBInspectable public var tagSelectedBackgroundColor: UIColor = UIColor.redColor() { didSet { for tagView in tagViews { tagView.tagSelectedBackgroundColor = tagSelectedBackgroundColor } } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { for tagView in tagViews { tagView.cornerRadius = cornerRadius } } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { for tagView in tagViews { tagView.borderWidth = borderWidth } } } @IBInspectable public var borderColor: UIColor? { didSet { for tagView in tagViews { tagView.borderColor = borderColor } } } @IBInspectable public var highlightedBorderColor: UIColor? { didSet { for tagView in tagViews { tagView.highlightedBorderColor = highlightedBorderColor } } } @IBInspectable public var paddingY: CGFloat = 2 { didSet { for tagView in tagViews { tagView.paddingY = paddingY } rearrangeViews() } } @IBInspectable public var paddingX: CGFloat = 5 { didSet { for tagView in tagViews { tagView.paddingX = paddingX } rearrangeViews() } } @IBInspectable public var marginY: CGFloat = 2 { didSet { rearrangeViews() } } @IBInspectable public var marginX: CGFloat = 5 { didSet { rearrangeViews() } } public var textFont: UIFont = UIFont.systemFontOfSize(12) { didSet { for tagView in tagViews { tagView.textFont = textFont } rearrangeViews() } } @IBOutlet public var delegate: TagListViewDelegate? var tagViews: [TagView] = [] var rowViews: [UIView] = [] var tagViewHeight: CGFloat = 0 var rows = 0 { didSet { invalidateIntrinsicContentSize() } } // MARK: - Interface Builder public override func prepareForInterfaceBuilder() { addTag("Welcome") addTag("to") addTag("TagListView").selected = true } // MARK: - Layout public override func layoutSubviews() { super.layoutSubviews() rearrangeViews() } private func rearrangeViews() { for tagView in tagViews { tagView.removeFromSuperview() } for rowView in rowViews { rowView.removeFromSuperview() } rowViews.removeAll(keepCapacity: true) var currentRow = 0 var currentRowTagCount = 0 var currentRowWidth: CGFloat = 0 var currentRowView: UIView! for tagView in tagViews { tagView.frame.size = tagView.intrinsicContentSize() tagViewHeight = tagView.frame.height if currentRow == 0 || currentRowWidth + tagView.frame.width + marginX > frame.width { currentRow += 1 currentRowWidth = 0 currentRowTagCount = 0 currentRowView = UIView() currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (tagViewHeight + marginY) rowViews.append(currentRowView) addSubview(currentRowView) } tagView.frame.origin = CGPoint(x: currentRowWidth, y: 0) currentRowView.addSubview(tagView) currentRowTagCount++ currentRowWidth += tagView.frame.width + marginX currentRowView.frame.origin.x = (frame.size.width - (currentRowWidth - marginX)) / 2 currentRowView.frame.size.width = currentRowWidth currentRowView.frame.size.height = max(tagViewHeight, currentRowView.frame.size.height) } rows = currentRow } // MARK: - Manage tags public override func intrinsicContentSize() -> CGSize { var height = CGFloat(rows) * (tagViewHeight + marginY) if rows > 0 { height -= marginY } return CGSizeMake(frame.width, height) } public func addTag(title: String) -> TagView { let tagView = TagView(title: title) tagView.textColor = textColor tagView.highlightedTextColor = highlightedTextColor tagView.tagBackgroundColor = tagBackgroundColor tagView.tagSelectedBackgroundColor = tagSelectedBackgroundColor tagView.cornerRadius = cornerRadius tagView.borderWidth = borderWidth tagView.borderColor = borderColor tagView.highlightedBorderColor = highlightedBorderColor tagView.paddingY = paddingY tagView.paddingX = paddingX tagView.textFont = textFont tagView.addTarget(self, action: "tagPressed:", forControlEvents: UIControlEvents.TouchUpInside) return addTagView(tagView) } public func addTagView(tagView: TagView) -> TagView { tagViews.append(tagView) rearrangeViews() return tagView } public func removeTag(title: String) { // loop the array in reversed order to remove items during loop for index in (tagViews.count - 1).stride(through: 0, by: -1) { let tagView = tagViews[index] if tagView.currentTitle == title { removeTagView(tagView) } } } public func removeTagView(tagView: TagView) { tagView.removeFromSuperview() if let index = tagViews.indexOf(tagView) { tagViews.removeAtIndex(index) } rearrangeViews() } public func removeAllTags() { for tagView in tagViews { tagView.removeFromSuperview() } tagViews = [] rearrangeViews() } public func selectedTags() -> [TagView] { return tagViews.filter() { $0.selected == true } } // MARK: - Events func tagPressed(sender: TagView!) { sender.onTap?(sender) delegate?.tagPressed?(sender.currentTitle ?? "", tagView: sender, sender: self) } }
mit