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
skladek/SKWebServiceController
Tests/WebServiceController/LocalFileRequestControllerSpec.swift
1
3282
import Foundation import Nimble import Quick @testable import SKWebServiceController class LocalFileRequestControllerSpec: QuickSpec { override func spec() { describe("LocalFileRequestController") { var unitUnderTest: LocalFileRequestController! beforeEach { let bundle = Bundle(for: type(of: self)) unitUnderTest = LocalFileRequestController(bundle: bundle) } context("getDataFromURL(_:completion:)") { it("Should return an error through the completion block if the URL is invalid.") { let url = URL(string: "https://invalidURL.example.com")! unitUnderTest.getDataFromURL(url, completion: { (_, _, error) in expect(error).toNot(beNil()) }) } it("Should return data through the completion block if a file is found at the provided URL") { let bundle = Bundle(for: type(of: self)) let path = bundle.path(forResource: "posts", ofType: ".json")! let pathWithScheme = "file://\(path)" let url = URL(string: pathWithScheme)! unitUnderTest.getDataFromURL(url, completion: { (data, _, error) in expect(data).toNot(beNil()) }) } } context("getFileURLFromRequest(_:completion:)") { it("Should return nil if a file cannot be found with the last path component") { let url = URL(string: "https://example.com/invalidLastPathComponent")! let request = URLRequest(url: url) let result = unitUnderTest.getFileURLFromRequest(request, completion: { (_, _, _) in }) expect(result).to(beNil()) } it("Should return an error through the completion if a file cannot be found with the last path component") { let url = URL(string: "https://example.com/invalidLastPathComponent")! let request = URLRequest(url: url) let _ = unitUnderTest.getFileURLFromRequest(request, completion: { (_, _, error) in expect(error).toNot(beNil()) }) } it("Should return a URL if the file is found with the last path component") { let url = URL(string: "https://example.com/posts")! let request = URLRequest(url: url) let result = unitUnderTest.getFileURLFromRequest(request, completion: { (_, _, _) in }) expect(result).toNot(beNil()) } } context("getFileWithRequest(_:completion:)") { it("Should return data through the completion for a valid file name") { let url = URL(string: "https://example.com/posts")! let request = URLRequest(url: url) unitUnderTest.getFileWithRequest(request, completion: { (data, _, _) in expect(data).toNot(beNil()) }) } } } } }
mit
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Error.swift
57
487
// // Error.swift // RxSwift // // Created by Krunoslav Zaher on 8/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Error<Element> : Producer<Element> { private let _error: Swift.Error init(error: Swift.Error) { _error = error } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { observer.on(.error(_error)) return Disposables.create() } }
apache-2.0
zsheikh-systango/WordPower
Skeleton/Pods/NotificationBannerSwift/NotificationBanner/Classes/NotificationBannerQueue.swift
2
3296
/* The MIT License (MIT) Copyright (c) 2017 Dalton Hinterscher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public enum QueuePosition { case back case front } public class NotificationBannerQueue: NSObject { /// The default instance of the NotificationBannerQueue public static let `default` = NotificationBannerQueue() /// The notification banners currently placed on the queue private(set) var banners: [BaseNotificationBanner] = [] /// The current number of notification banners on the queue public var numberOfBanners: Int { return banners.count } /** Adds a banner to the queue -parameter banner: The notification banner to add to the queue -parameter queuePosition: The position to show the notification banner. If the position is .front, the banner will be displayed immediately */ func addBanner(_ banner: BaseNotificationBanner, queuePosition: QueuePosition) { if queuePosition == .back { banners.append(banner) if banners.index(of: banner) == 0 { banner.show(placeOnQueue: false, bannerPosition: banner.bannerPosition) } } else { banner.show(placeOnQueue: false, bannerPosition: banner.bannerPosition) if let firstBanner = banners.first { firstBanner.suspend() } banners.insert(banner, at: 0) } } /** Shows the next notificaiton banner on the queue if one exists -parameter callback: The closure to execute after a banner is shown or when the queue is empty */ func showNext(callback: ((_ isEmpty: Bool) -> Void)) { if !banners.isEmpty { banners.removeFirst() } guard let banner = banners.first else { callback(true) return } if banner.isSuspended { banner.resume() } else { banner.show(placeOnQueue: false) } callback(false) } /** Removes all notification banners from the queue */ public func removeAll() { banners.removeAll() } }
mit
pengleelove/Reflect
Reflect/Reflect/Reflect/Reflect+Property.swift
4
1022
// // Reflect+Property.swift // Reflect // // Created by 冯成林 on 15/8/19. // Copyright (c) 2015年 冯成林. All rights reserved. // import Foundation extension Reflect{ /** 获取类名 */ var classNameString: String {return "\(self.dynamicType)"} /** 遍历成员属性:对象调用 */ func properties(property: (name: String, type: ReflectType, value: Any) -> Void){ for (var i=0; i<mirror.count; i++){ if mirror[i].0 == "super" {continue} let propertyNameString = mirror[i].0 let propertyValueInstaceMirrorType = mirror[i].1 property(name:propertyNameString , type: ReflectType(propertyMirrorType: propertyValueInstaceMirrorType), value: propertyValueInstaceMirrorType.value) } } /** 静态方法调用 */ class func properties(property: (name: String, type: ReflectType, value: Any) -> Void){self().properties(property)} }
mit
NunoAlexandre/broccoli_mobile
ios/Carthage/Checkouts/Eureka/Source/Rows/MultipleSelectorRow.swift
14
1804
// MultipleSelectorRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class _MultipleSelectorRow<T: Hashable, Cell: CellType>: GenericMultipleSelectorRow<T, Cell, MultipleSelectorViewController<T>> where Cell: BaseCell, Cell: TypedCellType, Cell.Value == Set<T> { public required init(tag: String?) { super.init(tag: tag) } } /// A selector row where the user can pick several options from a pushed view controller public final class MultipleSelectorRow<T: Hashable> : _MultipleSelectorRow<T, PushSelectorCell<Set<T>>>, RowType { public required init(tag: String?) { super.init(tag: tag) } }
mit
Monits/swift-compiler-crashes
fixed/01672-swift-typechecker-validatedecl.swift
11
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b struct a protocol b:A,i<{{}typealias B protocol A:A
mit
bingoogolapple/SwiftNote-PartOne
TableView1/TableView1Tests/TableView1Tests.swift
2
895
// // TableView1Tests.swift // TableView1Tests // // Created by bingoogol on 14-6-15. // Copyright (c) 2014年 bingoogol. All rights reserved. // import XCTest class TableView1Tests: 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
naru-jpn/pencil
Example/PencilExample/ApplicationState.swift
1
444
// // ApplicationState.swift // PencilExample // // Created by naru on 2016/12/16. // Copyright © 2016年 naru. All rights reserved. // import Foundation struct ApplicationState: CustomReadWriteElement { let tabIndex: Int static func read(from components: Components) -> ApplicationState? { return ApplicationState( tabIndex: components.component(for: "tabIndex", defaultValue: 0) ) } }
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/API/HTTP/HTTPMethod.swift
1
417
// // HTTPMethod.swift // Rocket.Chat // // Created by Matheus Cardoso on 12/12/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation enum HTTPMethod: String { case get = "GET" case post = "POST" case put = "PUT" case head = "HEAD" case delete = "DELETE" case patch = "PATCH" case trace = "TRACE" case options = "OPTIONS" case connect = "CONNECT" }
mit
marko628/Playground
Answers.playgroundbook/Contents/Sources/PlaygroundInternal/DateInputCell.swift
1
1118
// DateInputCell.swift import UIKit class DateInputCell : PopoverInputCell { private var dateFormatter = DateFormatter() private let datePicker = UIDatePicker() class override var reuseIdentifier: String { return "DateInputCell" } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) valueType = .date dateFormatter.dateStyle = .long datePicker.datePickerMode = .date datePicker.addTarget(self, action: #selector(DateInputCell.valueDidChange), for: .valueChanged) datePicker.autoresizingMask = [.flexibleWidth, .flexibleHeight] datePicker.frame = popoverViewController.view.bounds popoverViewController.view.addSubview(datePicker) popoverContentSize = datePicker.intrinsicContentSize } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func valueDidChange() { messageText = dateFormatter.string(from: datePicker.date) } }
mit
taketo1024/SwiftyAlgebra
Sources/SwmCore/Util/Format.swift
1
6979
// // Letters.swift // SwiftyMath // // Created by Taketo Sano on 2018/03/10. // Copyright © 2018年 Taketo Sano. All rights reserved. // // see: https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts public struct Format { public static func sup(_ i: Int) -> String { sup(String(i)) } public static func sup(_ s: String) -> String { String( s.map { c in switch c { case "0": return "⁰" case "1": return "¹" case "2": return "²" case "3": return "³" case "4": return "⁴" case "5": return "⁵" case "6": return "⁶" case "7": return "⁷" case "8": return "⁸" case "9": return "⁹" case "+": return "⁺" case "-": return "⁻" case "(": return "⁽" case ")": return "⁾" case ",": return " ̓" default: return c } } ) } public static func sub(_ i: Int) -> String { sub(String(i)) } public static func sub(_ s: String) -> String { String( s.map { c in switch c { case "0": return "₀" case "1": return "₁" case "2": return "₂" case "3": return "₃" case "4": return "₄" case "5": return "₅" case "6": return "₆" case "7": return "₇" case "8": return "₈" case "9": return "₉" case "+": return "₊" case "-": return "₋" case "(": return "₍" case ")": return "₎" case ",": return " ̦" case "*": return " ͙" default: return c } } ) } public static func symbol(_ x: String, _ i: Int) -> String { "\(x)\(sub(i))" } public static func power<X: CustomStringConvertible>(_ x: X, _ n: Int) -> String { let xStr = x.description return n == 0 ? "1" : n == 1 ? xStr : "\(xStr)\(sup(n))" } public static func term<R: Ring, X: CustomStringConvertible>(_ r: R = .identity, _ x: X, _ n: Int = 0) -> String { let p = power(x, n) switch (r, p) { case (.zero, _): return "0" case (_, "1"): return "\(r)" case (.identity, _): return p case (-.identity, _): return "-\(p)" default: return "\(r)\(p)" } } public static func linearCombination<S: Sequence, X: CustomStringConvertible, R: Ring>(_ terms: S) -> String where S.Element == (X, R) { func parenthesize(_ x: String) -> Bool { x.contains(" ") } let termsStr = terms.compactMap{ (x, a) -> String? in let aStr = a.description let xStr = x.description switch (aStr, parenthesize(aStr), xStr, parenthesize(xStr)) { case ("0", _, _, _): return nil case (_, _, "1", _): return aStr case ("1", _, _, _): return xStr case ("-1", _, _, false): return "-\(xStr)" case ("-1", _, _, true): return "-(\(xStr))" case (_, false, _, false): return "\(aStr)\(xStr)" case (_, true, _, false): return "(\(aStr))\(xStr)" default: return "(\(aStr))(\(xStr))" } } return termsStr.isEmpty ? "0" : termsStr.reduce(into: "") { (str, next) in if str.isEmpty { str += next } else if next.hasPrefix("-") { str += " - \(next[1...])" } else { str += " + \(next)" } } } public static func table<S1, S2, T>(rows: S1, cols: S2, symbol: String = "", separator s: String = "\t", printHeaders: Bool = true, op: (S1.Element, S2.Element) -> T) -> String where S1: Sequence, S2: Sequence { let head = printHeaders ? [[symbol] + cols.map{ y in "\(y)" }] : [] let body = rows.enumerated().map { (i, x) -> [String] in let head = printHeaders ? ["\(x)"] : [] let line = cols.enumerated().map { (j, y) in "\(op(x, y))" } return head + line } return (head + body).map{ $0.joined(separator: s) }.joined(separator: "\n") } public static func table<S, T>(elements: S, default d: String = "", symbol: String = "j\\i", separator s: String = "\t", printHeaders: Bool = true) -> String where S: Sequence, S.Element == (Int, Int, T) { let dict = Dictionary(elements.map{ (i, j, t) in ([i, j], t) } ) if dict.isEmpty { return "empty" } let I = dict.keys.map{ $0[0] }.uniqued().sorted() let J = dict.keys.map{ $0[1] }.uniqued().sorted() return Format.table(rows: J.reversed(), cols: I, symbol: symbol, separator: s, printHeaders: printHeaders) { (j, i) -> String in dict[ [i, j] ].map{ "\($0)" } ?? d } } public static func table<S, T>(elements: S, default d: String = "", symbol: String = "i", separator s: String = "\t", printHeaders: Bool = true) -> String where S: Sequence, S.Element == (Int, T) { let dict = Dictionary(elements) if dict.isEmpty { return "empty" } return Format.table(rows: [""], cols: dict.keys.sorted(), symbol: symbol, separator: s, printHeaders: printHeaders) { (_, i) -> String in dict[i].map{ "\($0)" } ?? d } } } public extension AdditiveGroup { static func printAddTable(values: [Self]) { print( Format.table(rows: values, cols: values, symbol: "+") { $0 + $1 } ) } } public extension AdditiveGroup where Self: FiniteSet { static func printAddTable() { printAddTable(values: allElements) } } public extension Monoid { static func printMulTable(values: [Self]) { print( Format.table(rows: values, cols: values, symbol: "*") { $0 * $1 } ) } static func printExpTable(values: [Self], upTo n: Int) { print( Format.table(rows: values, cols: Array(0 ... n), symbol: "^") { $0.pow($1) } ) } } public extension Monoid where Self: FiniteSet { static func printMulTable() { printMulTable(values: allElements) } static func printExpTable() { let all = allElements printExpTable(values: all, upTo: all.count - 1) } }
cc0-1.0
parkera/swift
test/AutoDiff/validation-test/optional_property.swift
3
6073
// RUN: %target-run-simple-swift // RUN: %target-swift-emit-sil -Xllvm -debug-only=differentiation -module-name null -o /dev/null 2>&1 %s | %FileCheck %s // REQUIRES: executable_test // REQUIRES: asserts // Test differentiation of `Optional` properties. import DifferentiationUnittest import StdlibUnittest var OptionalTests = TestSuite("OptionalPropertyDifferentiation") // Test `Optional` struct stored properties. struct Struct: Differentiable { var stored: Float var optional: Float? @differentiable(reverse) func method() -> Float { let s: Struct do { let tmp = Struct(stored: stored, optional: optional) let tuple = (tmp, tmp) s = tuple.0 } if let x = s.optional { return x * s.stored } return s.stored } } // Check active SIL instructions in representative original functions. // This tests SIL instruction coverage of derivative function cloners (e.g. PullbackCloner). // CHECK-LABEL: [AD] Activity info for ${{.*}}Struct{{.*}}method{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] {{.*}} struct_extract {{%.*}} : $Struct, #Struct.stored // CHECK: [ACTIVE] {{.*}} struct_extract {{%.*}} : $Struct, #Struct.optional // CHECK: [ACTIVE] {{.*}} tuple ({{%.*}} : $Struct, {{%.*}} : $Struct) // CHECK: [ACTIVE] {{.*}} destructure_tuple {{%.*}} : $(Struct, Struct) // CHECK: [ACTIVE] {{.*}} struct_element_addr {{%.*}} : $*Struct, #Struct.optional // CHECK: [ACTIVE] {{.*}} struct_element_addr {{%.*}} : $*Struct, #Struct.stored // CHECK-LABEL: [AD] Activity info for $s4null6StructV6stored8optionalACSf_SfSgtcfC at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] {{%.*}} struct $Struct ({{%.*}} : $Float, {{%.*}} : $Optional<Float>) struct StructTracked: Differentiable { var stored: NonresilientTracked<Float> var optional: NonresilientTracked<Float>? @differentiable(reverse) func method() -> NonresilientTracked<Float> { let s: StructTracked do { let tmp = StructTracked(stored: stored, optional: optional) let tuple = (tmp, tmp) s = tuple.0 } if let x = s.optional { return x * s.stored } return s.stored } } struct StructGeneric<T: Differentiable>: Differentiable { var stored: T var optional: T? @differentiable(reverse) func method() -> T { let s: StructGeneric do { let tmp = StructGeneric(stored: stored, optional: optional) let tuple = (tmp, tmp) s = tuple.0 } if let x = s.optional { return x } return s.stored } } OptionalTests.test("Optional struct stored properties") { expectEqual( valueWithGradient(at: Struct(stored: 3, optional: 4), of: { $0.method() }), (12, .init(stored: 4, optional: .init(3)))) expectEqual( valueWithGradient(at: Struct(stored: 3, optional: nil), of: { $0.method() }), (3, .init(stored: 1, optional: .init(0)))) expectEqual( valueWithGradient(at: StructTracked(stored: 3, optional: 4), of: { $0.method() }), (12, .init(stored: 4, optional: .init(3)))) expectEqual( valueWithGradient(at: StructTracked(stored: 3, optional: nil), of: { $0.method() }), (3, .init(stored: 1, optional: .init(0)))) expectEqual( valueWithGradient(at: StructGeneric<Float>(stored: 3, optional: 4), of: { $0.method() }), (4, .init(stored: 0, optional: .init(1)))) expectEqual( valueWithGradient(at: StructGeneric<Float>(stored: 3, optional: nil), of: { $0.method() }), (3, .init(stored: 1, optional: .init(0)))) } // Test `Optional` class stored properties. struct Class: Differentiable { var stored: Float var optional: Float? init(stored: Float, optional: Float?) { self.stored = stored self.optional = optional } @differentiable(reverse) func method() -> Float { let c: Class do { let tmp = Class(stored: stored, optional: optional) let tuple = (tmp, tmp) c = tuple.0 } if let x = c.optional { return x * c.stored } return c.stored } } struct ClassTracked: Differentiable { var stored: NonresilientTracked<Float> var optional: NonresilientTracked<Float>? init(stored: NonresilientTracked<Float>, optional: NonresilientTracked<Float>?) { self.stored = stored self.optional = optional } @differentiable(reverse) func method() -> NonresilientTracked<Float> { let c: ClassTracked do { let tmp = ClassTracked(stored: stored, optional: optional) let tuple = (tmp, tmp) c = tuple.0 } if let x = c.optional { return x * c.stored } return c.stored } } struct ClassGeneric<T: Differentiable>: Differentiable { var stored: T var optional: T? init(stored: T, optional: T?) { self.stored = stored self.optional = optional } @differentiable(reverse) func method() -> T { let c: ClassGeneric do { let tmp = ClassGeneric(stored: stored, optional: optional) let tuple = (tmp, tmp) c = tuple.0 } if let x = c.optional { return x } return c.stored } } OptionalTests.test("Optional class stored properties") { expectEqual( valueWithGradient(at: Class(stored: 3, optional: 4), of: { $0.method() }), (12, .init(stored: 4, optional: .init(3)))) expectEqual( valueWithGradient(at: Class(stored: 3, optional: nil), of: { $0.method() }), (3, .init(stored: 1, optional: .init(0)))) expectEqual( valueWithGradient(at: ClassTracked(stored: 3, optional: 4), of: { $0.method() }), (12, .init(stored: 4, optional: .init(3)))) expectEqual( valueWithGradient(at: ClassTracked(stored: 3, optional: nil), of: { $0.method() }), (3, .init(stored: 1, optional: .init(0)))) expectEqual( valueWithGradient(at: ClassGeneric<Tracked<Float>>(stored: 3, optional: 4), of: { $0.method() }), (4, .init(stored: 0, optional: .init(1)))) expectEqual( valueWithGradient(at: ClassGeneric<Tracked<Float>>(stored: 3, optional: nil), of: { $0.method() }), (3, .init(stored: 1, optional: .init(0)))) } runAllTests()
apache-2.0
rnystrom/GitHawk
Classes/Issues/Comments/Details/IssueDetailBadgeView.swift
1
1351
// // IssueDetailBadgeView.swift // Freetime // // Created by Ryan Nystrom on 7/29/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import UIKit final class IssueDetailBadgeView: UIImageView { init() { super.init(frame: .zero) image = UIImage(named: "githawk-badge").withRenderingMode(.alwaysTemplate) tintColor = Styles.Colors.Blue.medium.color isUserInteractionEnabled = true let tap = UITapGestureRecognizer( target: self, action: #selector(ShowMoreDetailsLabel.showMenu(recognizer:)) ) addGestureRecognizer(tap) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var canBecomeFirstResponder: Bool { return true } // MARK: Private API @objc func showMenu(recognizer: UITapGestureRecognizer) { becomeFirstResponder() let menu = UIMenuController.shared menu.menuItems = [ UIMenuItem( title: NSLocalizedString("Sent with GitHawk", comment: ""), action: #selector(IssueDetailBadgeView.empty) ) ] menu.setTargetRect(bounds, in: self) menu.setMenuVisible(true, animated: trueUnlessReduceMotionEnabled) } @objc func empty() {} }
mit
kimseongrim/KimSampleCode
UITextField/UITextFieldTests/UITextFieldTests.swift
1
905
// // UITextFieldTests.swift // UITextFieldTests // // Created by 金成林 on 15/1/19. // Copyright (c) 2015年 Kim. All rights reserved. // import UIKit import XCTest class UITextFieldTests: 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. } } }
gpl-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/02153-swift-constraints-constraintsystem-gettypeofmemberreference.swift
1
514
// 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 class a<B { class B : b : U>() -> { } func a: A> { } func f<U, b { } super.<H : a { map(")) let f = a class A : a {
apache-2.0
daniel-barros/Comedores-UGR
Comedores UGR/LastUpdateTableViewCell.swift
1
1784
// // LastUpdateTableViewCell.swift // Comedores UGR // // Created by Daniel Barros López on 3/28/16. /* MIT License Copyright (c) 2016 Daniel Barros Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // import UIKit class LastUpdateTableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! func configure(with date: Date?) { var string = NSLocalizedString("Last Update:") + " " if let lastUpdate = date { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short formatter.doesRelativeDateFormatting = true string += formatter.string(from: lastUpdate) } else { string += NSLocalizedString("Never") } label.text = string } }
mit
RobinFalko/Ubergang
Examples/TweenApp/TweenApp/AppDelegate.swift
1
2283
// // AppDelegate.swift // TweenApp // // Created by RF on 07/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import UIKit import Ubergang @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable") UTweenSetup.instance.enableLogging(true) 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:. } }
apache-2.0
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/UpdateWorkspace.swift
2
4230
/** * Copyright IBM Corporation 2018 * * 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 /** UpdateWorkspace. */ public struct UpdateWorkspace: Encodable { /// The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters. public var name: String? /// The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. public var description: String? /// The language of the workspace. public var language: String? /// An array of objects defining the intents for the workspace. public var intents: [CreateIntent]? /// An array of objects defining the entities for the workspace. public var entities: [CreateEntity]? /// An array of objects defining the nodes in the workspace dialog. public var dialogNodes: [CreateDialogNode]? /// An array of objects defining input examples that have been marked as irrelevant input. public var counterexamples: [CreateCounterexample]? /// Any metadata related to the workspace. public var metadata: [String: JSON]? /// Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. public var learningOptOut: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" case description = "description" case language = "language" case intents = "intents" case entities = "entities" case dialogNodes = "dialog_nodes" case counterexamples = "counterexamples" case metadata = "metadata" case learningOptOut = "learning_opt_out" } /** Initialize a `UpdateWorkspace` with member variables. - parameter name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters. - parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter language: The language of the workspace. - parameter intents: An array of objects defining the intents for the workspace. - parameter entities: An array of objects defining the entities for the workspace. - parameter dialogNodes: An array of objects defining the nodes in the workspace dialog. - parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input. - parameter metadata: Any metadata related to the workspace. - parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. - returns: An initialized `UpdateWorkspace`. */ public init(name: String? = nil, description: String? = nil, language: String? = nil, intents: [CreateIntent]? = nil, entities: [CreateEntity]? = nil, dialogNodes: [CreateDialogNode]? = nil, counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil) { self.name = name self.description = description self.language = language self.intents = intents self.entities = entities self.dialogNodes = dialogNodes self.counterexamples = counterexamples self.metadata = metadata self.learningOptOut = learningOptOut } }
mit
lucianomarisi/JSONUtilities
Tests/JSONUtilitiesTests/FileLoadingTests.swift
1
1468
// // FileLoadingTests.swift // FileLoadingTests // // Created by Luciano Marisi on 21/11/2015. // Copyright © 2015 Luciano Marisi All rights reserved. // import XCTest @testable import JSONUtilities typealias NoEscapeFunction = ( () throws -> Void) class FileLoadingTests: XCTestCase { func testLoadingJSONFile() { do { try JSONDictionary.from(url: JSONFilePath.correct) } catch { XCTFail("Unexpected error: \(error)") } } func testLoadingJSONFileLoadingFailed() { expectError(.fileLoadingFailed) { try JSONDictionary.from(url: JSONFilePath.missing) } } func testLoadingJSONFileDeserializationFailed() { expectError(.fileDeserializationFailed) { try JSONDictionary.from(url: JSONFilePath.invalid) } } func testLoadingJSONFileNotAJSONDictionary() { expectError(.fileNotAJSONDictionary) { try JSONDictionary.from(url: JSONFilePath.rootArray) } } // MARK: Helpers fileprivate func expectError(_ expectedError: JSONUtilsError, file: StaticString = #file, line: UInt = #line, block: NoEscapeFunction ) { do { try block() } catch let error { XCTAssert(error is JSONUtilsError, file: file, line: line) if let jsonUtilsError = error as? JSONUtilsError { XCTAssertEqual(jsonUtilsError, expectedError, file: file, line: line) } return } XCTFail("No error thrown, expected: \(expectedError)", file: file, line: line) } }
mit
Bartlebys/Bartleby
Bartlebys.playground/Sources/PlaygroundsConfiguration.swift
1
3330
// // TestsConfiguration.swift // bsync // // Created by Benoit Pereira da silva on 29/12/2015. // Copyright © 2015 Benoit Pereira da silva. All rights reserved. // import Alamofire import BartlebyKit // A shared configuration Model open class PlaygroundsConfiguration: BartlebyConfiguration { // The cryptographic key used to encrypt/decrypt the data open static var KEY: String="UDJDJJDJJDJDJDJDJJDDJJDJDJJDJ-O9393972AA" open static var SHARED_SALT: String="xyx38-d890x-899h-123e-30x6-3234e" // To conform to crypto legal context open static var KEY_SIZE: KeySize = .s128bits //MARK: - URLS static let trackAllApiCalls=true open static var API_BASE_URL=__BASE_URL // Bartleby Bprint open static var ENABLE_GLOG: Bool=true // Should Bprint entries be printed public static var PRINT_GLOG_ENTRIES: Bool=true // Use NoCrypto as CryptoDelegate (should be false) open static var DISABLE_DATA_CRYPTO: Bool=false //If set to true the created instances will be remove on maintenance Purge open static var EPHEMERAL_MODE=true //Should the app try to be online by default open static var ONLINE_BY_DEFAULT=true // Consignation open static var API_CALL_TRACKING_IS_ENABLED: Bool=true open static var BPRINT_API_TRACKED_CALLS: Bool=true // Should the registries metadata be crypted on export (should be true)! open static var CRYPTED_REGISTRIES_METADATA_EXPORT: Bool = true // Should we save the password by Default ? open static var SAVE_PASSWORD_DEFAULT_VALUE: Bool=false // If set to JSON for example would be Indented open static var HUMAN_FORMATTED_SERIALIZATON_FORMAT: Bool=false // Supervision loop interval (1 second min ) open static var LOOP_TIME_INTERVAL_IN_SECONDS: Double = 1 // To guarantee the sequential Execution use 1 open static var MAX_OPERATIONS_BUNCH_SIZE: Int = 10 // The min password size open static var MIN_PASSWORD_SIZE: UInt=6 // E.g : Default.DEFAULT_PASSWORD_CHAR_CART open static var PASSWORD_CHAR_CART: String="ABCDEFGH1234567890" // If set to true the keyed changes are stored in the ManagedModel - When opening the Inspector this default value is remplaced by true public static var CHANGES_ARE_INSPECTABLES_BY_DEFAULT: Bool = false //MARK: - Variable base URL enum Environment { case local case development case alternative case production } static var currentEnvironment: Environment = .development static fileprivate var __BASE_URL: URL { get { switch currentEnvironment { case .local: // On macOS you should point "yd.local" to your IP by editing /etc/host return URL(string:"http://yd.local:8001/api/v1")! case .development: return URL(string:"https://dev.api.lylo.tv/api/v1")! case .alternative: return URL(string: "https://demo.bartlebys.org/www/api/v1")! case .production: return URL(string:"https://api.lylo.tv/api/v1")! } } } open static let TIME_OUT_DURATION = 10.0 open static let LONG_TIME_OUT_DURATION = 360.0 open static let ENABLE_TEST_OBSERVATION=true }
apache-2.0
samhann/Every.swift
EveryTests/EveryTests.swift
1
4485
// // Every_swiftTests.swift // Every.swiftTests // // Created by Samhan on 08/01/16. // Copyright © 2016 Samhan. All rights reserved. // import XCTest /** Utility function to help fulfill expectations. - parameter seconds: Delay value in seconds. - parameter completion: Handler that will be called after `delay`. */ func delay(seconds seconds: Double, completion: Void -> Void) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds )) dispatch_after(popTime, dispatch_get_main_queue()) { completion() } } class Every_swiftTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testBasicTimerFunctionality() { let expectation = self.expectationWithDescription("Fires in 1 second") let startTime = NSDate() TimerManager.every(1.seconds, owner: self, elapsedHandler: { let fireTime = NSDate() let delta = fireTime.timeIntervalSinceReferenceDate - startTime.timeIntervalSinceReferenceDate print(delta) if delta >= 1 && delta <= 1.2 { expectation.fulfill() } return false }) self.waitForExpectationsWithTimeout(4, handler: nil) } func testClearAllTimers() { let expectation = expectationWithDescription("Doesn't fires in 200 milliseconds") let timerOwner1 = NSObject() let timerOwner2 = NSObject() var fired1 = false var fired2 = false TimerManager.every(200.milliseconds, owner: timerOwner1) { fired1 = true return false } TimerManager.every(200.milliseconds, owner: timerOwner2) { fired2 = true return false } TimerManager.clearAllTimers() delay(seconds: 1.0) { if !fired1 && !fired2 { expectation.fulfill() return } if fired1 { XCTFail("First timer fired") } if fired2 { XCTFail("Second timer fired") } } waitForExpectationsWithTimeout(1.5, handler: nil) } func testClearTimersForOwner() { let expectation = expectationWithDescription("First timer fires and second doesn't") let timerOwner1 = NSObject() let timerOwner2 = NSObject() var fired1 = false var fired2 = false TimerManager.every(200.milliseconds, owner: timerOwner1) { fired1 = true return false } TimerManager.every(200.milliseconds, owner: timerOwner2) { fired2 = true return false } TimerManager.clearTimersForOwner(timerOwner2) delay(seconds: 1.0) { if fired1 && !fired2 { expectation.fulfill() return } if !fired1 { XCTFail("First timer not fired") } if fired2 { XCTFail("Second timer fired") } } waitForExpectationsWithTimeout(1.5, handler: nil) } func testClearTimer() { let expectation = expectationWithDescription("First timer fires and second doesn't") let timerOwner = NSObject() var fired1 = false var fired2 = false let _ = TimerManager.every(200.milliseconds, owner: timerOwner) { fired1 = true return false } let secondHandler = TimerManager.every(200.milliseconds, owner: timerOwner) { fired2 = true return false } TimerManager.clearTimer(secondHandler) delay(seconds: 1.0) { if fired1 && !fired2 { expectation.fulfill() return } if !fired1 { XCTFail("First timer not fired") } if fired2 { XCTFail("Second timer fired") } } waitForExpectationsWithTimeout(1.5, handler: nil) } }
bsd-2-clause
khizkhiz/swift
test/SILGen/witnesses.swift
1
29566
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s infix operator <~> {} func archetype_method<T: X>(x x: T, y: T) -> T { var x = x var y = y return x.selfTypes(x: y) } // CHECK-LABEL: sil hidden @_TF9witnesses16archetype_method{{.*}} : $@convention(thin) <T where T : X> (@in T, @in T) -> @out T { // CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0 // CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0 // CHECK: } func archetype_generic_method<T: X>(x x: T, y: Loadable) -> Loadable { var x = x return x.generic(x: y) } // CHECK-LABEL: sil hidden @_TF9witnesses24archetype_generic_method{{.*}} : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable { // CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0 // CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0 // CHECK: } // CHECK-LABEL: sil hidden @_TF9witnesses32archetype_associated_type_method{{.*}} : $@convention(thin) <T where T : WithAssoc> (@in T, @in T.AssocType) -> @out T // CHECK: apply %{{[0-9]+}}<T, T.AssocType> func archetype_associated_type_method<T: WithAssoc>(x x: T, y: T.AssocType) -> T { return x.useAssocType(x: y) } protocol StaticMethod { static func staticMethod() } // CHECK-LABEL: sil hidden @_TF9witnesses23archetype_static_method{{.*}} : $@convention(thin) <T where T : StaticMethod> (@in T) -> () func archetype_static_method<T: StaticMethod>(x x: T) { // CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> () // CHECK: apply [[METHOD]]<T> T.staticMethod() } protocol Existentiable { func foo() -> Loadable func generic<T>() -> T } func protocol_method(x x: Existentiable) -> Loadable { return x.foo() } // CHECK-LABEL: sil hidden @_TF9witnesses15protocol_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable { // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1 // CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}}) // CHECK: } func protocol_generic_method(x x: Existentiable) -> Loadable { return x.generic() } // CHECK-LABEL: sil hidden @_TF9witnesses23protocol_generic_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable { // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1 // CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}}) // CHECK: } @objc protocol ObjCAble { func foo() } // CHECK-LABEL: sil hidden @_TF9witnesses20protocol_objc_methodFT1xPS_8ObjCAble__T_ : $@convention(thin) (@owned ObjCAble) -> () // CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign func protocol_objc_method(x x: ObjCAble) { x.foo() } struct Loadable {} protocol AddrOnly {} protocol Classes : class {} protocol X { mutating func selfTypes(x x: Self) -> Self mutating func loadable(x x: Loadable) -> Loadable mutating func addrOnly(x x: AddrOnly) -> AddrOnly mutating func generic<A>(x x: A) -> A mutating func classes<A2: Classes>(x x: A2) -> A2 func <~>(x: Self, y: Self) -> Self } protocol Y {} protocol WithAssoc { associatedtype AssocType func useAssocType(x x: AssocType) -> Self } protocol ClassBounded : class { func selfTypes(x x: Self) -> Self } struct ConformingStruct : X { mutating func selfTypes(x x: ConformingStruct) -> ConformingStruct { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingStruct, @inout ConformingStruct) -> @out ConformingStruct { // CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct): // CHECK-NEXT: %3 = load %1 : $*ConformingStruct // CHECK-NEXT: // function_ref // CHECK-NEXT: %4 = function_ref @_TFV9witnesses16ConformingStruct9selfTypes{{.*}} : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct // CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct // CHECK-NEXT: store %5 to %0 : $*ConformingStruct // CHECK-NEXT: %7 = tuple () // CHECK-NEXT: return %7 : $() // CHECK-NEXT: } mutating func loadable(x x: Loadable) -> Loadable { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8loadable{{.*}} : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable { // CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct8loadable{{.*}} : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable // CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable // CHECK-NEXT: return %3 : $Loadable // CHECK-NEXT: } mutating func addrOnly(x x: AddrOnly) -> AddrOnly { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly { // CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct8addrOnly{{.*}} : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly // CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() // CHECK-NEXT: } mutating func generic<C>(x x: C) -> C { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@in A, @inout ConformingStruct) -> @out A { // CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct7generic{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0 // CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0 // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() // CHECK-NEXT: } mutating func classes<C2: Classes>(x x: C2) -> C2 { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformingStruct) -> @owned A2 { // CHECK: bb0(%0 : $A2, %1 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct7classes{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0 // CHECK-NEXT: %3 = apply %2<A2>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0 // CHECK-NEXT: return %3 : $A2 // CHECK-NEXT: } } func <~>(x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> @out ConformingStruct { // CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct, %3 : $@thick ConformingStruct.Type): // CHECK-NEXT: %4 = load %1 : $*ConformingStruct // CHECK-NEXT: %5 = load %2 : $*ConformingStruct // CHECK-NEXT: // function_ref // CHECK-NEXT: %6 = function_ref @_TZF9witnessesoi3ltgFTVS_16ConformingStructS0__S0_ : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct // CHECK-NEXT: %7 = apply %6(%4, %5) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct // CHECK-NEXT: store %7 to %0 : $*ConformingStruct // CHECK-NEXT: %9 = tuple () // CHECK-NEXT: return %9 : $() // CHECK-NEXT: } final class ConformingClass : X { func selfTypes(x x: ConformingClass) -> ConformingClass { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingClass, @inout ConformingClass) -> @out ConformingClass { // CHECK: bb0(%0 : $*ConformingClass, %1 : $*ConformingClass, %2 : $*ConformingClass): // -- load and retain 'self' from inout witness 'self' parameter // CHECK-NEXT: %3 = load %2 : $*ConformingClass // CHECK-NEXT: strong_retain %3 : $ConformingClass // CHECK-NEXT: %5 = load %1 : $*ConformingClass // CHECK: %6 = function_ref @_TFC9witnesses15ConformingClass9selfTypes // CHECK-NEXT: %7 = apply %6(%5, %3) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass // CHECK-NEXT: store %7 to %0 : $*ConformingClass // CHECK-NEXT: %9 = tuple () // CHECK-NEXT: strong_release %3 // CHECK-NEXT: return %9 : $() // CHECK-NEXT: } func loadable(x x: Loadable) -> Loadable { return x } func addrOnly(x x: AddrOnly) -> AddrOnly { return x } func generic<D>(x x: D) -> D { return x } func classes<D2: Classes>(x x: D2) -> D2 { return x } } func <~>(x: ConformingClass, y: ConformingClass) -> ConformingClass { return x } extension ConformingClass : ClassBounded { } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_12ClassBoundedS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass { // CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass): // CHECK-NEXT: strong_retain [[C1]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFC9witnesses15ConformingClass9selfTypes // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass // CHECK-NEXT: strong_release [[C1]] // CHECK-NEXT: return [[RESULT]] : $ConformingClass // CHECK-NEXT: } struct ConformingAOStruct : X { var makeMeAO : AddrOnly mutating func selfTypes(x x: ConformingAOStruct) -> ConformingAOStruct { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18ConformingAOStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct { // CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_TFV9witnesses18ConformingAOStruct9selfTypes{{.*}} : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct // CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() // CHECK-NEXT: } func loadable(x x: Loadable) -> Loadable { return x } func addrOnly(x x: AddrOnly) -> AddrOnly { return x } func generic<D>(x x: D) -> D { return x } func classes<D2: Classes>(x x: D2) -> D2 { return x } } func <~>(x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x } struct ConformsWithMoreGeneric : X, Y { mutating func selfTypes<E>(x x: E) -> E { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> @out ConformsWithMoreGeneric { // CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric9selfTypes{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } func loadable<F>(x x: F) -> F { return x } mutating func addrOnly<G>(x x: G) -> G { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@in AddrOnly, @inout ConformsWithMoreGeneric) -> @out AddrOnly { // CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric8addrOnly{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } mutating func generic<H>(x x: H) -> H { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@in A, @inout ConformsWithMoreGeneric) -> @out A { // CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformsWithMoreGeneric): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7generic{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } mutating func classes<I>(x x: I) -> I { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformsWithMoreGeneric) -> @owned A2 { // CHECK: bb0(%0 : $A2, %1 : $*ConformsWithMoreGeneric): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $A2 // CHECK-NEXT: store %0 to [[SELF_BOX]] : $*A2 // CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes // CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7classes{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $A2 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<A2>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = load [[RESULT_BOX]] : $*A2 // CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*A2 // CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*A2 // CHECK-NEXT: return [[RESULT]] : $A2 // CHECK-NEXT: } } func <~> <J: Y, K: Y>(x: J, y: K) -> K { return y } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> @out ConformsWithMoreGeneric { // CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TZF9witnessesoi3ltg{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } protocol LabeledRequirement { func method(x x: Loadable) } struct UnlabeledWitness : LabeledRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16UnlabeledWitnessS_18LabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> () func method(x _: Loadable) {} } protocol LabeledSelfRequirement { func method(x x: Self) } struct UnlabeledSelfWitness : LabeledSelfRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses20UnlabeledSelfWitnessS_22LabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> () func method(x _: UnlabeledSelfWitness) {} } protocol UnlabeledRequirement { func method(x _: Loadable) } struct LabeledWitness : UnlabeledRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14LabeledWitnessS_20UnlabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> () func method(x x: Loadable) {} } protocol UnlabeledSelfRequirement { func method(_: Self) } struct LabeledSelfWitness : UnlabeledSelfRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18LabeledSelfWitnessS_24UnlabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> () func method(x: LabeledSelfWitness) {} } protocol ReadOnlyRequirement { var prop: String { get } static var prop: String { get } } struct ImmutableModel: ReadOnlyRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_FS1_g4propSS : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String let prop: String = "a" // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_ZFS1_g4propSS : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String static let prop: String = "b" } protocol FailableRequirement { init?(foo: Int) } protocol NonFailableRefinement: FailableRequirement { init(foo: Int) } protocol IUOFailableRequirement { init!(foo: Int) } struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_19FailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel> // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_21NonFailableRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out NonFailableModel // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_22IUOFailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out ImplicitlyUnwrappedOptional<NonFailableModel> init(foo: Int) {} } struct FailableModel: FailableRequirement, IUOFailableRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_19FailableRequirementS_FS1_C{{.*}} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_22IUOFailableRequirementS_FS1_C{{.*}} // CHECK: bb0([[SELF:%[0-9]+]] : $*ImplicitlyUnwrappedOptional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type): // CHECK: [[FN:%.*]] = function_ref @_TFV9witnesses13FailableModelC{{.*}} // CHECK: [[INNER:%.*]] = apply [[FN]]( // CHECK: [[OUTER:%.*]] = unchecked_trivial_bit_cast [[INNER]] : $Optional<FailableModel> to $ImplicitlyUnwrappedOptional<FailableModel> // CHECK: store [[OUTER]] to %0 // CHECK: return init?(foo: Int) {} } struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16IUOFailableModelS_21NonFailableRefinementS_FS1_C{{.*}} // CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type): // CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type // CHECK: [[INIT:%[0-9]+]] = function_ref @_TFV9witnesses16IUOFailableModelC{{.*}} : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel> // CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel> // CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<IUOFailableModel> // CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel> // CHECK: [[FORCE_FN:%[0-9]+]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x{{.*}} : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0 // CHECK: [[RESULT_TEMP:%[0-9]+]] = alloc_stack $IUOFailableModel // CHECK: apply [[FORCE_FN]]<IUOFailableModel>([[RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0 // CHECK: [[RESULT:%[0-9]+]] = load [[RESULT_TEMP]] : $*IUOFailableModel // CHECK: store [[RESULT]] to [[SELF]] : $*IUOFailableModel // CHECK: dealloc_stack [[RESULT_TEMP]] : $*IUOFailableModel // CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel> // CHECK: return init!(foo: Int) { return nil } } protocol FailableClassRequirement: class { init?(foo: Int) } protocol NonFailableClassRefinement: FailableClassRequirement { init(foo: Int) } protocol IUOFailableClassRequirement: class { init!(foo: Int) } final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel> // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned ImplicitlyUnwrappedOptional<NonFailableClassModel> init(foo: Int) {} } final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} // CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses18FailableClassModelC{{.*}} // CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1) // CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $Optional<FailableClassModel> to $ImplicitlyUnwrappedOptional<FailableClassModel> // CHECK: return [[OUTER]] : $ImplicitlyUnwrappedOptional<FailableClassModel> init?(foo: Int) {} } final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}} // CHECK: function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x // CHECK: return [[RESULT:%[0-9]+]] : $IUOFailableClassModel // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} init!(foo: Int) {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} // CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses21IUOFailableClassModelC{{.*}} // CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1) // CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $ImplicitlyUnwrappedOptional<IUOFailableClassModel> to $Optional<IUOFailableClassModel> // CHECK: return [[OUTER]] : $Optional<IUOFailableClassModel> } protocol HasAssoc { associatedtype Assoc } protocol GenericParameterNameCollisionProtocol { func foo<T>(x: T) associatedtype Assoc2 func bar<T>(x: T -> Assoc2) } struct GenericParameterNameCollision<T: HasAssoc> : GenericParameterNameCollisionProtocol { // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionProtocol{{.*}}foo{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@in T, @in_guaranteed GenericParameterNameCollision<T1>) -> () { // CHECK: bb0(%0 : $*T, %1 : $*GenericParameterNameCollision<T1>): // CHECK: apply {{%.*}}<T1, T1.Assoc, T> func foo<U>(x: U) {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionProtocol{{.*}}bar{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@owned @callee_owned (@in T) -> @out T1.Assoc, @in_guaranteed GenericParameterNameCollision<T1>) -> () { // CHECK: bb0(%0 : $@callee_owned (@in T) -> @out T1.Assoc, %1 : $*GenericParameterNameCollision<T1>): // CHECK: apply {{%.*}}<T1, T1.Assoc, T> func bar<V>(x: V -> T.Assoc) {} } protocol PropertyRequirement { var width: Int { get set } static var height: Int { get set } var depth: Int { get set } } class PropertyRequirementBase { var width: Int = 12 static var height: Int = 13 } class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement { var depth: Int = 14 // Make sure the contravariant return type in materializeForSet works correctly // If the witness is in a base class of the conforming class, make sure we have a bit_cast in there: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5widthSi : {{.*}} { // CHECK: upcast // CHECK-NEXT: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1 // CHECK-NEXT: [[RES:%.*]] = apply [[METH]] // CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0 // CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1 // CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]] // CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}}) // CHECK-NEXT: strong_release // CHECK-NEXT: return [[TUPLE]] // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_ZFS1_m6heightSi : {{.*}} { // CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type // CHECK: [[METH:%.*]] = function_ref @_TZFC9witnesses23PropertyRequirementBasem6heightSi // CHECK-NEXT: [[RES:%.*]] = apply [[METH]] // CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0 // CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1 // CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]] // CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}}) // CHECK-NEXT: return [[TUPLE]] // Otherwise, we shouldn't need the bit_cast: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5depthSi // CHECK: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1 // CHECK-NEXT: [[RES:%.*]] = apply [[METH]] // CHECK-NEXT: tuple_extract // CHECK-NEXT: tuple_extract // CHECK-NEXT: [[RES:%.*]] = tuple // CHECK-NEXT: strong_release // CHECK-NEXT: return [[RES]] }
apache-2.0
tkremenek/swift
test/IRGen/dllexport.swift
21
2598
// RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -disable-legacy-type-info -parse-stdlib -module-name dllexport %s -o - | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT // RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -disable-legacy-type-info -parse-stdlib -module-name dllexport %s -o - | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT // REQUIRES: CODEGENERATOR=ARM enum Never {} @_silgen_name("_swift_fatalError") func fatalError() -> Never public protocol p { func f() } open class c { public init() { } } public var ci : c = c() open class d { private func m() -> Never { fatalError() } } // CHECK-DAG: @"$s9dllexport2ciAA1cCvp" = dllexport global %T9dllexport1cC* null, align 4 // CHECK-DAG: @"$s9dllexport1pMp" = dllexport constant // CHECK-DAG: @"$s9dllexport1cCMn" = dllexport constant // CHECK-DAG: @"$s9dllexport1cCN" = dllexport alias %swift.type // CHECK-DAG: @"$s9dllexport1dCN" = dllexport alias %swift.type, bitcast ({{.*}}) // CHECK-DAG-OPT: @"$s9dllexport1dC1m33_C57BA610BA35E21738CC992438E660E9LLyyF" = dllexport alias void (), void ()* @_swift_dead_method_stub // CHECK-DAG-OPT: @"$s9dllexport1dCACycfc" = dllexport alias void (), void ()* @_swift_dead_method_stub // CHECK-DAG-OPT: @"$s9dllexport1cCACycfc" = dllexport alias void (), void ()* @_swift_dead_method_stub // CHECK-DAG-OPT: @"$s9dllexport1cCACycfC" = dllexport alias void (), void ()* @_swift_dead_method_stub // CHECK-DAG: define dllexport swiftcc %swift.refcounted* @"$s9dllexport1cCfd"(%T9dllexport1cC*{{.*}}) // CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1cC* @"$s9dllexport1cCACycfc"(%T9dllexport1cC* %0) // CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1cC* @"$s9dllexport1cCACycfC"(%swift.type* %0) // CHECK-DAG: define dllexport swiftcc i8* @"$s9dllexport2ciAA1cCvau"() // CHECK-DAG-NO-OPT: define dllexport swiftcc void @"$s9dllexport1dC1m33_C57BA610BA35E21738CC992438E660E9LLyyF"(%T9dllexport1dC* %0) // CHECK-DAG-NO-OPT: define dllexport swiftcc void @"$s9dllexport1dCfD"(%T9dllexport1dC* %0) // CHECK-DAG: define dllexport swiftcc %swift.refcounted* @"$s9dllexport1dCfd"(%T9dllexport1dC*{{.*}}) // CHECK-DAG: define dllexport swiftcc %swift.metadata_response @"$s9dllexport1cCMa"(i32 %0) // CHECK-DAG: define dllexport swiftcc %swift.metadata_response @"$s9dllexport1dCMa"(i32 %0) // CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1dC* @"$s9dllexport1dCACycfc"(%T9dllexport1dC* %0) // CHECK-DAG-OPT: define dllexport swiftcc void @"$s9dllexport1dCfD"(%T9dllexport1dC* %0)
apache-2.0
maxsokolov/Leeloo
Sources/NetworkClient.swift
1
7034
// // Copyright (c) 2017 Max Sokolov https://twitter.com/max_sokolov // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Alamofire public typealias HttpMethod = HTTPMethod extension Request: NetworkRequestTask {} open class NetworkClient { public let session: SessionManager private let defaultBehaviors: [NetworkRequestBehavior] public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default, defaultBehaviors: [NetworkRequestBehavior] = []) { self.session = SessionManager(configuration: configuration) self.defaultBehaviors = defaultBehaviors } // MARK: - Send methods open func sendMultipart<R: NetworkMultipartDataRequest, T>( request: R, behaviors: [NetworkRequestBehavior] = [], completion: ((_ result: NetworkRequestResult<T>) -> ())?) where R.Response == T { let requestBehaviors = [defaultBehaviors, behaviors].reduce([], +) session.upload( multipartFormData: { multipartFormData in if let parameters = request.parameters { for (key, value) in parameters { if let data = "\(value)".data(using: .utf8) { multipartFormData.append(data, withName: key) } } } request.files.forEach { switch $0.source { case .data(let data): multipartFormData.append( data, withName: $0.fileName, fileName: $0.fileName, mimeType: $0.mimeType ) case .file(let url): multipartFormData.append( url, withName: $0.fileName, fileName: $0.fileName, mimeType: $0.mimeType ) } } }, to: request.endpoint + request.path, method: request.method, headers: getHeaders(forRequest: request, requestBehaviors: requestBehaviors), encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload .uploadProgress { progress in // main queue by default } .responseObject( networkRequest: request, requestBehaviors: [], completionHandler: { response in switch response.result { case .success(let value): completion?(.value(value)) case .failure(let error): if let requestError = error as? NetworkRequestError { completion?(.error(requestError)) } else { completion?(.error(NetworkRequestError.connectionError(error: error))) } } } ) case .failure(let encodingError): print(encodingError) } } ) } @discardableResult open func send<R: NetworkRequest, T>( request: R, behaviors: [NetworkRequestBehavior] = [], completion: ((_ result: NetworkRequestResult<T>) -> ())?) -> NetworkRequestTask? where R.Response == T { guard let baseUrl = try? request.endpoint.asURL() else { return nil } let urlString = baseUrl.appendingPathComponent(request.path).absoluteString let requestBehaviors = [defaultBehaviors, behaviors].reduce([], +) // before send hook requestBehaviors.forEach({ $0.willSend() }) return session .request( urlString, method: request.method, parameters: request.parameters, encoding: JSONEncoding.default, headers: getHeaders(forRequest: request, requestBehaviors: requestBehaviors) ) .responseObject( networkRequest: request, requestBehaviors: requestBehaviors ) { (response) in switch response.result { case .success(let value): completion?(.value(value)) case .failure(let error): print(error) if let requestError = error as? NetworkRequestError { completion?(.error(requestError)) } else { completion?(.error(NetworkRequestError.connectionError(error: error))) } } } } // MARK: - Private private func getHeaders<R: NetworkRequest>( forRequest request: R, requestBehaviors: [NetworkRequestBehavior]) -> [String: String] { // combine additional headers from behaviors let headers = requestBehaviors.map({ $0.additionalHeaders }).reduce([], +) var additionalHeaders: [String: String] = [:] for item in headers { additionalHeaders.updateValue(item.1, forKey: item.0) } return additionalHeaders } }
mit
xwu/swift
test/Profiler/coverage_deinit.swift
18
712
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -suppress-warnings -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_deinit %s | %FileCheck %s // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s // REQUIRES: objc_interop import Foundation public class Derived: NSString { // CHECK-LABEL: sil @$s15coverage_deinit7DerivedCfD // CHECK: builtin "int_instrprof_increment" // CHECK-NEXT: super_method {{.*}} : $Derived, #NSString.deinit!deallocator.foreign deinit { } } // CHECK-LABEL: sil_coverage_map "{{.*}}coverage_deinit.swift" "$s15coverage_deinit7DerivedCfD" // CHECK-NEXT: [[@LINE-5]]:10 -> [[@LINE-4]]:4 : 0
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/21662-swift-type-walk.swift
11
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct b<H { var d = b func e { enum e { struct g<T where g: f { let : A. e class A
mit
radex/swift-compiler-crashes
crashes-fuzzing/02334-swift-constraints-solution-solution.swift
11
200
// 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<S where B:U }Any (A.f=0
mit
CodeDrunkard/Algorithm
Algorithm.playground/Pages/Tree.xcplaygroundpage/Contents.swift
1
2280
/*: Tree */ public class TreeNode<T> { public var value: T public weak var parent: TreeNode? public var children = [TreeNode]() public init(_ value: T) { self.value = value } public var isRoot: Bool { return parent == nil } public var depth: Int { var d = 0 var p = parent while p != nil { d += 1 p = p!.parent } return d } public func addChild(_ node: TreeNode) { children.append(node) node.parent = self } } extension TreeNode: CustomStringConvertible { public var description: String { var str = "\(value)" if !children.isEmpty { str += " {" + children.map { $0.description }.joined(separator: ", ") + "} " } return str } } extension TreeNode where T: Equatable { public func search(_ value: T) -> TreeNode? { if value == self.value { return self } for child in children { if let found = child.search(value) { return found } } return nil } } //: TEST let tree = TreeNode<String>("beverages") let hotNode = TreeNode<String>("hot") let coldNode = TreeNode<String>("cold") let teaNode = TreeNode<String>("tea") let coffeeNode = TreeNode<String>("coffee") let chocolateNode = TreeNode<String>("cocoa") let blackTeaNode = TreeNode<String>("black") let greenTeaNode = TreeNode<String>("green") let chaiTeaNode = TreeNode<String>("chai") let sodaNode = TreeNode<String>("soda") let milkNode = TreeNode<String>("milk") let gingerAleNode = TreeNode<String>("ginger ale") let bitterLemonNode = TreeNode<String>("bitter lemon") tree.addChild(hotNode) tree.addChild(coldNode) hotNode.addChild(teaNode) hotNode.addChild(coffeeNode) hotNode.addChild(chocolateNode) coldNode.addChild(sodaNode) coldNode.addChild(milkNode) teaNode.addChild(blackTeaNode) teaNode.addChild(greenTeaNode) teaNode.addChild(chaiTeaNode) sodaNode.addChild(gingerAleNode) sodaNode.addChild(bitterLemonNode) tree tree.search("cocoa") tree.search("chai") tree.search("bubbly") tree.depth hotNode.depth teaNode.depth //: [Contents](Contents) | [Previous](@previous) | [Next](@next)
mit
devpunk/velvet_room
Source/Model/Vita/MVitaPtpEvent.swift
1
527
enum MVitaPtpEvent:UInt16 { case unknown case sendItemsCount = 49412 case sendItemsMetadata = 49413 case sendItem = 49415 case requestItemStatus = 49423 case sendItemThumbnail = 49424 case requestSettings = 49426 case sendStorageSize = 49433 case requestItemTreat = 49442 case terminate = 49446 case itemPropertyChanged = 51201 }
mit
garygriswold/Bible.js
Plugins/AWS/src/ios/OBSOLETE/AWS.swift
2
8637
// // AWS.swift // AWS // // Created by Gary Griswold on 5/15/17. // Copyright © 2017 ShortSands. All rights reserved. // /** * This class is the cordova native interface code that calls the AwsS3. * It is a thin wrapper around the AwsS3 class that AwsS3 can also * be used directly by other .swift classes. */ //import AWS used for AWS.framework @objc(AWS) class AWS : CDVPlugin { @objc(initializeRegion:) func initializeRegion(command: CDVInvokedUrlCommand) { let manager = AwsS3Manager.getSingleton() let result = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(echo2:) func echo2(command: CDVInvokedUrlCommand) { let message = command.arguments[0] as? String ?? "" let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(echo3:) func echo3(command: CDVInvokedUrlCommand) { let message = command.arguments[0] as? String ?? "" let response = AwsS3Manager.findSS().echo3(message: message); let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: response) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(preSignedUrlGET:) func preSignedUrlGET(command: CDVInvokedUrlCommand) { AwsS3Manager.findSS().preSignedUrlGET( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", expires: command.arguments[2] as? Int ?? 3600, complete: { url in let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: url?.absoluteString) self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(preSignedUrlPUT:) func preSignedUrlPUT(command: CDVInvokedUrlCommand) { AwsS3Manager.findSS().preSignedUrlPUT( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", expires: command.arguments[2] as? Int ?? 3600, contentType: command.arguments[3] as? String ?? "", complete: { url in let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: url?.absoluteString) self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(downloadText:) func downloadText(command: CDVInvokedUrlCommand) { AwsS3Manager.findSS().downloadText( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", complete: { error, data in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: data) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(downloadData:) func downloadData(command: CDVInvokedUrlCommand) { AwsS3Manager.findSS().downloadData( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", complete: { error, data in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArrayBuffer: data) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(downloadFile:) func downloadFile(command: CDVInvokedUrlCommand) { print("Documents \(NSHomeDirectory())") let filePath: String = command.arguments[2] as? String ?? "" AwsS3Manager.findSS().downloadFile( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", filePath: URL(fileURLWithPath: NSHomeDirectory() + filePath), complete: { error in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(downloadZipFile:) func downloadZipFile(command: CDVInvokedUrlCommand) { print("Documents \(NSHomeDirectory())") let filePath: String = command.arguments[2] as? String ?? "" AwsS3Manager.findSS().downloadZipFile( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", filePath: URL(fileURLWithPath: NSHomeDirectory() + filePath), view: self.webView, complete: { error in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(uploadAnalytics:) func uploadVideoAnalytics(command: CDVInvokedUrlCommand) { let data = command.arguments[3] as? String ?? "" AwsS3Manager.findSS().uploadAnalytics( sessionId: command.arguments[0] as? String ?? "", timestamp: command.arguments[1] as? String ?? "", prefix: command.arguments[2] as? String ?? "", json: data.data(using: String.Encoding.utf8)!, complete: { error in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(uploadText:) func uploadText(command: CDVInvokedUrlCommand) { AwsS3Manager.findSS().uploadText( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", data: command.arguments[2] as? String ?? "", contentType: command.arguments[3] as? String ?? "", complete: { error in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } @objc(uploadData:) func uploadData(command: CDVInvokedUrlCommand) { AwsS3Manager.findSS().uploadData( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", data: command.arguments[2] as? Data ?? Data(), contentType: command.arguments[3] as? String ?? "", complete: { error in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } /** * Warning: this does not use the uploadFile method of TransferUtility, * See note in AwsS3.uploadFile for more info. */ @objc(uploadFile:) func uploadFile(command: CDVInvokedUrlCommand) { let filePath = command.arguments[2] as? String ?? "" AwsS3Manager.findSS().uploadFile( s3Bucket: command.arguments[0] as? String ?? "", s3Key: command.arguments[1] as? String ?? "", filePath: URL(fileURLWithPath: NSHomeDirectory() + filePath), contentType: command.arguments[3] as? String ?? "", complete: { error in var result: CDVPluginResult if let err = error { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription) } else { result = CDVPluginResult(status: CDVCommandStatus_OK) } self.commandDelegate!.send(result, callbackId: command.callbackId) } ) } }
mit
mvader/advent-of-code
2021/09/02.swift
1
2457
import Foundation struct Point: Hashable { let x: Int let y: Int init(_ x: Int, _ y: Int) { self.x = x self.y = y } } func findBasin(_ heightmap: [[Int]], _ x: Int, _ y: Int) -> [Int] { var result = [heightmap[y][x]] var seen: Set = [Point(x, y)] result.append(contentsOf: adjacentBasinPoints(heightmap, x, y, &seen)) return result } func adjacentBasinPoints(_ matrix: [[Int]], _ x: Int, _ y: Int, _ seen: inout Set<Point>) -> [Int] { var result = [Int]() if y > 0, matrix[y - 1][x] < 9, !seen.contains(Point(x, y - 1)) { seen.insert(Point(x, y - 1)) result.append(matrix[y - 1][x]) result.append(contentsOf: adjacentBasinPoints(matrix, x, y - 1, &seen)) } if y + 1 < matrix.count, matrix[y + 1][x] < 9, !seen.contains(Point(x, y + 1)) { seen.insert(Point(x, y + 1)) result.append(matrix[y + 1][x]) result.append(contentsOf: adjacentBasinPoints(matrix, x, y + 1, &seen)) } if x > 0, matrix[y][x - 1] < 9, !seen.contains(Point(x - 1, y)) { seen.insert(Point(x - 1, y)) result.append(matrix[y][x - 1]) result.append(contentsOf: adjacentBasinPoints(matrix, x - 1, y, &seen)) } if x + 1 < matrix[y].count, matrix[y][x + 1] < 9, !seen.contains(Point(x + 1, y)) { seen.insert(Point(x + 1, y)) result.append(matrix[y][x + 1]) result.append(contentsOf: adjacentBasinPoints(matrix, x + 1, y, &seen)) } return result } func adjacentPoints(_ matrix: [[Int]], _ x: Int, _ y: Int) -> [Int] { var result = [Int]() if y > 0 { result.append(matrix[y - 1][x]) } if y + 1 < matrix.count { result.append(matrix[y + 1][x]) } if x > 0 { result.append(matrix[y][x - 1]) } if x + 1 < matrix[y].count { result.append(matrix[y][x + 1]) } return result } func isLowPoint(_ heightmap: [[Int]], _ x: Int, _ y: Int) -> Bool { let adjacents = adjacentPoints(heightmap, x, y) return adjacents.allSatisfy { $0 > heightmap[y][x] } } func findBasins(_ heightmap: [[Int]]) -> [[Int]] { var result = [[Int]]() for y in 0 ..< heightmap.count { let row = heightmap[y] for x in 0 ..< row.count { if isLowPoint(heightmap, x, y) { let basin = findBasin(heightmap, x, y) result.append(basin) } } } return result } let heightmap = try String(contentsOfFile: "./input.txt", encoding: .utf8) .split(separator: "\n") .map { line in Array(line).map { c in Int(String(c))! } } let basins = findBasins(heightmap) print(basins.map { $0.count }.sorted().reversed().prefix(3).reduce(1, *))
mit
ResearchSuite/ResearchSuiteExtensions-iOS
source/Core/Classes/RSEmailStepViewController.swift
1
5017
// // RSEmailStepViewController.swift // ResearchSuiteExtensions // // Created by James Kizer on 2/7/18. // import UIKit import MessageUI open class RSEmailStepViewController: RSQuestionViewController, MFMailComposeViewControllerDelegate { open var emailSent: Bool = false func showErrorMessage(emailStep: RSEmailStep) { DispatchQueue.main.async { self.emailSent = true self.setContinueButtonTitle(title: "Continue") let alertController = UIAlertController(title: "Email failed", message: emailStep.errorMessage, preferredStyle: UIAlertController.Style.alert) // Replace UIAlertActionStyle.Default by UIAlertActionStyle.default let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } func generateMailLink(emailStep: RSEmailStep) -> URL? { let recipients: String = emailStep.recipientAddreses.joined(separator: ",") var emailLink = "mailto:\(recipients)" let params: [String: String] = { var paramDict: [String: String] = [:] if let subject = emailStep.messageSubject?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { paramDict["Subject"] = subject } if let body = emailStep.messageBody?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { paramDict["Body"] = body } return paramDict }() if params.count > 0 { let paramStrings: [String] = params.map({ (pair) -> String in return "\(pair.0)=\(pair.1)" }) let paramsString = paramStrings.joined(separator: "&") emailLink = "\(emailLink)?\(paramsString)" } return URL(string: emailLink) } func composeMail(emailStep: RSEmailStep) { if MFMailComposeViewController.canSendMail() { let composeVC = MFMailComposeViewController() composeVC.mailComposeDelegate = self // Configure the fields of the interface. composeVC.setToRecipients(emailStep.recipientAddreses) if let subject = emailStep.messageSubject { composeVC.setSubject(subject) } if let body = emailStep.messageBody { composeVC.setMessageBody(body, isHTML: emailStep.bodyIsHTML) } else { composeVC.setMessageBody("", isHTML: false) } // Present the view controller modally. composeVC.modalPresentationStyle = .fullScreen self.present(composeVC, animated: true, completion: nil) } else { if let url = self.generateMailLink(emailStep: emailStep), UIApplication.shared.canOpenURL(url) { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { (success) in if success { self.emailSent = true self.notifyDelegateAndMoveForward() } else { self.showErrorMessage(emailStep: emailStep) } }) } else { // Fallback on earlier versions let success = UIApplication.shared.openURL(url) if success { self.emailSent = true self.notifyDelegateAndMoveForward() } else { self.showErrorMessage(emailStep: emailStep) } } } else { self.showErrorMessage(emailStep: emailStep) } } } override open func continueTapped(_ sender: Any) { if self.emailSent { self.notifyDelegateAndMoveForward() } else if let emailStep = self.step as? RSEmailStep { //load email self.composeMail(emailStep: emailStep) } } open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if result != .cancelled && result != .failed { self.emailSent = true self.notifyDelegateAndMoveForward() } else { controller.dismiss(animated: true, completion: nil) } } }
apache-2.0
RobotsAndPencils/SwiftCharts
Examples/Examples/GroupedAndStackedBarsExample.swift
1
8758
// // GroupedAndStackedBarsExample.swift // Examples // // Created by ischuetz on 20/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class GroupedAndStackedBarsExample: UIViewController { private var chart: Chart? private let dirSelectorHeight: CGFloat = 50 private func barsChart(horizontal horizontal: Bool) -> Chart { let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let groupsData: [(title: String, bars: [(start: Double, quantities: [Double])])] = [ ("A", [ (0, [-20, -5, -10] ), (0, [10, 20, 30] ), (0, [30, 14, 5] ) ]), ("B", [ (0, [-10, -15, -5] ), (0, [30, 25, 40] ), (0, [25, 40, 10] ) ]), ("C", [ (0, [-15, -30, -10] ), (0, [-10, -10, -5] ), (0, [15, 30, 10] ) ]), ("D", [ (0, [-20, -10, -10] ), (0, [30, 15, 27] ), (0, [8, 10, 25] ) ]) ] let frameColors = [UIColor.redColor().colorWithAlphaComponent(0.6), UIColor.blueColor().colorWithAlphaComponent(0.6), UIColor.greenColor().colorWithAlphaComponent(0.6)] let groups: [ChartPointsBarGroup<ChartStackedBarModel>] = groupsData.enumerate().map {index, entry in let constant = ChartAxisValueDouble(Double(index)) let bars: [ChartStackedBarModel] = entry.bars.enumerate().map {index, bars in let items = bars.quantities.enumerate().map {index, quantity in ChartStackedBarItemModel(quantity, frameColors[index]) } return ChartStackedBarModel(constant: constant, start: ChartAxisValueDouble(bars.start), items: items) } return ChartPointsBarGroup(constant: constant, bars: bars) } let (axisValues1, axisValues2): ([ChartAxisValue], [ChartAxisValue]) = ( (-60).stride(through: 100, by: 20).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)}, [ChartAxisValueString(order: -1)] + groupsData.enumerate().map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} + [ChartAxisValueString(order: groupsData.count)] ) let (xValues, yValues) = horizontal ? (axisValues1, axisValues2) : (axisValues2, axisValues1) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let frame = ExamplesDefaults.chartFrame(self.view.bounds) let chartFrame = self.chart?.frame ?? CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height - self.dirSelectorHeight) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let groupsLayer = ChartGroupedStackedBarsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, groups: groups, horizontal: horizontal, barSpacing: 2, groupSpacing: 30, animDuration: 0.5) let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: horizontal ? .X : .Y, settings: settings) let dummyZeroChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0)) let zeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let width: CGFloat = 2 let viewFrame: CGRect = { if horizontal { return CGRectMake(chartPointModel.screenLoc.x - width / 2, innerFrame.origin.y, width, innerFrame.size.height) } else { return CGRectMake(innerFrame.origin.x, chartPointModel.screenLoc.y - width / 2, innerFrame.size.width, width) } }() let v = UIView(frame: viewFrame) v.backgroundColor = UIColor.blackColor() return v }) return Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, groupsLayer, zeroGuidelineLayer ] ) } private func showChart(horizontal horizontal: Bool) { self.chart?.clearView() let chart = self.barsChart(horizontal: horizontal) self.view.addSubview(chart.view) self.chart = chart } override func viewDidLoad() { self.showChart(horizontal: false) if let chart = self.chart { let dirSelector = DirSelector(frame: CGRectMake(0, chart.frame.origin.y + chart.frame.size.height, self.view.frame.size.width, self.dirSelectorHeight), controller: self) self.view.addSubview(dirSelector) } } class DirSelector: UIView { let horizontal: UIButton let vertical: UIButton weak var controller: GroupedAndStackedBarsExample? private let buttonDirs: [UIButton : Bool] init(frame: CGRect, controller: GroupedAndStackedBarsExample) { self.controller = controller self.horizontal = UIButton() self.horizontal.setTitle("Horizontal", forState: .Normal) self.vertical = UIButton() self.vertical.setTitle("Vertical", forState: .Normal) self.buttonDirs = [self.horizontal : true, self.vertical : false] super.init(frame: frame) self.addSubview(self.horizontal) self.addSubview(self.vertical) for button in [self.horizontal, self.vertical] { button.titleLabel?.font = ExamplesDefaults.fontWithSize(14) button.setTitleColor(UIColor.blueColor(), forState: .Normal) button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside) } } func buttonTapped(sender: UIButton) { let horizontal = sender == self.horizontal ? true : false controller?.showChart(horizontal: horizontal) } override func didMoveToSuperview() { let views = [self.horizontal, self.vertical] for v in views { v.translatesAutoresizingMaskIntoConstraints = false } let namedViews = views.enumerate().map{index, view in ("v\(index)", view) } let viewsDict = namedViews.reduce(Dictionary<String, UIView>()) {(var u, tuple) in u[tuple.0] = tuple.1 return u } let buttonsSpace: CGFloat = Env.iPad ? 20 : 10 let hConstraintStr = namedViews.reduce("H:|") {str, tuple in "\(str)-(\(buttonsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraintsWithVisualFormat("V:|[\($0.0)]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)} self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
apache-2.0
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/MailingAddressConnection.swift
1
5274
// // MailingAddressConnection.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// An auto-generated type for paginating through multiple MailingAddresses. open class MailingAddressConnectionQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = MailingAddressConnection /// A list of edges. @discardableResult open func edges(alias: String? = nil, _ subfields: (MailingAddressEdgeQuery) -> Void) -> MailingAddressConnectionQuery { let subquery = MailingAddressEdgeQuery() subfields(subquery) addField(field: "edges", aliasSuffix: alias, subfields: subquery) return self } /// A list of the nodes contained in MailingAddressEdge. @discardableResult open func nodes(alias: String? = nil, _ subfields: (MailingAddressQuery) -> Void) -> MailingAddressConnectionQuery { let subquery = MailingAddressQuery() subfields(subquery) addField(field: "nodes", aliasSuffix: alias, subfields: subquery) return self } /// Information to aid in pagination. @discardableResult open func pageInfo(alias: String? = nil, _ subfields: (PageInfoQuery) -> Void) -> MailingAddressConnectionQuery { let subquery = PageInfoQuery() subfields(subquery) addField(field: "pageInfo", aliasSuffix: alias, subfields: subquery) return self } } /// An auto-generated type for paginating through multiple MailingAddresses. open class MailingAddressConnection: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = MailingAddressConnectionQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "edges": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue) } return try value.map { return try MailingAddressEdge(fields: $0) } case "nodes": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue) } return try value.map { return try MailingAddress(fields: $0) } case "pageInfo": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue) } return try PageInfo(fields: value) default: throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue) } } /// A list of edges. open var edges: [Storefront.MailingAddressEdge] { return internalGetEdges() } func internalGetEdges(alias: String? = nil) -> [Storefront.MailingAddressEdge] { return field(field: "edges", aliasSuffix: alias) as! [Storefront.MailingAddressEdge] } /// A list of the nodes contained in MailingAddressEdge. open var nodes: [Storefront.MailingAddress] { return internalGetNodes() } func internalGetNodes(alias: String? = nil) -> [Storefront.MailingAddress] { return field(field: "nodes", aliasSuffix: alias) as! [Storefront.MailingAddress] } /// Information to aid in pagination. open var pageInfo: Storefront.PageInfo { return internalGetPageInfo() } func internalGetPageInfo(alias: String? = nil) -> Storefront.PageInfo { return field(field: "pageInfo", aliasSuffix: alias) as! Storefront.PageInfo } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "edges": internalGetEdges().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "nodes": internalGetNodes().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "pageInfo": response.append(internalGetPageInfo()) response.append(contentsOf: internalGetPageInfo().childResponseObjectMap()) default: break } } return response } } }
mit
MadAppGang/refresher
PullToRefreshDemo/BeatAnimator.swift
1
4919
// // BeatAnimator.swift // // Copyright (c) 2014 Josip Cavar // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Refresher import QuartzCore class BeatAnimator: UIView, PullToRefreshViewDelegate { enum Layout { case Top, Bottom } private let layerLoader = CAShapeLayer() private let layerSeparator = CAShapeLayer() var layout:Layout = .Bottom { didSet { self.setNeedsLayout() } } override init(frame: CGRect) { super.init(frame: frame) layerLoader.lineWidth = 4 layerLoader.strokeColor = UIColor(red: 0.13, green: 0.79, blue: 0.31, alpha: 1).CGColor layerLoader.strokeEnd = 0 layerSeparator.lineWidth = 1 layerSeparator.strokeColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1).CGColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pullToRefresh(view: PullToRefreshView, progressDidChange progress: CGFloat) { layerLoader.strokeEnd = progress } func pullToRefresh(view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) { } func pullToRefreshAnimationDidEnd(view: PullToRefreshView) { layerLoader.removeAllAnimations() } func pullToRefreshAnimationDidStart(view: PullToRefreshView) { addAnimations() } func addAnimations() { let pathAnimationEnd = CABasicAnimation(keyPath: "strokeEnd") pathAnimationEnd.duration = 0.5 pathAnimationEnd.repeatCount = 100 pathAnimationEnd.autoreverses = true pathAnimationEnd.fromValue = 1 pathAnimationEnd.toValue = 0.8 layerLoader.addAnimation(pathAnimationEnd, forKey: "strokeEndAnimation") let pathAnimationStart = CABasicAnimation(keyPath: "strokeStart") pathAnimationStart.duration = 0.5 pathAnimationStart.repeatCount = 100 pathAnimationStart.autoreverses = true pathAnimationStart.fromValue = 0 pathAnimationStart.toValue = 0.2 layerLoader.addAnimation(pathAnimationStart, forKey: "strokeStartAnimation") } override func layoutSubviews() { super.layoutSubviews() if let superview = superview { if layerLoader.superlayer == nil { superview.layer.addSublayer(layerLoader) } if layerSeparator.superlayer == nil { superview.layer.addSublayer(layerSeparator) } let verticalPosition = layout == .Bottom ? superview.frame.height - 3 : 2 let bezierPathLoader = UIBezierPath() bezierPathLoader.moveToPoint(CGPointMake(0, verticalPosition)) bezierPathLoader.addLineToPoint(CGPoint(x: superview.frame.width, y: verticalPosition)) let verticalPositionSeparator = layout == .Bottom ? superview.frame.height - 1 : 0 let bezierPathSeparator = UIBezierPath() bezierPathSeparator.moveToPoint(CGPointMake(0, verticalPositionSeparator)) bezierPathSeparator.addLineToPoint(CGPoint(x: superview.frame.width, y: verticalPositionSeparator)) layerLoader.path = bezierPathLoader.CGPath layerSeparator.path = bezierPathSeparator.CGPath } } } extension BeatAnimator: LoadMoreViewDelegate { func loadMoreAnimationDidStart(view: LoadMoreView) { addAnimations() } func loadMoreAnimationDidEnd(view: LoadMoreView) { layerLoader.removeAllAnimations() } func loadMore(view: LoadMoreView, progressDidChange progress: CGFloat) { layerLoader.strokeEnd = progress } func loadMore(view: LoadMoreView, stateDidChange state: LoadMoreViewState) { } }
mit
thefuntasty/TFBubbleItUp
Sources/TFBubbleItUp/TFBubbleItUpValidation.swift
1
1227
import Foundation public typealias Validation = (String) -> Bool precedencegroup DefaultPrecedence { associativity: left } infix operator |>> : DefaultPrecedence public func |>> (v1: @escaping Validation, v2: @escaping Validation) -> Validation { { text in v1(text) && v2(text) } } public class TFBubbleItUpValidation { /// Validates if text is not empty (empty string is not valid) public class func testEmptiness() -> Validation { { text in text != "" } } /// Validates if text is an email address public class func testEmailAddress() -> Validation { { text in let emailRegex = "^[+\\w\\.\\-']+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,})+$" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex) return emailTest.evaluate(with: text) } } public class func combine(v1: @escaping Validation, v2: @escaping Validation) -> Validation { { text in v1(text) && v2(text) } } class func isValid(text: String?) -> Bool { if let t = text, let validation = TFBubbleItUpViewConfiguration.itemValidation { return validation(t) } else { return true } } }
mit
chetca/Android_to_iOs
memuDemo/VideoSC/VideoAlbumCell.swift
1
627
// // VideoLectionCell.swift // memuDemo // // Created by Dugar Badagarov on 29/08/2017. // Copyright © 2017 Parth Changela. All rights reserved. // import UIKit class VideoAlbumCell: UITableViewCell { @IBOutlet var img: UIImageView! @IBOutlet var titleLbl: UILabel! @IBOutlet var spinner: UIActivityIndicatorView! 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 } }
mit
mbuchetics/DataSource
Example/ViewControllers/Examples/RandomPersonsViewController.swift
1
3407
// // RandomPersonsViewController.swift // DataSource // // Created by Matthias Buchetics on 27/02/2017. // Copyright © 2017 aaa - all about apps GmbH. All rights reserved. // import UIKit import DataSource // MARK: - View Controller class RandomPersonsViewController: UITableViewController { lazy var dataSource: DataSource = { DataSource( cellDescriptors: [ PersonCell.descriptor .didSelect { (item, indexPath) in print("\(item.firstName) \(item.lastName) selected") return .deselect } ], sectionDescriptors: [ SectionDescriptor<String>() .header { (title, _) in .title(title) } ]) }() override func viewDidLoad() { super.viewDidLoad() dataSource.fallbackDelegate = self tableView.dataSource = dataSource tableView.delegate = dataSource dataSource.sections = randomData() dataSource.reloadData(tableView, animated: false) } private func randomData() -> [SectionType] { let count = Int.random(5, 15) let persons = (0 ..< count).map { _ in Person.random() }.sorted() let letters = Set(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]) let firstGroup = persons.filter { $0.lastNameStartsWith(letters: letters) } let secondGroup = persons.filter { !$0.lastNameStartsWith(letters: letters) } return [ Section("A - L", items: firstGroup), Section("M - Z", items: secondGroup), ] } @IBAction func refresh(_ sender: Any) { dataSource.sections = randomData() dataSource.reloadData(tableView, animated: true) } } // MARK: - Scroll view delegate extension RandomPersonsViewController { override func scrollViewDidScroll(_ scrollView: UIScrollView) { print("scrolled: \(scrollView.contentOffset.y)") } } // MARK: - Person struct Person { let firstName: String let lastName: String func lastNameStartsWith(letters: Set<String>) -> Bool { let letter = String(lastName[lastName.startIndex]) return letters.contains(letter) } var fullName: String { return "\(firstName) \(lastName)" } static func random() -> Person { return Person( firstName: Randoms.randomFirstName(), lastName: Randoms.randomLastName() ) } } extension Person: Equatable { static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.fullName == rhs.fullName } } extension Person: Comparable { static func <(lhs: Person, rhs: Person) -> Bool { if lhs.lastName != rhs.lastName { return lhs.lastName < rhs.lastName } else if lhs.firstName != rhs.firstName { return lhs.firstName < rhs.firstName } else { return false } } } extension Person: Diffable { public var diffIdentifier: String { return fullName } } extension Person: CustomStringConvertible { var description: String { return fullName } }
mit
ihorvitruk/Github-Client
Github Client/Github Client/presentation/ui/vc/BaseVC.swift
1
784
// // BaseViewController.swift // Github Client // // Created by Ihor Vitruk on 1/14/17. // Copyright © 2017 Ihor Vitruk. All rights reserved. // import UIKit class BaseVC<PRESENTER: Presenter>: UIViewController, View { var presenter: PRESENTER? override func viewDidLoad() { super.viewDidLoad() presenter = initPresenter() initUi() presenter?.attachView(view: self) } deinit { presenter?.detachView() presenter = nil } func showMessage(message: String) { } func showProgress() { } func hideProgress() { } func initPresenter() -> PRESENTER? { return nil } func initUi() { } }
apache-2.0
stephentyrone/swift
validation-test/Reflection/reflect_empty_struct_compat.swift
3
3178
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest -I %S/Inputs/EmptyStruct/ %s -o %t/reflect_empty_struct // RUN: %target-codesign %t/reflect_empty_struct // RUN: %target-run %target-swift-reflection-test %t/reflect_empty_struct | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --dump-input fail // REQUIRES: objc_interop // REQUIRES: executable_test // REQUIRES: OS=macosx // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest import EmptyStruct @_alignment(1) struct EmptyStruct { } class Class { var a = EmptyStruct() var b: Any = EmptyStruct() var c = EmptyStructC() var d: Any = EmptyStructC() } var obj = Class() reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_empty_struct.Class) // CHECK-64: Type info: // CHECK-64: (class_instance size=80 alignment=8 stride=80 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=a offset=16 // CHECK-64: (struct size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-64: (field name=b offset=16 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647 bitwise_takable=1)))) // CHECK-64: (field name=c offset=48 // CHECK-64: (struct size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-64: (field name=d offset=48 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647 bitwise_takable=1))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_empty_struct.Class) // CHECK-32: Type info: // CHECK-32: (class_instance size=40 alignment=4 stride=40 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=a offset=8 // CHECK-32: (struct size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-32: (field name=b offset=8 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32: (field name=c offset=24 // CHECK-32: (struct size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-32: (field name=d offset=24 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
MarceloOscarJose/DynamicSkeleton
Pod/Classes/Gradient/GradientDirection.swift
1
798
// // GradientDirection.swift // Pods // // Created by Marcelo Oscar José on 7/29/17. // // import Foundation enum GradientProperty { case startPoint case endPoint } public enum GradientDirection { case right case left func transition(for point: GradientProperty) -> GradientTransition { switch (self, point) { case (.right, .startPoint): return GradientPoint(x: .negativeOne) --> GradientPoint(x: .one) case (.right, .endPoint): return GradientPoint(x: .zero) --> GradientPoint(x: .two) case (.left, .startPoint): return GradientPoint(x: .one) --> GradientPoint(x: .negativeOne) case (.left, .endPoint): return GradientPoint(x: .two) --> GradientPoint(x: .zero) } } }
mit
feliperuzg/CleanExample
CleanExampleTests/Core/Network/NetworkConfiguration/NetworkConfigurationSpec.swift
1
801
// // NetworkConfigurationSpec.swift // CleanExampleTests // // Created by Felipe Ruz on 13-12-17. // Copyright © 2017 Felipe Ruz. All rights reserved. // import XCTest @testable import CleanExample class NetworkConfigurationSpec: XCTestCase { var sut: NetworkConfiguration! override func tearDown() { super.tearDown() sut = nil } func testNetworkConfigiurationReturnsURL() { sut = NetworkConfiguration() let url = sut.authenticationURL(for: .login) XCTAssertNotNil(url) } func testNetworkConfigurationReturnsNil() { sut = NetworkConfiguration() sut.networkConfigurationList = "none" sut.prepare() let url = sut.authenticationURL(for: .login) XCTAssertNil(url) } }
mit
glorybird/KeepReading2
kr/kr/ui/CupView.swift
1
1686
// // CupView.swift // kr // // Created by FanFamily on 16/1/31. // Copyright © 2016年 glorybird. All rights reserved. // import UIKit class CupView: UIView { var waveView: SCSiriWaveformView! var level:CGFloat = 0.1 var dampTimer:NSTimer? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) waveView = SCSiriWaveformView() waveView.backgroundColor = UIColor.whiteColor() waveView.waveColor = UIColor.orangeColor() waveView.primaryWaveLineWidth = 2.0 waveView.secondaryWaveLineWidth = 0.0 waveView.idleAmplitude = 0.0 waveView.density = 1.0 addSubview(waveView) waveView.snp_makeConstraints { (make) -> Void in make.margins.equalTo(self).offset(0) } let displaylink = CADisplayLink(target: self, selector:Selector.init("updateWave")) displaylink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) } func updateWave() { if level >= 0 { waveView.updateWithLevel(level) } } func damping() { level -= 0.01 if level < 0 { if dampTimer != nil { dampTimer!.invalidate() dampTimer = nil } } } func changeProgress(progress:CGFloat) { waveView.stage = progress level = 0.1 // 自然衰减 if dampTimer != nil { dampTimer!.invalidate() } dampTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector.init("damping"), userInfo: nil, repeats: true) } }
apache-2.0
googleprojectzero/fuzzilli
Sources/Fuzzilli/Mutators/ProbingMutator.swift
1
20439
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 /// This mutator inserts probes into a program to determine how existing variables are used. /// /// Its main purpose is to determine which (non-existent) properties are accessed on existing objects and to then add these properties (or install accessors for them). /// /// This mutator achieves this by doing the following: /// 1. It instruments the given program by inserting special Probe operations which turn an existing variable into a "probe" /// that records accesses to non-existent properties on the original value. In JavaScript, probing is implemented by /// replacing an object's prototype with a Proxy around the original prototype. This Proxy will then see all accesses to /// non-existent properties. Alternatively, the probed object itself could be replaced with a Proxy, however that will /// cause various builtin methods to fail because they for example expect |this| to have a specific type. /// 2. It executes the instrumented program. The program collects the property names of non-existent properties that were accessed /// on a probe and reports this information to Fuzzilli through the FUZZOUT channel at the end of the program's execution. /// 3. The mutator processes the output of step 2 and randomly selects properties to install (either as plain value or /// accessor). It then converts the Probe operations to an appropriate FuzzIL operation (e.g. StoreProperty). /// /// A large bit of the logic of this mutator is located in the lifter code that implements Probe operations /// in the target language. For JavaScript, that logic can be found in JavaScriptProbeLifting.swift. public class ProbingMutator: Mutator { private let logger = Logger(withLabel: "ProbingMutator") // If true, this mutator will log detailed statistics. // Enable verbose mode by default while this feature is still under development. private let verbose = true // Statistics about how often we've installed a particular property. Printed in regular intervals if verbose mode is active, then reset. private var installedPropertiesForGetAccess = [Property: Int]() private var installedPropertiesForSetAccess = [Property: Int]() // Counts the total number of installed properties installed. Printed in regular intervals if verbose mode is active, then reset. private var installedPropertyCounter = 0 // The number of programs produced so far, mostly used for the verbose mode. private var producedSamples = 0 // Normally, we will not overwrite properties that already exist on the prototype (e.g. Array.prototype.slice). This list contains the exceptions to this rule. private let propertiesOnPrototypeToOverwrite = ["valueOf", "toString", "constructor"] // The different outcomes of probing. Used for statistics in verbose mode. private enum ProbingOutcome: String, CaseIterable { case success = "Success" case cannotInstrument = "Cannot instrument input" case instrumentedProgramCrashed = "Instrumented program crashed" case instrumentedProgramFailed = "Instrumented program failed" case instrumentedProgramTimedOut = "Instrumented program timed out" case noActions = "No actions received" case unexpectedError = "Unexpected Error" } private var probingOutcomeCounts = [ProbingOutcome: Int]() public override init() { if verbose { for outcome in ProbingOutcome.allCases { probingOutcomeCounts[outcome] = 0 } } } override func mutate(_ program: Program, using b: ProgramBuilder, for fuzzer: Fuzzer) -> Program? { guard let instrumentedProgram = instrument(program, for: fuzzer) else { // This means there are no variables that could be probed. return failure(.cannotInstrument) } // Execute the instrumented program (with a higher timeout) and collect the output. let execution = fuzzer.execute(instrumentedProgram, withTimeout: fuzzer.config.timeout * 2) guard execution.outcome == .succeeded else { if case .crashed(let signal) = execution.outcome { // This is unexpected but we should still be able to handle it. fuzzer.processCrash(instrumentedProgram, withSignal: signal, withStderr: execution.stderr, withStdout: execution.stdout, origin: .local) return failure(.instrumentedProgramCrashed) } else if case .failed(_) = execution.outcome { // This is generally unexpected as the JavaScript code attempts to be as transparent as possible and to not alter the behavior of the program. // However, there are some rare edge cases where this isn't possible, for example when the JavaScript code observes the modified prototype. return failure(.instrumentedProgramFailed) } assert(execution.outcome == .timedOut) return failure(.instrumentedProgramTimedOut) } let output = execution.fuzzout // Parse the output: look for either "PROBING_ERROR" or "PROBING_RESULTS" and process the content. var results = [String: Result]() for line in output.split(whereSeparator: \.isNewline) { guard line.starts(with: "PROBING") else { continue } let errorMarker = "PROBING_ERROR: " let resultsMarker = "PROBING_RESULTS: " if line.hasPrefix(errorMarker) { let ignoredErrors = ["maximum call stack size exceeded", "out of memory", "too much recursion"] for error in ignoredErrors { if line.lowercased().contains(error) { return failure(.instrumentedProgramFailed) } } // Everything else is unexpected and probably means there's a bug in the JavaScript implementation, so treat that as an error. logger.error("\n" + fuzzer.lifter.lift(instrumentedProgram, withOptions: .includeLineNumbers)) logger.error("\nProbing failed: \(line.dropFirst(errorMarker.count))\n") //maybeLogFailingExecution(execution, of: instrumentedProgram, usingLifter: fuzzer.lifter, usingLogLevel: .error) // We could probably still continue in these cases, but since this is unexpected, it's probably better to stop here and treat this as an unexpected failure. return failure(.unexpectedError) } guard line.hasPrefix(resultsMarker) else { logger.error("Invalid probing result: \(line)") return failure(.unexpectedError) } let decoder = JSONDecoder() let payload = Data(line.dropFirst(resultsMarker.count).utf8) guard let decodedResults = try? decoder.decode([String: Result].self, from: payload) else { logger.error("Failed to decode JSON payload in \"\(line)\"") return failure(.unexpectedError) } results = decodedResults } guard !results.isEmpty else { return failure(.noActions) } // Now build the final program by parsing the results and replacing the Probe operations // with FuzzIL operations that install one of the non-existent properties (if any). b.adopting(from: instrumentedProgram) { for instr in instrumentedProgram.code { if let op = instr.op as? Probe { if let results = results[op.id] { let probedValue = b.adopt(instr.input(0)) b.trace("Probing value \(probedValue)") processProbeResults(results, on: probedValue, using: b) b.trace("Probing finished") } } else { b.adopt(instr) } } } producedSamples += 1 let N = 1000 if verbose && (producedSamples % N) == 0 { logger.info("Properties installed during the last \(N) successful runs:") var statsAsList = installedPropertiesForGetAccess.map({ (key: $0, count: $1, op: "get") }) statsAsList += installedPropertiesForSetAccess.map({ (key: $0, count: $1, op: "set") }) for (key, count, op) in statsAsList.sorted(by: { $0.count > $1.count }) { let type = isCallableProperty(key) ? "function" : "anything" logger.info(" \(count)x \(key.description) (access: \(op), type: \(type))") } logger.info(" Total number of properties installed: \(installedPropertyCounter)") installedPropertiesForGetAccess.removeAll() installedPropertiesForSetAccess.removeAll() installedPropertyCounter = 0 logger.info("Frequencies of probing outcomes:") let totalOutcomes = probingOutcomeCounts.values.reduce(0, +) for outcome in ProbingOutcome.allCases { let count = probingOutcomeCounts[outcome]! let frequency = (Double(count) / Double(totalOutcomes)) * 100.0 logger.info(" \(outcome.rawValue.rightPadded(toLength: 30)): \(String(format: "%.2f%%", frequency))") } } return success(b.finalize()) } private func processProbeResults(_ result: Result, on obj: Variable, using b: ProgramBuilder) { // Extract all candidates: properties that are accessed but not present (or explicitly marked as overwritable). let loadCandidates = result.loads.filter({ $0.value == .notFound || ($0.value == .found && propertiesOnPrototypeToOverwrite.contains($0.key)) }).map({ $0.key }) // For stores we only care about properties that don't exist anywhere on the prototype chain. let storeCandidates = result.stores.filter({ $0.value == .notFound }).map({ $0.key }) let candidates = Set(loadCandidates).union(storeCandidates) guard !candidates.isEmpty else { return } // Pick a random property from the candidates. let propertyName = chooseUniform(from: candidates) let propertyIsLoaded = result.loads.keys.contains(propertyName) let propertyIsStored = result.stores.keys.contains(propertyName) // Install the property, either as regular property or as a property accessor. let property = parsePropertyName(propertyName) if probability(0.8) { installRegularProperty(property, on: obj, using: b) } else { installPropertyAccessor(for: property, on: obj, using: b, shouldHaveGetter: propertyIsLoaded, shouldHaveSetter: propertyIsStored) } // Update our statistics. if verbose && propertyIsLoaded { installedPropertiesForGetAccess[property] = (installedPropertiesForGetAccess[property] ?? 0) + 1 } if verbose && propertyIsStored { installedPropertiesForSetAccess[property] = (installedPropertiesForSetAccess[property] ?? 0) + 1 } installedPropertyCounter += 1 } private func installRegularProperty(_ property: Property, on obj: Variable, using b: ProgramBuilder) { let value = selectValue(for: property, using: b) switch property { case .regular(let name): assert(name.rangeOfCharacter(from: .whitespacesAndNewlines) == nil) b.storeProperty(value, as: name, on: obj) case .element(let index): b.storeElement(value, at: index, of: obj) case .symbol(let desc): let Symbol = b.loadBuiltin("Symbol") let symbol = b.loadProperty(extractSymbolNameFromDescription(desc), of: Symbol) b.storeComputedProperty(value, as: symbol, on: obj) } } private func installPropertyAccessor(for property: Property, on obj: Variable, using b: ProgramBuilder, shouldHaveGetter: Bool, shouldHaveSetter: Bool) { assert(shouldHaveGetter || shouldHaveSetter) let installAsValue = probability(0.5) let installGetter = !installAsValue && (shouldHaveGetter || probability(0.5)) let installSetter = !installAsValue && (shouldHaveSetter || probability(0.5)) let config: ProgramBuilder.PropertyConfiguration if installAsValue { config = .value(selectValue(for: property, using: b)) } else if installGetter && installSetter { let getter = b.buildPlainFunction(with: .parameters(n: 0)) { _ in let value = selectValue(for: property, using: b) b.doReturn(value) } let setter = b.buildPlainFunction(with: .parameters(n: 1)) { _ in b.build(n: 1) } config = .getterSetter(getter, setter) } else if installGetter { let getter = b.buildPlainFunction(with: .parameters(n: 0)) { _ in let value = selectValue(for: property, using: b) b.doReturn(value) } config = .getter(getter) } else { assert(installSetter) let setter = b.buildPlainFunction(with: .parameters(n: 1)) { _ in b.build(n: 1) } config = .setter(setter) } switch property { case .regular(let name): assert(name.rangeOfCharacter(from: .whitespacesAndNewlines) == nil) b.configureProperty(name, of: obj, usingFlags: PropertyFlags.random(), as: config) case .element(let index): b.configureElement(index, of: obj, usingFlags: PropertyFlags.random(), as: config) case .symbol(let desc): let Symbol = b.loadBuiltin("Symbol") let symbol = b.loadProperty(extractSymbolNameFromDescription(desc), of: Symbol) b.configureComputedProperty(symbol, of: obj, usingFlags: PropertyFlags.random(), as: config) } } private func extractSymbolNameFromDescription(_ desc: String) -> String { // Well-known symbols are of the form "Symbol.toPrimitive". All other symbols should've been filtered out by the instrumented code. let wellKnownSymbolPrefix = "Symbol." guard desc.hasPrefix(wellKnownSymbolPrefix) else { logger.error("Received invalid symbol property from instrumented code: \(desc)") return desc } return String(desc.dropFirst(wellKnownSymbolPrefix.count)) } private func isCallableProperty(_ property: Property) -> Bool { let knownFunctionPropertyNames = ["valueOf", "toString", "constructor", "then", "get", "set"] let knownNonFunctionSymbolNames = ["Symbol.isConcatSpreadable", "Symbol.unscopables", "Symbol.toStringTag"] // Check if the property should be a function. switch property { case .regular(let name): return knownFunctionPropertyNames.contains(name) case .symbol(let desc): return !knownNonFunctionSymbolNames.contains(desc) case .element(_): return false } } private func selectValue(for property: Property, using b: ProgramBuilder) -> Variable { if isCallableProperty(property) { // Either create a new function or reuse an existing one let probabilityOfReusingExistingFunction = 2.0 / 3.0 if let f = b.randVar(ofConservativeType: .function()), probability(probabilityOfReusingExistingFunction) { return f } else { let f = b.buildPlainFunction(with: .parameters(n: Int.random(in: 0..<3))) { args in b.build(n: 2) // TODO maybe forbid generating any nested blocks here? b.doReturn(b.randVar()) } return f } } else { // Otherwise, just return a random variable. return b.randVar() } } private func parsePropertyName(_ propertyName: String) -> Property { // Anything that parses as an Int64 is an element index. if let index = Int64(propertyName) { return .element(index) } // Symbols will be encoded as "Symbol(symbolDescription)". let symbolPrefix = "Symbol(" let symbolSuffix = ")" if propertyName.hasPrefix(symbolPrefix) && propertyName.hasSuffix(symbolSuffix) { let desc = propertyName.dropFirst(symbolPrefix.count).dropLast(symbolSuffix.count) return .symbol(String(desc)) } // Everything else is a regular property name. return .regular(propertyName) } private func instrument(_ program: Program, for fuzzer: Fuzzer) -> Program? { // Determine candidates for probing: every variable that is used at least once as an input is a candidate. var usedVariables = VariableSet() for instr in program.code { usedVariables.formUnion(instr.inputs) } let candidates = Array(usedVariables) guard !candidates.isEmpty else { return nil } // Select variables to instrument from the candidates. let numVariablesToProbe = Int((Double(candidates.count) * 0.5).rounded(.up)) let variablesToProbe = VariableSet(candidates.shuffled().prefix(numVariablesToProbe)) var pendingVariablesToInstrument = [(v: Variable, depth: Int)]() var depth = 0 let b = fuzzer.makeBuilder() b.adopting(from: program) { for instr in program.code { b.adopt(instr) for v in instr.innerOutputs where variablesToProbe.contains(v) { b.probe(v, id: v.identifier) } for v in instr.outputs where variablesToProbe.contains(v) { // We only want to instrument outer outputs of block heads after the end of that block. // For example, a function definition should be turned into a probe not inside its body // but right after the function definition ends in the surrounding block. if instr.isBlockGroupStart { pendingVariablesToInstrument.append((v, depth)) } else { b.probe(v, id: v.identifier) } } if instr.isBlockGroupStart { depth += 1 } else if instr.isBlockGroupEnd { depth -= 1 while pendingVariablesToInstrument.last?.depth == depth { let (v, _) = pendingVariablesToInstrument.removeLast() b.probe(v, id: v.identifier) } } } } return b.finalize() } private func failure(_ outcome: ProbingOutcome) -> Program? { assert(outcome != .success) probingOutcomeCounts[outcome]! += 1 return nil } private func success(_ program: Program) -> Program { probingOutcomeCounts[.success]! += 1 return program } private enum Property: Hashable, CustomStringConvertible { case regular(String) case symbol(String) case element(Int64) var description: String { switch self { case .regular(let name): return name case .symbol(let desc): return desc case .element(let index): return String(index) } } } private struct Result: Decodable { enum outcome: Int, Decodable { case notFound = 0 case found = 1 } let loads: [String: outcome] let stores: [String: outcome] } }
apache-2.0
brunopinheiro/sabadinho
Sabadinho/Interactors/CalendarInteractor.swift
1
3632
// // CalendarInteractor.swift // Sabadinho // // Created by Bruno Pinheiro on 26/01/18. // Copyright © 2018 Bruno Pinheiro. All rights reserved. // import Foundation import RxSwift protocol CalendarInteractorProtocol { var today: Single<Day> { get } func dayByAdding(months amount: Int, to day: Day) -> Single<Day> func daysWithinSameMonth(as date: Date) -> Single<[Day]> func daysWithinSameWeekBefore(_ date: Date) -> Single<[Day]> func daysWithinSameWeekAfter(_ date: Date) -> Single<[Day]> func week(of day: Day) -> Int? } class CalendarInteractor: CalendarInteractorProtocol { private let calendarRepository: CalendarRepositoryProtocol init(calendarRepository: CalendarRepositoryProtocol = CalendarRepository()) { self.calendarRepository = calendarRepository } var today: Single<Day> { return calendarRepository.today().map { Day(date: $0, timeEntries: []) } } func dayByAdding(months amount: Int, to day: Day) -> Single<Day> { return calendarRepository .dateByAdding(months: amount, to: day.date) .map { Day(date: $0, timeEntries: []) } } func daysWithinSameMonth(as date: Date) -> Single<[Day]> { return calendarRepository.datesWithinSameMonth(as: date).map { $0.map { Day(date: $0, timeEntries: []) } } } func daysWithinSameWeekBefore(_ date: Date) -> Single<[Day]> { return belongsToFirstWeek(date) .flatMap { $0 ? self.calendarRepository.dateByAdding(months: -1, to: date).asObservable() : Observable<Date>.empty() } .flatMap(self.calendarRepository.datesWithinSameMonth) .map { self.completeWeek(from: date, withPreviousDates: $0) } .map(days) .asObservable() .ifEmpty(default: []) .asSingle() } private func belongsToFirstWeek(_ date: Date) -> Observable<Bool> { return .just(week(from: date) == 1) } private func week(from date: Date) -> Int { guard let weekOfMonth = calendarRepository.calendar.dateComponents([.weekOfMonth], from: date).weekOfMonth else { return -1 } return weekOfMonth } private func completeWeek(from date: Date, withPreviousDates dates: [Date]) -> [Date] { guard let weekday = calendarRepository.calendar.dateComponents([.weekday], from: date).weekday else { return [] } return Array(dates.suffix(weekday - 1)) } private func days(from dates: [Date]) -> [Day] { return dates.map { Day(date: $0, timeEntries: [Double]()) } } func daysWithinSameWeekAfter(_ date: Date) -> Single<[Day]> { return belongsToLastWeek(date) .flatMap { $0 ? self.calendarRepository.dateByAdding(months: 1, to: date).asObservable() : Observable<Date>.empty() } .flatMap(self.calendarRepository.datesWithinSameMonth) .map { self.completeWeek(from: date, withFollowingDates: $0) } .map(days) .asObservable() .ifEmpty(default: []) .asSingle() } private func belongsToLastWeek(_ date: Date) -> Observable<Bool> { return Observable<Date> .just(date) .flatMap(calendarRepository.datesWithinSameMonth) .map { self.week(from: date) == self.countWeeks(from: $0) } } private func countWeeks(from dates: [Date]) -> Int { let weeks = dates.map { self.week(from: $0) } return weeks.max() ?? 0 } private func completeWeek(from date: Date, withFollowingDates dates: [Date]) -> [Date] { guard let weekday = calendarRepository.calendar.dateComponents([.weekday], from: date).weekday else { return [] } return Array(dates.prefix(7 - weekday)) } func week(of day: Day) -> Int? { return calendarRepository.week(of: day.date) } }
mit
artkirillov/DesignPatterns
Composite.playground/Contents.swift
1
1543
import Foundation protocol Component { var id: UInt32 { get } func description() -> String } final class WashingMachine: Component { var id = arc4random_uniform(100) func description() -> String { return "WashingMachine-\(id)" } } final class Computer: Component { var id = arc4random_uniform(100) func description() -> String { return "Computer-\(id)" } } final class Speakers: Component { var id = arc4random_uniform(100) func description() -> String { return "Speakers-\(id)" } } final class Composite: Component { private var components: [Component] = [] func add(component: Component) { components.append(component) } func remove(component: Component) { if let index = components.index(where: { $0.id == component.id }) { components.remove(at: index) } } var id = arc4random_uniform(100) func description() -> String { return components.reduce("", {"\($0)\($1.description()) "}) } } let computer = Computer() let smallBox = Composite() let mediumBox = Composite() let bigBox = Composite() smallBox.add(component: WashingMachine()) mediumBox.add(component: Computer()) mediumBox.add(component: Speakers()) bigBox.add(component: smallBox) bigBox.add(component: mediumBox) bigBox.add(component: WashingMachine()) print(computer.description()) print(smallBox.description()) print(mediumBox.description()) print(bigBox.description())
mit
my-mail-ru/swiftperl
Sources/Perl/UnsafeCV.swift
1
3553
import CPerl public typealias UnsafeCvPointer = UnsafeMutablePointer<CV> typealias CvBody = (UnsafeXSubStack) throws -> Void typealias UnsafeCvBodyPointer = UnsafeMutablePointer<CvBody> extension CV { fileprivate var bodyPointer: UnsafeCvBodyPointer { mutating get { return CvXSUBANY(&self).pointee.any_ptr.assumingMemoryBound(to: CvBody.self) } mutating set { CvXSUBANY(&self).pointee.any_ptr = UnsafeMutableRawPointer(newValue) } } } struct UnsafeCvContext { let cv: UnsafeCvPointer let perl: PerlInterpreter private static var mgvtbl = MGVTBL( svt_get: nil, svt_set: nil, svt_len: nil, svt_clear: nil, svt_free: { (perl, sv, magic) in let bodyPointer = UnsafeMutableRawPointer(sv!).assumingMemoryBound(to: CV.self).pointee.bodyPointer bodyPointer.deinitialize(count: 1) bodyPointer.deallocate() return 0 }, svt_copy: nil, svt_dup: nil, svt_local: nil ) static func new(name: String? = nil, file: StaticString = #file, body: @escaping CvBody, perl: PerlInterpreter) -> UnsafeCvContext { func newXS(_ name: UnsafePointer<CChar>?) -> UnsafeCvPointer { return perl.pointee.newXS_flags(name, cvResolver, file.description, nil, UInt32(XS_DYNAMIC_FILENAME)) } let cv = name?.withCString(newXS) ?? newXS(nil) cv.withMemoryRebound(to: SV.self, capacity: 1) { _ = perl.pointee.sv_magicext($0, nil, PERL_MAGIC_ext, &mgvtbl, nil, 0) } let bodyPointer = UnsafeCvBodyPointer.allocate(capacity: 1) bodyPointer.initialize(to: body) cv.pointee.bodyPointer = bodyPointer return UnsafeCvContext(cv: cv, perl: perl) } var name: String? { guard let gv = perl.pointee.CvGV(cv) else { return nil } return String(cString: GvNAME(gv)) } var fullname: String? { guard let name = name else { return nil } guard let gv = perl.pointee.CvGV(cv), let stash = GvSTASH(gv), let hvn = HvNAME(stash) else { return name } return "\(String(cString: hvn))::\(name)" } var file: String? { return CvFILE(cv).map { String(cString: $0) } } } extension UnsafeCvContext { init(dereference svc: UnsafeSvContext) throws { guard let rvc = svc.referent, rvc.type == SVt_PVCV else { throw PerlError.unexpectedValueType(fromUnsafeSvContext(inc: svc), want: PerlSub.self) } self.init(rebind: rvc) } init(rebind svc: UnsafeSvContext) { let cv = UnsafeMutableRawPointer(svc.sv).bindMemory(to: CV.self, capacity: 1) self.init(cv: cv, perl: svc.perl) } } let PERL_MAGIC_ext = Int32(UnicodeScalar("~").value) // mg_vtable.h private func cvResolver(perl: PerlInterpreter.Pointer, cv: UnsafeCvPointer) -> Void { let perl = PerlInterpreter(perl) let errsv: UnsafeSvPointer? do { let stack = UnsafeXSubStack(perl: perl) try cv.pointee.bodyPointer.pointee(stack) errsv = nil } catch PerlError.died(let scalar) { errsv = scalar.withUnsafeSvContext { UnsafeSvContext.new(copy: $0).mortal() } } catch let error as PerlScalarConvertible { let usv = error._toUnsafeSvPointer(perl: perl) errsv = perl.pointee.sv_2mortal(usv) } catch { errsv = "\(error)".withCString { error in let name = UnsafeCvContext(cv: cv, perl: perl).fullname ?? "__ANON__" return name.withCString { name in withVaList([name, error]) { perl.pointee.vmess("Exception in %s: %s", unsafeBitCast($0, to: UnsafeMutablePointer.self)) } } } } if let e = errsv { perl.pointee.croak_sv(e) // croak_sv() function never returns. It unwinds stack instead. // No memory managment SIL operations should exist after it. // Check it using --emit-sil if modification of this function required. } }
mit
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Leica/LeicaDLux4.swift
3
487
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Leica { public struct DLux4: CameraModel { public init() {} public let name = "Leica D-Lux 4" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Leica.self } } public typealias LeicaDLux4 = Cameras.Manufacturers.Leica.DLux4
mit
Crisfole/SwiftWeather
SwiftWeather/WeatherViewController.swift
2
1379
// // WeatherViewController.swift // SwiftWeather // // Created by Jake Lin on 8/18/15. // Copyright © 2015 Jake Lin. All rights reserved. // import UIKit class WeatherViewController: UIViewController { @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var iconLabel: UILabel! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet var forecastViews: [ForecastView]! override func viewDidLoad() { super.viewDidLoad() viewModel = WeatherViewModel() viewModel?.startLocationService() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: ViewModel var viewModel: WeatherViewModel? { didSet { viewModel?.location.observe { [unowned self] in self.locationLabel.text = $0 } viewModel?.iconText.observe { [unowned self] in self.iconLabel.text = $0 } viewModel?.temperature.observe { [unowned self] in self.temperatureLabel.text = $0 } viewModel?.forecasts.observe { [unowned self] (let forecastViewModels) in if forecastViewModels.count >= 4 { for (index, forecastView) in self.forecastViews.enumerate() { forecastView.loadViewModel(forecastViewModels[index]) } } } } } }
mit
mnespor/transit-swift
ExampleApp-iOS/ViewController.swift
1
461
// // ViewController.swift // ExampleApp-iOS // // Created by Matthew Nespor on 9/16/14. // // 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
SebastienVProject/openjarvis-ios
openjarvis/ViewController.swift
1
10021
// // ViewController.swift // openjarvis // // Created by utilisateur on 04/06/2017. // Copyright © 2017 SVInfo. All rights reserved. // import UIKit import Speech import SwiftyPlistManager class ViewController: UIViewController, SFSpeechRecognizerDelegate { static var urljarvis: String! static var portjarvis: String! static var audioServeur: Bool! static var audioApplication: Bool! static var fontSize: Int! static var fontSizeJarvis: Int! static var fontStyle: String! static var fontStyleJarvis: String! static var keyAPIJarvis: String? static var gitAPIKey: String! static var heightContainer: Double! @IBOutlet weak var imageJarvis: UIImageView! @IBOutlet var containerView: UIView! @IBOutlet weak var microphoneButton: UIButton! @IBOutlet weak var scrollVue: UIScrollView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var MessageVue: UIView! @IBOutlet weak var labelMenuHelp: UIBarButtonItem! @IBOutlet weak var labelMenuParameter: UIBarButtonItem! var HandleDeleteAllBubble: ((UIAlertAction?) -> Void)! let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: NSLocalizedString("codeLangue", comment: "Language code for speech recognizer")))! var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? var recognitionTask: SFSpeechRecognitionTask? let audioEngine = AVAudioEngine() var whatIwant = "" override func viewDidLoad() { super.viewDidLoad() labelMenuHelp.title = NSLocalizedString("labelMenuHelp", comment: "Help label") labelMenuParameter.title = NSLocalizedString("labelMenuParameter", comment: "Parameter label") microphoneButton.isEnabled = false speechRecognizer.delegate = self SFSpeechRecognizer.requestAuthorization { (authStatus) in var isButtonEnabled = false switch authStatus { case .authorized: isButtonEnabled = true case .denied: isButtonEnabled = false print("User denied access to speech recognition") case .restricted: isButtonEnabled = false print("Speech recognition restricted on this device") case .notDetermined: isButtonEnabled = false print("Speech recognition not yet authorized") } OperationQueue.main.addOperation() { self.microphoneButton.isEnabled = isButtonEnabled } } //on recupere les parametres de l'applicatif SwiftyPlistManager.shared.getValue(for: "urlJarvis", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.urljarvis = result as! String } } SwiftyPlistManager.shared.getValue(for: "portJarvis", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.portjarvis = result as! String } } SwiftyPlistManager.shared.getValue(for: "audioApplication", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.audioApplication = result as! Bool } } SwiftyPlistManager.shared.getValue(for: "audioServeur", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.audioServeur = result as! Bool } } SwiftyPlistManager.shared.getValue(for: "fontSize", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.fontSize = result as! Int } } SwiftyPlistManager.shared.getValue(for: "fontSizeJarvis", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.fontSizeJarvis = result as! Int } } SwiftyPlistManager.shared.getValue(for: "fontStyle", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.fontStyle = result as! String } } SwiftyPlistManager.shared.getValue(for: "fontStyleJarvis", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.fontStyleJarvis = result as! String } } SwiftyPlistManager.shared.getValue(for: "keyApiJarvis", fromPlistWithName: "parametres") { (result, err) in if err == nil { ViewController.keyAPIJarvis = result as? String } } SwiftyPlistManager.shared.getValue(for: "gitApiKey", fromPlistWithName: "parametresGitIgnore") { (result, err) in if err == nil { ViewController.gitAPIKey = result as? String } } ViewController.heightContainer = 10 /* let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = imageJarvis.bounds imageJarvis.addSubview(blurEffectView) */ let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:))) lpgr.minimumPressDuration = 1.2 scrollVue.addGestureRecognizer(lpgr) HandleDeleteAllBubble = { (action: UIAlertAction!) -> Void in while self.containerView.subviews.count > 0 { self.containerView.subviews.first?.removeFromSuperview() } ViewController.heightContainer = 10 } } func handleLongPress(_ gesture: UILongPressGestureRecognizer){ if gesture.state != .began { return } let alert = UIAlertController(title: NSLocalizedString("deletePopupTitle", comment: "title of the popup to delete conversation"), message: NSLocalizedString("deletePopupMessage", comment: "message of the popup to delete conversation"), preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: NSLocalizedString("actionDelete", comment: "Delete action"), style: UIAlertActionStyle.destructive, handler: HandleDeleteAllBubble)) alert.addAction(UIAlertAction(title: NSLocalizedString("actionCancel", comment: "Cancel action"), style: UIAlertActionStyle.cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBAction func microphoneTapped(_ sender: AnyObject) { if audioEngine.isRunning { audioEngine.stop() recognitionRequest?.endAudio() microphoneButton.isEnabled = false microphoneButton.setTitle("Start Recording", for: .normal) microphoneButton.setImage(UIImage(named: "micro.png"), for: .normal) } else { startRecording() microphoneButton.setTitle("Stop Recording", for: .normal) microphoneButton.setImage(UIImage(named: "microON.png"), for: .normal) } } func startRecording() { if recognitionTask != nil { recognitionTask?.cancel() recognitionTask = nil } let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { print("audioSession properties weren't set because of an error.") } recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object") } recognitionRequest.shouldReportPartialResults = true recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in var isFinal = false if result != nil { self.textView.text = result?.bestTranscription.formattedString //self.whatIwant = result?.bestTranscription.formattedString isFinal = (result?.isFinal)! } if error != nil || isFinal { self.audioEngine.stop() inputNode.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil self.microphoneButton.isEnabled = true TraiterDemande(bulleText: self.textView.text, containerVue: self.containerView, scrollVue: self.scrollVue, messageVue: self.MessageVue) } }) let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() do { try audioEngine.start() } catch { print("audioEngine couldn't start because of an error.") } textView.text = "" } func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) { if available { microphoneButton.isEnabled = true } else { microphoneButton.isEnabled = false } } }
mit
hpsoar/Today
Today/ViewUtility.swift
1
1236
// // ViewUtility.swift // Today // // Created by HuangPeng on 8/16/14. // Copyright (c) 2014 beacon. All rights reserved. // import UIKit extension UIView { convenience init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.init(frame: CGRectMake(x, y, width, height)) } func snapshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0) self.layer.renderInContext(UIGraphicsGetCurrentContext()) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image; } func drawLine(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) { var context = UIGraphicsGetCurrentContext(); CGContextMoveToPoint(context, x1, y1) CGContextAddLineToPoint(context, x2, y2) } } typealias UIViewPointer = AutoreleasingUnsafePointer<UIView?> extension UIColor { class func color(hexColor: NSInteger) -> UIColor! { var r = CGFloat((hexColor >> 16) & 0xFF) / 255.5 var g = CGFloat((hexColor >> 8) & 0xFF) / 255.5 var b = CGFloat(hexColor & 0xFF) / 255.5 return UIColor(red: r, green: g, blue: b, alpha: 1) } }
gpl-2.0
dfortuna/theCraic3
theCraic3/Main/New Event/NewEventDetailsTableViewCell.swift
1
5873
// // NewEventDetailsTableViewCell.swift // theCraic3 // // Created by Denis Fortuna on 13/5/18. // Copyright © 2018 Denis. All rights reserved. // import UIKit protocol DetailsProtocol: class { func detailAdded(sender: NewEventDetailsTableViewCell) } class NewEventDetailsTableViewCell: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { @IBOutlet weak var eventNameTextField: UITextField! @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var categoryImageView: UIImageView! @IBOutlet weak var categoryPickerTextField: UITextField! @IBOutlet weak var pricePickerTextField: UITextField! @IBOutlet weak var datePickerTextField: UITextField! @IBOutlet weak var categoryQuestionLabel: UILabel! @IBOutlet weak var priceDollarLabel: UILabel! @IBOutlet weak var publicPostSwitchOutlet: UISwitch! var isPublic = false private var model = UserModel() weak var delegate: DetailsProtocol? private var categoryPicker = UIPickerView() private let datePicker = UIDatePicker() private var pricePicker = UIPickerView() func formatUI(event: Event) { eventNameTextField.delegate = self addressTextField.delegate = self createCategoryPicker() createpricePicker() categoryImageView.layer.cornerRadius = 5 categoryImageView.layer.masksToBounds = true publicPostSwitchOutlet.addTarget(self, action: #selector(publicPostSwitch), for: UIControlEvents.touchUpInside) loadData(event: event) } func loadData(event: Event) { publicPostSwitchOutlet.setOn(event.isPublicEvent, animated: false) if (event.eventCategory != "-- Select --") && (event.eventCategory != "") { let (categoryImage, categoryColor) = model.getImagesForCategory(category: event.eventCategory) categoryImageView.alpha = 1 categoryImageView.image = categoryImage categoryImageView.tintColor = categoryColor categoryQuestionLabel.alpha = 0 } eventNameTextField.text = event.eventName addressTextField.text = event.eventAddress datePickerTextField.text = event.eventDate categoryPickerTextField.text = event.eventCategory pricePickerTextField.text = event.eventprice } @objc func publicPostSwitch(_ sender: UISwitch) { if sender.isOn { self.isPublic = true } else { self.isPublic = false } delegate?.detailAdded(sender: self) } @IBAction func dateTextFieldAction(_ sender: UITextField) { let datePickerView:UIDatePicker = UIDatePicker() datePickerView.datePickerMode = UIDatePickerMode.dateAndTime sender.inputView = datePickerView datePickerView.addTarget(self, action: #selector(self.datePickerValueChanged), for: UIControlEvents.valueChanged) } @objc func datePickerValueChanged(sender:UIDatePicker) { let dateString = sender.date.getDateAndTimeStringFromDate() datePickerTextField.text = dateString delegate?.detailAdded(sender: self) datePickerTextField.resignFirstResponder() } func createCategoryPicker() { categoryPicker.tag = 1 categoryPicker.delegate = self categoryPicker.dataSource = self categoryPickerTextField.inputView = categoryPicker } func createpricePicker() { pricePicker.tag = 2 pricePicker.delegate = self pricePicker.dataSource = self pricePickerTextField.inputView = pricePicker } // MARK: - PickerView Delegate func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView.tag == 1 { return model.categories[row] } else if pickerView.tag == 2 { return model.priceRange[row] } return "" } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView.tag == 1 { return model.categories.count } else if pickerView.tag == 2 { return model.priceRange.count } return 0 } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView.tag == 1 { formatCategoryTextField(fromRow: row) } else if pickerView.tag == 2 { formatPriceTextField(fromRow: row) } } func formatPriceTextField(fromRow row: Int) { let selected = model.priceRange[row] if selected != "-- Select --" { priceDollarLabel.text = model.getPrice(price: selected) pricePickerTextField.text = model.priceRange[row] delegate?.detailAdded(sender: self) pricePickerTextField.resignFirstResponder() } } func formatCategoryTextField(fromRow row: Int) { let selected = model.categories[row] if selected != "-- Select --" { categoryPickerTextField.text = model.categories[row] guard let eventCategory = categoryPickerTextField.text else { return } let (categoryImage, categoryColor) = model.getImagesForCategory(category: eventCategory) categoryImageView.alpha = 1 categoryImageView.image = categoryImage categoryImageView.tintColor = categoryColor categoryQuestionLabel.alpha = 0 delegate?.detailAdded(sender: self) categoryPickerTextField.resignFirstResponder() } } func textFieldDidEndEditing(_ textField: UITextField) { delegate?.detailAdded(sender: self) } }
apache-2.0
yeziahehe/Gank
Pods/LeanCloud/Sources/Storage/CQLClient.swift
1
3503
// // CQLClient.swift // LeanCloud // // Created by Tang Tianyong on 5/30/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** A type represents the result value of CQL execution. */ public final class LCCQLValue { let response: LCResponse init(response: LCResponse) { self.response = response } var results: [[String: Any]] { return (response.results as? [[String: Any]]) ?? [] } var className: String { return response["className"] ?? LCObject.objectClassName() } /** Get objects for object query. */ public var objects: [LCObject] { let results = self.results let className = self.className do { let objects = try results.map { dictionary in try ObjectProfiler.shared.object(dictionary: dictionary, className: className) } return objects } catch { return [] } } /** Get count value for count query. */ public var count: Int { return response.count } } /** CQL client. CQLClient allow you to use CQL (Cloud Query Language) to make CRUD for object. */ public final class LCCQLClient { static let endpoint = "cloudQuery" /** Assemble parameters for CQL execution. - parameter cql: The CQL statement. - parameter parameters: The parameters for placeholders in CQL statement. - returns: The parameters for CQL execution. */ static func parameters(_ cql: String, parameters: LCArrayConvertible?) -> [String: Any] { var result = ["cql": cql] if let parameters = parameters?.lcArray { if !parameters.isEmpty { result["pvalues"] = Utility.jsonString(parameters.lconValue!) } } return result } /** Execute CQL statement synchronously. - parameter cql: The CQL statement to be executed. - parameter parameters: The parameters for placeholders in CQL statement. - returns: The result of CQL statement. */ public static func execute(_ cql: String, parameters: LCArrayConvertible? = nil) -> LCCQLResult { return expect { fulfill in execute(cql, parameters: parameters, completionInBackground: { result in fulfill(result) }) } } /** Execute CQL statement asynchronously. - parameter cql: The CQL statement to be executed. - parameter parameters: The parameters for placeholders in CQL statement. - parameter completion: The completion callback closure. */ public static func execute(_ cql: String, parameters: LCArrayConvertible? = nil, completion: @escaping (_ result: LCCQLResult) -> Void) -> LCRequest { return execute(cql, parameters: parameters, completionInBackground: { result in mainQueueAsync { completion(result) } }) } @discardableResult private static func execute(_ cql: String, parameters: LCArrayConvertible? = nil, completionInBackground completion: @escaping (LCCQLResult) -> Void) -> LCRequest { let parameters = self.parameters(cql, parameters: parameters) let request = HTTPClient.default.request(.get, endpoint, parameters: parameters) { response in let result = LCCQLResult(response: response) completion(result) } return request } }
gpl-3.0
yeziahehe/Gank
Gank/Views/Cells/Me/SettingCell.swift
1
609
// // SettingCell.swift // Gank // // Created by 叶帆 on 2017/8/3. // Copyright © 2017年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved. // import UIKit class SettingCell: UITableViewCell { @IBOutlet weak var annotationLabel: UILabel! @IBOutlet weak var newTag: 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 } }
gpl-3.0
yanniks/Robonect-iOS
Robonect/Views/Engines/EngineViewController.swift
1
5049
// // Copyright (C) 2017 Yannik Ehlert. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // // EngineViewController.swift // Robonect // // Created by Yannik Ehlert on 07.06.17. // import UIKit class EngineViewController: UIViewController { @IBOutlet weak var labelPowerStageLeft: UILabel! @IBOutlet weak var labelPowerStageRight: UILabel! @IBOutlet weak var labelSpeedLeft: UILabel! @IBOutlet weak var labelSpeedRight: UILabel! @IBOutlet weak var labelCurrentLeft: UILabel! @IBOutlet weak var labelCurrentRight: UILabel! @IBOutlet weak var labelBladeMotorSpeed: UILabel! @IBOutlet weak var labelBladeMotorCurrent: UILabel! @IBOutlet weak var progressPowerStageLeft: UIProgressView! @IBOutlet weak var progressPowerStageRight: UIProgressView! @IBOutlet weak var progressSpeedLeft: UIProgressView! @IBOutlet weak var progressSpeedRight: UIProgressView! @IBOutlet weak var progressCurrentLeft: UIProgressView! @IBOutlet weak var progressCurrentRight: UIProgressView! @IBOutlet weak var progressBladeMotorSpeed: UIProgressView! @IBOutlet weak var progressBladeMotorCurrent: UIProgressView! @IBOutlet weak var valuePowerStageLeft: UILabel! @IBOutlet weak var valuePowerStageRight: UILabel! @IBOutlet weak var valueSpeedLeft: UILabel! @IBOutlet weak var valueSpeedRight: UILabel! @IBOutlet weak var valueCurrentLeft: UILabel! @IBOutlet weak var valueCurrentRight: UILabel! @IBOutlet weak var valueBladeMotorSpeed: UILabel! @IBOutlet weak var valueBladeMotorCurrent: UILabel! private var engine : RobonectAPIResponse.Engine? = nil private var timer : Timer? = nil override func viewDidLoad() { super.viewDidLoad() title = "Engines" fetchData() } func fetchData() { NetworkingRequest.fetchEngine(mower: SharedSettings.shared.mower) { callback in if !callback.isSuccessful { ShowMessage.showMessage(message: .actionFailed) } if let engine = callback.value { self.engine = engine DispatchQueue.main.async { self.updateValues() } } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) timer?.invalidate() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(EngineViewController.fetchData), userInfo: nil, repeats: true) } func updateValues() { progressPowerStageLeft.progress = abs(Float(engine?.pdrvpercentl ?? 0) / 100) valuePowerStageLeft.text = String(engine?.pdrvpercentl ?? 0) + " %" progressPowerStageRight.progress = abs(Float(engine?.pdrvpercentr ?? 0) / 100) valuePowerStageRight.text = String(engine?.pdrvpercentr ?? 0) + " %" progressSpeedLeft.progress = abs(Float(engine?.pdrvspeedl ?? 0) / 100) valueSpeedLeft.text = String(engine?.pdrvspeedl ?? 0) + " cm/s" progressSpeedRight.progress = abs(Float(engine?.pdrvspeedr ?? 0) / 100) valueSpeedRight.text = String(engine?.pdrvspeedr ?? 0) + " cm/s" progressCurrentLeft.progress = abs(Float(engine?.pdrvcurrentl ?? 0) / 100) * 0.2 valueCurrentLeft.text = String(engine?.pdrvcurrentl ?? 0) + " mA" progressCurrentRight.progress = abs(Float(engine?.pdrvcurrentr ?? 0) / 100) * 0.2 valueCurrentRight.text = String(engine?.pdrvcurrentr ?? 0) + " mA" progressBladeMotorSpeed.progress = abs(Float(engine?.pcutspeed ?? 0) / 100) * 0.02843439534 valueBladeMotorSpeed.text = String(engine?.pcutspeed ?? 0) + " RPM" progressBladeMotorCurrent.progress = abs(Float(engine?.pcutcurrent ?? 0) / 100) * 0.2 valueBladeMotorCurrent.text = String(engine?.pcutcurrent ?? 0) + " mA" } }
mit
mstevenson/VetteViewer
VetteViewer/RendererView.swift
1
211
// // Renderer.swift // VetteViewer // // Created by Michael Stevenson on 6/8/14. // Copyright (c) 2014 Michael Stevenson. All rights reserved. // import SceneKit class RendererView: SCNView { }
mit
jasonhenderson/examples-ios
UITableView/UITableViewExample/AppDelegate.swift
1
2804
// // AppDelegate.swift // UITableViewExample // // Created by Jason Henderson on 10/14/16. // // This file is part of examples-ios. // // examples-ios is free software: you c an 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. // // examples-ios 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 examples-ios. If not, see <http://www.gnu.org/licenses/>. // 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:. } }
gpl-3.0
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Commands/CommandProtocol.swift
2
1456
// // CommandProtocol.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 23/10/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. All rights reserved. // import UIKit protocol CommandProtocol { func canExecute(error: inout ErrorEntity) -> Bool func executeWithCallback(callback: Callback?) }
mit
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/Views/Map/BasicMapAnnotationView.swift
1
1059
// // BasicMapAnnotationView2.swift // travelMap // // Created by green on 15/7/22. // Copyright (c) 2015年 com.city8. All rights reserved. // import UIKit class BasicMapAnnotationView: MKAnnotationView { var indexL: UILabel! override init!(annotation: MKAnnotation!, reuseIdentifier: String!) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) self.frame = CGRectMake(0, 0, 16, 16) let circleV = GCircleControl(frame: CGRectMake(0, 0, 16, 16)) circleV.fillColor = UIColor.yellowColor() circleV.borderWidth = 0 indexL = UILabel(frame: CGRectMake(0, 0, 16, 16)) indexL.textAlignment = NSTextAlignment.Center indexL.font = UIFont.systemFontOfSize(14) self.addSubview(circleV) self.addSubview(indexL) } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
MChainZhou/DesignPatterns
Mediator/Mediator/Simple_2_生活案例/Soundcard.swift
1
298
// // Soundcard.swift // Mediator // // Created by apple on 2017/8/30. // Copyright © 2017年 apple. All rights reserved. // import UIKit //具体的对像 class Soundcard: ComputerColleague { //播放声音 func soundPlay(data:String) { print("播放声音\(data)") } }
mit
reactive-swift/Future
Package.swift
1
948
//===--- Package.swift ----------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 PackageDescription let package = Package( name: "Future", dependencies: [ .Package(url: "https://github.com/reactive-swift/Event.git", majorVersion: 0, minor: 2) ] )
apache-2.0
turingcorp/kitkat
kitkat/Category/CategoryUICollectionReusableView.swift
2
218
import UIKit extension UICollectionReusableView { class func reusableIdentifier() -> String { let classType:AnyClass = object_getClass(self) return NSStringFromClass(classType) } }
mit
HabitRPG/habitrpg-ios
HabitRPG/UI/Challenges/Details/ChallengeDetailViewModel.swift
1
21588
// // ChallengeDetailViewModel.swift // Habitica // // Created by Elliot Schrock on 10/17/17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import ReactiveSwift import Habitica_Models enum ChallengeButtonState { case uninitialized, join, leave, publishDisabled, publishEnabled, viewParticipants, endChallenge } protocol ChallengeDetailViewModelInputs { func viewDidLoad() func setChallenge(_ challenge: ChallengeProtocol) } protocol ChallengeDetailViewModelOutputs { var cellModelsSignal: Signal<[MultiModelDataSourceSection], Never> { get } var reloadTableSignal: Signal<Void, Never> { get } var animateUpdatesSignal: Signal<(), Never> { get } var nextViewControllerSignal: Signal<UIViewController, Never> { get } } protocol ChallengeDetailViewModelProtocol { var inputs: ChallengeDetailViewModelInputs { get } var outputs: ChallengeDetailViewModelOutputs { get } } class ChallengeDetailViewModel: ChallengeDetailViewModelProtocol, ChallengeDetailViewModelInputs, ChallengeDetailViewModelOutputs, ResizableTableViewCellDelegate, ChallengeCreatorCellDelegate { var inputs: ChallengeDetailViewModelInputs { return self } var outputs: ChallengeDetailViewModelOutputs { return self } let cellModelsSignal: Signal<[MultiModelDataSourceSection], Never> let reloadTableSignal: Signal<Void, Never> let animateUpdatesSignal: Signal<(), Never> let nextViewControllerSignal: Signal<UIViewController, Never> let challengeID: String? let challengeProperty: MutableProperty<ChallengeProtocol?> let challengeMembershipProperty = MutableProperty<ChallengeMembershipProtocol?>(nil) let challengeCreatorProperty = MutableProperty<MemberProtocol?>(nil) let viewDidLoadProperty = MutableProperty(()) let reloadTableProperty = MutableProperty(()) let animateUpdatesProperty = MutableProperty(()) let nextViewControllerProperty = MutableProperty<UIViewController?>(nil) let cellModelsProperty: MutableProperty<[MultiModelDataSourceSection]> = MutableProperty<[MultiModelDataSourceSection]>([]) let infoSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection()) let habitsSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection()) let dailiesSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection()) let todosSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection()) let rewardsSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection()) let endSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection()) let mainButtonItemProperty: MutableProperty<ButtonCellMultiModelDataSourceItem?> = MutableProperty<ButtonCellMultiModelDataSourceItem?>(nil) let endButtonItemProperty: MutableProperty<ButtonCellMultiModelDataSourceItem?> = MutableProperty<ButtonCellMultiModelDataSourceItem?>(nil) let doubleEndButtonItemProperty: MutableProperty<DoubleButtonMultiModelDataSourceItem?> = MutableProperty<DoubleButtonMultiModelDataSourceItem?>(nil) let joinLeaveStyleProvider: JoinLeaveButtonAttributeProvider let publishStyleProvider: PublishButtonAttributeProvider let participantsStyleProvider: ParticipantsButtonAttributeProvider let endChallengeStyleProvider: EndChallengeButtonAttributeProvider var joinInteractor: JoinChallengeInteractor? var leaveInteractor: LeaveChallengeInteractor? private let socialRepository = SocialRepository() private let disposable = ScopedDisposable(CompositeDisposable()) init(challenge: ChallengeProtocol) { self.challengeID = challenge.id challengeProperty = MutableProperty<ChallengeProtocol?>(challenge) reloadTableSignal = reloadTableProperty.signal animateUpdatesSignal = animateUpdatesProperty.signal nextViewControllerSignal = nextViewControllerProperty.signal.skipNil() self.joinInteractor = JoinChallengeInteractor() if let viewController = UIApplication.shared.keyWindow?.visibleController() { self.leaveInteractor = LeaveChallengeInteractor(presentingViewController: viewController) } joinLeaveStyleProvider = JoinLeaveButtonAttributeProvider(challenge) publishStyleProvider = PublishButtonAttributeProvider(challenge) participantsStyleProvider = ParticipantsButtonAttributeProvider(challenge) endChallengeStyleProvider = EndChallengeButtonAttributeProvider(challenge) let initialCellModelsSignal = cellModelsProperty.signal.sample(on: viewDidLoadProperty.signal) cellModelsSignal = Signal.merge(cellModelsProperty.signal, initialCellModelsSignal) setup(challenge: challenge) reloadChallenge() } init(challengeID: String) { self.challengeID = challengeID challengeProperty = MutableProperty<ChallengeProtocol?>(nil) reloadTableSignal = reloadTableProperty.signal animateUpdatesSignal = animateUpdatesProperty.signal nextViewControllerSignal = nextViewControllerProperty.signal.skipNil() joinLeaveStyleProvider = JoinLeaveButtonAttributeProvider(nil) publishStyleProvider = PublishButtonAttributeProvider(nil) participantsStyleProvider = ParticipantsButtonAttributeProvider(nil) endChallengeStyleProvider = EndChallengeButtonAttributeProvider(nil) let initialCellModelsSignal = cellModelsProperty.signal.sample(on: viewDidLoadProperty.signal) cellModelsSignal = Signal.merge(cellModelsProperty.signal, initialCellModelsSignal) setup(challenge: nil) reloadChallenge() } private func setup(challenge: ChallengeProtocol?) { Signal.combineLatest(infoSectionProperty.signal, habitsSectionProperty.signal, dailiesSectionProperty.signal, todosSectionProperty.signal, rewardsSectionProperty.signal, endSectionProperty.signal) .map { sectionTuple -> [MultiModelDataSourceSection] in return [sectionTuple.0, sectionTuple.1, sectionTuple.2, sectionTuple.3, sectionTuple.4, sectionTuple.5] } .observeValues {[weak self] sections in self?.cellModelsProperty.value = sections.filter { $0.items?.count ?? 0 > 0 } } setupInfo() setupButtons() challengeProperty.signal.observeValues {[weak self] newChallenge in self?.joinLeaveStyleProvider.challengeProperty.value = newChallenge self?.publishStyleProvider.challengeProperty.value = newChallenge self?.participantsStyleProvider.challengeProperty.value = newChallenge self?.endChallengeStyleProvider.challengeProperty.value = newChallenge } challengeMembershipProperty.signal.observeValues {[weak self] (membership) in self?.joinLeaveStyleProvider.challengeMembershipProperty.value = membership } joinLeaveStyleProvider.challengeUpdatedProperty.signal.observeValues {[weak self] _ in self?.reloadChallenge() } joinLeaveStyleProvider.buttonStateSignal.sample(on: joinLeaveStyleProvider.buttonPressedProperty.signal).observeValues { [weak self] (state) in guard let challenge = self?.challengeProperty.value else { return } if state == .join { self?.joinInteractor?.run(with: challenge) } else { self?.leaveInteractor?.run(with: challenge) } } } func setupInfo() { Signal.combineLatest(challengeProperty.signal.skipNil(), mainButtonItemProperty.signal, challengeCreatorProperty.signal) .observeValues { (challenge, mainButtonValue, creator) in let infoItem = ChallengeMultiModelDataSourceItem<ChallengeDetailInfoTableViewCell>(challenge, identifier: "info") let creatorItem = ChallengeCreatorMultiModelDataSourceItem(challenge, creator: creator, cellDelegate: self, identifier: "creator") let categoryItem = ChallengeResizableMultiModelDataSourceItem<ChallengeCategoriesTableViewCell>(challenge, resizingDelegate: self, identifier: "categories") let descriptionItem = ChallengeResizableMultiModelDataSourceItem<ChallengeDescriptionTableViewCell>(challenge, resizingDelegate: self, identifier: "description") let infoSection = MultiModelDataSourceSection() if let mainButton = mainButtonValue { infoSection.items = [infoItem, mainButton, creatorItem, categoryItem, descriptionItem] } else { infoSection.items = [infoItem, creatorItem, categoryItem, descriptionItem] } self.infoSectionProperty.value = infoSection } } func setupTasks() { disposable.inner.add(socialRepository.getChallengeTasks(challengeID: challengeProperty.value?.id ?? "").on(value: {[weak self] (tasks, _) in let habitsSection = MultiModelDataSourceSection() habitsSection.title = "Habits" habitsSection.items = tasks.filter({ (task) -> Bool in return task.type == TaskType.habit }).map({ (task) -> MultiModelDataSourceItem in return ChallengeTaskMultiModelDataSourceItem<HabitTableViewCell>(task, identifier: "habit") }) self?.habitsSectionProperty.value = habitsSection let dailiesSection = MultiModelDataSourceSection() dailiesSection.title = "Dailies" dailiesSection.items = tasks.filter({ (task) -> Bool in return task.type == TaskType.daily }).map({ (task) -> MultiModelDataSourceItem in return ChallengeTaskMultiModelDataSourceItem<DailyTableViewCell>(task, identifier: "daily") }) self?.dailiesSectionProperty.value = dailiesSection let todosSection = MultiModelDataSourceSection() todosSection.title = "Todos" todosSection.items = tasks.filter({ (task) -> Bool in return task.type == TaskType.todo }).map({ (task) -> MultiModelDataSourceItem in return ChallengeTaskMultiModelDataSourceItem<ToDoTableViewCell>(task, identifier: "todo") }) self?.todosSectionProperty.value = todosSection let rewardsSection = MultiModelDataSourceSection() rewardsSection.title = "Rewards" rewardsSection.items = tasks.filter({ (task) -> Bool in return task.type == TaskType.reward }).map({ (task) -> MultiModelDataSourceItem in return RewardMultiModelDataSourceItem<ChallengeRewardTableViewCell>(task, identifier: "reward") }) self?.rewardsSectionProperty.value = rewardsSection }).start()) } func setupButtons() { let ownedChallengeSignal = challengeProperty.signal.skipNil().filter { (challenge) -> Bool in return challenge.isOwner() } let unownedChallengeSignal = challengeProperty.signal.skipNil().filter { (challenge) -> Bool in return !challenge.isOwner() } endButtonItemProperty.signal.skipNil().observeValues { (item) in let endSection = MultiModelDataSourceSection() endSection.items = [item] self.endSectionProperty.value = endSection } doubleEndButtonItemProperty.signal.skipNil().observeValues { (item) in let endSection = MultiModelDataSourceSection() endSection.items = [item] self.endSectionProperty.value = endSection } let endButtonNilSignal = endButtonItemProperty.signal.map { $0 == nil } let doubleEndButtonNilSignal = doubleEndButtonItemProperty.signal.map { $0 == nil } endButtonNilSignal.and(doubleEndButtonNilSignal).filter({ $0 }).observeValues({ _ in let endSection = MultiModelDataSourceSection() self.endSectionProperty.value = endSection }) ownedChallengeSignal.observeValues {[weak self] _ in self?.doubleEndButtonItemProperty.value = DoubleButtonMultiModelDataSourceItem(identifier: "endButton", leftAttributeProvider: self?.joinLeaveStyleProvider, leftInputs: self?.joinLeaveStyleProvider, rightAttributeProvider: self?.endChallengeStyleProvider, rightInputs: self?.endChallengeStyleProvider) } ownedChallengeSignal .filter({ (challenge) -> Bool in return challenge.isPublished() }).observeValues {[weak self] _ in self?.mainButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.participantsStyleProvider, inputs: self?.participantsStyleProvider, identifier: "mainButton") } ownedChallengeSignal .filter({ (challenge) -> Bool in return !challenge.isPublished() }).observeValues {[weak self] _ in self?.mainButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.publishStyleProvider, inputs: self?.publishStyleProvider, identifier: "mainButton") } unownedChallengeSignal.observeValues { _ in self.doubleEndButtonItemProperty.value = nil } challengeMembershipProperty.signal.combineLatest(with: unownedChallengeSignal) .skipRepeats({ (first, second) -> Bool in return (first.0 == nil) == (second.0 == nil) }) .filter({ (membership, _) -> Bool in return membership == nil }) .observeValues {[weak self] _ in self?.mainButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.joinLeaveStyleProvider, inputs: self?.joinLeaveStyleProvider, identifier: "mainButton") self?.endButtonItemProperty.value = nil self?.doubleEndButtonItemProperty.value = nil } challengeMembershipProperty.signal.combineLatest(with: unownedChallengeSignal) .skipRepeats({ (first, second) -> Bool in return (first.0 == nil) == (second.0 == nil) }) .filter({ (membership, _) -> Bool in return membership != nil }) .observeValues {[weak self] _ in self?.mainButtonItemProperty.value = nil self?.endButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.joinLeaveStyleProvider, inputs: self?.joinLeaveStyleProvider, identifier: "mainButton") self?.doubleEndButtonItemProperty.value = nil } } func reloadChallenge() { DispatchQueue.main.async {[weak self] in self?.socialRepository.retrieveChallenge(challengeID: self?.challengeID ?? "").observeCompleted { } } } // MARK: Resizing delegate func cellResized() { animateUpdatesProperty.value = () } // MARK: Creator delegate func userPressed(_ member: MemberProtocol) { let secondStoryBoard = UIStoryboard(name: "Social", bundle: nil) if let userViewController: UserProfileViewController = secondStoryBoard.instantiateViewController(withIdentifier: "UserProfileViewController") as? UserProfileViewController { userViewController.userID = member.id userViewController.username = member.profile?.name nextViewControllerProperty.value = userViewController } } func messagePressed(member: MemberProtocol) { let secondStoryBoard = UIStoryboard(name: "Social", bundle: nil) if let chatViewController: InboxChatViewController = secondStoryBoard.instantiateViewController(withIdentifier: "InboxChatViewController") as? InboxChatViewController { chatViewController.userID = member.id chatViewController.username = member.profile?.name chatViewController.isPresentedModally = true nextViewControllerProperty.value = chatViewController } } // MARK: ChallengeDetailViewModelInputs func viewDidLoad() { viewDidLoadProperty.value = () disposable.inner.add(socialRepository.getChallenge(challengeID: challengeID ?? "") .skipNil() .on(value: {[weak self] challenge in self?.setChallenge(challenge) }) .map { challenge in return challenge.leaderID } .skipNil() .observe(on: QueueScheduler.main) .flatMap(.latest, {[weak self] leaderID in return self?.socialRepository.getMember(userID: leaderID, retrieveIfNotFound: true) ?? SignalProducer.empty }) .on(value: {[weak self] creator in self?.challengeCreatorProperty.value = creator }) .start()) if let challengeID = self.challengeID { disposable.inner.add(socialRepository.getChallengeMembership(challengeID: challengeID).on(value: {[weak self] membership in self?.setChallengeMembership(membership) }).start()) } setupTasks() } func setChallenge(_ challenge: ChallengeProtocol) { challengeProperty.value = challenge } func setChallengeMembership(_ membership: ChallengeMembershipProtocol?) { challengeMembershipProperty.value = membership } } // MARK: - protocol ChallengeConfigurable { func configure(with challenge: ChallengeProtocol) } // MARK: - class ChallengeMultiModelDataSourceItem<T>: ConcreteMultiModelDataSourceItem<T> where T: UITableViewCell, T: ChallengeConfigurable { private let challenge: ChallengeProtocol init(_ challenge: ChallengeProtocol, identifier: String) { self.challenge = challenge super.init(identifier: identifier) } override func configureCell(_ cell: UITableViewCell) { if let clazzCell: T = cell as? T { clazzCell.configure(with: challenge) } } } // MARK: - class ChallengeCreatorMultiModelDataSourceItem: ChallengeMultiModelDataSourceItem<ChallengeCreatorTableViewCell> { private let challenge: ChallengeProtocol private let creator: MemberProtocol? private weak var cellDelegate: ChallengeCreatorCellDelegate? init(_ challenge: ChallengeProtocol, creator: MemberProtocol?, cellDelegate: ChallengeCreatorCellDelegate, identifier: String) { self.challenge = challenge self.creator = creator self.cellDelegate = cellDelegate super.init(challenge, identifier: identifier) } override func configureCell(_ cell: UITableViewCell) { super.configureCell(cell) if let creatorCell = cell as? ChallengeCreatorTableViewCell { creatorCell.delegate = cellDelegate creatorCell.configure(member: creator) } } } // MARK: - class ChallengeResizableMultiModelDataSourceItem<T>: ChallengeMultiModelDataSourceItem<T> where T: ChallengeConfigurable, T: ResizableTableViewCell { weak var resizingDelegate: ResizableTableViewCellDelegate? init(_ challenge: ChallengeProtocol, resizingDelegate: ResizableTableViewCellDelegate?, identifier: String) { super.init(challenge, identifier: identifier) self.resizingDelegate = resizingDelegate } override func configureCell(_ cell: UITableViewCell) { super.configureCell(cell) if let clazzCell: T = cell as? T { clazzCell.resizingDelegate = resizingDelegate } } } // MARK: - class ChallengeTaskMultiModelDataSourceItem<T>: ConcreteMultiModelDataSourceItem<T> where T: TaskTableViewCell { private let challengeTask: TaskProtocol public init(_ challengeTask: TaskProtocol, identifier: String) { self.challengeTask = challengeTask super.init(identifier: identifier) } override func configureCell(_ cell: UITableViewCell) { if let clazzCell: T = cell as? T { clazzCell.configure(task: challengeTask) } } } // MARK: - class RewardMultiModelDataSourceItem<T>: ConcreteMultiModelDataSourceItem<T> where T: ChallengeRewardTableViewCell { private let challengeTask: TaskProtocol public init(_ challengeTask: TaskProtocol, identifier: String) { self.challengeTask = challengeTask super.init(identifier: identifier) } override func configureCell(_ cell: UITableViewCell) { if let clazzCell: T = cell as? T { clazzCell.configure(reward: challengeTask) } } }
gpl-3.0
LinDing/Positano
Positano/Extensions/Double+Yep.swift
1
396
// // Double+Yep.swift // Yep // // Created by kevinzhow on 15/5/22. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import Foundation extension Double { var yep_feedAudioTimeLengthString: String { let minutes = Int(self / 60) let seconds = Int(self.truncatingRemainder(dividingBy: 60)) return String(format: "%02d:%02d", minutes, seconds) } }
mit
hryk224/SnapView
Tests/LinuxMain.swift
1
98
import XCTest @testable import SnapViewTests XCTMain([ testCase(SnapViewTests.allTests), ])
mit
pixyzehn/MediumMenu
MediumMenu-Sample/AppDelegate.swift
1
433
// // AppDelegate.swift // MediumMenu-Sample // // Created by pixyzehn on 2/8/15. // Copyright (c) 2015 pixyzehn. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } }
mit
JesusAntonioGil/Design-Patterns-Swift-2
StructuralPatterns2/CompositePattern/CompositePattern/Model/VODCategory.swift
1
1203
// // VODCategory.swift // CompositePattern // // Created by Jesus Antonio Gil on 18/12/15. // Copyright © 2015 Jesus Antonio Gil. All rights reserved. // import UIKit class VODCategory: VODComponent { var vodComponents = [VODComponent]() private var name: String! private var descriptionCategory: String! init(name:String!, descriptionCategory:String!) { self.name = name self.descriptionCategory = descriptionCategory } //MARK: PUBLIC override func add(vodComponent: VODComponent) { vodComponents.append(vodComponent) } override func remove(vodComponent: VODComponent) { vodComponents.remove(vodComponent) } override func getChild(i: Int) -> VODComponent { return vodComponents[i] } override func getName() -> String { return name } override func getDescription() -> String { return descriptionCategory } override func display() { print("\(name), \(descriptionCategory) \r\n ------------") for e in vodComponents { e.display() } } }
mit
nathawes/swift
test/decl/protocol/conforms/fixit_stub_editor.swift
15
6386
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %S/Inputs/fixit_stub_mutability_proto_module.swift -emit-module -parse-as-library -o %t // RUN: %target-swift-frontend -typecheck %s -I %t -verify -diagnostics-editor-mode protocol P0_A { associatedtype T } protocol P0_B { associatedtype T } class C0: P0_A, P0_B {} // expected-error{{type 'C0' does not conform to protocol 'P0_A'}} expected-error{{type 'C0' does not conform to protocol 'P0_B'}} expected-note{{do you want to add protocol stubs?}}{{23-23=\n typealias T = <#type#>\n}} protocol P1 { @available(*, deprecated) func foo1() func foo2() func foo3(arg: Int, arg2: String) func foo4<T: P1>(_: T) } protocol P2 { func bar1() func bar2() func foo2() func foo3(arg: Int, arg2: String) func foo3(arg: Int, arg2: Int) func foo4<T: P1>(_: T) func foo4<T: P2>(_: T) } class C1 : P1, P2 {} // expected-error{{type 'C1' does not conform to protocol 'P1'}} expected-error{{type 'C1' does not conform to protocol 'P2'}} expected-note{{do you want to add protocol stubs?}}{{20-20=\n func foo1() {\n <#code#>\n \}\n\n func foo2() {\n <#code#>\n \}\n\n func foo3(arg: Int, arg2: String) {\n <#code#>\n \}\n\n func foo4<T>(_: T) where T : P1 {\n <#code#>\n \}\n\n func bar1() {\n <#code#>\n \}\n\n func bar2() {\n <#code#>\n \}\n\n func foo3(arg: Int, arg2: Int) {\n <#code#>\n \}\n}} protocol P3 { associatedtype T1 associatedtype T2 associatedtype T3 } protocol P4 : P3 { associatedtype T1 associatedtype T4 = T1 associatedtype T5 = T2 associatedtype T6 = T3 } class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n typealias T1 = <#type#>\n\n typealias T2 = <#type#>\n\n typealias T3 = <#type#>\n}} protocol P5 { func foo1() func foo2(arg: Int, arg2: String) func foo3<T: P3>(_: T) } protocol P6: P5 { func foo1() func foo2(arg: Int, arg2: String) func foo2(arg: Int, arg2: Int) func foo3<T: P3>(_: T) func foo3<T: P4>(_: T) } class C3 : P6 {} // expected-error{{type 'C3' does not conform to protocol 'P5'}} expected-error{{type 'C3' does not conform to protocol 'P6'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n func foo1() {\n <#code#>\n \}\n\n func foo2(arg: Int, arg2: String) {\n <#code#>\n \}\n\n func foo2(arg: Int, arg2: Int) {\n <#code#>\n \}\n\n func foo3<T>(_: T) where T : P3 {\n <#code#>\n \}\n}} // ============================================================================= // Test how we print stubs for mutating and non-mutating requirements. // // - Test that we don't print 'mutating' in classes. // - Test that we print 'non-mutating' for non-mutating setters // in structs. // ============================================================================= protocol MutabilityProto { mutating func foo() subscript() -> Int { get nonmutating set } } class Class1: MutabilityProto { // expected-error{{type 'Class1' does not conform to protocol 'MutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{32-32=\n func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n get {\n <#code#>\n \}\n set {\n <#code#>\n \}\n \}\n}} } struct Struct1: MutabilityProto { // expected-error{{type 'Struct1' does not conform to protocol 'MutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{34-34=\n mutating func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n get {\n <#code#>\n \}\n nonmutating set {\n <#code#>\n \}\n \}\n}} } import fixit_stub_mutability_proto_module class Class2: ExternalMutabilityProto { // expected-error{{type 'Class2' does not conform to protocol 'ExternalMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{40-40=\n func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n get {\n <#code#>\n \}\n set(newValue) {\n <#code#>\n \}\n \}\n}} } struct Struct2: ExternalMutabilityProto { // expected-error{{type 'Struct2' does not conform to protocol 'ExternalMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{42-42=\n mutating func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n mutating get {\n <#code#>\n \}\n nonmutating set(newValue) {\n <#code#>\n \}\n \}\n}} } protocol PropertyMutabilityProto { var computed: Int { mutating get nonmutating set } var stored: Int { mutating get set } } class Class3: PropertyMutabilityProto { // expected-error{{type 'Class3' does not conform to protocol 'PropertyMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{40-40=\n var computed: Int\n\n var stored: Int\n}} } struct Struct3: PropertyMutabilityProto { // expected-error{{type 'Struct3' does not conform to protocol 'PropertyMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{42-42=\n var computed: Int {\n mutating get {\n <#code#>\n \}\n nonmutating set {\n <#code#>\n \}\n \}\n\n var stored: Int\n}} } class Class4 {} extension Class4: PropertyMutabilityProto { // expected-error{{type 'Class4' does not conform to protocol 'PropertyMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{44-44=\n var computed: Int {\n get {\n <#code#>\n \}\n set {\n <#code#>\n \}\n \}\n\n var stored: Int {\n get {\n <#code#>\n \}\n set {\n <#code#>\n \}\n \}\n}} } // https://bugs.swift.org/browse/SR-9868 protocol FooProto { typealias CompletionType = (Int) -> Void func doSomething(then completion: @escaping CompletionType) } struct FooType : FooProto { // expected-error {{type 'FooType' does not conform to protocol 'FooProto'}} expected-note {{do you want to add protocol stubs?}} {{28-28=\n func doSomething(then completion: @escaping CompletionType) {\n <#code#>\n \}\n}} }
apache-2.0
jmtrachy/poc-game
ProofOfConceptGame/AppDelegate.swift
1
2554
// // AppDelegate.swift // ProofOfConceptGame // // Created by James Trachy on 6/22/14. // Copyright (c) 2014 James Trachy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func testCallingCircleService() { let cService = CircleService() print("Circles size A = \(cService.circles.count) with center point of (\(cService.circles[0].xCoord), \(cService.circles[0].yCoord))") cService.createRandomCircle() print("Circles size B = \(cService.circles.count) with center point of (\(cService.circles[1].xCoord), \(cService.circles[1].yCoord))") cService.createRandomCircle() print("Circles size C = \(cService.circles.count) with center point of (\(cService.circles[2].xCoord), \(cService.circles[2].yCoord))") } 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:. } }
apache-2.0
peterlafferty/LuasLife
LuasLife/AppDelegate.swift
1
912
// // AppDelegate.swift // LuasLife // // Created by Peter Lafferty on 27/02/2016. // Copyright © 2016 Peter Lafferty. 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) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
mit
devlucky/Kakapo
Tests/PropertyPolicyTests.swift
1
2203
// // PropertyPolicyTests.swift // Kakapo // // Created by Alex Manzella on 29/04/16. // Copyright © 2016 devlucky. All rights reserved. // import Foundation import Quick import Nimble @testable import Kakapo private struct Test<T>: Serializable { let value: PropertyPolicy<T> } private struct Person: Serializable { let name: String } class IgnorableNilPropertySpec: QuickSpec { override func spec() { describe("Property policy serialization") { it("is not serialized if nil") { let serialized = Test(value: PropertyPolicy<Int>.none).serialized() as! [String: AnyObject] expect(serialized.count) == 0 } it("is serialized if not nil") { let serialized = Test(value: PropertyPolicy.some(1)).serialized() as! [String: AnyObject] expect(serialized.count) == 1 let value = serialized["value"] as? Int expect(value) == 1 } it("return NSNull when .null") { let serialized = Test(value: PropertyPolicy<Int>.null).serialized() as! [String: AnyObject] expect(serialized.count) == 1 let value = serialized["value"] as? NSNull expect(value).toNot(beNil()) } it("recursively serialize the object if needed") { let serialized = Test(value: PropertyPolicy.some(Person(name: "Alex"))).serialized() as! [String: AnyObject] expect(serialized.count) == 1 let value = serialized["value"] as? [String: AnyObject] expect(value?["name"] as? String).to(equal("Alex")) } it("recursively serialize PropertyPolicy") { let policy = PropertyPolicy.some(1) let policyOfPolicy = PropertyPolicy.some(policy) let serialized = Test(value: policyOfPolicy).serialized() as! [String: AnyObject] expect(serialized.count) == 1 let value = serialized["value"] as? Int expect(value) == 1 } } } }
mit
vzhikserg/GoHappy
src/app/ios/KooKoo/KooKoo/SecurityViewController.swift
1
1721
// // SecurityViewController.swift // KooKoo // // Created by Channa Karunathilake on 6/25/16. // Copyright © 2016 KooKoo. All rights reserved. // import UIKit import CircleProgressBar class SecurityViewController: UIViewController { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var securityContainer: UIView! @IBOutlet weak var progressBar: CircleProgressBar! let icons = ["bird", "cat", "elephant", "pig"] override func viewDidLoad() { super.viewDidLoad() let img = UIImage(named: icons[Int((NSDate().timeIntervalSince1970 / 10) % 4)])?.imageWithRenderingMode(.AlwaysTemplate) iconImageView.image = img } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) securityContainer.alpha = 0 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) securityContainer.popIn { (finished) in self.progressBar.setProgress(0, animated: true, duration: 4) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { let transition: CATransition = CATransition() transition.duration = 0.15 transition.type = kCATransitionFade self.navigationController?.view.layer.addAnimation(transition, forKey: nil) self.navigationController?.popViewControllerAnimated(false) } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() securityContainer.layer.cornerRadius = securityContainer.bounds.width / 2 } }
bsd-2-clause
practicalswift/swift
validation-test/execution/dsohandle-multi-module.swift
5
1011
// RUN: %empty-directory(%t) // RUN: (cd %t && %target-build-swift %S/Inputs/dsohandle-first.swift -emit-library -emit-module -module-name first -Xlinker -install_name -Xlinker '@executable_path/libfirst.dylib') // RUN: (cd %t && %target-build-swift %S/Inputs/dsohandle-second.swift -emit-library -emit-module -module-name second -Xlinker -install_name -Xlinker '@executable_path/libsecond.dylib') // RUN: %target-build-swift -I %t -L %t -lfirst -lsecond %s -o %t/main // RUN: %target-codesign %t/main %t/%target-library-name(first) %t/%target-library-name(second) // RUN: %target-run %t/main %t/%target-library-name(first) %t/%target-library-name(second) // REQUIRES: executable_test // UNSUPPORTED: linux import first import second import StdlibUnittest let DSOHandleTests = TestSuite("DSOHandle") DSOHandleTests.test("Unique handles for different images") { let firstHandle = getFirstDSOHandle() let secondHandle = getSecondDSOHandle() expectNotEqual(firstHandle, secondHandle) } runAllTests()
apache-2.0
PJayRushton/stats
Stats/UIButton+Helpers.swift
1
407
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit public extension UIButton { func setTitleWithoutFlashing(to title: String?, for state: UIControlState = .normal) { UIView.performWithoutAnimation { setTitle(title, for: state) layoutIfNeeded() } } }
mit
ashfurrow/eidolon
Kiosk/Bid Fulfillment/BidDetailsPreviewView.swift
2
4039
import UIKit import Artsy_UILabels import Artsy_UIButtons import UIImageViewAligned import RxSwift import RxCocoa class BidDetailsPreviewView: UIView { let _bidDetails = Variable<BidDetails?>(nil) var bidDetails: BidDetails? { didSet { self._bidDetails.value = bidDetails } } @objc dynamic let artworkImageView = UIImageViewAligned() @objc dynamic let artistNameLabel = ARSansSerifLabel() @objc dynamic let artworkTitleLabel = ARSerifLabel() @objc dynamic let currentBidPriceLabel = ARSerifLabel() override func awakeFromNib() { self.backgroundColor = .white artistNameLabel.numberOfLines = 1 artworkTitleLabel.numberOfLines = 1 currentBidPriceLabel.numberOfLines = 1 artworkImageView.alignRight = true artworkImageView.alignBottom = true artworkImageView.contentMode = .scaleAspectFit artistNameLabel.font = UIFont.sansSerifFont(withSize: 14) currentBidPriceLabel.font = UIFont.serifBoldFont(withSize: 14) let artwork = _bidDetails .asObservable() .filterNil() .map { bidDetails in return bidDetails.saleArtwork?.artwork } .take(1) artwork .subscribe(onNext: { [weak self] artwork in if let url = artwork?.defaultImage?.thumbnailURL() { self?.bidDetails?.setImage(url, self!.artworkImageView) } else { self?.artworkImageView.image = nil } }) .disposed(by: rx.disposeBag) artwork .map { artwork in return artwork?.artists?.first?.name } .map { name in return name ?? "" } .bind(to: artistNameLabel.rx.text) .disposed(by: rx.disposeBag) artwork .map { artwork -> NSAttributedString in guard let artwork = artwork else { return NSAttributedString() } return artwork.titleAndDate } .mapToOptional() .bind(to: artworkTitleLabel.rx.attributedText) .disposed(by: rx.disposeBag) _bidDetails .asObservable() .filterNil() .take(1) .map { bidDetails in guard let cents = bidDetails.bidAmountCents.value else { return "" } guard let currencySymbol = bidDetails.saleArtwork?.currencySymbol else { return "" } return "Your bid: " + centsToPresentableDollarsString(cents.currencyValue, currencySymbol: currencySymbol) } .bind(to: currentBidPriceLabel.rx.text) .disposed(by: rx.disposeBag) for subview in [artworkImageView, artistNameLabel, artworkTitleLabel, currentBidPriceLabel] { self.addSubview(subview) } self.constrainHeight("60") artworkImageView.alignTop("0", leading: "0", bottom: "0", trailing: nil, to: self) artworkImageView.constrainWidth("84") artworkImageView.constrainHeight("60") artistNameLabel.alignAttribute(.top, to: .top, of: self, predicate: "0") artistNameLabel.constrainHeight("16") artworkTitleLabel.alignAttribute(.top, to: .bottom, of: artistNameLabel, predicate: "8") artworkTitleLabel.constrainHeight("16") currentBidPriceLabel.alignAttribute(.top, to: .bottom, of: artworkTitleLabel, predicate: "4") currentBidPriceLabel.constrainHeight("16") UIView.alignAttribute(.leading, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], to:.trailing, ofViews: [artworkImageView, artworkImageView, artworkImageView], predicate: "20") UIView.alignAttribute(.trailing, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], to:.trailing, ofViews: [self, self, self], predicate: "0") } }
mit
jensmeder/DarkLightning
Tests/Daemon/AttachMessageSpec.swift
1
562
// // AttachMessageSpec.swift // DarkLightning // // Created by Jens Meder on 16.05.17. // // import XCTest @testable import DarkLightning class AttachMessageSpec: XCTestCase { func test_GIVEN_AttachMessageWithValidPList_WHEN_decode_THEN_shouldInsertDevice() { let cache = Memory<[Int : Data]>(initialValue: [:]) AttachMessage( plist: [ "MessageType": "Attached", "DeviceID": 0, "Properties": [:] ], devices: MemoryDevices( devices: cache ) ).decode() XCTAssertNotNil(cache.rawValue[0]) } }
mit
eneko/MyFramework.swift
MyFramework/MyFrameworkiOSTests/MyFrameworkiOSTests.swift
1
1003
// // MyFrameworkiOSTests.swift // MyFrameworkiOSTests // // Created by Eneko Alonso on 2/5/16. // Copyright © 2016 Eneko Alonso. All rights reserved. // import XCTest @testable import MyFrameworkiOS class MyFrameworkiOSTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
googlearchive/science-journal-ios
ScienceJournal/SensorData/GetSensorDataAsProtoOperation.swift
1
2860
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import third_party_sciencejournal_ios_ScienceJournalProtos enum SensorDataExportError: Error { /// Error fetching sensor data from the database. Associated data are the trial ID and sensor ID. case failedToFetchDatabaseSensorData(String, String) /// The sensor dumps recieved by dependent operations doesn't match the expected count. case invalidSensorDumpCount /// Error converting the sensor data proto into data. case errorGettingDataFromProto /// Error saving the data to disk. case errorSavingDataToDisk } /// An operation that assembles sensor data dumps into a GSJScalarSensorData proto. This operation /// requires one or more `GetTrialSensorDumpOperation`s as dependencies which provide the /// GSJScalarSensorDataDump protos for GSJScalarSensorData. class GetSensorDataAsProtoOperation: GSJOperation { private let expectedSensorsCount: Int private let saveFileURL: URL /// Designated initializer. /// /// - Parameters: /// - saveFileURL: The file url where the proto should be saved. /// - expectedSensorsCount: The expected number of sensor dumps created by dependencies. /// Used for error checking. init(saveFileURL: URL, expectedSensorsCount: Int) { self.saveFileURL = saveFileURL self.expectedSensorsCount = expectedSensorsCount } override func execute() { let sensors = dependencies.compactMap { ($0 as? GetTrialSensorDumpOperation)?.dump } // Verify the number of sensors equals the number we expected. guard sensors.count == expectedSensorsCount else { finish(withErrors: [SensorDataExportError.invalidSensorDumpCount]) return } // Don't save a proto unless there is at least one recording. guard sensors.count > 0 else { finish() return } let sensorData = GSJScalarSensorData() sensorData.sensorsArray = NSMutableArray(array: sensors) guard let data = sensorData.data() else { finish(withErrors: [SensorDataExportError.errorGettingDataFromProto]) return } do { try data.write(to: saveFileURL) } catch { finish(withErrors: [SensorDataExportError.errorSavingDataToDisk]) return } finish() } }
apache-2.0
Fitbit/RxBluetoothKit
Source/Array+Utils.swift
2
279
import Foundation extension Array where Element: Equatable { @discardableResult mutating func remove(object: Element) -> Bool { if let index = firstIndex(of: object) { self.remove(at: index) return true } return false } }
apache-2.0
RoverPlatform/rover-ios
Sources/Foundation/Meta.swift
1
224
// // Meta.swift // // // Created by Andrew Clunis on 2021-09-30. // Copyright © 2021 Rover Labs Inc. All rights reserved. // import Foundation public enum Meta { public static let SDKVersion: String = "4.0.0" }
apache-2.0
ldt25290/MyInstaMap
MyInstaMap/InstagramHelper.swift
1
1533
// // InstagramHelper.swift // MyMapBook // // Created by User on 8/30/17. // Copyright © 2017 User. All rights reserved. // import Foundation import UIKit class InstagramHelper: NSObject { var webView: UIWebView? func getAccessTokenFromWebView() { self.webView = UIWebView(frame: CGRect.init(origin: CGPoint.init(x: 0, y: 0) , size: CGSize.init(width: 200, height: 200))) guard let myWebView = self.webView else { return } myWebView.delegate = self let url = NSURL (string: "http://www.instagram.com/oauth/authorize/?client_id=7179d974f29d414d8f596b8d0cff796c&redirect_uri=http://localhost&response_type=token&scope=basic") let requestObj = NSURLRequest(url: url! as URL) myWebView.loadRequest(requestObj as URLRequest) } deinit { print("deinit InstagramHelper") } } extension InstagramHelper: UIWebViewDelegate { public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { print("1.2. shouldStartLoadWith request ", request.url?.absoluteString ?? "") return true; } public func webViewDidStartLoad(_ webView: UIWebView) { print(webView) } public func webViewDidFinishLoad(_ webView: UIWebView) { print(webView) } public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { print(error) } }
mit
trungp/MulticastDelegate
MulticastDelegate/MulticastDelegate.swift
1
3670
// // MulticastCallback.swift // MulticastDelegate // // Created by TrungP1 on 4/7/16. // Copyright © 2016 TrungP1. All rights reserved. // /** * It provides a way for multiple delegates to be called, each on its own delegate queue. * There are some versions for Objective-C on github. And this is the version for Swift. */ import Foundation // Operator to compare two weakNodes func ==(lhs: WeakNode, rhs: WeakNode) -> Bool { return lhs.callback === rhs.callback } infix operator ~> {} // Operator to perform closure on delegate func ~> <T> (inout left: MulticastDelegate<T>?, right: ((T) -> Void)?) { if let left = left, right = right { left.performClosure(right) } } infix operator += {} // Operator to add delegate to multicast object func += <T> (inout left: MulticastDelegate<T>?, right: T?) { if let left = left, right = right { left.addCallback(right) } } func += <T> (inout left: MulticastDelegate<T>?, right: (T?, dispatch_queue_t?)?) { if let left = left, right = right { left.addCallback(right.0, queue: right.1) } } // Operator to remove delegate from multicast object func -= <T> (inout left: MulticastDelegate<T>?, right: T?) { if let left = left, right = right { left.removeCallback(right) } } // This class provide the way to perform selector or notify to multiple object. // Basically, it works like observer pattern, send message to all observer which registered with the multicast object. // The multicast object hold the observer inside as weak storage so make sure you are not lose the object without any reason. public class MulticastDelegate<T>: NSObject { private var nodes: [WeakNode]? public override init() { super.init() nodes = [WeakNode]() } /** Ask to know number of nodes or delegates are in multicast object whhich are ready to perform selector. - Returns Int: Number of delegates in multicast object. */ public func numberOfNodes() -> Int { return nodes?.count ?? 0 } /** Add callback to perform selector on later. - Parameter callback: The callback to perform selector in the future. - Parameter queue: The queue to perform the callback on. Default is main queue */ public func addCallback(callback: T?, queue: dispatch_queue_t? = nil) { // Default is main queue let queue: dispatch_queue_t = { guard let q = queue else { return dispatch_get_main_queue() } return q }() if var nodes = nodes, let callback = callback { let node = WeakNode(callback as? AnyObject, queue: queue) nodes.append(node) self.nodes = nodes } } public func removeCallback(callback: T?) { if let nodes = nodes, let cb1 = callback as? AnyObject { self.nodes = nodes.filter { node in if let cb = node.callback where cb === cb1 { return false } return true } } } func performClosure(closure: ((T) -> Void)?) { if let nodes = nodes, closure = closure { nodes.forEach { node in if let cb = node.callback as? T { let queue: dispatch_queue_t = { guard let q = node.queue else { return dispatch_get_main_queue() } return q }() dispatch_async(queue, { closure(cb) }) } } } } }
mit
pokitdok/pokitdok-swift
pokitdok/PokitdokRequest.swift
1
8835
// // PokitdokRequest.swift // pokitdok // // Copyright (C) 2016, All Rights Reserved, PokitDok, Inc. // https://www.pokitdok.com // // Please see the License.txt file for more information. // All other rights reserved. // import Foundation public class PokitdokRequest: NSObject { /* Class to facilitate a single HTTP request and the resulting response Capable of packaging and transmitting all necessary parameters of the request and translating a JSON response back from the server :VAR requestObject: URLRequest type object used to hold all request transmission information :VAR responseObject: PokitdokResponse type object used to hold response information */ var requestObject: URLRequest var responseObject: PokitdokResponse public init(path: String, method: String = "GET", headers: Dictionary<String, String>? = nil, params: Dictionary<String, Any>? = nil, files: Array<FileData>? = nil) throws { /* Initialize requestObject variables :PARAM path: String type url path for request :PARAM method: String type http method for request, defaulted to "GET" :PARAM headers: [String:String] type key:value headers for request :PARAM params: [String:Any] type key:value parameters for request :PARAM files: Array(FileData) type array of file information to accompany request */ requestObject = URLRequest(url: NSURL(string: path)! as URL) responseObject = PokitdokResponse() super.init() requestObject.httpMethod = method buildRequestHeaders(headers: headers) try buildRequestBody(params: params, files: files) } public func call() throws -> PokitdokResponse { /* Send the request off and return result :RETURNS responseObject: PokitdokResponse type holding all the response information */ let sema = DispatchSemaphore( value: 0 ) URLSession.shared.dataTask(with: requestObject, completionHandler: { (data, response, error) -> Void in self.responseObject.response = response self.responseObject.data = data self.responseObject.error = error if let response = response as? HTTPURLResponse { self.responseObject.status = response.statusCode if 200...299 ~= response.statusCode { self.responseObject.success = true } else if 401 ~= response.statusCode { self.responseObject.message = "TOKEN_EXPIRED" } } sema.signal() // signal request is complete }).resume() sema.wait() // wait for request to complete if let data = responseObject.data { do { responseObject.json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? Dictionary<String, Any> } catch { throw DataConversionError.FromJSON("Failed to parse JSON from data") } } return responseObject } private func buildRequestHeaders(headers: Dictionary<String, String>? = nil){ /* Set the header values on the requestObject :PARAM headers: [String:Any] type key:value headers for the request */ if let headers = headers { for (key, value) in headers { setHeader(key: key, value: value) } } } private func buildRequestBody(params: Dictionary<String, Any>? = nil, files: Array<FileData>? = nil) throws -> Void { /* Create the data body of the request and set it on the requestObject :PARAM params: [String:Any] type key:value parameters to be sent with request :PARAM files: Array(FileData) type array of file information to be sent with request */ var body = Data() if let files = files { let boundary = "Boundary-\(UUID().uuidString)" setHeader(key: "Content-Type", value: "multipart/form-data; boundary=\(boundary)") if let params = params { for (key, value) in params { body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)\r\n".data(using: .utf8)!) } } for file in files { body.append("--\(boundary)\r\n".data(using: .utf8)!) try body.append(file.httpEncode()) } body.append("--\(boundary)--\r\n".data(using: .utf8)!) } else { if let params = params { if getMethod() == "GET" { setPath(path: "\(getPath())?\(buildParamString(params: params))") } else { let contentType = getHeader(key: "Content-Type") if contentType == "application/json" { do { body = try JSONSerialization.data(withJSONObject: params, options: []) } catch { throw DataConversionError.ToJSON("Failed to convert params to JSON") } } else if contentType == "application/x-www-form-urlencoded" { body = buildParamString(params: params).data(using: .utf8)! } } } } setBody(data: body) } private func buildParamString(params: Dictionary<String, Any>) -> String { /* Create a url safe parameter string based on a dictionary of key:values :PARAM params: [String:Any] type to be encoded to query string :RETURNS paramString: String type query string ex(key=val&key2=val2) */ var pcs = [String]() for (key, value) in params { var valStr = "" if let value = value as? String { valStr = value } else if let value = value as? Dictionary<String, Any> { // could use some work here valStr = buildParamString(params: value) } else if let value = value as? Array<String> { // could use some work here valStr = value.joined(separator: ",") } let escapedKey = key.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) let escapedValue = valStr.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) pcs.append("\(escapedKey ?? "")=\(escapedValue ?? "")") } return pcs.joined(separator: "&") } public func getHeader(key: String) -> String? { /* Enables user to manipulate headers from outside the class return the header at the key from the requestObject :PARAM key: String type header name :RETURNS value: String? type value at header name */ return requestObject.value(forHTTPHeaderField: key) } public func setHeader(key: String, value: String){ /* Enables user to manipulate headers from outside the class set the header to the key: value pair :PARAM key: String type header name :PARAM value: String type header value */ requestObject.setValue(value, forHTTPHeaderField: key) } public func getMethod() -> String? { /* getter for httpMethod of requestObject :RETURNS httpMethod: String? type http method */ return requestObject.httpMethod } public func setMethod(method: String){ /* setter for httpMethod of requestObject :PARAM method: String type http method, ex("GET", "POST", etc.) */ requestObject.httpMethod = method } public func getPath() -> String { /* getter for url of requestObject :RETURNS url: String type url path of requestObject */ return (requestObject.url?.absoluteString)! } public func setPath(path: String){ /* setter for url of requestObject :PARAM path: String type to be wrapped by URL and passed to requestObject */ requestObject.url = NSURL(string: path)! as URL } public func getBody() -> Data?{ /* getter for httpBody of the requestObject :RETURNS httpBody: Data? type returned from httpBody */ return requestObject.httpBody } public func setBody(data: Data?){ /* setter for httpBody of the requestObject :PARAM data: Data? type to be sent into httpBody */ requestObject.httpBody = data } }
mit
ZulwiyozaPutra/Alien-Adventure-Tutorial
Alien Adventure/BoostItemValue.swift
1
690
// // BoostItemValue.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func boostItemValue(inventory: [UDItem]) -> [UDItem] { let boostedInventory = inventory.map { (item) -> UDItem in var boostedItem = item boostedItem.baseValue += 100 return boostedItem } return boostedInventory } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 4"
mit
dbart01/Spyder
Spyder Tests/JWT/JWT.KeyTests.swift
1
797
// // JWT.KeyTests.swift // Spyder Tests // // Created by Dima Bart on 2018-02-06. // Copyright © 2018 Dima Bart. All rights reserved. // import XCTest class JWT_KeyTests: XCTestCase { func testValues() { XCTAssertEqual(JWT.Key.alg.rawValue, "alg") XCTAssertEqual(JWT.Key.kid.rawValue, "kid") XCTAssertEqual(JWT.Key.cty.rawValue, "cty") XCTAssertEqual(JWT.Key.typ.rawValue, "typ") XCTAssertEqual(JWT.Key.iss.rawValue, "iss") XCTAssertEqual(JWT.Key.sub.rawValue, "sub") XCTAssertEqual(JWT.Key.aud.rawValue, "aud") XCTAssertEqual(JWT.Key.exp.rawValue, "exp") XCTAssertEqual(JWT.Key.nbf.rawValue, "nbf") XCTAssertEqual(JWT.Key.iat.rawValue, "iat") XCTAssertEqual(JWT.Key.jti.rawValue, "jti") } }
bsd-2-clause
justinhester/hacking-with-swift
src/Project37/Project37 WatchKit Extension/ExtensionDelegate.swift
1
1028
// // ExtensionDelegate.swift // Project37 WatchKit Extension // // Created by Justin Lawrence Hester on 2/26/16. // Copyright © 2016 Justin Lawrence Hester. All rights reserved. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { // 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 applicationWillResignActive() { // 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, etc. } }
gpl-3.0
jmont/tutorial-TableViewFooter
TableViewFooterExample/TableViewFooter.swift
1
2547
// // TableViewFooter.swift // TableViewFooterExample // // Created by Montemayor Elosua, Juan Carlos on 7/14/15. // Copyright (c) 2015 jmont. All rights reserved. // import UIKit class TableViewFooter: UIView { let titleLabel : UILabel override init(frame: CGRect) { self.titleLabel = UILabel() super.init(frame: frame) self.setupTitleLabel(self.titleLabel) } required init(coder aDecoder: NSCoder) { self.titleLabel = UILabel() super.init(coder: aDecoder) self.setupTitleLabel(self.titleLabel) } func setupTitleLabel(label: UILabel) { label.numberOfLines = 0 label.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(label) self.addConstraint(NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 20.0)) self.addConstraint(NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -20.0)) self.addConstraint(NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: -20.0)) self.addConstraint(NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 20.0)) } override func layoutSubviews() { super.layoutSubviews() // Don't forget to set `preferredMaxLayoutWidth` so that multiline labels work self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame) super.layoutSubviews() } } extension UITableView { /// @note MUST be called in UITableViewController's `-viewDidLayoutSubviews` func layoutFooterView(footerView: TableViewFooter) { // Since AutoLayout doesn't play well with UITableView.tableFooterView, we have to calculate the size, and then set the frame of the tableFooterView. let calculatedHeight = footerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height let tableViewFooterFrame = CGRectMake(0, 0, CGRectGetWidth(self.frame), calculatedHeight) if self.tableFooterView != footerView || !CGSizeEqualToSize(tableViewFooterFrame.size, footerView.frame.size) { footerView.frame = tableViewFooterFrame footerView.setNeedsLayout() footerView.layoutIfNeeded() self.tableFooterView = footerView } } }
mit
stripe/stripe-ios
StripeCore/StripeCoreTestUtils/XCTestCase+Stripe.swift
1
1682
// // XCTestCase+Stripe.swift // StripeCoreTestUtils // // Created by Mel Ludowise on 11/3/21. // import XCTest extension XCTestCase { public func expectation<Object, Value: Equatable>( for object: Object, keyPath: KeyPath<Object, Value>, equalsToValue value: Value, description: String? = nil ) -> KeyPathExpectation { return KeyPathExpectation( object: object, keyPath: keyPath, equalsToValue: value, description: description ) } public func expectation<Object, Value: Equatable>( for object: Object, keyPath: KeyPath<Object, Value>, notEqualsToValue value: Value, description: String? = nil ) -> KeyPathExpectation { return KeyPathExpectation( object: object, keyPath: keyPath, notEqualsToValue: value, description: description ) } public func notNullExpectation<Object, Value>( for object: Object, keyPath: KeyPath<Object, Value?>, description: String? = nil ) -> KeyPathExpectation { let description = description ?? "Expect predicate `\(keyPath)` != nil for \(String(describing: object))" return KeyPathExpectation( object: object, keyPath: keyPath, evaluatedWith: { $0 != nil }, description: description ) } } public func XCTAssertIs<T>( _ item: Any, _ t: T.Type, file: StaticString = #filePath, line: UInt = #line ) { XCTAssert(item is T, "\(type(of: item)) is not type \(T.self)", file: file, line: line) }
mit
Havi4/Proposer
Proposer/Proposer.swift
7
6290
// // Proposer.swift // Lady // // Created by NIX on 15/7/11. // Copyright (c) 2015年 nixWork. All rights reserved. // import Foundation import AVFoundation import Photos import AddressBook import CoreLocation public enum PrivateResource { case Photos case Camera case Microphone case Contacts public enum LocationUsage { case WhenInUse case Always } case Location(LocationUsage) public var isNotDeterminedAuthorization: Bool { switch self { case .Photos: return PHPhotoLibrary.authorizationStatus() == .NotDetermined case .Camera: return AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == .NotDetermined case .Microphone: return AVAudioSession.sharedInstance().recordPermission() == .Undetermined case .Contacts: return ABAddressBookGetAuthorizationStatus() == .NotDetermined case .Location: return CLLocationManager.authorizationStatus() == .NotDetermined } } } public typealias Propose = () -> Void public typealias ProposerAction = () -> Void public func proposeToAccess(resource: PrivateResource, agreed successAction: ProposerAction, rejected failureAction: ProposerAction) { switch resource { case .Photos: proposeToAccessPhotos(agreed: successAction, rejected: failureAction) case .Camera: proposeToAccessCamera(agreed: successAction, rejected: failureAction) case .Microphone: proposeToAccessMicrophone(agreed: successAction, rejected: failureAction) case .Contacts: proposeToAccessContacts(agreed: successAction, rejected: failureAction) case .Location(let usage): proposeToAccessLocation(usage, agreed: successAction, rejected: failureAction) } } private func proposeToAccessPhotos(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) { PHPhotoLibrary.requestAuthorization { status in dispatch_async(dispatch_get_main_queue()) { switch status { case .Authorized: successAction() default: failureAction() } } } } private func proposeToAccessCamera(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) { granted in dispatch_async(dispatch_get_main_queue()) { granted ? successAction() : failureAction() } } } private func proposeToAccessMicrophone(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) { AVAudioSession.sharedInstance().requestRecordPermission { granted in dispatch_async(dispatch_get_main_queue()) { granted ? successAction() : failureAction() } } } private func proposeToAccessContacts(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) { switch ABAddressBookGetAuthorizationStatus() { case .Authorized: successAction() case .NotDetermined: if let addressBook: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil)?.takeRetainedValue() { ABAddressBookRequestAccessWithCompletion(addressBook, { granted, error in dispatch_async(dispatch_get_main_queue()) { if granted { successAction() } else { failureAction() } } }) } default: failureAction() } } private var _locationManager: CLLocationManager? // as strong ref private func proposeToAccessLocation(locationUsage: PrivateResource.LocationUsage, agreed successAction: ProposerAction, rejected failureAction: ProposerAction) { switch CLLocationManager.authorizationStatus() { case .AuthorizedWhenInUse: if locationUsage == .WhenInUse { successAction() } else { failureAction() } case .AuthorizedAlways: successAction() case .NotDetermined: if CLLocationManager.locationServicesEnabled() { let locationManager = CLLocationManager() _locationManager = locationManager let delegate = LocationDelegate(locationUsage: locationUsage, successAction: successAction, failureAction: failureAction) _locationDelegate = delegate locationManager.delegate = delegate switch locationUsage { case .WhenInUse: locationManager.requestWhenInUseAuthorization() case .Always: locationManager.requestAlwaysAuthorization() } locationManager.startUpdatingLocation() } else { failureAction() } default: failureAction() } } // MARK: LocationDelegate private var _locationDelegate: LocationDelegate? // as strong ref class LocationDelegate: NSObject, CLLocationManagerDelegate { let locationUsage: PrivateResource.LocationUsage let successAction: ProposerAction let failureAction: ProposerAction init(locationUsage: PrivateResource.LocationUsage, successAction: ProposerAction, failureAction: ProposerAction) { self.locationUsage = locationUsage self.successAction = successAction self.failureAction = failureAction } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { dispatch_async(dispatch_get_main_queue()) { switch status { case .AuthorizedWhenInUse: self.locationUsage == .WhenInUse ? self.successAction() : self.failureAction() _locationManager = nil _locationDelegate = nil case .AuthorizedAlways: self.locationUsage == .Always ? self.successAction() : self.failureAction() _locationManager = nil _locationDelegate = nil case .Denied: self.failureAction() _locationManager = nil _locationDelegate = nil default: break } } } }
mit
stripe/stripe-ios
Example/Basic Integration/Basic Integration/Buttons.swift
1
2340
// // Buttons.swift // Basic Integration // // Created by Ben Guo on 4/25/16. // Copyright © 2016 Stripe. All rights reserved. // import Stripe import UIKit class HighlightingButton: UIButton { var highlightColor = UIColor(white: 0, alpha: 0.05) convenience init(highlightColor: UIColor) { self.init() self.highlightColor = highlightColor } override var isHighlighted: Bool { didSet { if isHighlighted { self.backgroundColor = self.highlightColor } else { self.backgroundColor = .clear } } } } class BuyButton: UIButton { static let defaultHeight = CGFloat(52) static let defaultFont = UIFont.boldSystemFont(ofSize: 20) var disabledColor = UIColor.lightGray var enabledColor = UIColor.stripeBrightGreen override var isEnabled: Bool { didSet { let color = isEnabled ? enabledColor : disabledColor setTitleColor(.white, for: UIControl.State()) backgroundColor = color } } init(enabled: Bool, title: String) { super.init(frame: .zero) // Shadow layer.cornerRadius = 8 layer.shadowOpacity = 0.10 layer.shadowColor = UIColor.black.cgColor layer.shadowRadius = 7 layer.shadowOffset = CGSize(width: 0, height: 7) setTitle(title, for: UIControl.State()) titleLabel!.font = type(of: self).defaultFont isEnabled = enabled } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class BrowseBuyButton: BuyButton { let priceLabel = UILabel() init(enabled: Bool) { super.init(enabled: enabled, title: "Buy Now") priceLabel.textColor = .white addSubview(priceLabel) priceLabel.translatesAutoresizingMaskIntoConstraints = false priceLabel.font = type(of: self).defaultFont priceLabel.textAlignment = .right NSLayoutConstraint.activate([ priceLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), priceLabel.centerYAnchor.constraint(equalTo: centerYAnchor), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ming1016/smck
smck/main.swift
1
264
// // main.swift // smck // // Created by daiming on 2017/3/11. // Copyright © 2017年 Starming. All rights reserved. // import Foundation let checker = Checker() if CommandLine.argc < 2 { checker.interactiveModel() } else { checker.staticMode() }
apache-2.0
LucianoPAlmeida/SwifterSwift
Tests/SwiftStdlibTests/CollectionExtensionsTests.swift
2
583
// // CollectionExtensionsTests.swift // SwifterSwift // // Created by Omar Albeik on 09/02/2017. // Copyright © 2017 SwifterSwift // import XCTest @testable import SwifterSwift final class CollectionExtensionsTests: XCTestCase { func testForEachInParallel() { let collection = [1, 2, 3, 4, 5] collection.forEachInParallel { item in XCTAssert(collection.contains(item)) } } func testSafeSubscript() { let collection = [1, 2, 3, 4, 5] XCTAssertNotNil(collection[safe: 2]) XCTAssertEqual(collection[safe: 2], 3) XCTAssertNil(collection[safe: 10]) } }
mit
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/Common/Operations/Generators/Oscillators/triangleWave.swift
3
845
// // triangleWave.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation extension AKOperation { /// Bandlimited triangleoscillator This is a bandlimited triangle oscillator /// ported from the "triangle" function from the Faust programming language. /// /// - returns: AKOperation /// - parameter frequency: In cycles per second, or Hz. (Default: 440, Minimum: 0.0, Maximum: 20000.0) /// - parameter amplitude: Output Amplitude. (Default: 0.5, Minimum: 0.0, Maximum: 1.0) /// public static func triangleWave( frequency frequency: AKParameter = 440, amplitude: AKParameter = 0.5 ) -> AKOperation { return AKOperation("(\(frequency) \(amplitude) bltriangle)") } }
apache-2.0
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/ReactiveCocoaTestsConfiguration.swift
6
287
import Quick #if os(iOS) || os(tvOS) import UIKit #endif class ReactiveCocoaTestsConfiguration: QuickConfiguration { override class func configure(_ configuration: Configuration) { #if os(iOS) || os(tvOS) configuration.beforeSuite { UIControl._initialize() } #endif } }
gpl-3.0
ben-ng/swift
validation-test/compiler_crashers_fixed/01521-getselftypeforcontainer.swift
1
630
// 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 class B<T: a func g: c<S { let start = [0) -> (i: b: T> T where H) { } protocol C { return self] = { public class A { } } enum a((start, AnyObject.Type) -> { } let foo as String) typealias d: B<d>(n: B return S<(t: S(" class func b
apache-2.0
swiftde/29-NSBundleJSONSearchBar
Namensverzeichnis-Tutorial/Namensverzeichnis-TutorialTests/Namensverzeichnis_TutorialTests.swift
2
966
// // Namensverzeichnis_TutorialTests.swift // Namensverzeichnis-TutorialTests // // Created by Benjamin Herzog on 19.10.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit import XCTest class Namensverzeichnis_TutorialTests: 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. } } }
gpl-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/12388-swift-typebase-getcanonicaltype.swift
11
250
// 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 { protocol B { typealias b: b } let a { { } let a { let a { func a { let
mit
cnoon/swift-compiler-crashes
crashes-duplicates/03981-swift-sourcemanager-getmessage.swift
11
2461
// 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 A { func g<T> typealias e : c, class func g let f = { var d = { func g class c, case c<d where g: NSObject { func i() { class a<T { class c<T { class a<T where g: BooleanType, A { let t: Int -> (" return "[Void{ } } struct A { return " } class a { println(f: NSObject { println() -> U) func f: a { typealias e == [1) func i(" func g func a<T>: T>: T>: e == { case c<T where g let f = " } } return " println(""\(f: e : a { protocol P { func g func a<T: a { class b: NSObject { } case c, case c, class a { case c, func g<T> struct A { let t: T> class protocol A { let t: a { protocol A : C { func g<T> class typealias e == { protocol A { protocol A { class func f: C { struct Q<T where T : b } case c<T: P println(f: a { class c, typealias e : e case c, } protocol A { { var d = [1) class a struct Q<T { class return " class func a func f: C { func a struct Q<T : BooleanType, A { func g let t: Int -> () -> () { let i: C { protocol A { protocol P { let t: b: BooleanType, A { class c<T where T : e == "" struct Q<T { func f: NSObject { class typealias e : c { let f = ""\() { func g<T where T : NSObject { typealias e : e protocol A { } protocol A { protocol A { typealias e : a { return " } class b var d = [Void{ typealias e : b: T> println(" protocol P { typealias e == { func f: c, func i: NSObject { } case c<T where g<T : T: C { case c, class c<T where g typealias e : C { protocol A : e : e { return "\(" let i: Int -> () -> () -> U)))" let i(""\() { { var d where T : Int -> U) } } class typealias e { } func f: e println(f: a { func i() { class a { protocol P { println() -> ("[Void{ protocol A { func g: c { class func f: e == [Void{ var d where T : c { typealias e : b: a { func g: NSObject { func a<T where g protocol A : T> let t: a { case c, let f = " class a { let f = [1)) struct Q<T : a { let f = "\() -> U) func i() -> U)"[1) class func g<T where g { func f: a { println(f: a { class b class func g: a { typealias e : e : T> class case c, return "[Void{ class typealias e { struct S<T : a { var d where T : a { let i: e class b: a { protocol A { } func i: Int -> U)" case c, func g: b: C { { typealias e : e return " return " class c, class a<T : a { protocol A { } class a<T>: e { { func i(f: C { protocol A { protocol P { case c, class func f: c<T: BooleanType, A
mit
codefellows/sea-b19-ios
Projects/Week2Day1ImageDownload/urldemo/ViewController.swift
1
1483
// // ViewController.swift // urldemo // // Created by Bradley Johnson on 7/28/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageVIew: UIImageView! 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. } @IBOutlet weak var downloadImage: UIButton! @IBAction func download(sender: AnyObject) { //setup url var url = NSURL(string: "http://blogimages.thescore.com/nfl/files/2014/02/russell-Wilson-again.jpg") var myQueue = NSOperationQueue() myQueue.maxConcurrentOperationCount = 1 myQueue.addOperationWithBlock( {() -> Void in var data = NSData(contentsOfURL: url) NSOperationQueue.mainQueue().addOperationWithBlock( {() -> Void in var myImage = UIImage(data: data) self.imageVIew.image = myImage }) }) var imageOperation = NSOperation() var blockOperation = NSBlockOperation({() -> Void in //do something }) myQueue.addOperation(blockOperation) } }
gpl-2.0