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
brennanMKE/StravaKit
Sources/Activity.swift
2
7540
// // Activity.swift // StravaKit // // Created by Brennan Stehling on 8/22/16. // Copyright © 2016 SmallSharpTools LLC. All rights reserved. // import Foundation import CoreLocation /** Model Representation of an activity. */ public struct Activity { public let activityId: Int public let externalId: String public let uploadId: Int public let athleteId: Int public let athleteResourceState: Int public let name: String public let distance: Float public let movingTime: Int public let elapsedTime: Int public let totalElevationGain: Float public let type: String public let timezone: String public let startCoordinates: [CLLocationDegrees] public let endCoordinates: [CLLocationDegrees] public let city: String public let state: String public let country: String public let achievementCount: Int public let kudosCount: Int public let commentCount: Int public let athleteCount: Int public let photoCount: Int public let map: Map public let trainer: Bool public let commute: Bool public let manual: Bool public let privateActivity: Bool public let flagged: Bool public let gearId: Int? public let averageSpeed: Float public let maxSpeed: Float public let deviceWatts: Bool public let hasHeartrate: Bool public let elevationHigh: Float public let elevationLow: Float public let totalPhotoCount: Int public let hasKudoed: Bool internal let startDateString: String internal let startDateLocalString: String public let averageWatts: Float? public let weightedAverageWatts: Float? public let kilojoules: Float? public let workoutType: Int? /** Failable initializer. */ init?(dictionary: JSONDictionary) { if let s = JSONSupport(dictionary: dictionary), let activityId: Int = s.value("id"), let externalId: String = s.value("external_id"), let uploadId: Int = s.value("upload_id"), let athleteDictionary: JSONDictionary = s.value("athlete"), let a = JSONSupport(dictionary: athleteDictionary), let athleteId: Int = a.value("id"), let athleteResourceState: Int = a.value("resource_state"), let name: String = s.value("name"), let distance: Float = s.value("distance"), let movingTime: Int = s.value("moving_time"), let elapsedTime: Int = s.value("elapsed_time"), let totalElevationGain: Float = s.value("total_elevation_gain"), let type: String = s.value("type"), let startDate: String = s.value("start_date"), let startDateLocal: String = s.value("start_date_local"), let timezone: String = s.value("timezone"), let startCoordinates: [CLLocationDegrees] = s.value("start_latlng"), startCoordinates.count == 2, let endCoordinates: [CLLocationDegrees] = s.value("end_latlng"), endCoordinates.count == 2, let city: String = s.value("location_city"), let state: String = s.value("location_state"), let country: String = s.value("location_country"), let achievementCount: Int = s.value("achievement_count"), let kudosCount: Int = s.value("kudos_count"), let commentCount: Int = s.value("comment_count"), let athleteCount: Int = s.value("athlete_count"), let photoCount: Int = s.value("photo_count"), let mapDictionary: JSONDictionary = s.value("map"), let map = Map(dictionary: mapDictionary), let trainer: Bool = s.value("trainer"), let commute: Bool = s.value("commute"), let manual: Bool = s.value("manual"), let privateActivity: Bool = s.value("private"), let flagged: Bool = s.value("flagged"), let averageSpeed: Float = s.value("average_speed"), let maxSpeed: Float = s.value("max_speed"), let deviceWatts: Bool = s.value("device_watts"), let hasHeartrate: Bool = s.value("has_heartrate"), let elevationHigh: Float = s.value("elev_high"), let elevationLow: Float = s.value("elev_low"), let totalPhotoCount: Int = s.value("total_photo_count"), let hasKudoed: Bool = s.value("has_kudoed") { self.activityId = activityId self.externalId = externalId self.uploadId = uploadId self.athleteId = athleteId self.athleteResourceState = athleteResourceState self.name = name self.distance = distance self.movingTime = movingTime self.elapsedTime = elapsedTime self.totalElevationGain = totalElevationGain self.type = type self.startDateString = startDate self.startDateLocalString = startDateLocal self.timezone = timezone self.startCoordinates = startCoordinates self.endCoordinates = endCoordinates self.city = city self.state = state self.country = country self.achievementCount = achievementCount self.kudosCount = kudosCount self.commentCount = commentCount self.athleteCount = athleteCount self.photoCount = photoCount self.map = map self.trainer = trainer self.commute = commute self.manual = manual self.privateActivity = privateActivity self.flagged = flagged self.averageSpeed = averageSpeed self.maxSpeed = maxSpeed self.deviceWatts = deviceWatts self.hasHeartrate = hasHeartrate self.elevationHigh = elevationHigh self.elevationLow = elevationLow self.totalPhotoCount = totalPhotoCount self.hasKudoed = hasKudoed // Optional Properties self.gearId = s.value("gear_id", required: false) self.averageWatts = s.value("average_watts", required: false) self.weightedAverageWatts = s.value("weighted_average_watts", required: false) self.kilojoules = s.value("kilojoules", required: false) self.workoutType = s.value("workout_type", required: false) } else { return nil } } public static func activities(_ dictionaries: [JSONDictionary]) -> [Activity]? { let activities = dictionaries.flatMap { (d) in return Activity(dictionary: d) } return activities.count > 0 ? activities : nil } public var startCoordinate: CLLocationCoordinate2D { guard let latitude = startCoordinates.first, let longitude = startCoordinates.last else { return kCLLocationCoordinate2DInvalid } return CLLocationCoordinate2DMake(latitude, longitude) } public var endCoordinate: CLLocationCoordinate2D { guard let latitude = endCoordinates.first, let longitude = endCoordinates.last else { return kCLLocationCoordinate2DInvalid } return CLLocationCoordinate2DMake(latitude, longitude) } public var startDate: Date? { return Strava.dateFromString(startDateString) } public var startDateLocal: Date? { return Strava.dateFromString(startDateLocalString) } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/25877-firsttarget.swift
11
428
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class c{ init{ struct A{class case,
apache-2.0
timd/SwiftTable
SwiftTableTests/SwiftTableTests.swift
1
903
// // SwiftTableTests.swift // SwiftTableTests // // Created by Tim on 20/07/14. // Copyright (c) 2014 Charismatic Megafauna Ltd. All rights reserved. // import XCTest class SwiftTableTests: 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. } } }
mit
lokinfey/MyPerfectframework
Examples/Ultimate Noughts and Crosses/GameState.swift
1
2695
// // GameState.swift // Ultimate Noughts and Crosses // // Created by Kyle Jessup on 2015-10-28. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // // X,Y // Across, Down // _________________ // | 0,0 | 1,0 | 2,0 | // | 0,1 | 1,1 | 2,1 | // | 0,2 | 1,2 | 2,2 | // ----------------- let INVALID_ID = -1 let MAX_X = 8 let MAX_Y = 8 enum PieceType: Int { case None = 0, Oh = 1, Ex = 2, OhWin = 3, ExWin = 4 } class Player { let nick: String let gameId: Int let type: PieceType init(nick: String, gameId: Int, type: PieceType) { self.nick = nick self.gameId = gameId self.type = type } } class Board: CustomStringConvertible { typealias IndexType = (Int, Int) var slots: [[PieceType]] = [[.None, .None, .None], [.None, .None, .None], [.None, .None, .None]] var owner: PieceType = .None init() {} subscript(index: IndexType) -> PieceType { get { return self.slots[index.0][index.1] } set(newValue) { self.slots[index.0][index.1] = newValue } } var description: String { var s = "" for y in 0..<3 { if y != 0 { s.appendContentsOf("\n") } for x in 0..<3 { let curr = self[(x, y)] switch curr { case .Ex: s.appendContentsOf("X") case .Oh: s.appendContentsOf("O") default: s.appendContentsOf("_") } } } return s } } class Field: CustomStringConvertible { typealias IndexType = (Int, Int) var boards: [[Board]] = [[Board(), Board(), Board()], [Board(), Board(), Board()], [Board(), Board(), Board()]] init() {} subscript(index: IndexType) -> Board { get { return self.boards[index.0][index.1] } set(newValue) { self.boards[index.0][index.1] = newValue } } var description: String { var s = "" for y in 0..<3 { if y != 0 { s.appendContentsOf("\n\n") } let b0 = self[(0, y)].description.characters.split("\n") let b1 = self[(1, y)].description.characters.split("\n") let b2 = self[(2, y)].description.characters.split("\n") for x in 0..<3 { if x != 0 { s.appendContentsOf("\n") } s.appendContentsOf(b0[x]) s.appendContentsOf(" ") s.appendContentsOf(b1[x]) s.appendContentsOf(" ") s.appendContentsOf(b2[x]) } } return s } } class GameState { }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/05148-swift-sourcemanager-getmessage.swift
11
350
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing : a { var e(Any) { protocol e : T where g: A? { { func g: a { var d where g: d where T: a { var d = a(Any) { for () { class c : T: T.h() { func j>(v: a { class case c, protocol A :
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/03850-swift-parser-skipsingle.swift
11
289
// 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 a<T>: b { func a case c, { func c, let end = [[Void{ { class case c, { [[[[[[Void{ deinit { { Void{ { { { { { case
mit
Shashikant86/XCFit
XCFit-Demo/XCFit-Demo/AppDelegate.swift
1
2189
// // AppDelegate.swift // XCFit-Demo // // Created by Shashikant Jagtap on 29/04/2018. // Copyright © 2018 Shashikant Jagtap. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/2174-swift-modulefile-lookupvalue.swift
13
321
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func g<Int) { enum b { convenience init(f.Type) { struct c](self.Type func b) + seq: Int = T) -> T? { c()
apache-2.0
mightydeveloper/swift
test/Serialization/Inputs/def_transparent.swift
10
1625
@_transparent public func testTransparent(x x: Bool) -> Bool { return x } @_transparent public func testBuiltin() -> Int32 { var y: Int32 = 300; var z = "foo" return y } @_transparent public func standalone_function(x x: Int32, y: Int32) -> Int32 { return x } @_transparent public func curried_function(x x: Int32)(y: Int32) -> Int32 { return standalone_function(x: x, y: y) } @_transparent public func calls(i i: Int32, j: Int32) { var f1 = curried_function(x: i) f1(y: j); } public func foo() -> Int32 { return 0 } public func runced() -> Bool { return true } public func a() {} public func b() {} public func c() {} public func d() {} public func e() {} @_transparent public func test_br() { switch foo() { case _ where runced(): a() case _: b() } c() } public enum MaybePair { case Neither case Left(Int32) case Right(String) case Both(Int32, String) } public func do_switch(u u: MaybePair) { switch u { case .Neither: a() case .Left: b() case .Right: c() case .Both: d() } e() } public struct Wrapper { public var value: Int32 @_transparent public init(Val: Int32) { value = Val } @_transparent public func getValue() -> Int32 { return value } public var valueAgain: Int32 { @_transparent get { return value } } } @_transparent public extension Wrapper { func getValueAgain() -> Int32 { return self.value } } public protocol P { func f() -> Self } public protocol CP : class { func f() -> Self } @_transparent public func open_existentials(p p: P, cp: CP) { p.f() cp.f() }
apache-2.0
Prince2k3/TableViewDataSource
Example Projects/Example Project Swift/Example Project Swift/TableViewDataSource.swift
1
9555
import UIKit @objc(MSTableViewCellDataSource) public protocol TableViewCellDataSource: class { @objc(configureDataForCell:) func configure(_ data: Any?) } @objc(MSTableViewDataSourceDelegate) public protocol TableViewDataSourceDelegate: class { @objc(dataSource:didConfigureCellAtIndexPath:) func didConfigureCell(_ cell: TableViewCellDataSource, atIndexPath indexPath: IndexPath) @objc(dataSource:commitEditingStyleForIndexPath:) optional func commitEditingStyle(_ editingStyle: UITableViewCellEditingStyle, forIndexPath indexPath: IndexPath) } @objc(MSTableViewDataSourceCellItem) open class TableViewDataSourceCellItem: NSObject { open var cellIdentifier: String? open var item: Any? open var cellHeight: CGFloat? } @objc(MSTableViewDataSource) open class TableViewDataSource: NSObject, UITableViewDataSource { internal var cellItems: [TableViewDataSourceCellItem]? internal(set) var cellIdentifier: String? open var items: [Any]? open var title: String? open weak var delegate: TableViewDataSourceDelegate? open var sectionHeaderView: UIView? open var reusableHeaderFooterViewIdentifier: String? open var editable: Bool = false open var movable: Bool = false open var editableCells: [IndexPath: UITableViewCellEditingStyle]? // NSNumber represents the UITableViewCellEditingStyle open var movableCells: [IndexPath]? override init() { super.init() } public convenience init(cellItems: [TableViewDataSourceCellItem]) { self.init() self.cellItems = cellItems } public convenience init(cellIdentifier: String, items: [Any]? = nil) { self.init() self.cellIdentifier = cellIdentifier self.items = items } //MARK: - @objc(itemAtIndexPath:) open func item(at indexPath: IndexPath) -> Any? { if let items = self.items , items.count > 0 && indexPath.row < items.count { return items[indexPath.row] } return nil } @objc(cellItemAtIndexPath:) open func cellItem(at indexPath: IndexPath) -> TableViewDataSourceCellItem? { if let cellItems = self.cellItems , cellItems.count > 0 && indexPath.row < cellItems.count { return cellItems[indexPath.row] } return nil } //MARK: - UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return 1 } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let cellItems = self.cellItems { return cellItems.count } if let items = self.items { return items.count } return 0 } open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { if self.movable { if let movableCells = movableCells { return movableCells.contains(indexPath) } } return false } open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if self.editable { if let editableCells = editableCells { return editableCells.keys.contains(indexPath) } } return false } open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { self.delegate?.commitEditingStyle?(editingStyle, forIndexPath: indexPath) } open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { if let item = items?[sourceIndexPath.row] { self.items?.remove(at: sourceIndexPath.row) self.items?.insert(item, at: destinationIndexPath.row) } } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var identifier: String? var item: Any? if let cellItems = cellItems , cellItems.count > 0 { let cellItem = self.cellItem(at: indexPath)! identifier = cellItem.cellIdentifier item = cellItem.item } else { item = self.item(at: indexPath) identifier = cellIdentifier } let cell = tableView.dequeueReusableCell(withIdentifier: identifier!, for: indexPath) if cell is TableViewCellDataSource { let sourceCell = cell as! TableViewCellDataSource sourceCell.configure(item) delegate?.didConfigureCell(sourceCell, atIndexPath: indexPath) } return cell } } @objc(MSTableViewSectionDataSource) open class TableViewSectionDataSource: NSObject, UITableViewDataSource { open weak var delegate: TableViewDataSourceDelegate? open fileprivate(set) var dataSources: [TableViewDataSource]? open var enableIndexing: Bool = false open var showDefaultHeaderTitle: Bool = true public convenience init(dataSources: [TableViewDataSource]) { self.init() self.dataSources = dataSources } @objc(itemAtIndexPath:) open func item(at indexPath: IndexPath) -> Any? { let dataSource = self.dataSources![indexPath.section] return dataSource.item(at: indexPath) } @objc(cellItemAtIndexPath:) open func cellItem(at indexPath: IndexPath) -> TableViewDataSourceCellItem? { let dataSource = self.dataSources![indexPath.section] return dataSource.cellItem(at: indexPath) } @objc(dataSourceAtIndexPath:) open func dataSource(at indexPath: IndexPath) -> TableViewDataSource { return self.dataSources![indexPath.section] } @objc(titleAtIndexPath:) open func title(at indexPath: IndexPath) -> String? { let dataSource = self.dataSources![indexPath.section] return dataSource.title } @objc(sectionHeaderViewAtIndexPath:) open func sectionHeaderView(at indexPath: IndexPath) -> UIView? { let dataSource = self.dataSources![indexPath.section] return dataSource.sectionHeaderView } //MARK: - UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { if let dataSources = self.dataSources { return dataSources.count } return 1 } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let dataSources = self.dataSources { let dataSource = dataSources[section] return dataSource.tableView(tableView, numberOfRowsInSection: section) } return 0 } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dataSource = self.dataSources![indexPath.section] return dataSource.tableView(tableView, cellForRowAt: indexPath) } open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { let dataSource = self.dataSources![indexPath.section] return dataSource.tableView(tableView, canMoveRowAt: indexPath) } open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let dataSource = self.dataSources![indexPath.section] return dataSource.tableView(tableView, canEditRowAt: indexPath) } open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { self.delegate?.commitEditingStyle?(editingStyle, forIndexPath: indexPath) } open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { if var sourceItems = self.dataSource(at: sourceIndexPath).items, var destinationItems = self.dataSource(at: destinationIndexPath).items { let item = sourceItems.remove(at: sourceIndexPath.row) destinationItems.insert(item, at: destinationIndexPath.row) self.dataSources?[sourceIndexPath.section].items = sourceItems self.dataSources?[destinationIndexPath.section].items = destinationItems } } //MARK - Indexing open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if self.showDefaultHeaderTitle { if let dataSources = self.dataSources { let dataSource = dataSources[section] return dataSource.title } return nil } if !self.enableIndexing { return nil } let numberOfRows = self.tableView(tableView, numberOfRowsInSection: section) if numberOfRows == 0 { return nil } return UILocalizedIndexedCollation.current().sectionTitles[section] } open func sectionIndexTitles(for tableView: UITableView) -> [String]? { if !self.enableIndexing { return nil } return UILocalizedIndexedCollation.current().sectionTitles } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return UILocalizedIndexedCollation.current().section(forSectionIndexTitle: index) } }
mit
mightydeveloper/swift
validation-test/compiler_crashers/27216-swift-typebase-getcanonicaltype.swift
9
279
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import a}struct Q<H{let:{class d<T enum S<T where H.h=l
apache-2.0
ymkim50/MFImageSlider
Example/Tests/Tests.swift
1
763
import UIKit import XCTest import MFImageSlider class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
weissmar/CharacterSheet
iOS_Files/characterSheet/Character.swift
1
819
// // Character.swift // characterSheet // // Created by Rachel Weissman-Hohler on 8/12/16. // Copyright © 2016 Rachel Weissman-Hohler. All rights reserved. // import UIKit class Character { // MARK: Properties var name: String var id: String var XP: Int? var IQ: Int? var STR: Int? var DEX: Int? var charImage: UIImage? var inventory: [Item]? // Mark: Initializer init?(name: String, id: String, XP: Int?, IQ: Int?, STR: Int?, DEX: Int?) { // initialize properties to passed-in values self.name = name self.id = id self.XP = XP self.IQ = IQ self.STR = STR self.DEX = DEX // check for empty name and empty id if name.isEmpty || id.isEmpty { return nil } } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/20611-no-stacktrace.swift
11
243
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d { ( [ ] var { extension NSData { func b { protocol A { class case ,
mit
CaptainTeemo/Saffron
Saffron/GifToVideo.swift
1
6707
// // GifToVideo.swift // Saffron // // Created by CaptainTeemo on 7/17/16. // Copyright © 2016 Captain Teemo. All rights reserved. // import Foundation import AVFoundation public final class GifToVideo: NSObject { fileprivate let gifQueue = DispatchQueue(label: "com.saffron.gifToVideo", attributes: DispatchQueue.Attributes.concurrent) fileprivate static let instance = GifToVideo() fileprivate var done: ((String) -> Void)? /** Convert gif image to video. - parameter gifImage: A UIImage contains gif data. - parameter saveToLibrary: Save to library or not. - parameter done: Callback with video path when convert finished. */ public class func convert(_ gifImage: UIImage, saveToLibrary: Bool = true, done: ((String) -> Void)? = nil) throws { try instance.convertToVideo(gifImage, saveToLibrary: saveToLibrary, done: done) } fileprivate func convertToVideo(_ gifImage: UIImage, saveToLibrary: Bool = true, done: ((String) -> Void)? = nil) throws { guard let data = gifImage.gifData else { throw Error.error(-100, description: "Gif data is nil.") } self.done = done let (frames, duration) = UIImage.animatedFrames(data) let tempPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/temp.mp4" if FileManager.default.fileExists(atPath: tempPath) { try FileManager.default.removeItem(atPath: tempPath) } let writer = try AVAssetWriter(outputURL: URL(fileURLWithPath: tempPath), fileType: AVFileTypeQuickTimeMovie) let settings: [String: AnyObject] = [AVVideoCodecKey: AVVideoCodecH264 as AnyObject, AVVideoWidthKey: gifImage.size.width as AnyObject, AVVideoHeightKey: gifImage.size.height as AnyObject] let input = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: settings) guard writer.canAdd(input) else { fatalError("cannot add input") } writer.add(input) let sourceBufferAttributes: [String : AnyObject] = [ kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_32ARGB) as AnyObject, kCVPixelBufferWidthKey as String : gifImage.size.width as AnyObject, kCVPixelBufferHeightKey as String : gifImage.size.height as AnyObject] let pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: sourceBufferAttributes) writer.startWriting() writer.startSession(atSourceTime: kCMTimeZero) let fps = Int32(Double(frames.count) / duration) let frameDuration = CMTimeMake(1, fps) var frameCount = 0 input.requestMediaDataWhenReady(on: gifQueue, using: { while input.isReadyForMoreMediaData && frameCount < frames.count { let lastFrameTime = CMTimeMake(Int64(frameCount), fps) let presentationTime = frameCount == 0 ? lastFrameTime : CMTimeAdd(lastFrameTime, frameDuration) let image = frames[frameCount] do { try self.appendPixelBuffer(image, adaptor: pixelBufferAdaptor, presentationTime: presentationTime) } catch let error as NSError { fatalError(error.localizedDescription) } frameCount += 1 } if (frameCount >= frames.count) { input.markAsFinished() writer.finishWriting { dispatchOnMain { if (writer.error != nil) { print("Error converting images to video: \(writer.error)") } else { if saveToLibrary { UISaveVideoAtPathToSavedPhotosAlbum(tempPath, self, #selector(self.video), nil) } else { done?(tempPath) } } } } } }) } fileprivate func appendPixelBuffer(_ image: UIImage, adaptor: AVAssetWriterInputPixelBufferAdaptor, presentationTime: CMTime) throws { if let pixelBufferPool = adaptor.pixelBufferPool { let pixelBufferPointer = UnsafeMutablePointer<CVPixelBuffer?>.allocate(capacity: 1) let status: CVReturn = CVPixelBufferPoolCreatePixelBuffer( kCFAllocatorDefault, pixelBufferPool, pixelBufferPointer ) if let pixelBuffer = pixelBufferPointer.pointee, status == 0 { CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() // Create CGBitmapContext let context = CGContext( data: pixelData, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue ) // Draw image into context if let cgImage = image.cgImage { context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) } CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))) adaptor.append(pixelBuffer, withPresentationTime: presentationTime) pixelBufferPointer.deinitialize() } else { throw Error.error(-100, description: "Error: Failed to allocate pixel buffer from pool.") } pixelBufferPointer.deallocate(capacity: 1) } } // - (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; @objc fileprivate func video(_ videoPath: String, didFinishSavingWithError: NSError, contextInfo: UnsafeMutableRawPointer) { done?(videoPath) } }
mit
peaks-cc/iOS11_samplecode
chapter_12/HomeKitSample/App/Code/Lib/HomeKitUtils/HMEventTriggerActivationState+Description.swift
1
585
// // HMEventTriggerActivationState+Description.swift // // Created by ToKoRo on 2017-09-04. // import HomeKit extension HMEventTriggerActivationState: CustomStringConvertible { public var description: String { switch self { case .disabled: return "disabled" case .disabledNoCompatibleHomeHub: return "disabledNoCompatibleHomeHub" case .disabledNoHomeHub: return "disabledNoHomeHub" case .disabledNoLocationServicesAuthorization: return "disabledNoLocationServicesAuthorization" case .enabled: return "enabled" } } }
mit
grpc/grpc-swift
Sources/GRPC/Interceptor/ClientTransport.swift
1
34432
/* * Copyright 2020, gRPC Authors 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 Logging import NIOCore import NIOHPACK import NIOHTTP2 /// This class is the glue between a `NIO.Channel` and the `ClientInterceptorPipeline`. In fact /// this object owns the interceptor pipeline and is also a `ChannelHandler`. The caller has very /// little API to use on this class: they may configure the transport by adding it to a /// `NIO.ChannelPipeline` with `configure(_:)`, send request parts via `send(_:promise:)` and /// attempt to cancel the RPC with `cancel(promise:)`. Response parts – after traversing the /// interceptor pipeline – are emitted to the `onResponsePart` callback supplied to the initializer. /// /// In most instances the glue code is simple: transformations are applied to the request and /// response types used by the interceptor pipeline and the `NIO.Channel`. In addition, the /// transport keeps track of the state of the call and the `Channel`, taking appropriate action /// when these change. This includes buffering request parts from the interceptor pipeline until /// the `NIO.Channel` becomes active. /// /// ### Thread Safety /// /// This class is not thread safe. All methods **must** be executed on the transport's `callEventLoop`. @usableFromInline internal final class ClientTransport<Request, Response> { /// The `EventLoop` the call is running on. State must be accessed from this event loop. @usableFromInline internal let callEventLoop: EventLoop /// The current state of the transport. private var state: ClientTransportState = .idle /// A promise for the underlying `Channel`. We'll succeed this when we transition to `active` /// and fail it when we transition to `closed`. private var channelPromise: EventLoopPromise<Channel>? // Note: initial capacity is 4 because it's a power of 2 and most calls are unary so will // have 3 parts. /// A buffer to store request parts and promises in before the channel has become active. private var writeBuffer = MarkedCircularBuffer<RequestAndPromise>(initialCapacity: 4) /// The request serializer. private let serializer: AnySerializer<Request> /// The response deserializer. private let deserializer: AnyDeserializer<Response> /// A request part and a promise. private struct RequestAndPromise { var request: GRPCClientRequestPart<Request> var promise: EventLoopPromise<Void>? } /// Details about the call. internal let callDetails: CallDetails /// A logger. internal var logger: GRPCLogger /// Is the call streaming requests? private var isStreamingRequests: Bool { switch self.callDetails.type { case .unary, .serverStreaming: return false case .clientStreaming, .bidirectionalStreaming: return true } } // Our `NIO.Channel` will fire trailers and the `GRPCStatus` to us separately. It's more // convenient to have both at the same time when intercepting response parts. We'll hold on to the // trailers here and only forward them when we receive the status. private var trailers: HPACKHeaders? /// The interceptor pipeline connected to this transport. The pipeline also holds references /// to `self` which are dropped when the interceptor pipeline is closed. @usableFromInline internal var _pipeline: ClientInterceptorPipeline<Request, Response>? /// The `NIO.Channel` used by the transport, if it is available. private var channel: Channel? /// A callback which is invoked once when the stream channel becomes active. private let onStart: () -> Void /// Our current state as logging metadata. private var stateForLogging: Logger.MetadataValue { if self.state.mayBuffer { return "\(self.state) (\(self.writeBuffer.count) parts buffered)" } else { return "\(self.state)" } } internal init( details: CallDetails, eventLoop: EventLoop, interceptors: [ClientInterceptor<Request, Response>], serializer: AnySerializer<Request>, deserializer: AnyDeserializer<Response>, errorDelegate: ClientErrorDelegate?, onStart: @escaping () -> Void, onError: @escaping (Error) -> Void, onResponsePart: @escaping (GRPCClientResponsePart<Response>) -> Void ) { self.callEventLoop = eventLoop self.callDetails = details self.onStart = onStart let logger = GRPCLogger(wrapping: details.options.logger) self.logger = logger self.serializer = serializer self.deserializer = deserializer // The references to self held by the pipeline are dropped when it is closed. self._pipeline = ClientInterceptorPipeline( eventLoop: eventLoop, details: details, logger: logger, interceptors: interceptors, errorDelegate: errorDelegate, onError: onError, onCancel: self.cancelFromPipeline(promise:), onRequestPart: self.sendFromPipeline(_:promise:), onResponsePart: onResponsePart ) } // MARK: - Call Object API /// Configure the transport to communicate with the server. /// - Parameter configurator: A callback to invoke in order to configure this transport. /// - Important: This *must* to be called from the `callEventLoop`. internal func configure(_ configurator: @escaping (ChannelHandler) -> EventLoopFuture<Void>) { self.callEventLoop.assertInEventLoop() if self.state.configureTransport() { self.configure(using: configurator) } } /// Send a request part – via the interceptor pipeline – to the server. /// - Parameters: /// - part: The part to send. /// - promise: A promise which will be completed when the request part has been handled. /// - Important: This *must* to be called from the `callEventLoop`. @inlinable internal func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?) { self.callEventLoop.assertInEventLoop() if let pipeline = self._pipeline { pipeline.send(part, promise: promise) } else { promise?.fail(GRPCError.AlreadyComplete()) } } /// Attempt to cancel the RPC notifying any interceptors. /// - Parameter promise: A promise which will be completed when the cancellation attempt has /// been handled. internal func cancel(promise: EventLoopPromise<Void>?) { self.callEventLoop.assertInEventLoop() if let pipeline = self._pipeline { pipeline.cancel(promise: promise) } else { promise?.fail(GRPCError.AlreadyComplete()) } } /// A request for the underlying `Channel`. internal func getChannel() -> EventLoopFuture<Channel> { self.callEventLoop.assertInEventLoop() // Do we already have a promise? if let promise = self.channelPromise { return promise.futureResult } else { // Make and store the promise. let promise = self.callEventLoop.makePromise(of: Channel.self) self.channelPromise = promise // Ask the state machine if we can have it. switch self.state.getChannel() { case .succeed: if let channel = self.channel { promise.succeed(channel) } case .fail: promise.fail(GRPCError.AlreadyComplete()) case .doNothing: () } return promise.futureResult } } } // MARK: - Pipeline API extension ClientTransport { /// Sends a request part on the transport. Should only be called from the interceptor pipeline. /// - Parameters: /// - part: The request part to send. /// - promise: A promise which will be completed when the part has been handled. /// - Important: This *must* to be called from the `callEventLoop`. private func sendFromPipeline( _ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>? ) { self.callEventLoop.assertInEventLoop() switch self.state.send() { case .writeToBuffer: self.buffer(part, promise: promise) case .writeToChannel: // Banging the channel is okay here: we'll only be told to 'writeToChannel' if we're in the // correct state, the requirements of that state are having an active `Channel`. self.writeToChannel( self.channel!, part: part, promise: promise, flush: self.shouldFlush(after: part) ) case .alreadyComplete: promise?.fail(GRPCError.AlreadyComplete()) } } /// Attempt to cancel the RPC. Should only be called from the interceptor pipeline. /// - Parameter promise: A promise which will be completed when the cancellation has been handled. /// - Important: This *must* to be called from the `callEventLoop`. private func cancelFromPipeline(promise: EventLoopPromise<Void>?) { self.callEventLoop.assertInEventLoop() if self.state.cancel() { let error = GRPCError.RPCCancelledByClient() let status = error.makeGRPCStatus() self.forwardToInterceptors(.end(status, [:])) self.failBufferedWrites(with: error) self.channel?.close(mode: .all, promise: nil) self.channelPromise?.fail(error) promise?.succeed(()) } else { promise?.succeed(()) } } } // MARK: - ChannelHandler API extension ClientTransport: ChannelInboundHandler { @usableFromInline typealias InboundIn = _RawGRPCClientResponsePart @usableFromInline typealias OutboundOut = _RawGRPCClientRequestPart @usableFromInline internal func handlerRemoved(context: ChannelHandlerContext) { self.dropReferences() } @usableFromInline internal func handlerAdded(context: ChannelHandlerContext) { if context.channel.isActive { self.transportActivated(channel: context.channel) } } @usableFromInline internal func errorCaught(context: ChannelHandlerContext, error: Error) { self.handleError(error) } @usableFromInline internal func channelActive(context: ChannelHandlerContext) { self.transportActivated(channel: context.channel) } @usableFromInline internal func channelInactive(context: ChannelHandlerContext) { self.transportDeactivated() } @usableFromInline internal func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch self.unwrapInboundIn(data) { case let .initialMetadata(headers): self.receiveFromChannel(initialMetadata: headers) case let .message(box): self.receiveFromChannel(message: box.message) case let .trailingMetadata(trailers): self.receiveFromChannel(trailingMetadata: trailers) case let .status(status): self.receiveFromChannel(status: status) } // (We're the end of the channel. No need to forward anything.) } } extension ClientTransport { /// The `Channel` became active. Send out any buffered requests. private func transportActivated(channel: Channel) { if self.callEventLoop.inEventLoop { self._transportActivated(channel: channel) } else { self.callEventLoop.execute { self._transportActivated(channel: channel) } } } /// On-loop implementation of `transportActivated(channel:)`. private func _transportActivated(channel: Channel) { self.callEventLoop.assertInEventLoop() switch self.state.activate() { case .unbuffer: self.logger.addIPAddressMetadata(local: channel.localAddress, remote: channel.remoteAddress) self._pipeline?.logger = self.logger self.logger.debug("activated stream channel") self.channel = channel self.onStart() self.unbuffer() case .close: channel.close(mode: .all, promise: nil) case .doNothing: () } } /// The `Channel` became inactive. Fail any buffered writes and forward an error to the /// interceptor pipeline if necessary. private func transportDeactivated() { if self.callEventLoop.inEventLoop { self._transportDeactivated() } else { self.callEventLoop.execute { self._transportDeactivated() } } } /// On-loop implementation of `transportDeactivated()`. private func _transportDeactivated() { self.callEventLoop.assertInEventLoop() switch self.state.deactivate() { case .doNothing: () case .tearDown: let status = GRPCStatus(code: .unavailable, message: "Transport became inactive") self.forwardErrorToInterceptors(status) self.failBufferedWrites(with: status) self.channelPromise?.fail(status) case .failChannelPromise: self.channelPromise?.fail(GRPCError.AlreadyComplete()) } } /// Drops any references to the `Channel` and interceptor pipeline. private func dropReferences() { if self.callEventLoop.inEventLoop { self.channel = nil } else { self.callEventLoop.execute { self.channel = nil } } } /// Handles an error caught in the pipeline or from elsewhere. The error may be forwarded to the /// interceptor pipeline and any buffered writes will be failed. Any underlying `Channel` will /// also be closed. internal func handleError(_ error: Error) { if self.callEventLoop.inEventLoop { self._handleError(error) } else { self.callEventLoop.execute { self._handleError(error) } } } /// On-loop implementation of `handleError(_:)`. private func _handleError(_ error: Error) { self.callEventLoop.assertInEventLoop() switch self.state.handleError() { case .doNothing: () case .propagateError: self.forwardErrorToInterceptors(error) self.failBufferedWrites(with: error) case .propagateErrorAndClose: self.forwardErrorToInterceptors(error) self.failBufferedWrites(with: error) self.channel?.close(mode: .all, promise: nil) } } /// Receive initial metadata from the `Channel`. private func receiveFromChannel(initialMetadata headers: HPACKHeaders) { if self.callEventLoop.inEventLoop { self._receiveFromChannel(initialMetadata: headers) } else { self.callEventLoop.execute { self._receiveFromChannel(initialMetadata: headers) } } } /// On-loop implementation of `receiveFromChannel(initialMetadata:)`. private func _receiveFromChannel(initialMetadata headers: HPACKHeaders) { self.callEventLoop.assertInEventLoop() if self.state.channelRead(isEnd: false) { self.forwardToInterceptors(.metadata(headers)) } } /// Receive response message bytes from the `Channel`. private func receiveFromChannel(message buffer: ByteBuffer) { if self.callEventLoop.inEventLoop { self._receiveFromChannel(message: buffer) } else { self.callEventLoop.execute { self._receiveFromChannel(message: buffer) } } } /// On-loop implementation of `receiveFromChannel(message:)`. private func _receiveFromChannel(message buffer: ByteBuffer) { self.callEventLoop.assertInEventLoop() do { let message = try self.deserializer.deserialize(byteBuffer: buffer) if self.state.channelRead(isEnd: false) { self.forwardToInterceptors(.message(message)) } } catch { self.handleError(error) } } /// Receive trailing metadata from the `Channel`. private func receiveFromChannel(trailingMetadata trailers: HPACKHeaders) { // The `Channel` delivers trailers and `GRPCStatus` separately, we want to emit them together // in the interceptor pipeline. if self.callEventLoop.inEventLoop { self.trailers = trailers } else { self.callEventLoop.execute { self.trailers = trailers } } } /// Receive the final status from the `Channel`. private func receiveFromChannel(status: GRPCStatus) { if self.callEventLoop.inEventLoop { self._receiveFromChannel(status: status) } else { self.callEventLoop.execute { self._receiveFromChannel(status: status) } } } /// On-loop implementation of `receiveFromChannel(status:)`. private func _receiveFromChannel(status: GRPCStatus) { self.callEventLoop.assertInEventLoop() if self.state.channelRead(isEnd: true) { self.forwardToInterceptors(.end(status, self.trailers ?? [:])) self.trailers = nil } } } // MARK: - State Handling private enum ClientTransportState { /// Idle. We're waiting for the RPC to be configured. /// /// Valid transitions: /// - `awaitingTransport` (the transport is being configured) /// - `closed` (the RPC cancels) case idle /// Awaiting transport. The RPC has requested transport and we're waiting for that transport to /// activate. We'll buffer any outbound messages from this state. Receiving messages from the /// transport in this state is an error. /// /// Valid transitions: /// - `activatingTransport` (the channel becomes active) /// - `closing` (the RPC cancels) /// - `closed` (the channel fails to become active) case awaitingTransport /// The transport is active but we're unbuffering any requests to write on that transport. /// We'll continue buffering in this state. Receiving messages from the transport in this state /// is okay. /// /// Valid transitions: /// - `active` (we finish unbuffering) /// - `closing` (the RPC cancels, the channel encounters an error) /// - `closed` (the channel becomes inactive) case activatingTransport /// Fully active. An RPC is in progress and is communicating over an active transport. /// /// Valid transitions: /// - `closing` (the RPC cancels, the channel encounters an error) /// - `closed` (the channel becomes inactive) case active /// Closing. Either the RPC was cancelled or any `Channel` associated with the transport hasn't /// become inactive yet. /// /// Valid transitions: /// - `closed` (the channel becomes inactive) case closing /// We're closed. Any writes from the RPC will be failed. Any responses from the transport will /// be ignored. /// /// Valid transitions: /// - none: this state is terminal. case closed /// Whether writes may be unbuffered in this state. internal var isUnbuffering: Bool { switch self { case .activatingTransport: return true case .idle, .awaitingTransport, .active, .closing, .closed: return false } } /// Whether this state allows writes to be buffered. (This is useful only to inform logging.) internal var mayBuffer: Bool { switch self { case .idle, .activatingTransport, .awaitingTransport: return true case .active, .closing, .closed: return false } } } extension ClientTransportState { /// The caller would like to configure the transport. Returns a boolean indicating whether we /// should configure it or not. mutating func configureTransport() -> Bool { switch self { // We're idle until we configure. Anything else is just a repeat request to configure. case .idle: self = .awaitingTransport return true case .awaitingTransport, .activatingTransport, .active, .closing, .closed: return false } } enum SendAction { /// Write the request into the buffer. case writeToBuffer /// Write the request into the channel. case writeToChannel /// The RPC has already completed, fail any promise associated with the write. case alreadyComplete } /// The pipeline would like to send a request part to the transport. mutating func send() -> SendAction { switch self { // We don't have any transport yet, just buffer the part. case .idle, .awaitingTransport, .activatingTransport: return .writeToBuffer // We have a `Channel`, we can pipe the write straight through. case .active: return .writeToChannel // The transport is going or has gone away. Fail the promise. case .closing, .closed: return .alreadyComplete } } enum UnbufferedAction { /// Nothing needs to be done. case doNothing /// Succeed the channel promise associated with the transport. case succeedChannelPromise } /// We finished dealing with the buffered writes. mutating func unbuffered() -> UnbufferedAction { switch self { // These can't happen since we only begin unbuffering when we transition to // '.activatingTransport', which must come after these two states.. case .idle, .awaitingTransport: preconditionFailure("Requests can't be unbuffered before the transport is activated") // We dealt with any buffered writes. We can become active now. This is the only way to become // active. case .activatingTransport: self = .active return .succeedChannelPromise case .active: preconditionFailure("Unbuffering completed but the transport is already active") // Something caused us to close while unbuffering, that's okay, we won't take any further // action. case .closing, .closed: return .doNothing } } /// Cancel the RPC and associated `Channel`, if possible. Returns a boolean indicated whether /// cancellation can go ahead (and also whether the channel should be torn down). mutating func cancel() -> Bool { switch self { case .idle: // No RPC has been started and we don't have a `Channel`. We need to tell the interceptor // we're done, fail any writes, and then deal with the cancellation promise. self = .closed return true case .awaitingTransport: // An RPC has started and we're waiting for the `Channel` to activate. We'll mark ourselves as // closing. We don't need to explicitly close the `Channel`, this will happen as a result of // the `Channel` becoming active (see `channelActive(context:)`). self = .closing return true case .activatingTransport: // The RPC has started, the `Channel` is active and we're emptying our write buffer. We'll // mark ourselves as closing: we'll error the interceptor pipeline, close the channel, fail // any buffered writes and then complete the cancellation promise. self = .closing return true case .active: // The RPC and channel are up and running. We'll fail the RPC and close the channel. self = .closing return true case .closing, .closed: // We're already closing or closing. The cancellation is too late. return false } } enum ActivateAction { case unbuffer case close case doNothing } /// `channelActive` was invoked on the transport by the `Channel`. mutating func activate() -> ActivateAction { // The channel has become active: what now? switch self { case .idle: preconditionFailure("Can't activate an idle transport") case .awaitingTransport: self = .activatingTransport return .unbuffer case .activatingTransport, .active: // Already activated. return .doNothing case .closing: // We remain in closing: we only transition to closed on 'channelInactive'. return .close case .closed: preconditionFailure("Invalid state: stream is already inactive") } } enum ChannelInactiveAction { /// Tear down the transport; forward an error to the interceptors and fail any buffered writes. case tearDown /// Fail the 'Channel' promise, if one exists; the RPC is already complete. case failChannelPromise /// Do nothing. case doNothing } /// `channelInactive` was invoked on the transport by the `Channel`. mutating func deactivate() -> ChannelInactiveAction { switch self { case .idle: // We can't become inactive before we've requested a `Channel`. preconditionFailure("Can't deactivate an idle transport") case .awaitingTransport, .activatingTransport, .active: // We're activating the transport - i.e. offloading any buffered requests - and the channel // became inactive. We haven't received an error (otherwise we'd be `closing`) so we should // synthesize an error status to fail the RPC with. self = .closed return .tearDown case .closing: // We were already closing, now we're fully closed. self = .closed return .failChannelPromise case .closed: // We're already closed. return .doNothing } } /// `channelRead` was invoked on the transport by the `Channel`. Returns a boolean value /// indicating whether the part that was read should be forwarded to the interceptor pipeline. mutating func channelRead(isEnd: Bool) -> Bool { switch self { case .idle, .awaitingTransport: // If there's no `Channel` or the `Channel` isn't active, then we can't read anything. preconditionFailure("Can't receive response part on idle transport") case .activatingTransport, .active: // We have an active `Channel`, we can forward the request part but we may need to start // closing if we see the status, since it indicates the call is terminating. if isEnd { self = .closing } return true case .closing, .closed: // We closed early, ignore any reads. return false } } enum HandleErrorAction { /// Propagate the error to the interceptor pipeline and fail any buffered writes. case propagateError /// As above, but close the 'Channel' as well. case propagateErrorAndClose /// No action is required. case doNothing } /// An error was caught. mutating func handleError() -> HandleErrorAction { switch self { case .idle: // The `Channel` can't error if it doesn't exist. preconditionFailure("Can't catch error on idle transport") case .awaitingTransport: // We're waiting for the `Channel` to become active. We're toast now, so close, failing any // buffered writes along the way. self = .closing return .propagateError case .activatingTransport, .active: // We're either fully active or unbuffering. Forward an error, fail any writes and then close. self = .closing return .propagateErrorAndClose case .closing, .closed: // We're already closing/closed, we can ignore this. return .doNothing } } enum GetChannelAction { /// No action is required. case doNothing /// Succeed the Channel promise. case succeed /// Fail the 'Channel' promise, the RPC is already complete. case fail } /// The caller has asked for the underlying `Channel`. mutating func getChannel() -> GetChannelAction { switch self { case .idle, .awaitingTransport, .activatingTransport: // Do nothing, we'll complete the promise when we become active or closed. return .doNothing case .active: // We're already active, so there was no promise to succeed when we made this transition. We // can complete it now. return .succeed case .closing: // We'll complete the promise when we transition to closed. return .doNothing case .closed: // We're already closed; there was no promise to fail when we made this transition. We can go // ahead and fail it now though. return .fail } } } // MARK: - State Actions extension ClientTransport { /// Configures this transport with the `configurator`. private func configure(using configurator: (ChannelHandler) -> EventLoopFuture<Void>) { configurator(self).whenFailure { error in // We might be on a different EL, but `handleError` will sort that out for us, so no need to // hop. if error is GRPCStatus || error is GRPCStatusTransformable { self.handleError(error) } else { // Fallback to something which will mark the RPC as 'unavailable'. self.handleError(ConnectionFailure(reason: error)) } } } /// Append a request part to the write buffer. /// - Parameters: /// - part: The request part to buffer. /// - promise: A promise to complete when the request part has been sent. private func buffer( _ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>? ) { self.callEventLoop.assertInEventLoop() self.logger.trace("buffering request part", metadata: [ "request_part": "\(part.name)", "call_state": self.stateForLogging, ]) self.writeBuffer.append(.init(request: part, promise: promise)) } /// Writes any buffered request parts to the `Channel`. private func unbuffer() { self.callEventLoop.assertInEventLoop() guard let channel = self.channel else { return } // Save any flushing until we're done writing. var shouldFlush = false self.logger.trace("unbuffering request parts", metadata: [ "request_parts": "\(self.writeBuffer.count)", ]) // Why the double loop? A promise completed as a result of the flush may enqueue more writes, // or causes us to change state (i.e. we may have to close). If we didn't loop around then we // may miss more buffered writes. while self.state.isUnbuffering, !self.writeBuffer.isEmpty { // Pull out as many writes as possible. while let write = self.writeBuffer.popFirst() { self.logger.trace("unbuffering request part", metadata: [ "request_part": "\(write.request.name)", ]) if !shouldFlush { shouldFlush = self.shouldFlush(after: write.request) } self.writeToChannel(channel, part: write.request, promise: write.promise, flush: false) } // Okay, flush now. if shouldFlush { shouldFlush = false channel.flush() } } if self.writeBuffer.isEmpty { self.logger.trace("request buffer drained") } else { self.logger.notice("unbuffering aborted", metadata: ["call_state": self.stateForLogging]) } // We're unbuffered. What now? switch self.state.unbuffered() { case .doNothing: () case .succeedChannelPromise: self.channelPromise?.succeed(channel) } } /// Fails any promises that come with buffered writes with `error`. /// - Parameter error: The `Error` to fail promises with. private func failBufferedWrites(with error: Error) { self.logger.trace("failing buffered writes", metadata: ["call_state": self.stateForLogging]) while let write = self.writeBuffer.popFirst() { write.promise?.fail(error) } } /// Write a request part to the `Channel`. /// - Parameters: /// - channel: The `Channel` to write `part` to. /// - part: The request part to write. /// - promise: A promise to complete once the write has been completed. /// - flush: Whether to flush the `Channel` after writing. private func writeToChannel( _ channel: Channel, part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?, flush: Bool ) { switch part { case let .metadata(headers): let head = self.makeRequestHead(with: headers) channel.write(self.wrapOutboundOut(.head(head)), promise: promise) case let .message(request, metadata): do { let bytes = try self.serializer.serialize(request, allocator: channel.allocator) let message = _MessageContext<ByteBuffer>(bytes, compressed: metadata.compress) channel.write(self.wrapOutboundOut(.message(message)), promise: promise) } catch { self.handleError(error) } case .end: channel.write(self.wrapOutboundOut(.end), promise: promise) } if flush { channel.flush() } } /// Forward the response part to the interceptor pipeline. /// - Parameter part: The response part to forward. private func forwardToInterceptors(_ part: GRPCClientResponsePart<Response>) { self.callEventLoop.assertInEventLoop() self._pipeline?.receive(part) } /// Forward the error to the interceptor pipeline. /// - Parameter error: The error to forward. private func forwardErrorToInterceptors(_ error: Error) { self.callEventLoop.assertInEventLoop() self._pipeline?.errorCaught(error) } } // MARK: - Helpers extension ClientTransport { /// Returns whether the `Channel` should be flushed after writing the given part to it. private func shouldFlush(after part: GRPCClientRequestPart<Request>) -> Bool { switch part { case .metadata: // If we're not streaming requests then we hold off on the flush until we see end. return self.isStreamingRequests case let .message(_, metadata): // Message flushing is determined by caller preference. return metadata.flush case .end: // Always flush at the end of the request stream. return true } } /// Make a `_GRPCRequestHead` with the provided metadata. private func makeRequestHead(with metadata: HPACKHeaders) -> _GRPCRequestHead { return _GRPCRequestHead( method: self.callDetails.options.cacheable ? "GET" : "POST", scheme: self.callDetails.scheme, path: self.callDetails.path, host: self.callDetails.authority, deadline: self.callDetails.options.timeLimit.makeDeadline(), customMetadata: metadata, encoding: self.callDetails.options.messageEncoding ) } } extension GRPCClientRequestPart { /// The name of the request part, used for logging. fileprivate var name: String { switch self { case .metadata: return "metadata" case .message: return "message" case .end: return "end" } } } // A wrapper for connection errors: we need to be able to preserve the underlying error as // well as extract a 'GRPCStatus' with code '.unavailable'. internal struct ConnectionFailure: Error, GRPCStatusTransformable, CustomStringConvertible { /// The reason the connection failed. var reason: Error init(reason: Error) { self.reason = reason } var description: String { return String(describing: self.reason) } func makeGRPCStatus() -> GRPCStatus { return GRPCStatus( code: .unavailable, message: String(describing: self.reason), cause: self.reason ) } }
apache-2.0
grpc/grpc-swift
Sources/GRPC/GRPCChannel/GRPCChannel.swift
1
11890
/* * Copyright 2020, gRPC Authors 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 NIOCore import NIOHTTP2 import SwiftProtobuf public protocol GRPCChannel: GRPCPreconcurrencySendable { /// Makes a gRPC call on the channel with requests and responses conforming to /// `SwiftProtobuf.Message`. /// /// Note: this is a lower-level construct that any of ``UnaryCall``, ``ClientStreamingCall``, /// ``ServerStreamingCall`` or ``BidirectionalStreamingCall`` and does not have an API to protect /// users against protocol violations (such as sending to requests on a unary call). /// /// After making the ``Call``, users must ``Call/invoke(onError:onResponsePart:)`` the call with a callback which is invoked /// for each response part (or error) received. Any call to ``Call/send(_:)`` prior to calling /// ``Call/invoke(onError:onResponsePart:)`` will fail and not be sent. Users are also responsible for closing the request stream /// by sending the `.end` request part. /// /// - Parameters: /// - path: The path of the RPC, e.g. "/echo.Echo/get". /// - type: The type of the RPC, e.g. ``GRPCCallType/unary``. /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. func makeCall<Request: SwiftProtobuf.Message, Response: SwiftProtobuf.Message>( path: String, type: GRPCCallType, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] ) -> Call<Request, Response> /// Makes a gRPC call on the channel with requests and responses conforming to ``GRPCPayload``. /// /// Note: this is a lower-level construct that any of ``UnaryCall``, ``ClientStreamingCall``, /// ``ServerStreamingCall`` or ``BidirectionalStreamingCall`` and does not have an API to protect /// users against protocol violations (such as sending to requests on a unary call). /// /// After making the ``Call``, users must ``Call/invoke(onError:onResponsePart:)`` the call with a callback which is invoked /// for each response part (or error) received. Any call to ``Call/send(_:)`` prior to calling /// ``Call/invoke(onError:onResponsePart:)`` will fail and not be sent. Users are also responsible for closing the request stream /// by sending the `.end` request part. /// /// - Parameters: /// - path: The path of the RPC, e.g. "/echo.Echo/get". /// - type: The type of the RPC, e.g. ``GRPCCallType/unary``. /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. func makeCall<Request: GRPCPayload, Response: GRPCPayload>( path: String, type: GRPCCallType, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] ) -> Call<Request, Response> /// Close the channel, and any connections associated with it. Any ongoing RPCs may fail. /// /// - Returns: Returns a future which will be resolved when shutdown has completed. func close() -> EventLoopFuture<Void> /// Close the channel, and any connections associated with it. Any ongoing RPCs may fail. /// /// - Parameter promise: A promise which will be completed when shutdown has completed. func close(promise: EventLoopPromise<Void>) /// Attempt to gracefully shutdown the channel. New RPCs will be failed immediately and existing /// RPCs may continue to run until they complete. /// /// - Parameters: /// - deadline: A point in time by which the graceful shutdown must have completed. If the /// deadline passes and RPCs are still active then the connection will be closed forcefully /// and any remaining in-flight RPCs may be failed. /// - promise: A promise which will be completed when shutdown has completed. func closeGracefully(deadline: NIODeadline, promise: EventLoopPromise<Void>) } // Default implementations to avoid breaking API. Implementations provided by GRPC override these. extension GRPCChannel { public func close(promise: EventLoopPromise<Void>) { promise.completeWith(self.close()) } public func closeGracefully(deadline: NIODeadline, promise: EventLoopPromise<Void>) { promise.completeWith(self.close()) } } extension GRPCChannel { /// Make a unary gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - request: The request to send. /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. public func makeUnaryCall<Request: Message, Response: Message>( path: String, request: Request, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [] ) -> UnaryCall<Request, Response> { let unary: UnaryCall<Request, Response> = UnaryCall( call: self.makeCall( path: path, type: .unary, callOptions: callOptions, interceptors: interceptors ) ) unary.invoke(request) return unary } /// Make a unary gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - request: The request to send. /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. public func makeUnaryCall<Request: GRPCPayload, Response: GRPCPayload>( path: String, request: Request, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [] ) -> UnaryCall<Request, Response> { let rpc: UnaryCall<Request, Response> = UnaryCall( call: self.makeCall( path: path, type: .unary, callOptions: callOptions, interceptors: interceptors ) ) rpc.invoke(request) return rpc } /// Makes a client-streaming gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. public func makeClientStreamingCall<Request: Message, Response: Message>( path: String, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [] ) -> ClientStreamingCall<Request, Response> { let rpc: ClientStreamingCall<Request, Response> = ClientStreamingCall( call: self.makeCall( path: path, type: .clientStreaming, callOptions: callOptions, interceptors: interceptors ) ) rpc.invoke() return rpc } /// Makes a client-streaming gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. public func makeClientStreamingCall<Request: GRPCPayload, Response: GRPCPayload>( path: String, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [] ) -> ClientStreamingCall<Request, Response> { let rpc: ClientStreamingCall<Request, Response> = ClientStreamingCall( call: self.makeCall( path: path, type: .clientStreaming, callOptions: callOptions, interceptors: interceptors ) ) rpc.invoke() return rpc } /// Make a server-streaming gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - request: The request to send. /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. /// - handler: Response handler; called for every response received from the server. public func makeServerStreamingCall<Request: Message, Response: Message>( path: String, request: Request, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [], handler: @escaping (Response) -> Void ) -> ServerStreamingCall<Request, Response> { let rpc: ServerStreamingCall<Request, Response> = ServerStreamingCall( call: self.makeCall( path: path, type: .serverStreaming, callOptions: callOptions, interceptors: interceptors ), callback: handler ) rpc.invoke(request) return rpc } /// Make a server-streaming gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - request: The request to send. /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. /// - handler: Response handler; called for every response received from the server. public func makeServerStreamingCall<Request: GRPCPayload, Response: GRPCPayload>( path: String, request: Request, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [], handler: @escaping (Response) -> Void ) -> ServerStreamingCall<Request, Response> { let rpc: ServerStreamingCall<Request, Response> = ServerStreamingCall( call: self.makeCall( path: path, type: .serverStreaming, callOptions: callOptions, interceptors: [] ), callback: handler ) rpc.invoke(request) return rpc } /// Makes a bidirectional-streaming gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. /// - handler: Response handler; called for every response received from the server. public func makeBidirectionalStreamingCall<Request: Message, Response: Message>( path: String, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [], handler: @escaping (Response) -> Void ) -> BidirectionalStreamingCall<Request, Response> { let rpc: BidirectionalStreamingCall<Request, Response> = BidirectionalStreamingCall( call: self.makeCall( path: path, type: .bidirectionalStreaming, callOptions: callOptions, interceptors: interceptors ), callback: handler ) rpc.invoke() return rpc } /// Makes a bidirectional-streaming gRPC call. /// /// - Parameters: /// - path: Path of the RPC, e.g. "/echo.Echo/Get" /// - callOptions: Options for the RPC. /// - interceptors: A list of interceptors to intercept the request and response stream with. /// - handler: Response handler; called for every response received from the server. public func makeBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>( path: String, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] = [], handler: @escaping (Response) -> Void ) -> BidirectionalStreamingCall<Request, Response> { let rpc: BidirectionalStreamingCall<Request, Response> = BidirectionalStreamingCall( call: self.makeCall( path: path, type: .bidirectionalStreaming, callOptions: callOptions, interceptors: interceptors ), callback: handler ) rpc.invoke() return rpc } }
apache-2.0
hsoi/RxSwift
RxExample/RxExample/Examples/APIWrappers/APIWrappersViewController.swift
2
6324
// // APIWrappersViewController.swift // RxExample // // Created by Carlos García on 8/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit import CoreLocation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif extension UILabel { public override var accessibilityValue: String! { get { return self.text } set { self.text = newValue self.accessibilityValue = newValue } } } class APIWrappersViewController: ViewController { @IBOutlet weak var debugLabel: UILabel! @IBOutlet weak var openActionSheet: UIButton! @IBOutlet weak var openAlertView: UIButton! @IBOutlet weak var bbitem: UIBarButtonItem! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var switcher: UISwitch! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var button: UIButton! @IBOutlet weak var slider: UISlider! @IBOutlet weak var textField: UITextField! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var mypan: UIPanGestureRecognizer! @IBOutlet weak var textView: UITextView! let manager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() datePicker.date = NSDate(timeIntervalSince1970: 0) let ash = UIActionSheet(title: "Title", delegate: nil, cancelButtonTitle: "Cancel", destructiveButtonTitle: "OK") let av = UIAlertView(title: "Title", message: "The message", delegate: nil, cancelButtonTitle: "Cancel", otherButtonTitles: "OK", "Two", "Three", "Four", "Five") openActionSheet.rx_tap .subscribeNext { [weak self] x in if let view = self?.view { ash.showInView(view) } } .addDisposableTo(disposeBag) openAlertView.rx_tap .subscribeNext { x in av.show() } .addDisposableTo(disposeBag) // MARK: UIActionSheet ash.rx_clickedButtonAtIndex .subscribeNext { [weak self] x in self?.debug("UIActionSheet clickedButtonAtIndex \(x)") } .addDisposableTo(disposeBag) ash.rx_willDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIActionSheet willDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) ash.rx_didDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIActionSheet didDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) // MARK: UIAlertView av.rx_clickedButtonAtIndex .subscribeNext { [weak self] x in self?.debug("UIAlertView clickedButtonAtIndex \(x)") } .addDisposableTo(disposeBag) av.rx_willDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIAlertView willDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) av.rx_didDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIAlertView didDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) // MARK: UIBarButtonItem bbitem.rx_tap .subscribeNext { [weak self] x in self?.debug("UIBarButtonItem Tapped") } .addDisposableTo(disposeBag) // MARK: UISegmentedControl segmentedControl.rx_value .subscribeNext { [weak self] x in self?.debug("UISegmentedControl value \(x)") } .addDisposableTo(disposeBag) // MARK: UISwitch switcher.rx_value .subscribeNext { [weak self] x in self?.debug("UISwitch value \(x)") } .addDisposableTo(disposeBag) // MARK: UIActivityIndicatorView switcher.rx_value .bindTo(activityIndicator.rx_animating) .addDisposableTo(disposeBag) // MARK: UIButton button.rx_tap .subscribeNext { [weak self] x in self?.debug("UIButton Tapped") } .addDisposableTo(disposeBag) // MARK: UISlider slider.rx_value .subscribeNext { [weak self] x in self?.debug("UISlider value \(x)") } .addDisposableTo(disposeBag) // MARK: UIDatePicker datePicker.rx_date .subscribeNext { [weak self] x in self?.debug("UIDatePicker date \(x)") } .addDisposableTo(disposeBag) // MARK: UITextField textField.rx_text .subscribeNext { [weak self] x in self?.debug("UITextField text \(x)") } .addDisposableTo(disposeBag) // MARK: UIGestureRecognizer mypan.rx_event .subscribeNext { [weak self] x in self?.debug("UIGestureRecognizer event \(x.state)") } .addDisposableTo(disposeBag) // MARK: UITextView textView.rx_text .subscribeNext { [weak self] x in self?.debug("UITextView event \(x)") } .addDisposableTo(disposeBag) // MARK: CLLocationManager #if !RX_NO_MODULE manager.requestWhenInUseAuthorization() #endif manager.rx_didUpdateLocations .subscribeNext { [weak self] x in self?.debug("rx_didUpdateLocations \(x)") } .addDisposableTo(disposeBag) _ = manager.rx_didFailWithError .subscribeNext { [weak self] x in self?.debug("rx_didFailWithError \(x)") } manager.rx_didChangeAuthorizationStatus .subscribeNext { status in print("Authorization status \(status)") } .addDisposableTo(disposeBag) manager.startUpdatingLocation() } func debug(string: String) { print(string) debugLabel.text = string } }
mit
an-indya/WorldWatch
WorldWatch WatchKit Extension/InterfaceController.swift
1
2009
// // InterfaceController.swift // AppleWatchDemo WatchKit Extension // // Created by Anindya Sengupta on 24/11/2014. // Copyright (c) 2014 Anindya Sengupta. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet weak var table: WKInterfaceTable! override init(context: AnyObject?) { super.init(context: context) populateTable() } private func populateTable () { var plistKeys: NSDictionary? var timeZones: NSDictionary? if let path = NSBundle.mainBundle().pathForResource("Timezones", ofType: "plist") { plistKeys = NSDictionary(contentsOfFile: path)! timeZones = plistKeys!["TimeZones"] as NSDictionary? } if let dict = timeZones { table.setNumberOfRows(dict.count, withRowType: "LocalTimeRowController") var keyArray = dict.allKeys as [String] func alphabaticalSort(s1: String, s2: String) -> Bool { return s1 < s2 } var sortedCityNamesArray = sorted(keyArray, alphabaticalSort) for (index, key) in enumerate(sortedCityNamesArray) { let row = table.rowControllerAtIndex(index) as LocalTimeRowController row.countryLabel.setText((key as String)) var value: AnyObject? = dict[key as String] row.localTimeLabel.setTimeZone(NSTimeZone(name: value as String)) } } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() NSLog("%@ will activate", self) } override func didDeactivate() { // This method is called when watch view controller is no longer visible NSLog("%@ did deactivate", self) super.didDeactivate() } }
mit
Sajjon/Zeus
Examples/SpotifyAPI/SpotifyAPI/Models/ExternalUrl.swift
1
246
// // ExternalUrl+CoreDataClass.swift // SpotifyAPI // // Created by Cyon Alexander (Ext. Netlight) on 31/08/16. // Copyright © 2016 com.cyon. All rights reserved. // import Foundation import CoreData class ExternalUrl: NSManagedObject {}
apache-2.0
dymx101/Gamers
Pods/Starscream/WebSocket.swift
1
29758
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CoreFoundation public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(socket: WebSocket, text: String) func websocketDidReceiveData(socket: WebSocket, data: NSData) } public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocket) } public class WebSocket : NSObject, NSStreamDelegate { enum OpCode : UInt8 { case ContinueFrame = 0x0 case TextFrame = 0x1 case BinaryFrame = 0x2 //3-7 are reserved. case ConnectionClose = 0x8 case Ping = 0x9 case Pong = 0xA //B-F reserved. } enum CloseCode : UInt16 { case Normal = 1000 case GoingAway = 1001 case ProtocolError = 1002 case ProtocolUnhandledType = 1003 // 1004 reserved. case NoStatusReceived = 1005 //1006 reserved. case Encoding = 1007 case PolicyViolated = 1008 case MessageTooBig = 1009 } enum InternalErrorCode : UInt16 { // 0-999 WebSocket status codes not used case OutputStreamWriteError = 1 } //Where the callback is executed. It defaults to the main UI thread queue. public var queue = dispatch_get_main_queue() var optionalProtocols : Array<String>? //Constant Values. let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 class WSResponse { var isFin = false var code: OpCode = .ContinueFrame var bytesLeft = 0 var frameCount = 0 var buffer: NSMutableData? } public weak var delegate: WebSocketDelegate? public weak var pongDelegate: WebSocketPongDelegate? public var onConnect: ((Void) -> Void)? public var onDisconnect: ((NSError?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((NSData) -> Void)? public var onPong: ((Void) -> Void)? public var headers = Dictionary<String,String>() public var voipEnabled = false public var selfSignedSSL = false public var security: Security? public var isConnected :Bool { return connected } private var url: NSURL private var inputStream: NSInputStream? private var outputStream: NSOutputStream? private var isRunLoop = false private var connected = false private var isCreated = false private var writeQueue: NSOperationQueue? private var readStack = Array<WSResponse>() private var inputQueue = Array<NSData>() private var fragBuffer: NSData? private var certValidated = false private var didDisconnect = false //init the websocket with a url public init(url: NSURL) { self.url = url } //used for setting protocols. public convenience init(url: NSURL, protocols: Array<String>) { self.init(url: url) optionalProtocols = protocols } ///Connect to the websocket server on a background thread public func connect() { if isCreated { return } dispatch_async(queue,{ [weak self] in self?.didDisconnect = false }) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { [weak self] in self?.isCreated = true self?.createHTTPRequest() self?.isCreated = false }) } ///disconnect from the websocket server public func disconnect() { writeError(CloseCode.Normal.rawValue) } ///write a string to the websocket. This sends it as a text frame. public func writeString(str: String) { dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame) } ///write binary data to the websocket. This sends it as a binary frame. public func writeData(data: NSData) { dequeueWrite(data, code: .BinaryFrame) } //write a ping to the websocket. This sends it as a control frame. //yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s public func writePing(data: NSData) { dequeueWrite(data, code: .Ping) } //private methods below! //private method that starts the connection private func createHTTPRequest() { let str: NSString = url.absoluteString! let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET", url, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if url.scheme == "wss" || url.scheme == "https" { port = 443 } else { port = 80 } } self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols)) } self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey()) self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!) self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key,value) in headers { self.addHeader(urlRequest, key: key, val: value) } let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest).takeRetainedValue() self.initStreamsWithData(serializedRequest, Int(port!)) } //Add a header to the CFHTTPMessage by using the NSString bridges to CFString private func addHeader(urlRequest: CFHTTPMessage,key: String, val: String) { let nsKey: NSString = key let nsVal: NSString = val CFHTTPMessageSetHeaderFieldValue(urlRequest, nsKey, nsVal) } //generate a websocket key as needed in rfc private func generateWebSocketKey() -> String { var key = "" let seed = 16 for (var i = 0; i < seed; i++) { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni))" } var data = key.dataUsingEncoding(NSUTF8StringEncoding) var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0)) return baseKey! } //Start the stream connection and write the data to the output stream private func initStreamsWithData(data: NSData, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h: NSString = url.host! CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() inputStream!.delegate = self outputStream!.delegate = self if url.scheme == "wss" || url.scheme == "https" { inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey) outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey) } else { certValidated = true //not a https session, so no need to check SSL pinning } if self.voipEnabled { inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) } if self.selfSignedSSL { let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull] inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as! String) outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as! String) } isRunLoop = true inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream!.open() outputStream!.open() let bytes = UnsafePointer<UInt8>(data.bytes) outputStream!.write(bytes, maxLength: data.length) while(isRunLoop) { NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate) } } //delegate for the stream methods. Processes incoming bytes public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) { if let sec = security where !certValidated && (eventCode == .HasBytesAvailable || eventCode == .HasSpaceAvailable) { var possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as! String) if let trust: AnyObject = possibleTrust { var domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as! String) if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) { certValidated = true } else { let error = self.errorWithDetail("Invalid SSL certificate", code: 1) doDisconnect(error) disconnectStream(error) return } } } if eventCode == .HasBytesAvailable { if(aStream == inputStream) { processInputStream() } } else if eventCode == .ErrorOccurred { disconnectStream(aStream.streamError) } else if eventCode == .EndEncountered { disconnectStream(nil) } } //disconnect the stream object private func disconnectStream(error: NSError?) { if writeQueue != nil { writeQueue!.waitUntilAllOperationsAreFinished() } if let stream = inputStream { stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) stream.close() } if let stream = outputStream { stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) stream.close() } outputStream = nil isRunLoop = false certValidated = false self.doDisconnect(error) connected = false } ///handles the incoming bytes and sending them to the proper processing method private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) if length > 0 { if !connected { let status = processHTTP(buffer, bufferLen: length) if !status { doDisconnect(self.errorWithDetail("Invalid HTTP upgrade", code: 1)) } } else { var process = false if inputQueue.count == 0 { process = true } inputQueue.append(NSData(bytes: buffer, length: length)) if process { dequeueInput() } } } } ///dequeue the incoming input so it is processed in order private func dequeueInput() { if inputQueue.count > 0 { let data = inputQueue[0] var work = data if (fragBuffer != nil) { var combine = NSMutableData(data: fragBuffer!) combine.appendData(data) work = combine fragBuffer = nil } let buffer = UnsafePointer<UInt8>(work.bytes) processRawMessage(buffer, bufferLen: work.length) inputQueue = inputQueue.filter{$0 != data} dequeueInput() } } ///Finds the HTTP Packet in the TCP stream, by looking for the CRLF. private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for var i = 0; i < bufferLen; i++ { if buffer[i] == CRLFBytes[k] { k++ if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { if validateResponse(buffer, bufferLen: totalSize) { dispatch_async(queue,{ [weak self] in self?.connected = true if let connectBlock = self?.onConnect { connectBlock() } if let s = self { s.delegate?.websocketDidConnect(s) } }) totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessage((buffer+totalSize),bufferLen: restSize) } return true } } return false } ///validates the HTTP is a 101 as per the RFC spec private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) if CFHTTPMessageGetResponseStatusCode(response) != 101 { return false } let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) let headers: NSDictionary = cfHeaders.takeRetainedValue() let acceptKey = headers[headerWSAcceptName] as! NSString if acceptKey.length > 0 { return true } return false } ///process the websocket data private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) { var response = readStack.last if response != nil && bufferLen < 2 { fragBuffer = NSData(bytes: buffer, length: bufferLen) return } if response != nil && response!.bytesLeft > 0 { let resp = response! var len = resp.bytesLeft var extra = bufferLen - resp.bytesLeft if resp.bytesLeft > bufferLen { len = bufferLen extra = 0 } resp.bytesLeft -= len resp.buffer?.appendData(NSData(bytes: buffer, length: len)) processResponse(resp) var offset = bufferLen - extra if extra > 0 { processExtra((buffer+offset), bufferLen: extra) } return } else { let isFin = (FinMask & buffer[0]) let receivedOpcode = (OpCodeMask & buffer[0]) let isMasked = (MaskMask & buffer[1]) let payloadLen = (PayloadLenMask & buffer[1]) var offset = 2 if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) { let errCode = CloseCode.ProtocolError.rawValue let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode) self.doDisconnect(error) writeError(errCode) return } let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue) if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue && receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) { let errCode = CloseCode.ProtocolError.rawValue let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode) self.doDisconnect(error) writeError(errCode) return } if isControlFrame && isFin == 0 { let errCode = CloseCode.ProtocolError.rawValue let error = self.errorWithDetail("control frames can't be fragmented", code: errCode) self.doDisconnect(error) writeError(errCode) return } if receivedOpcode == OpCode.ConnectionClose.rawValue { var code = CloseCode.Normal.rawValue if payloadLen == 1 { code = CloseCode.ProtocolError.rawValue } else if payloadLen > 1 { var codeBuffer = UnsafePointer<UInt16>((buffer+offset)) code = codeBuffer[0].bigEndian if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) { code = CloseCode.ProtocolError.rawValue } offset += 2 } if payloadLen > 2 { let len = Int(payloadLen-2) if len > 0 { let bytes = UnsafePointer<UInt8>((buffer+offset)) var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding) if str == nil { code = CloseCode.ProtocolError.rawValue } } } let error = self.errorWithDetail("connection closed by server", code: code) self.doDisconnect(error) writeError(code) return } if isControlFrame && payloadLen > 125 { writeError(CloseCode.ProtocolError.rawValue) return } var dataLength = UInt64(payloadLen) if dataLength == 127 { let bytes = UnsafePointer<UInt64>((buffer+offset)) dataLength = bytes[0].bigEndian offset += sizeof(UInt64) } else if dataLength == 126 { let bytes = UnsafePointer<UInt16>((buffer+offset)) dataLength = UInt64(bytes[0].bigEndian) offset += sizeof(UInt16) } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = NSData(bytes: buffer, length: bufferLen) return } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } var data: NSData! if len < 0 { len = 0 data = NSData() } else { data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len)) } if receivedOpcode == OpCode.Pong.rawValue { dispatch_async(queue,{ [weak self] in if let pongBlock = self?.onPong { pongBlock() } if let s = self { s.pongDelegate?.websocketDidReceivePong(s) } }) let step = Int(offset+numericCast(len)) let extra = bufferLen-step if extra > 0 { processRawMessage((buffer+step), bufferLen: extra) } return } var response = readStack.last if isControlFrame { response = nil //don't append pings } if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil { let errCode = CloseCode.ProtocolError.rawValue let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode) self.doDisconnect(error) writeError(errCode) return } var isNew = false if(response == nil) { if receivedOpcode == OpCode.ContinueFrame.rawValue { let errCode = CloseCode.ProtocolError.rawValue let error = self.errorWithDetail("first frame can't be a continue frame", code: errCode) self.doDisconnect(error) writeError(errCode) return } isNew = true response = WSResponse() response!.code = OpCode(rawValue: receivedOpcode)! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == OpCode.ContinueFrame.rawValue { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.ProtocolError.rawValue let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode) self.doDisconnect(error) writeError(errCode) return } response!.buffer!.appendData(data) } if response != nil { response!.bytesLeft -= Int(len) response!.frameCount++ response!.isFin = isFin > 0 ? true : false if(isNew) { readStack.append(response!) } processResponse(response!) } let step = Int(offset+numericCast(len)) let extra = bufferLen-step if(extra > 0) { processExtra((buffer+step), bufferLen: extra) } } } ///process the extra of a buffer private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) { if bufferLen < 2 { fragBuffer = NSData(bytes: buffer, length: bufferLen) } else { processRawMessage(buffer, bufferLen: bufferLen) } } ///process the finished response of a buffer private func processResponse(response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .Ping { let data = response.buffer! //local copy so it is perverse for writing dequeueWrite(data, code: OpCode.Pong) } else if response.code == .TextFrame { var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding) if str == nil { writeError(CloseCode.Encoding.rawValue) return false } dispatch_async(queue,{ [weak self] in if let textBlock = self?.onText { textBlock(str! as! String) } if let s = self { s.delegate?.websocketDidReceiveMessage(s, text: str! as! String) } }) } else if response.code == .BinaryFrame { let data = response.buffer! //local copy so it is perverse for writing dispatch_async(queue,{ [weak self] in if let dataBlock = self?.onData { dataBlock(data) } if let s = self { s.delegate?.websocketDidReceiveData(s, data: data) } }) } readStack.removeLast() return true } return false } ///Create an error private func errorWithDetail(detail: String, code: UInt16) -> NSError { var details = Dictionary<String,String>() details[NSLocalizedDescriptionKey] = detail return NSError(domain: "Websocket", code: Int(code), userInfo: details) } ///write a an error to the socket private func writeError(code: UInt16) { let buf = NSMutableData(capacity: sizeof(UInt16)) var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes) buffer[0] = code.bigEndian dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose) } ///used to write things to the stream private func dequeueWrite(data: NSData, code: OpCode) { if writeQueue == nil { writeQueue = NSOperationQueue() writeQueue!.maxConcurrentOperationCount = 1 } writeQueue!.addOperationWithBlock { [unowned self] in //stream isn't ready, let's wait var tries = 0; while self.outputStream == nil || !self.connected { if(tries < 5) { sleep(1); } else { break; } tries++; } if !self.connected { return } var offset = 2 let bytes = UnsafeMutablePointer<UInt8>(data.bytes) let dataLength = data.length let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize) let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes) buffer[0] = self.FinMask | code.rawValue if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset)) sizeBuffer[0] = UInt16(dataLength).bigEndian offset += sizeof(UInt16) } else { buffer[1] = 127 var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset)) sizeBuffer[0] = UInt64(dataLength).bigEndian offset += sizeof(UInt64) } buffer[1] |= self.MaskMask var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey) offset += sizeof(UInt32) for (var i = 0; i < dataLength; i++) { buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)] offset += 1 } var total = 0 while true { if self.outputStream == nil { break } let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total) var len = self.outputStream?.write(writeBuffer, maxLength: offset-total) if len == nil || len! < 0 { var error: NSError? if let streamError = self.outputStream?.streamError { error = streamError } else { let errCode = InternalErrorCode.OutputStreamWriteError.rawValue error = self.errorWithDetail("output stream error during write", code: errCode) } self.doDisconnect(error) break } else { total += len! } if total >= offset { break } } } } ///used to preform the disconnect delegate private func doDisconnect(error: NSError?) { if !self.didDisconnect { dispatch_async(queue,{ [weak self] in self?.didDisconnect = true if let disconnect = self?.onDisconnect { disconnect(error) } if let s = self { s.delegate?.websocketDidDisconnect(s, error: error) } }) } } }
apache-2.0
arn00s/barceloneta
Barceloneta/AppDelegate.swift
1
1188
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, COSTouchVisualizerWindowDelegate { var window: UIWindow? // var window: UIWindow? = { // var customWindow = COSTouchVisualizerWindow(frame: UIScreen.main.bounds) // customWindow.touchVisualizerWindowDelegate = self // // customWindow.fillColor = UIColor(red:0.07, green:0.73, blue:0.86, alpha:1) // customWindow.strokeColor = UIColor.clear // customWindow.touchAlpha = 0.4 // // customWindow.rippleFillColor = UIColor(red:0.98, green:0.68, blue:0.22, alpha:1) // customWindow.rippleStrokeColor = UIColor.clear // customWindow.rippleAlpha = 0.4 // // return customWindow // }() // swiftlint:disable:next line_length private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func touchVisualizerWindowShouldAlwaysShowFingertip(_ window: COSTouchVisualizerWindow!) -> Bool { return true } }
mit
ualch9/onebusaway-iphone
OneBusAway/ui/MapTable/ChevronCardCell.swift
2
3543
// // ChevronCardCell.swift // OneBusAway // // Created by Aaron Brethorst on 9/12/18. // Copyright © 2018 OneBusAway. All rights reserved. // import UIKit import OBAKit import SnapKit class ChevronCardCell: SelfSizingCollectionCell { override open func prepareForReuse() { super.prepareForReuse() imageView.image = nil contentStack.removeArrangedSubview(imageView) imageView.removeFromSuperview() } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = OBATheme.mapTableBackgroundColor let imageViewWrapper = imageView.oba_embedInWrapperView(withConstraints: false) imageViewWrapper.backgroundColor = .white imageView.snp.remakeConstraints { make in make.width.equalTo(16.0) make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: OBATheme.defaultPadding, bottom: 0, right: 0)) } let cardWrapper = contentStack.oba_embedInCardWrapper() contentView.addSubview(cardWrapper) cardWrapper.snp.makeConstraints { make in make.edges.equalToSuperview().inset(SelfSizingCollectionCell.leftRightInsets) } contentView.layer.addSublayer(separator) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let bounds = contentView.bounds let height: CGFloat = 0.5 let sideInset = OBATheme.defaultEdgeInsets.left separator.frame = CGRect(x: sideInset, y: bounds.height - height, width: bounds.width - (2 * sideInset), height: height) } // MARK: - Properties private lazy var contentStack: UIStackView = { return UIStackView.oba_horizontalStack(withArrangedSubviews: [imageView, contentWrapper, chevronWrapper]) }() public let contentWrapper: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 13, *) { view.backgroundColor = .secondarySystemGroupedBackground } else { view.backgroundColor = .white } return view }() private let imageView: UIImageView = { let imageView = UIImageView() if #available(iOS 13, *) { imageView.backgroundColor = .secondarySystemGroupedBackground } else { imageView.backgroundColor = .white } imageView.contentMode = .scaleAspectFit return imageView }() private let separator: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor(red: 200 / 255.0, green: 199 / 255.0, blue: 204 / 255.0, alpha: 1).cgColor return layer }() private let chevronWrapper: UIView = { let chevronImage = UIImageView(image: #imageLiteral(resourceName: "chevron")) chevronImage.tintColor = .darkGray let chevronWrapper = chevronImage.oba_embedInWrapperView(withConstraints: false) chevronImage.snp.makeConstraints { make in make.height.equalTo(14) make.width.equalTo(8) make.leading.trailing.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: OBATheme.defaultPadding)) make.centerY.equalToSuperview() } if #available(iOS 13, *) { chevronWrapper.backgroundColor = .secondarySystemGroupedBackground } else { chevronWrapper.backgroundColor = .white } return chevronWrapper }() }
apache-2.0
GoodMorningCody/EverybodySwift
UIKitSample/UIKitSample/TestTableViewController.swift
1
1189
// // TestTableViewController.swift // UIKitSample // // Created by Cody on 2014. 12. 29.. // Copyright (c) 2014년 tiekle. All rights reserved. // import UIKit class TestTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
sora0077/iTunesMusic
Sources/Model/DiskCache.swift
1
4811
// // DiskCache.swift // iTunesMusic // // Created by 林達也 on 2016/10/24. // Copyright © 2016年 jp.sora0077. All rights reserved. // import Foundation import RxSwift extension Model { public final class DiskCache { public static let shared = DiskCache(dir: Settings.Track.Cache.directory) fileprivate let impl: DiskCacheImpl fileprivate var downloading: Set<Int> = [] fileprivate let threshold = 3 private init(dir: URL) { impl = DiskCacheImpl(dir: dir) } public var diskSizeInBytes: Int { return impl.diskSizeInBytes } public func removeAll() -> Observable<Void> { return impl.removeAll() } } } extension Model.DiskCache: PlayerMiddleware { public func didEndPlayTrack(_ trackId: Int) { guard canDownload(trackId: trackId) else { return } let realm = iTunesRealm() guard let track = realm.object(ofType: _Track.self, forPrimaryKey: trackId), let url = track.metadata?.previewURL, let duration = track.metadata?.duration, track.metadata?.fileURL == nil else { return } let dir = impl.dir let filename = url.lastPathComponent downloading.insert(trackId) URLSession.shared.downloadTask(with: url, completionHandler: { [weak self] (url, _, error) in defer { _ = self?.downloading.remove(trackId) } guard let src = url else { return } let realm = iTunesRealm() guard let track = realm.object(ofType: _Track.self, forPrimaryKey: trackId) else { return } do { try realm.write { let to = dir.appendingPathComponent(filename) try? FileManager.default.removeItem(at: to) try FileManager.default.moveItem(at: src, to: to) let metadata = _TrackMetadata(track: track) metadata.updateCache(filename: filename) metadata.duration = duration realm.add(metadata, update: true) } } catch { print("\(error)") } }).resume() } private func canDownload(trackId: Int) -> Bool { if downloading.contains(trackId) { return false } let realm = iTunesRealm() let cache = realm.object(ofType: _DiskCacheCounter.self, forPrimaryKey: trackId) ?? { let cache = _DiskCacheCounter() cache.trackId = trackId return cache }() // swiftlint:disable:next force_try try! realm.write { cache.counter += 1 realm.add(cache, update: true) } guard cache.counter >= threshold else { return false } return true } } extension Model.DiskCache: ReactiveCompatible {} extension Reactive where Base: Model.DiskCache { public var diskSizeInBytes: Observable<Int> { return base.impl._diskSizeInBytes.asObservable() } } private final class DiskCacheImpl: NSObject, NSFilePresenter { fileprivate private(set) lazy var _diskSizeInBytes: Variable<Int> = Variable<Int>(self.diskSizeInBytes) let dir: URL var presentedItemURL: URL? { return dir } let presentedItemOperationQueue = OperationQueue() init(dir: URL) { self.dir = dir super.init() NSFileCoordinator.addFilePresenter(self) } func presentedSubitemDidChange(at url: URL) { _diskSizeInBytes.value = diskSizeInBytes } var diskSizeInBytes: Int { do { let paths = try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.fileSizeKey]) let sizes = try paths.map { try $0.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 } return sizes.reduce(0, +) } catch { print(error) return 0 } } func removeAll() -> Observable<Void> { let dir = self.dir return Observable.create { subscriber in do { try FileManager.default.removeItem(at: dir) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil) let realm = iTunesRealm() try realm.write { realm.delete(realm.objects(_DiskCacheCounter.self)) } subscriber.onNext(()) subscriber.onCompleted() } catch { subscriber.onError(error) } return Disposables.create() }.subscribeOn(SerialDispatchQueueScheduler(qos: .background)) } }
mit
mobilabsolutions/jenkins-ios
JenkinsiOS/Controller/ComputerTableViewController.swift
1
4235
// // ComputerTableViewController.swift // JenkinsiOS // // Created by Robert on 10.08.18. // Copyright © 2018 MobiLab Solutions. All rights reserved. // import UIKit class ComputerTableViewController: UITableViewController { var computer: Computer? { didSet { computerData = computer != nil ? data(for: computer!) : [] } } private var computerData: [(String, String)] = [] override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "DetailTableViewCell", bundle: .main), forCellReuseIdentifier: Constants.Identifiers.computerCell) tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constants.Identifiers.headerCell) tableView.separatorStyle = .none tableView.backgroundColor = Constants.UI.backgroundColor title = computer?.displayName ?? "Node" } private func data(for computer: Computer) -> [(String, String)] { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal let gbOfTotalPhysicalMemory = computer.monitorData?.totalPhysicalMemory?.bytesToGigabytesString(numberFormatter: numberFormatter) ?? "Unknown" let gbOfAvailablePhysicalMemory = computer.monitorData?.availablePhysicalMemory?.bytesToGigabytesString(numberFormatter: numberFormatter) ?? "Unknown" let gbOfTotalSwapMemory = computer.monitorData?.totalSwapSpace?.bytesToGigabytesString(numberFormatter: numberFormatter) ?? "Unknown" let gbOfAvailableSwapMemory = computer.monitorData?.availableSwapSpace?.bytesToGigabytesString(numberFormatter: numberFormatter) ?? "Unknown" return [ ("Name", computer.displayName), ("Executors", "\(computer.numExecutors)"), ("Idle", "\(computer.idle)"), ("JNLP Agent", "\(computer.jnlpAgent)"), ("Offline", "\(computer.offline)"), ("Temporarily Offline", "\((computer.temporarilyOffline).textify())"), ("Launch Supported", "\(computer.launchSupported)"), ("Available Physical Memory", gbOfAvailablePhysicalMemory), ("Physical Memory", gbOfTotalPhysicalMemory), ("Available Swap Space", gbOfAvailableSwapMemory), ("Swap Space", gbOfTotalSwapMemory), ] } // MARK: - Table view data source override func numberOfSections(in _: UITableView) -> Int { return 2 } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } return computerData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.headerCell, for: indexPath) cell.textLabel?.text = computer?.displayName.uppercased() ?? "NODE" cell.contentView.backgroundColor = Constants.UI.backgroundColor cell.textLabel?.textColor = Constants.UI.greyBlue cell.textLabel?.font = UIFont.boldDefaultFont(ofSize: 13) return cell } let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.computerCell, for: indexPath) as! DetailTableViewCell cell.titleLabel.text = computerData[indexPath.row].0 cell.detailLabel.text = computerData[indexPath.row].1 cell.container.borders = [.left, .right, .bottom] if indexPath.row == 0 { cell.container.cornersToRound = [.topLeft, .topRight] cell.container.borders.insert(.top) } else if indexPath.row == computerData.count - 1 { cell.container.cornersToRound = [.bottomLeft, .bottomRight] } return cell } override func tableView(_: UITableView, willDisplay cell: UITableViewCell, forRowAt _: IndexPath) { guard let cell = cell as? DetailTableViewCell else { return } cell.setNeedsLayout() cell.layoutIfNeeded() } override func tableView(_: UITableView, willSelectRowAt _: IndexPath) -> IndexPath? { return nil } }
mit
Pencroff/ai-hackathon-2017
IOS APP/FoodAI/FoodAPIResponse.swift
1
1136
// // FoodAPIResponse.swift // FoodAI // // Created by Pablo on 2/19/17. // Copyright © 2017 Pablo Carvalho. All rights reserved. // import Foundation import Gloss class FoodAPIResponse : Decodable { let code: Int let needCheck: Bool let status: String let qid: Int let tags: [String:Double] lazy var foodName : String! = { [unowned self] in if let first = self.tags.first { return first.key } return "Not Food :(" }() required init?(json: JSON) { self.code = ("code" <~~ json)! self.status = ("status" <~~ json)! self.qid = ("qid" <~~ json)! let needCheck = ("need_check" <~~ json)! == "true" self.needCheck = needCheck var tags = [String:Double]() let tagsArrays : [[String]] = ("tags" <~~ json)! tagsArrays.forEach { (array) in if array.count == 2 { if let value = Double(array[1]), value > 0.0 { tags[array[0]] = value } } } self.tags = tags } }
mit
nakau1/Formations
Formations/Sources/Modules/FormationTemplate/Views/Edit/FormationTemplatePin.swift
1
951
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit import Rswift @IBDesignable class FormationTemplatePin: UIView { @IBOutlet private weak var imageView: UIImageView! class func create(position: Position) -> FormationTemplatePin { let ret = R.nib.formationTemplatePin.firstView(owner: nil)! ret.imageView.isUserInteractionEnabled = true ret.imageView.layer.cornerRadius = ret.bounds.width / 2 ret.imageView.layer.borderColor = position.backgroundColor.withBrightnessComponent(0.64).cgColor ret.imageView.layer.borderWidth = 2 ret.imageView.clipsToBounds = true ret.imageView.image = UIImage.filled(color: position.backgroundColor, size: ret.bounds.size) return ret } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingUI/Order/SSNInputView.swift
1
3921
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import ComposableArchitecture import FeatureCardIssuingDomain import Localization import SwiftUI import ToolKit struct SSNInputView: View { @State var isFirstResponder: Bool = false @State var hideSsn: Bool = true private typealias L10n = LocalizationConstants.CardIssuing.Order.KYC private let store: Store<CardOrderingState, CardOrderingAction> init(store: Store<CardOrderingState, CardOrderingAction>) { self.store = store } var body: some View { WithViewStore(store) { viewStore in VStack(spacing: Spacing.padding3) { VStack(alignment: .leading, spacing: Spacing.padding1) { Text(L10n.SSN.title) .typography(.title3) .multilineTextAlignment(.center) Text(L10n.SSN.description) .typography(.paragraph1) .foregroundColor(.WalletSemantic.body) .multilineTextAlignment(.leading) } .padding(.horizontal, Spacing.padding2) VStack(alignment: .leading) { Text(L10n.SSN.Input.title) .typography(.paragraph2) // Password Input( text: viewStore.binding(\.$ssn), isFirstResponder: $isFirstResponder, placeholder: L10n.SSN.Input.placeholder, state: 1...8 ~= viewStore.state.ssn.count ? .error : .default, configuration: { textField in textField.isSecureTextEntry = hideSsn textField.textContentType = .password textField.returnKeyType = .next }, trailing: { if hideSsn { IconButton(icon: .lockClosed) { hideSsn = false } } else { IconButton(icon: .lockOpen) { hideSsn = true } } }, onReturnTapped: { isFirstResponder = false } ) Text(L10n.SSN.Input.caption) .typography(.caption1) .foregroundColor(.semantic.muted) } .padding(.horizontal, Spacing.padding2) Spacer() PrimaryButton(title: L10n.Buttons.next) { viewStore.send(.binding(.set(\.$isProductSelectionVisible, true))) } .disabled(viewStore.state.ssn.count < 9) .padding(Spacing.padding2) } .padding(.vertical, Spacing.padding3) .primaryNavigation(title: L10n.SSN.Navigation.title) PrimaryNavigationLink( destination: ProductSelectionView(store: store), isActive: viewStore.binding(\.$isProductSelectionVisible), label: EmptyView.init ) } } } #if DEBUG struct SSNInput_Previews: PreviewProvider { static var previews: some View { NavigationView { SSNInputView( store: Store( initialState: CardOrderingState( address: MockServices.address, ssn: "" ), reducer: cardOrderingReducer, environment: .preview ) ) } } } #endif
lgpl-3.0
kstaring/swift
validation-test/compiler_crashers_fixed/01383-swift-clangmoduleunit-getimportedmodules.swift
11
513
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse import CoreData let d>(g> [0.E == c() } let c { protocol A { func f<D> { enum b in return " class B { } typealias B : B,
apache-2.0
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/QuickStartChecklistHeader.swift
1
4981
import Gridicons class QuickStartChecklistHeader: UIView { var collapseListener: ((Bool) -> Void)? var collapse: Bool = false { didSet { collapseListener?(collapse) /* The animation will always take the shortest way. * Therefore CGFloat.pi and -CGFloat.pi animates in same position. * As we need anti-clockwise rotation we forcefully made it a shortest way by using 0.999 */ let rotate = (collapse ? 0.999 : 180.0) * CGFloat.pi let alpha = collapse ? 0.0 : 1.0 animator.animateWithDuration(0.3, animations: { [weak self] in self?.bottomStroke.alpha = CGFloat(alpha) self?.chevronView.transform = CGAffineTransform(rotationAngle: rotate) }) updateCollapseHeaderAccessibility() } } var count: Int = 0 { didSet { titleLabel.text = String(format: Constant.title, count) updateCollapseHeaderAccessibility() } } @IBOutlet private var titleLabel: UILabel! { didSet { WPStyleGuide.configureLabel(titleLabel, textStyle: .body) titleLabel.textColor = .neutral(.shade30) } } @IBOutlet private var chevronView: UIImageView! { didSet { chevronView.image = .gridicon(.chevronDown) chevronView.tintColor = .textTertiary } } @IBOutlet var topStroke: UIView! { didSet { topStroke.backgroundColor = .divider } } @IBOutlet private var bottomStroke: UIView! { didSet { bottomStroke.backgroundColor = .divider } } @IBOutlet private var contentView: UIView! { didSet { contentView.leadingAnchor.constraint(equalTo: contentViewLeadingAnchor).isActive = true contentView.trailingAnchor.constraint(equalTo: contentViewTrailingAnchor).isActive = true } } private let animator = Animator() private var contentViewLeadingAnchor: NSLayoutXAxisAnchor { return WPDeviceIdentification.isiPhone() ? safeAreaLayoutGuide.leadingAnchor : layoutMarginsGuide.leadingAnchor } private var contentViewTrailingAnchor: NSLayoutXAxisAnchor { return WPDeviceIdentification.isiPhone() ? safeAreaLayoutGuide.trailingAnchor : layoutMarginsGuide.trailingAnchor } @IBAction private func headerDidTouch(_ sender: UIButton) { collapse.toggle() } override func awakeFromNib() { super.awakeFromNib() contentView.backgroundColor = .listForeground prepareForVoiceOver() } } private enum Constant { static let title = NSLocalizedString("Complete (%i)", comment: "The table view header title that displays the number of completed tasks") } // MARK: - Accessible extension QuickStartChecklistHeader: Accessible { func prepareForVoiceOver() { // Here we explicit configure the subviews, to prepare for the desired composite behavior bottomStroke.isAccessibilityElement = false contentView.isAccessibilityElement = false titleLabel.isAccessibilityElement = false chevronView.isAccessibilityElement = false // Neither the top stroke nor the button (overlay) are outlets, so we configured them in the nib // From an accessibility perspective, this view is essentially monolithic, so we configure it accordingly isAccessibilityElement = true accessibilityTraits = [.header, .button] updateCollapseHeaderAccessibility() } func updateCollapseHeaderAccessibility() { let accessibilityHintText: String let accessibilityLabelFormat: String if collapse { accessibilityHintText = NSLocalizedString("Collapses the list of completed tasks.", comment: "Accessibility hint for the list of completed tasks presented during Quick Start.") accessibilityLabelFormat = NSLocalizedString("Expanded, %i completed tasks, toggling collapses the list of these tasks", comment: "Accessibility description for the list of completed tasks presented during Quick Start. Parameter is a number representing the count of completed tasks.") } else { accessibilityHintText = NSLocalizedString("Expands the list of completed tasks.", comment: "Accessibility hint for the list of completed tasks presented during Quick Start.") accessibilityLabelFormat = NSLocalizedString("Collapsed, %i completed tasks, toggling expands the list of these tasks", comment: "Accessibility description for the list of completed tasks presented during Quick Start. Parameter is a number representing the count of completed tasks.") } accessibilityHint = accessibilityHintText let localizedAccessibilityDescription = String(format: accessibilityLabelFormat, arguments: [count]) accessibilityLabel = localizedAccessibilityDescription } }
gpl-2.0
FlexMonkey/Filterpedia
Filterpedia/AppDelegate.swift
1
2153
// // AppDelegate.swift // Filterpedia // // Created by Simon Gladman on 29/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-3.0
nighttime/EchoiOS
Echo/SwipeHintArrowsView.swift
1
3542
// // SwipeHintArrowsView.swift // Echo // // Created by Nick McKenna on 11/1/14. // Copyright (c) 2014 nighttime software. All rights reserved. // import UIKit enum ArrowType { case Green case Red } class SwipeHintArrowsView : UIView { var type: ArrowType let arrow1 = UIImageView(image: UIImage(named: "arrowGreen.png")) let arrow2 = UIImageView(image: UIImage(named: "arrowGreen.png")) let arrow3 = UIImageView(image: UIImage(named: "arrowGreen.png")) let low: CGFloat = 0.2 let high: CGFloat = 1.0 let inDur: NSTimeInterval = 0.75 let outDur: NSTimeInterval = 1.0 var animating = false init(type: ArrowType) { self.type = type super.init(frame: CGRectMake(0, 0, arrow1.viewWidth, arrow1.viewWidth + 20)) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { var imageName: String if type == .Green { arrow1.center = CGPointMake(CGRectGetMidX(self.bounds), self.viewHeight - CGRectGetMidY(arrow1.bounds)) arrow2.center = CGPointMake(arrow1.center.x, arrow1.center.y - 10) arrow3.center = CGPointMake(arrow2.center.x, arrow2.center.y - 10) } else { arrow1.image = UIImage(named: "arrowRed.png") arrow2.image = UIImage(named: "arrowRed.png") arrow3.image = UIImage(named: "arrowRed.png") arrow1.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(arrow1.bounds)) arrow2.center = CGPointMake(arrow1.center.x, arrow1.center.y + 10) arrow3.center = CGPointMake(arrow2.center.x, arrow2.center.y + 10) } arrow1.alpha = 0.0 arrow2.alpha = 0.0 arrow3.alpha = 0.0 self.addSubview(arrow1) self.addSubview(arrow2) self.addSubview(arrow3) } func animate() { if !animating { animateFirst() } } private func animateFirst() { UIView.animateWithDuration(inDur, delay: 0.0, options: (.CurveEaseIn), animations: { self.arrow1.alpha = self.high }, completion: {done in UIView.animateWithDuration(self.outDur, delay: 0.0, options: (.CurveEaseOut), animations: { self.arrow1.alpha = self.low }, completion: {done in self.animateSecond() }) }) } private func animateSecond() { UIView.animateWithDuration(inDur, delay: 0.0, options: (.CurveEaseIn), animations: { self.arrow2.alpha = self.high }, completion: {done in UIView.animateWithDuration(self.outDur, delay: 0.0, options: (.CurveEaseOut), animations: { self.arrow2.alpha = self.low }, completion: {done in self.animateThird() }) }) } private func animateThird() { UIView.animateWithDuration(inDur, delay: 0.0, options: (.CurveEaseIn), animations: { self.arrow3.alpha = self.high }, completion: {done in UIView.animateWithDuration(self.outDur, delay: 0.0, options: (.CurveEaseOut), animations: { self.arrow3.alpha = self.low }, completion: {done in self.animateFirst() }) }) } }
mit
abertelrud/swift-package-manager
Sources/PackageRegistry/RegistryDownloadsManager.swift
2
13842
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Dispatch import Foundation import PackageModel import TSCBasic import PackageLoading public class RegistryDownloadsManager: Cancellable { public typealias Delegate = RegistryDownloadsManagerDelegate private let fileSystem: FileSystem private let path: AbsolutePath private let cachePath: AbsolutePath? private let registryClient: RegistryClient private let checksumAlgorithm: HashAlgorithm private let delegate: Delegate? private var pendingLookups = [PackageIdentity: DispatchGroup]() private var pendingLookupsLock = NSLock() public init( fileSystem: FileSystem, path: AbsolutePath, cachePath: AbsolutePath?, registryClient: RegistryClient, checksumAlgorithm: HashAlgorithm, delegate: Delegate? ) { self.fileSystem = fileSystem self.path = path self.cachePath = cachePath self.registryClient = registryClient self.checksumAlgorithm = checksumAlgorithm self.delegate = delegate } public func lookup( package: PackageIdentity, version: Version, observabilityScope: ObservabilityScope, delegateQueue: DispatchQueue, callbackQueue: DispatchQueue, completion: @escaping (Result<AbsolutePath, Error>) -> Void ) { // wrap the callback in the requested queue let completion = { result in callbackQueue.async { completion(result) } } let packageRelativePath: RelativePath let packagePath: AbsolutePath do { packageRelativePath = try package.downloadPath(version: version) packagePath = self.path.appending(packageRelativePath) // TODO: we can do some finger-print checking to improve the validation // already exists and valid, we can exit early if try self.fileSystem.validPackageDirectory(packagePath) { return completion(.success(packagePath)) } } catch { return completion(.failure(error)) } // next we check if there is a pending lookup self.pendingLookupsLock.lock() if let pendingLookup = self.pendingLookups[package] { self.pendingLookupsLock.unlock() // chain onto the pending lookup pendingLookup.notify(queue: callbackQueue) { // at this point the previous lookup should be complete and we can re-lookup self.lookup( package: package, version: version, observabilityScope: observabilityScope, delegateQueue: delegateQueue, callbackQueue: callbackQueue, completion: completion ) } } else { // record the pending lookup assert(self.pendingLookups[package] == nil) let group = DispatchGroup() group.enter() self.pendingLookups[package] = group self.pendingLookupsLock.unlock() // inform delegate that we are starting to fetch // calculate if cached (for delegate call) outside queue as it may change while queue is processing let isCached = self.cachePath.map{ self.fileSystem.exists($0.appending(packageRelativePath)) } ?? false delegateQueue.async { let details = FetchDetails(fromCache: isCached, updatedCache: false) self.delegate?.willFetch(package: package, version: version, fetchDetails: details) } // make sure destination is free. try? self.fileSystem.removeFileTree(packagePath) let start = DispatchTime.now() self.downloadAndPopulateCache( package: package, version: version, packagePath: packagePath, observabilityScope: observabilityScope, delegateQueue: delegateQueue, callbackQueue: callbackQueue ) { result in // inform delegate that we finished to fetch let duration = start.distance(to: .now()) delegateQueue.async { self.delegate?.didFetch(package: package, version: version, result: result, duration: duration) } // remove the pending lookup self.pendingLookupsLock.lock() self.pendingLookups[package]?.leave() self.pendingLookups[package] = nil self.pendingLookupsLock.unlock() // and done completion(result.map{ _ in packagePath }) } } } /// Cancel any outstanding requests public func cancel(deadline: DispatchTime) throws { try self.registryClient.cancel(deadline: deadline) } private func downloadAndPopulateCache( package: PackageIdentity, version: Version, packagePath: AbsolutePath, observabilityScope: ObservabilityScope, delegateQueue: DispatchQueue, callbackQueue: DispatchQueue, completion: @escaping (Result<FetchDetails, Error>) -> Void ) { if let cachePath = self.cachePath { do { let relativePath = try package.downloadPath(version: version) let cachedPackagePath = cachePath.appending(relativePath) try self.initializeCacheIfNeeded(cachePath: cachePath) try self.fileSystem.withLock(on: cachedPackagePath, type: .exclusive) { // download the package into the cache unless already exists if try self.fileSystem.validPackageDirectory(cachedPackagePath) { // extra validation to defend from racy edge cases if self.fileSystem.exists(packagePath) { throw StringError("\(packagePath) already exists unexpectedly") } // copy the package from the cache into the package path. try self.fileSystem.createDirectory(packagePath.parentDirectory, recursive: true) try self.fileSystem.copy(from: cachedPackagePath, to: packagePath) completion(.success(.init(fromCache: true, updatedCache: false))) } else { // it is possible that we already created the directory before from failed attempts, so clear leftover data if present. try? self.fileSystem.removeFileTree(cachedPackagePath) // download the package from the registry self.registryClient.downloadSourceArchive( package: package, version: version, fileSystem: self.fileSystem, destinationPath: cachedPackagePath, checksumAlgorithm: self.checksumAlgorithm, progressHandler: updateDownloadProgress, observabilityScope: observabilityScope, callbackQueue: callbackQueue ) { result in completion(result.tryMap { // extra validation to defend from racy edge cases if self.fileSystem.exists(packagePath) { throw StringError("\(packagePath) already exists unexpectedly") } // copy the package from the cache into the package path. try self.fileSystem.createDirectory(packagePath.parentDirectory, recursive: true) try self.fileSystem.copy(from: cachedPackagePath, to: packagePath) return FetchDetails(fromCache: true, updatedCache: true) }) } } } } catch { // download without populating the cache in the case of an error. observabilityScope.emit(warning: "skipping cache due to an error: \(error)") // it is possible that we already created the directory from failed attempts, so clear leftover data if present. try? self.fileSystem.removeFileTree(packagePath) self.registryClient.downloadSourceArchive( package: package, version: version, fileSystem: self.fileSystem, destinationPath: packagePath, checksumAlgorithm: self.checksumAlgorithm, progressHandler: updateDownloadProgress, observabilityScope: observabilityScope, callbackQueue: callbackQueue ) { result in completion(result.map{ FetchDetails(fromCache: false, updatedCache: false) }) } } } else { // it is possible that we already created the directory from failed attempts, so clear leftover data if present. try? self.fileSystem.removeFileTree(packagePath) // download without populating the cache when no `cachePath` is set. self.registryClient.downloadSourceArchive( package: package, version: version, fileSystem: self.fileSystem, destinationPath: packagePath, checksumAlgorithm: self.checksumAlgorithm, progressHandler: updateDownloadProgress, observabilityScope: observabilityScope, callbackQueue: callbackQueue ) { result in completion(result.map{ FetchDetails(fromCache: false, updatedCache: false) }) } } // utility to update progress func updateDownloadProgress(downloaded: Int64, total: Int64?) -> Void { delegateQueue.async { self.delegate?.fetching( package: package, version: version, bytesDownloaded: downloaded, totalBytesToDownload: total ) } } } public func remove(package: PackageIdentity) throws { let relativePath = try package.downloadPath() let packagesPath = self.path.appending(relativePath) try self.fileSystem.removeFileTree(packagesPath) } public func reset() throws { try self.fileSystem.removeFileTree(self.path) } public func purgeCache() throws { guard let cachePath = self.cachePath else { return } try self.fileSystem.withLock(on: cachePath, type: .exclusive) { let cachedPackages = try self.fileSystem.getDirectoryContents(cachePath) for packagePath in cachedPackages { try self.fileSystem.removeFileTree(cachePath.appending(component: packagePath)) } } } private func initializeCacheIfNeeded(cachePath: AbsolutePath) throws { if !self.fileSystem.exists(cachePath) { try self.fileSystem.createDirectory(cachePath, recursive: true) } } } /// Delegate to notify clients about actions being performed by RegistryManager. public protocol RegistryDownloadsManagerDelegate { /// Called when a package is about to be fetched. func willFetch(package: PackageIdentity, version: Version, fetchDetails: RegistryDownloadsManager.FetchDetails) /// Called when a package has finished fetching. func didFetch(package: PackageIdentity, version: Version, result: Result<RegistryDownloadsManager.FetchDetails, Error>, duration: DispatchTimeInterval) /// Called every time the progress of a repository fetch operation updates. func fetching(package: PackageIdentity, version: Version, bytesDownloaded: Int64, totalBytesToDownload: Int64?) } extension RegistryDownloadsManager { /// Additional information about a fetch public struct FetchDetails: Equatable { /// Indicates if the repository was fetched from the cache or from the remote. public let fromCache: Bool /// Indicates wether the wether the repository was already present in the cache and updated or if a clean fetch was performed. public let updatedCache: Bool } } extension FileSystem { func validPackageDirectory(_ path: AbsolutePath) throws -> Bool { if !self.exists(path) { return false } return try self.getDirectoryContents(path).contains(Manifest.filename) } } extension PackageIdentity { internal func downloadPath() throws -> RelativePath { guard let (scope, name) = self.scopeAndName else { throw StringError("invalid package identity, expected registry scope and name") } return RelativePath(scope.description).appending(component: name.description) } internal func downloadPath(version: Version) throws -> RelativePath { try self.downloadPath().appending(component: version.description) } }
apache-2.0
tjw/swift
stdlib/public/core/Mirror.swift
1
35581
//===--- Mirror.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: ExistentialCollection needs to be supported before this will work // without the ObjC Runtime. /// A representation of the substructure and display style of an instance of /// any type. /// /// A mirror describes the parts that make up a particular instance, such as /// the instance's stored properties, collection or tuple elements, or its /// active enumeration case. Mirrors also provide a "display style" property /// that suggests how this mirror might be rendered. /// /// Playgrounds and the debugger use the `Mirror` type to display /// representations of values of any type. For example, when you pass an /// instance to the `dump(_:_:_:_:)` function, a mirror is used to render that /// instance's runtime contents. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "▿ Point /// // - x: 21 /// // - y: 30" /// /// To customize the mirror representation of a custom type, add conformance to /// the `CustomReflectable` protocol. @_fixed_layout // FIXME(sil-serialize-all) public struct Mirror { /// Representation of descendant classes that don't override /// `customMirror`. /// /// Note that the effect of this setting goes no deeper than the /// nearest descendant class that overrides `customMirror`, which /// in turn can determine representation of *its* descendants. @_frozen // FIXME(sil-serialize-all) @usableFromInline // FIXME(sil-serialize-all) internal enum _DefaultDescendantRepresentation { /// Generate a default mirror for descendant classes that don't /// override `customMirror`. /// /// This case is the default. case generated /// Suppress the representation of descendant classes that don't /// override `customMirror`. /// /// This option may be useful at the root of a class cluster, where /// implementation details of descendants should generally not be /// visible to clients. case suppressed } /// The representation to use for ancestor classes. /// /// A class that conforms to the `CustomReflectable` protocol can control how /// its mirror represents ancestor classes by initializing the mirror /// with an `AncestorRepresentation`. This setting has no effect on mirrors /// reflecting value type instances. public enum AncestorRepresentation { /// Generates a default mirror for all ancestor classes. /// /// This case is the default when initializing a `Mirror` instance. /// /// When you use this option, a subclass's mirror generates default mirrors /// even for ancestor classes that conform to the `CustomReflectable` /// protocol. To avoid dropping the customization provided by ancestor /// classes, an override of `customMirror` should pass /// `.customized({ super.customMirror })` as `ancestorRepresentation` when /// initializing its mirror. case generated /// Uses the nearest ancestor's implementation of `customMirror` to create /// a mirror for that ancestor. /// /// Other classes derived from such an ancestor are given a default mirror. /// The payload for this option should always be `{ super.customMirror }`: /// /// var customMirror: Mirror { /// return Mirror( /// self, /// children: ["someProperty": self.someProperty], /// ancestorRepresentation: .customized({ super.customMirror })) // <== /// } case customized(() -> Mirror) /// Suppresses the representation of all ancestor classes. /// /// In a mirror created with this ancestor representation, the /// `superclassMirror` property is `nil`. case suppressed } /// Creates a mirror that reflects on the given instance. /// /// If the dynamic type of `subject` conforms to `CustomReflectable`, the /// resulting mirror is determined by its `customMirror` property. /// Otherwise, the result is generated by the language. /// /// If the dynamic type of `subject` has value semantics, subsequent /// mutations of `subject` will not observable in `Mirror`. In general, /// though, the observability of mutations is unspecified. /// /// - Parameter subject: The instance for which to create a mirror. @inlinable // FIXME(sil-serialize-all) public init(reflecting subject: Any) { if case let customized as CustomReflectable = subject { self = customized.customMirror } else { self = Mirror(internalReflecting: subject) } } /// An element of the reflected instance's structure. /// /// When the `label` component in not `nil`, it may represent the name of a /// stored property or an active `enum` case. If you pass strings to the /// `descendant(_:_:)` method, labels are used for lookup. public typealias Child = (label: String?, value: Any) /// The type used to represent substructure. /// /// When working with a mirror that reflects a bidirectional or random access /// collection, you may find it useful to "upgrade" instances of this type /// to `AnyBidirectionalCollection` or `AnyRandomAccessCollection`. For /// example, to display the last twenty children of a mirror if they can be /// accessed efficiently, you write the following code: /// /// if let b = AnyBidirectionalCollection(someMirror.children) { /// for element in b.suffix(20) { /// print(element) /// } /// } public typealias Children = AnyCollection<Child> /// A suggestion of how a mirror's subject is to be interpreted. /// /// Playgrounds and the debugger will show a representation similar /// to the one used for instances of the kind indicated by the /// `DisplayStyle` case name when the mirror is used for display. public enum DisplayStyle { case `struct`, `class`, `enum`, tuple, optional, collection case dictionary, `set` } @inlinable // FIXME(sil-serialize-all) internal static func _noSuperclassMirror() -> Mirror? { return nil } @_semantics("optimize.sil.specialize.generic.never") @inline(never) @inlinable // FIXME(sil-serialize-all) internal static func _superclassIterator<Subject>( _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation ) -> () -> Mirror? { if let subjectClass = Subject.self as? AnyClass, let superclass = _getSuperclass(subjectClass) { switch ancestorRepresentation { case .generated: return { Mirror(internalReflecting: subject, subjectType: superclass) } case .customized(let makeAncestor): return { let ancestor = makeAncestor() if superclass == ancestor.subjectType || ancestor._defaultDescendantRepresentation == .suppressed { return ancestor } else { return Mirror(internalReflecting: subject, subjectType: superclass, customAncestor: ancestor) } } case .suppressed: break } } return Mirror._noSuperclassMirror } /// Creates a mirror representing the given subject with a specified /// structure. /// /// You use this initializer from within your type's `customMirror` /// implementation to create a customized mirror. /// /// If `subject` is a class instance, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, the /// `customMirror` implementation of any ancestors is ignored. To prevent /// bypassing customized ancestors, pass /// `.customized({ super.customMirror })` as the `ancestorRepresentation` /// parameter when implementing your type's `customMirror` property. /// /// - Parameters: /// - subject: The instance to represent in the new mirror. /// - children: The structure to use for the mirror. The collection /// traversal modeled by `children` is captured so that the resulting /// mirror's children may be upgraded to a bidirectional or random /// access collection later. See the `children` property for details. /// - displayStyle: The preferred display style for the mirror when /// presented in the debugger or in a playground. The default is `nil`. /// - ancestorRepresentation: The means of generating the subject's /// ancestor representation. `ancestorRepresentation` is ignored if /// `subject` is not a class instance. The default is `.generated`. @inlinable // FIXME(sil-serialize-all) public init<Subject, C : Collection>( _ subject: Subject, children: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where C.Element == Child { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children(children) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Creates a mirror representing the given subject with unlabeled children. /// /// You use this initializer from within your type's `customMirror` /// implementation to create a customized mirror, particularly for custom /// types that are collections. The labels of the resulting mirror's /// `children` collection are all `nil`. /// /// If `subject` is a class instance, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, the /// `customMirror` implementation of any ancestors is ignored. To prevent /// bypassing customized ancestors, pass /// `.customized({ super.customMirror })` as the `ancestorRepresentation` /// parameter when implementing your type's `customMirror` property. /// /// - Parameters: /// - subject: The instance to represent in the new mirror. /// - unlabeledChildren: The children to use for the mirror. The collection /// traversal modeled by `unlabeledChildren` is captured so that the /// resulting mirror's children may be upgraded to a bidirectional or /// random access collection later. See the `children` property for /// details. /// - displayStyle: The preferred display style for the mirror when /// presented in the debugger or in a playground. The default is `nil`. /// - ancestorRepresentation: The means of generating the subject's /// ancestor representation. `ancestorRepresentation` is ignored if /// `subject` is not a class instance. The default is `.generated`. @inlinable // FIXME(sil-serialize-all) public init<Subject, C : Collection>( _ subject: Subject, unlabeledChildren: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = unlabeledChildren.lazy.map { Child(label: nil, value: $0) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Creates a mirror representing the given subject using a dictionary /// literal for the structure. /// /// You use this initializer from within your type's `customMirror` /// implementation to create a customized mirror. Pass a dictionary literal /// with string keys as `children`. Although an *actual* dictionary is /// arbitrarily-ordered, when you create a mirror with a dictionary literal, /// the ordering of the mirror's `children` will exactly match that of the /// literal you pass. /// /// If `subject` is a class instance, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, the /// `customMirror` implementation of any ancestors is ignored. To prevent /// bypassing customized ancestors, pass /// `.customized({ super.customMirror })` as the `ancestorRepresentation` /// parameter when implementing your type's `customMirror` property. /// /// - Parameters: /// - subject: The instance to represent in the new mirror. /// - children: A dictionary literal to use as the structure for the /// mirror. The `children` collection of the resulting mirror may be /// upgraded to a random access collection later. See the `children` /// property for details. /// - displayStyle: The preferred display style for the mirror when /// presented in the debugger or in a playground. The default is `nil`. /// - ancestorRepresentation: The means of generating the subject's /// ancestor representation. `ancestorRepresentation` is ignored if /// `subject` is not a class instance. The default is `.generated`. @inlinable // FIXME(sil-serialize-all) public init<Subject>( _ subject: Subject, children: DictionaryLiteral<String, Any>, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// The static type of the subject being reflected. /// /// This type may differ from the subject's dynamic type when this mirror /// is the `superclassMirror` of another mirror. public let subjectType: Any.Type /// A collection of `Child` elements describing the structure of the /// reflected subject. public let children: Children /// A suggested display style for the reflected subject. public let displayStyle: DisplayStyle? /// A mirror of the subject's superclass, if one exists. @inlinable // FIXME(sil-serialize-all) public var superclassMirror: Mirror? { return _makeSuperclassMirror() } @usableFromInline // FIXME(sil-serialize-all) internal let _makeSuperclassMirror: () -> Mirror? @usableFromInline // FIXME(sil-serialize-all) internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation } /// A type that explicitly supplies its own mirror. /// /// You can create a mirror for any type using the `Mirror(reflecting:)` /// initializer, but if you are not satisfied with the mirror supplied for /// your type by default, you can make it conform to `CustomReflectable` and /// return a custom `Mirror` instance. public protocol CustomReflectable { /// The custom mirror for this instance. /// /// If this type has value semantics, the mirror should be unaffected by /// subsequent mutations of the instance. var customMirror: Mirror { get } } /// A type that explicitly supplies its own mirror, but whose /// descendant classes are not represented in the mirror unless they /// also override `customMirror`. public protocol CustomLeafReflectable : CustomReflectable {} //===--- Addressing -------------------------------------------------------===// /// A protocol for legitimate arguments to `Mirror`'s `descendant` /// method. /// /// Do not declare new conformances to this protocol; they will not /// work as expected. public protocol MirrorPath { // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and // you shouldn't be able to create conformances. } extension Int : MirrorPath {} extension String : MirrorPath {} extension Mirror { @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline // FIXME(sil-serialize-all) internal struct _Dummy : CustomReflectable { @inlinable // FIXME(sil-serialize-all) internal init(mirror: Mirror) { self.mirror = mirror } @usableFromInline // FIXME(sil-serialize-all) internal var mirror: Mirror @inlinable // FIXME(sil-serialize-all) internal var customMirror: Mirror { return mirror } } /// Returns a specific descendant of the reflected subject, or `nil` if no /// such descendant exists. /// /// Pass a variadic list of string and integer arguments. Each string /// argument selects the first child with a matching label. Each integer /// argument selects the child at that offset. For example, passing /// `1, "two", 3` as arguments to `myMirror.descendant(_:_:)` is equivalent /// to: /// /// var result: Any? = nil /// let children = myMirror.children /// if let i0 = children.index( /// children.startIndex, offsetBy: 1, limitedBy: children.endIndex), /// i0 != children.endIndex /// { /// let grandChildren = Mirror(reflecting: children[i0].value).children /// if let i1 = grandChildren.index(where: { $0.label == "two" }) { /// let greatGrandChildren = /// Mirror(reflecting: grandChildren[i1].value).children /// if let i2 = greatGrandChildren.index( /// greatGrandChildren.startIndex, /// offsetBy: 3, /// limitedBy: greatGrandChildren.endIndex), /// i2 != greatGrandChildren.endIndex /// { /// // Success! /// result = greatGrandChildren[i2].value /// } /// } /// } /// /// This function is suitable for exploring the structure of a mirror in a /// REPL or playground, but is not intended to be efficient. The efficiency /// of finding each element in the argument list depends on the argument /// type and the capabilities of the each level of the mirror's `children` /// collections. Each string argument requires a linear search, and unless /// the underlying collection supports random-access traversal, each integer /// argument also requires a linear operation. /// /// - Parameters: /// - first: The first mirror path component to access. /// - rest: Any remaining mirror path components. /// - Returns: The descendant of this mirror specified by the given mirror /// path components if such a descendant exists; otherwise, `nil`. @inlinable // FIXME(sil-serialize-all) public func descendant( _ first: MirrorPath, _ rest: MirrorPath... ) -> Any? { var result: Any = _Dummy(mirror: self) for e in [first] + rest { let children = Mirror(reflecting: result).children let position: Children.Index if case let label as String = e { position = children.index { $0.label == label } ?? children.endIndex } else if let offset = e as? Int { position = children.index(children.startIndex, offsetBy: offset, limitedBy: children.endIndex) ?? children.endIndex } else { _preconditionFailure( "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library") } if position == children.endIndex { return nil } result = children[position].value } return result } } //===--- QuickLooks -------------------------------------------------------===// /// The sum of types that can be used as a Quick Look representation. /// /// The `PlaygroundQuickLook` protocol is deprecated, and will be removed from /// the standard library in a future Swift release. To customize the logging of /// your type in a playground, conform to the /// `CustomPlaygroundDisplayConvertible` protocol, which does not use the /// `PlaygroundQuickLook` enum. /// /// If you need to provide a customized playground representation in Swift 4.0 /// or Swift 3.2 or earlier, use a conditional compilation block: /// /// #if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0)) /// // With Swift 4.1 and later (including Swift 3.3 and later), use /// // the CustomPlaygroundDisplayConvertible protocol. /// #else /// // With Swift 4.0 and Swift 3.2 and earlier, use PlaygroundQuickLook /// // and the CustomPlaygroundQuickLookable protocol. /// #endif @_frozen // rdar://problem/38719739 - needed by LLDB @available(*, deprecated, message: "PlaygroundQuickLook will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.") public enum PlaygroundQuickLook { /// Plain text. case text(String) /// An integer numeric value. case int(Int64) /// An unsigned integer numeric value. case uInt(UInt64) /// A single precision floating-point numeric value. case float(Float32) /// A double precision floating-point numeric value. case double(Float64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An image. case image(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A sound. case sound(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A color. case color(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A bezier path. case bezierPath(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An attributed string. case attributedString(Any) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A rectangle. case rectangle(Float64, Float64, Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A point. case point(Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A size. case size(Float64, Float64) /// A boolean value. case bool(Bool) // FIXME: Uses explicit values to avoid coupling a particular Cocoa type. /// A range. case range(Int64, Int64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A GUI view. case view(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A graphical sprite. case sprite(Any) /// A Uniform Resource Locator. case url(String) /// Raw data that has already been encoded in a format the IDE understands. case _raw([UInt8], String) } extension PlaygroundQuickLook { /// Creates a new Quick Look for the given instance. /// /// If the dynamic type of `subject` conforms to /// `CustomPlaygroundQuickLookable`, the result is found by calling its /// `customPlaygroundQuickLook` property. Otherwise, the result is /// synthesized by the language. In some cases, the synthesized result may /// be `.text(String(reflecting: subject))`. /// /// - Note: If the dynamic type of `subject` has value semantics, subsequent /// mutations of `subject` will not observable in the Quick Look. In /// general, though, the observability of such mutations is unspecified. /// /// - Parameter subject: The instance to represent with the resulting Quick /// Look. @inlinable // FIXME(sil-serialize-all) @available(*, deprecated, message: "PlaygroundQuickLook will be removed in a future Swift version.") public init(reflecting subject: Any) { if let customized = subject as? CustomPlaygroundQuickLookable { self = customized.customPlaygroundQuickLook } else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable { self = customized._defaultCustomPlaygroundQuickLook } else { if let q = Mirror.quickLookObject(subject) { self = q } else { self = .text(String(reflecting: subject)) } } } } /// A type that explicitly supplies its own playground Quick Look. /// /// The `CustomPlaygroundQuickLookable` protocol is deprecated, and will be /// removed from the standard library in a future Swift release. To customize /// the logging of your type in a playground, conform to the /// `CustomPlaygroundDisplayConvertible` protocol. /// /// If you need to provide a customized playground representation in Swift 4.0 /// or Swift 3.2 or earlier, use a conditional compilation block: /// /// #if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0)) /// // With Swift 4.1 and later (including Swift 3.3 and later), /// // conform to CustomPlaygroundDisplayConvertible. /// extension MyType: CustomPlaygroundDisplayConvertible { /*...*/ } /// #else /// // Otherwise, on Swift 4.0 and Swift 3.2 and earlier, /// // conform to CustomPlaygroundQuickLookable. /// extension MyType: CustomPlaygroundQuickLookable { /*...*/ } /// #endif @available(*, deprecated, message: "CustomPlaygroundQuickLookable will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.") public protocol CustomPlaygroundQuickLookable { /// A custom playground Quick Look for this instance. /// /// If this type has value semantics, the `PlaygroundQuickLook` instance /// should be unaffected by subsequent mutations. var customPlaygroundQuickLook: PlaygroundQuickLook { get } } // A workaround for <rdar://problem/26182650> // FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib. @available(*, deprecated, message: "_DefaultCustomPlaygroundQuickLookable will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.") public protocol _DefaultCustomPlaygroundQuickLookable { var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get } } //===--- General Utilities ------------------------------------------------===// // This component could stand alone, but is used in Mirror's public interface. /// A lightweight collection of key-value pairs. /// /// Use a `DictionaryLiteral` instance when you need an ordered collection of /// key-value pairs and don't require the fast key lookup that the /// `Dictionary` type provides. Unlike key-value pairs in a true dictionary, /// neither the key nor the value of a `DictionaryLiteral` instance must /// conform to the `Hashable` protocol. /// /// You initialize a `DictionaryLiteral` instance using a Swift dictionary /// literal. Besides maintaining the order of the original dictionary literal, /// `DictionaryLiteral` also allows duplicates keys. For example: /// /// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49, /// "Evelyn Ashford": 10.76, /// "Evelyn Ashford": 10.79, /// "Marlies Gohr": 10.81] /// print(recordTimes.first!) /// // Prints "("Florence Griffith-Joyner", 10.49)" /// /// Some operations that are efficient on a dictionary are slower when using /// `DictionaryLiteral`. In particular, to find the value matching a key, you /// must search through every element of the collection. The call to /// `index(where:)` in the following example must traverse the whole /// collection to find the element that matches the predicate: /// /// let runner = "Marlies Gohr" /// if let index = recordTimes.index(where: { $0.0 == runner }) { /// let time = recordTimes[index].1 /// print("\(runner) set a 100m record of \(time) seconds.") /// } else { /// print("\(runner) couldn't be found in the records.") /// } /// // Prints "Marlies Gohr set a 100m record of 10.81 seconds." /// /// Dictionary Literals as Function Parameters /// ------------------------------------------ /// /// When calling a function with a `DictionaryLiteral` parameter, you can pass /// a Swift dictionary literal without causing a `Dictionary` to be created. /// This capability can be especially important when the order of elements in /// the literal is significant. /// /// For example, you could create an `IntPairs` structure that holds a list of /// two-integer tuples and use an initializer that accepts a /// `DictionaryLiteral` instance. /// /// struct IntPairs { /// var elements: [(Int, Int)] /// /// init(_ elements: DictionaryLiteral<Int, Int>) { /// self.elements = Array(elements) /// } /// } /// /// When you're ready to create a new `IntPairs` instance, use a dictionary /// literal as the parameter to the `IntPairs` initializer. The /// `DictionaryLiteral` instance preserves the order of the elements as /// passed. /// /// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1]) /// print(pairs.elements) /// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]" @_fixed_layout // FIXME(sil-serialize-all) public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral { /// Creates a new `DictionaryLiteral` instance from the given dictionary /// literal. /// /// The order of the key-value pairs is kept intact in the resulting /// `DictionaryLiteral` instance. @inlinable // FIXME(sil-serialize-all) public init(dictionaryLiteral elements: (Key, Value)...) { self._elements = elements } @usableFromInline // FIXME(sil-serialize-all) internal let _elements: [(Key, Value)] } /// `Collection` conformance that allows `DictionaryLiteral` to /// interoperate with the rest of the standard library. extension DictionaryLiteral : RandomAccessCollection { public typealias Indices = Range<Int> /// The position of the first element in a nonempty collection. /// /// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to /// `endIndex`. @inlinable // FIXME(sil-serialize-all) public var startIndex: Int { return 0 } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to /// `startIndex`. @inlinable // FIXME(sil-serialize-all) public var endIndex: Int { return _elements.endIndex } // FIXME(ABI)#174 (Type checker): a typealias is needed to prevent <rdar://20248032> /// The element type of a `DictionaryLiteral`: a tuple containing an /// individual key-value pair. public typealias Element = (key: Key, value: Value) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// - Returns: The key-value pair at position `position`. @inlinable // FIXME(sil-serialize-all) public subscript(position: Int) -> Element { return _elements[position] } } extension String { /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" @inlinable // FIXME(sil-serialize-all) public init<Subject>(describing instance: Subject) { self.init() _print_unlocked(instance, &self) } /// Creates a string with a detailed representation of the given value, /// suitable for debugging. /// /// Use this initializer to convert an instance of any type to its custom /// debugging representation. The initializer creates the string /// representation of `instance` in one of the following ways, depending on /// its protocol conformance: /// /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `subject.debugDescription`. /// - If `subject` conforms to the `CustomStringConvertible` protocol, the /// result is `subject.description`. /// - If `subject` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `subject.write(to: s)` on an empty /// string `s`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing /// the `debugDescription` property, `Point` provides its own custom /// debugging representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" @inlinable // FIXME(sil-serialize-all) public init<Subject>(reflecting subject: Subject) { self.init() _debugPrint_unlocked(subject, &self) } } /// Reflection for `Mirror` itself. extension Mirror : CustomStringConvertible { @inlinable // FIXME(sil-serialize-all) public var description: String { return "Mirror for \(self.subjectType)" } } extension Mirror : CustomReflectable { @inlinable // FIXME(sil-serialize-all) public var customMirror: Mirror { return Mirror(self, children: [:]) } }
apache-2.0
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift
1
1883
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /// Array of bytes. Caution: don't use directly because generic is slow. /// /// - parameter value: integer value /// - parameter length: length of output array. By default size of value type /// /// - returns: Array of bytes @_specialize(where T == Int) @_specialize(where T == UInt) @_specialize(where T == UInt8) @_specialize(where T == UInt16) @_specialize(where T == UInt32) @_specialize(where T == UInt64) func arrayOfBytes<T: FixedWidthInteger>(value: T, length totalBytes: Int = MemoryLayout<T>.size) -> Array<UInt8> { let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytesPointer = UnsafeMutablePointer<UInt8>(OpaquePointer(valuePointer)) var bytes = Array<UInt8>(repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } valuePointer.deinitialize(count: 1) valuePointer.deallocate() return bytes }
gpl-3.0
brettg/Signal-iOS
Signal/src/call/OutboundCallInitiator.swift
1
2311
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation /** * Creates an outbound call via WebRTC. */ @objc class OutboundCallInitiator: NSObject { let TAG = "[OutboundCallInitiator]" let contactsManager: OWSContactsManager let contactsUpdater: ContactsUpdater init(contactsManager: OWSContactsManager, contactsUpdater: ContactsUpdater) { self.contactsManager = contactsManager self.contactsUpdater = contactsUpdater super.init() } /** * |handle| is a user formatted phone number, e.g. from a system contacts entry */ public func initiateCall(handle: String) -> Bool { Logger.info("\(TAG) in \(#function) with handle: \(handle)") guard let recipientId = PhoneNumber(fromUserSpecifiedText: handle)?.toE164() else { Logger.warn("\(TAG) unable to parse signalId from phone number: \(handle)") return false } return initiateCall(recipientId: recipientId) } /** * |recipientId| is a e164 formatted phone number. */ public func initiateCall(recipientId: String) -> Bool { // Rather than an init-assigned dependency property, we access `callUIAdapter` via Environment // because it can change after app launch due to user settings guard let callUIAdapter = Environment.getCurrent().callUIAdapter else { assertionFailure() Logger.error("\(TAG) can't initiate call because callUIAdapter is nil") return false } // Check for microphone permissions // Alternative way without prompting for permissions: // if AVAudioSession.sharedInstance().recordPermission() == .denied { AVAudioSession.sharedInstance().requestRecordPermission { isGranted in DispatchQueue.main.async { // Here the permissions are either granted or denied guard isGranted == true else { Logger.warn("\(self.TAG) aborting due to missing microphone permissions.") OWSAlerts.showNoMicrophonePermissionAlert() return } callUIAdapter.startAndShowOutgoingCall(recipientId: recipientId) } } return true } }
gpl-3.0
guoziyan/Reader
Reader/RssItem.swift
1
456
// // RssItem.swift // Reader // // Created by 李晓辉 on 10/18/15. // Copyright © 2015 李晓辉. All rights reserved. // import Foundation import RealmSwift class RssItem: Object { dynamic var title = "" dynamic var describe = "" dynamic var data = "" } class RssItemManager { static let sharedInstance = RssItemManager() func addRssItem(item: RssItem) { } func updateRssItem() { } }
apache-2.0
braintree/braintree_ios
Sources/BraintreeSEPADirectDebit/BTSEPADirectDebitRequest.swift
1
2227
import Foundation #if canImport(BraintreeCore) import BraintreeCore #endif /// Parameters for creating a SEPA Direct Debit tokenization request. @objcMembers public class BTSEPADirectDebitRequest: NSObject { /// Required. The account holder name. public var accountHolderName: String? /// Required. The full IBAN. public var iban: String? /// Required. The customer ID. public var customerID: String? /// Optional. The `BTSEPADebitMandateType`. If not set, defaults to `.oneOff` public var mandateType: BTSEPADirectDebitMandateType? /// Required. The user's billing address. public var billingAddress: BTPostalAddress? /// Optional. A non-default merchant account to use for tokenization. public var merchantAccountID: String? var cancelURL: String var returnURL: String /// Initialize a new SEPA Direct Debit request. /// - Parameters: /// - accountHolderName:Required. The account holder name. /// - iban: Required. The full IBAN. /// - customerID: Required. The customer ID. /// - mandateType: Optional. The `BTSEPADebitMandateType`. If not set, defaults to `.oneOff` /// - billingAddress: Required. The user's billing address. /// - merchantAccountID: Optional. A non-default merchant account to use for tokenization. // NEXT_MAJOR_VERSION consider refactoring public request initializers to include required parameters instead of defaulting everything to optional public init( accountHolderName: String? = nil, iban: String? = nil, customerID: String? = nil, mandateType: BTSEPADirectDebitMandateType? = .oneOff, billingAddress: BTPostalAddress? = nil, merchantAccountID: String? = nil ) { self.accountHolderName = accountHolderName self.iban = iban self.customerID = customerID self.mandateType = mandateType self.billingAddress = billingAddress self.merchantAccountID = merchantAccountID let bundleID = Bundle.main.bundleIdentifier ?? "" self.cancelURL = bundleID.appending("://sepa/cancel") self.returnURL = bundleID.appending("://sepa/success") } }
mit
AndrewBennet/readinglist
ReadingList/ViewControllers/Settings/Appearance.swift
1
3541
import Foundation import SwiftUI class AppearanceSettings: ObservableObject { @Published var showExpandedDescription: Bool = GeneralSettings.showExpandedDescription { didSet { GeneralSettings.showExpandedDescription = showExpandedDescription } } @Published var showAmazonLinks: Bool = GeneralSettings.showAmazonLinks { didSet { GeneralSettings.showAmazonLinks = showAmazonLinks } } @Published var darkModeOverride: Bool? = GeneralSettings.darkModeOverride { didSet { GeneralSettings.darkModeOverride = darkModeOverride } } } struct Appearance: View { @EnvironmentObject var hostingSplitView: HostingSettingsSplitView @ObservedObject var settings = AppearanceSettings() var inset: Bool { hostingSplitView.isSplit } func updateWindowInterfaceStyle() { if let darkModeOverride = settings.darkModeOverride { AppDelegate.shared.window?.overrideUserInterfaceStyle = darkModeOverride ? .dark : .light } else { AppDelegate.shared.window?.overrideUserInterfaceStyle = .unspecified } } var darkModeSystemSettingToggle: Binding<Bool> { Binding( get: { settings.darkModeOverride == nil }, set: { settings.darkModeOverride = $0 ? nil : false updateWindowInterfaceStyle() } ) } var body: some View { SwiftUI.List { Section( header: HeaderText("Dark Mode", inset: inset) ) { Toggle(isOn: darkModeSystemSettingToggle) { Text("Use System Setting") } if let darkModeOverride = settings.darkModeOverride { CheckmarkCellRow("Light Appearance", checkmark: !darkModeOverride) .onTapGesture { settings.darkModeOverride = false updateWindowInterfaceStyle() } CheckmarkCellRow("Dark Appearance", checkmark: darkModeOverride) .onTapGesture { settings.darkModeOverride = true updateWindowInterfaceStyle() } } } Section( header: HeaderText("Book Details", inset: inset), footer: FooterText("Enable Expanded Descriptions to automatically show each book's full description.", inset: inset) ) { Toggle(isOn: $settings.showAmazonLinks) { Text("Show Amazon Links") } Toggle(isOn: $settings.showExpandedDescription) { Text("Expanded Descriptions") } } }.possiblyInsetGroupedListStyle(inset: inset) } } struct CheckmarkCellRow: View { let text: String let checkmark: Bool init(_ text: String, checkmark: Bool) { self.text = text self.checkmark = checkmark } var body: some View { HStack { Text(text) Spacer() if checkmark { Image(systemName: "checkmark").foregroundColor(Color(.systemBlue)) } }.contentShape(Rectangle()) } } struct Appearance_Previews: PreviewProvider { static var previews: some View { Appearance().environmentObject(HostingSettingsSplitView()) } }
gpl-3.0
dnevera/IMProcessing
IMPlatforms/IMProcessingiOS/IMProcessingiOS/AppDelegate.swift
1
2330
// // AppDelegate.swift // IMProcessingiOS // // Created by denis svinarchuk on 24.12.15. // Copyright © 2015 ImageMetalling. All rights reserved. // import UIKit import IMProcessing public extension IMProcessing{ public struct css { static let background = IMPColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.8) } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
allbto/WayThere
ios/WayThere/WayThere/Classes/Controllers/Cities/Cells/CityWeatherTableViewCell.swift
2
739
// // CityWeatherTableViewCell.swift // WayThere // // Created by Allan BARBATO on 5/20/15. // Copyright (c) 2015 Allan BARBATO. All rights reserved. // import Foundation import UIKit class CityWeatherTableViewCell: UITableViewCell { @IBOutlet weak var weatherImageView: UIImageView! @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var temperatureLabel: 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 } }
mit
kickstarter/ios-oss
Kickstarter-iOS/Features/FindFriends/Datasource/FindFriendsDataSource.swift
1
1540
import KsApi import Library import Prelude import UIKit internal final class FindFriendsDataSource: ValueCellDataSource { fileprivate enum Section: Int { case facebookConnect case stats case friends } internal func facebookConnect(source: FriendsSource, visible: Bool) { self.set( values: visible ? [source] : [], cellClass: FindFriendsFacebookConnectCell.self, inSection: Section.facebookConnect.rawValue ) } internal func stats(stats: FriendStatsEnvelope, source: FriendsSource) { self.set( values: [(stats, source)], cellClass: FindFriendsStatsCell.self, inSection: Section.stats.rawValue ) } internal func friends(_ friends: [User], source: FriendsSource) { let friendAndSource = friends.map { (friend: $0, source: source) } self.set( values: friendAndSource, cellClass: FindFriendsFriendFollowCell.self, inSection: Section.friends.rawValue ) } override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) { switch (cell, value) { case let (cell as FindFriendsStatsCell, value as (FriendStatsEnvelope, FriendsSource)): cell.configureWith(value: value) case let (cell as FindFriendsFriendFollowCell, value as (User, FriendsSource)): cell.configureWith(value: value) case let (cell as FindFriendsFacebookConnectCell, value as FriendsSource): cell.configureWith(value: value) default: assertionFailure("Unrecognized combo: \(cell), \(value)") } } }
apache-2.0
jpgilchrist/pitch-perfect
Pitch Perfect/PlaySoundsViewController.swift
1
3929
// // PlaySoundsViewController.swift // Pitch Perfect // // Created by James Gilchrist on 3/7/15. // Copyright (c) 2015 James Gilchrist. All rights reserved. // import UIKit import AVFoundation class PlaySoundsViewController: UIViewController { @IBOutlet weak var recordedAudioTitleLabel: UILabel! @IBOutlet weak var playWithReverb: UISwitch! let audioEngine = AVAudioEngine() let audioPlayer = AVAudioPlayerNode() let audioPitchEffect = AVAudioUnitTimePitch() let audioDelayEffect = AVAudioUnitDelay() let audioReverbEffect = AVAudioUnitReverb() var receivedAudio: RecordedAudio! override func viewDidLoad() { super.viewDidLoad() audioEngine.attachNode(audioPlayer) audioEngine.attachNode(audioPitchEffect) audioEngine.attachNode(audioDelayEffect) audioEngine.attachNode(audioReverbEffect) recordedAudioTitleLabel.text = receivedAudio.title playWithReverb.on = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func snailPlaybackButton(sender: UIButton) { playRecording(rate: 0.5, overlap: nil, pitch: nil) } @IBAction func rabbitPlaybackButton(sender: UIButton) { playRecording(rate: 2.0, overlap: nil, pitch: nil) } @IBAction func chipmunkPlaybackButton(sender: UIButton) { playRecording(rate: nil, overlap: nil, pitch: 1000.0) } @IBAction func darthVaderPlaybackButton(sender: UIButton) { playRecording(rate: nil, overlap: nil, pitch: -1000.0) } @IBAction func playReverbPlaybackButton(sender: UIButton) { playRecording(rate: nil, overlap: nil, pitch: nil, reverb: true) } @IBAction func stopPlaybackButton(sender: UIButton) { audioPlayer.stop() audioEngine.stop() } func playRecording(#rate: Float?, overlap: Float?, pitch: Float?) { playRecording(rate: rate, overlap: overlap, pitch: pitch, reverb: false) } func playRecording(#rate: Float?, overlap: Float?, pitch: Float?, reverb: Bool) { audioPlayer.stop() audioEngine.stop() audioEngine.reset() //setup rate, pitch, and overlap; if nil set to defaults if rate != nil { audioPitchEffect.rate = rate! } else { audioPitchEffect.rate = 1.0 } if overlap != nil { audioPitchEffect.overlap = overlap! } else { audioPitchEffect.overlap = 8.0 } if pitch != nil { audioPitchEffect.pitch = pitch! } else { audioPitchEffect.pitch = 1.0 } if playWithReverb.on { audioDelayEffect.delayTime = 0.25 audioDelayEffect.feedback = 80 audioReverbEffect.loadFactoryPreset(AVAudioUnitReverbPreset.LargeHall2) } else { audioDelayEffect.delayTime = 0.0 audioDelayEffect.feedback = 0 audioReverbEffect.loadFactoryPreset(AVAudioUnitReverbPreset.SmallRoom) } audioEngine.connect(audioPlayer, to: audioPitchEffect, format: receivedAudio.audioFile.processingFormat) audioEngine.connect(audioPitchEffect, to: audioDelayEffect, format: receivedAudio.audioFile.processingFormat) audioEngine.connect(audioDelayEffect, to: audioReverbEffect, format: receivedAudio.audioFile.processingFormat) audioEngine.connect(audioReverbEffect, to: audioEngine.outputNode, format: receivedAudio.audioFile.processingFormat) audioPlayer.scheduleFile(receivedAudio.audioFile, atTime: nil, completionHandler: nil) audioEngine.startAndReturnError(nil) println("play rate: \(rate) overlap: \(overlap) pitch: \(pitch) reverb: \(reverb)") audioPlayer.play() } }
mit
getsentry/sentry-swift
Tests/SentryTests/Networking/TestProtocolClient.swift
1
2409
import Foundation class TestProtocolClient: NSObject, URLProtocolClient { var testCallback: ((String, [String: Any?]) -> Void)? func urlProtocol(_ callingProtocol: URLProtocol, wasRedirectedTo request: URLRequest, redirectResponse: URLResponse) { testCallback?("urlProtocol:wasRedirectedTo:redirectResponse:", ["urlProtocol": callingProtocol, "wasRedirectedTo": request, "redirectResponse": redirectResponse]) } func urlProtocol(_ callingProtocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse) { testCallback?("urlProtocol:cachedResponseIsValid:", ["urlProtocol": callingProtocol, "cachedResponseIsValid": cachedResponse]) } func urlProtocol(_ callingProtocol: URLProtocol, didReceive response: URLResponse, cacheStoragePolicy policy: URLCache.StoragePolicy) { testCallback?("urlProtocol:didReceive:cacheStoragePolicy:", ["urlProtocol": callingProtocol, "didReceive": response, "cacheStoragePolicy": policy]) } func urlProtocol(_ callingProtocol: URLProtocol, didLoad data: Data) { testCallback?("urlProtocol:didLoad:", ["urlProtocol": callingProtocol, "didLoad": data]) } func urlProtocolDidFinishLoading(_ callingProtocol: URLProtocol) { testCallback?("urlProtocolDidFinishLoading:", ["urlProtocol": callingProtocol]) } func urlProtocol(_ callingProtocol: URLProtocol, didFailWithError error: Error) { testCallback?("urlProtocol:didFailWithError:", ["urlProtocol": callingProtocol, "didFailWithError": error]) } func urlProtocol(_ callingProtocol: URLProtocol, didReceive challenge: URLAuthenticationChallenge) { testCallback?("urlProtocol:didReceive:", ["urlProtocol": callingProtocol, "didReceive": challenge]) } func urlProtocol(_ callingProtocol: URLProtocol, didCancel challenge: URLAuthenticationChallenge) { testCallback?("urlProtocol:didCancel:", ["urlProtocol": callingProtocol, "didCancel": challenge]) } }
mit
lanjing99/RxSwiftDemo
08-transforming-operators-in-practice/starter/GitFeed/GitFeed/Event.swift
1
2048
/* * Copyright (c) 2016 Razeware LLC * * 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 typealias AnyDict = [String: Any] class Event { let repo: String let name: String let imageUrl: URL let action: String // MARK: - JSON -> Event init(dictionary: AnyDict) { guard let repoDict = dictionary["repo"] as? AnyDict, let actor = dictionary["actor"] as? AnyDict, let repoName = repoDict["name"] as? String, let actorName = actor["display_login"] as? String, let actorUrlString = actor["avatar_url"] as? String, let actorUrl = URL(string: actorUrlString), let actionType = dictionary["type"] as? String else { fatalError() } repo = repoName name = actorName imageUrl = actorUrl action = actionType } // MARK: - Event -> JSON var dictionary: AnyDict { return [ "repo" : ["name": repo], "actor": ["display_login": name, "avatar_url": imageUrl.absoluteString], "type" : action ] } }
mit
garethpaul/swift-sample-apps
basic-note-taker/basic-note-taker/NoteListViewController.swift
1
2174
// // NoteListViewController.swift // basic-note-taker // // Created by Gareth Paul Jones on 6/4/14. // Copyright (c) 2014 Gareth Paul Jones. All rights reserved. // import UIKit class NoteListViewController: UITableViewController, NoteEditorViewControllerDelegate { let cellClass = UITableViewCell.self var cellIdentifier: String { return NSStringFromClass(cellClass) } var editor: NoteEditorViewController? { didSet { if let eeditor: NoteEditorViewController = editor { navigationController.pushViewController(eeditor, animated: true) eeditor.delegate = self } } } var notes: String[] var selectedNote: Int? init(notes: String[] = []) { self.notes = notes super.init(nibName: nil, bundle: nil) self.title = NSBundle.mainBundle().infoDictionary["CFBundleName"] as? String } override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(cellClass, forCellReuseIdentifier: NSStringFromClass(cellClass)) } override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { editor = NoteEditorViewController(note: note(indexPath)) selectedNote = indexPath.row } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return notes.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { // I think I ought to use an optional here to explicity cope with potential nils let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell cell.textLabel.text = note(indexPath) return cell } func note(indexPath: NSIndexPath) -> String { return notes[indexPath.row] } func noteEditorDidUpdateNote(editor: NoteEditorViewController) { if let sselectedNote: Int = selectedNote { notes[sselectedNote] = editor.note tableView.reloadData() } } }
apache-2.0
PumpMagic/ostrich
gameboy/gameboy/Source/Memories/DataBus.swift
1
7004
// // DataBus.swift // ostrichframework // // Created by Ryan Conway on 4/4/16. // Copyright © 2016 Ryan Conway. All rights reserved. // import Foundation protocol DelegatesReads: HandlesReads { func connectReadable(_ readable: BusListener & HandlesReads) } protocol DelegatesWrites: HandlesWrites { func connectWriteable(_ writeable: BusListener & HandlesWrites) } /// A data bus that connects any numbers of peripherals. open class DataBus: DelegatesReads, DelegatesWrites { //@todo consider using Intervals instead of Ranges: //http://oleb.net/blog/2015/09/swift-ranges-and-intervals/ /// (ID, peripheral, address range) var readables: [(HandlesReads, CountableClosedRange<Address>, String?)] var writeables: [(HandlesWrites, CountableClosedRange<Address>, String?)] enum TransactionDirection { case read case write } struct Transaction: CustomStringConvertible { let direction: TransactionDirection let address: Address let number: UInt8 var description: String { switch direction { case .read: return "\(address.hexString) -> \(number.hexString)" case .write: return "\(address.hexString) <- \(number.hexString)" } } } let logTransactions: Bool = false var transactions: [Transaction] = [] public init() { self.readables = [(HandlesReads, CountableClosedRange<Address>, String?)]() self.writeables = [(HandlesWrites, CountableClosedRange<Address>, String?)]() } open func connectReadable(_ readable: BusListener & HandlesReads) { self.readables.append((readable, readable.addressRange, nil)) } open func connectWriteable(_ writeable: BusListener & HandlesWrites) { self.writeables.append((writeable, writeable.addressRange, nil)) } open func connectReadable(_ readable: BusListener & HandlesReads, id: String) { self.readables.append((readable, readable.addressRange, id)) } open func connectWriteable(_ readable: BusListener & HandlesWrites, id: String) { self.writeables.append((readable, readable.addressRange, id)) } open func disconnectReadable(id: String) { var elementFound: Bool repeat { elementFound = false for (index, (_, _, elementID)) in self.readables.enumerated() { if elementID == id { self.readables.remove(at: index) elementFound = true break } } } while elementFound } //@todo the logic here is duplicated with disconnectReadable(). // This is because there's no common type between self.readables and self.writeables. open func disconnectWriteable(id: String) { var elementFound: Bool repeat { elementFound = false for (index, (_, _, elementID)) in self.writeables.enumerated() { if elementID == id { self.readables.remove(at: index) elementFound = true break } } } while elementFound } open func read(_ addr: Address) -> UInt8 { for (readable, range, _) in self.readables { if range ~= addr { let val = readable.read(addr) if self.logTransactions { if addr > 0x7FFF { let transaction = Transaction(direction: .read, address: addr, number: val) self.transactions.append(transaction) } } return val } } // Hack: implement divider register here // Increments at 16384Hz, or ABOUT once every 61 microseconds // 8-bit value -> overflows at (16384/256) = 64Hz //@todo don't be so sloppy if addr == 0xFF04 { let secs = Date().timeIntervalSince1970 let remainder = secs - round(secs) let us = remainder*1000000 return UInt8(truncatingBitPattern: (Int((us/61).truncatingRemainder(dividingBy: 255)))) } // Hack: implement echo RAM here // 0xE000 - 0xFDFF is an echo of 0xC000 - 0xDDFF. // Nintendo said not to use it, but apparently some games did anyway if Address(0xE000) ... Address(0xFDFF) ~= addr { print("WARNING: attempt to use echo RAM. Parsing failure?") return self.read(addr - 0x2000) } //print("WARNING: no one listening to read of address \(addr.hexString)") //@todo probably shouldn't return 0 return 0 //exit(1) } open func write(_ val: UInt8, to addr: Address) { for (writeable, range, _) in self.writeables { if range ~= addr { writeable.write(val, to: addr) if self.logTransactions { let transaction = Transaction(direction: .write, address: addr, number: val) self.transactions.append(transaction) } return } } // Hack: memory bank controller is unimplemented for now; ignore communication with it //@todo implement the memory bank controller if Address(0x0000) ... Address(0x7FFF) ~= addr { print("WARNING! Ignoring memory bank controller communication in the form of writing \(val.hexString) to \(addr.hexString)") if Address(0x0000) ... Address(0x1FFF) ~= addr { print("(external RAM control)") } return } print("WARNING: no one listening to write of \(val.hexString) to address \(addr.hexString)") //@todo actually exit // exit(1) } // Convenience functions func readSigned(_ addr: Address) -> Int8 { return Int8(bitPattern: self.read(addr)) } /// Reads two bytes of memory and returns them in host endianness func read16(_ addr: Address) -> UInt16 { let low = self.read(addr) let high = self.read(addr+1) return make16(high: high, low: low) } /// Writes two bytes of memory (given in host endianness) func write16(_ val: UInt16, to addr: Address) { self.write(getLow(val), to: addr) self.write(getHigh(val), to: addr+1) } open func dumpTransactions() { print(self.transactions) } open func clearTransactions() { self.transactions = [] } func clearAllWriteables() { for (writeable, range, _) in self.writeables { for addr in range { writeable.write(0, to: addr) } } } }
mit
roambotics/swift
test/IDE/complete_type.swift
2
37781
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t //===--- Helper types that are used in this test struct FooStruct { } var fooObject: FooStruct func fooFunc() -> FooStruct { return fooObject } enum FooEnum { } class FooClass { } protocol FooProtocol { var fooInstanceVar: Int typealias FooTypeAlias1 func fooInstanceFunc0() -> Double func fooInstanceFunc1(a: Int) -> Double subscript(i: Int) -> Double } protocol BarProtocol { var barInstanceVar: Int typealias BarTypeAlias1 func barInstanceFunc0() -> Double func barInstanceFunc1(a: Int) -> Double } typealias FooTypealias = Int // WITH_GLOBAL_TYPES: Begin completions // Global completions // WITH_GLOBAL_TYPES-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_GLOBAL_TYPES-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}} // WITH_GLOBAL_TYPES-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}} // WITH_GLOBAL_TYPES-DAG: Decl[Protocol]/CurrModule: FooProtocol[#FooProtocol#]{{; name=.+$}} // WITH_GLOBAL_TYPES-DAG: Decl[TypeAlias]/CurrModule: FooTypealias[#Int#]{{; name=.+$}} // WITH_GLOBAL_TYPES: End completions // WITH_GLOBAL_TYPES_EXPR: Begin completions // Global completions at expression position // WITH_GLOBAL_TYPES_EXPR-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_GLOBAL_TYPES_EXPR-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}} // WITH_GLOBAL_TYPES_EXPR-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}} // WITH_GLOBAL_TYPES_EXPR-DAG: Decl[Protocol]/CurrModule/Flair[RareType]: FooProtocol[#FooProtocol#]{{; name=.+$}} // WITH_GLOBAL_TYPES_EXPR-DAG: Decl[TypeAlias]/CurrModule: FooTypealias[#Int#]{{; name=.+$}} // WITH_GLOBAL_TYPES_EXPR: End completions // GLOBAL_NEGATIVE-NOT: Decl.*: fooObject // GLOBAL_NEGATIVE-NOT: Decl.*: fooFunc // WITHOUT_GLOBAL_TYPES-NOT: Decl.*: FooStruct // WITHOUT_GLOBAL_TYPES-NOT: Decl.*: FooEnum // WITHOUT_GLOBAL_TYPES-NOT: Decl.*: FooClass // WITHOUT_GLOBAL_TYPES-NOT: Decl.*: FooProtocol // WITHOUT_GLOBAL_TYPES-NOT: Decl.*: FooTypealias // ERROR_COMMON: found code completion token // ERROR_COMMON-NOT: Begin completions //===--- //===--- Test that we include 'Self' type while completing inside a protocol. //===--- // TYPE_IN_PROTOCOL: Begin completions // TYPE_IN_PROTOCOL-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]{{; name=.+$}} // TYPE_IN_PROTOCOL: End completions protocol TestSelf1 { func instanceFunc() -> #^TYPE_IN_PROTOCOL_1?check=TYPE_IN_PROTOCOL;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } //===--- //===--- Test that we include types from generic parameter lists. //===--- // FIXME: tests for constructors and destructors. func testTypeInParamGeneric1< GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_1?check=TYPE_IN_FUNC_PARAM_GENERIC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# // TYPE_IN_FUNC_PARAM_GENERIC_1: Begin completions // Generic parameters of the function. // TYPE_IN_FUNC_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_1: End completions struct TestTypeInParamGeneric2< StructGenericFoo : FooProtocol, StructGenericBar : FooProtocol & BarProtocol, StructGenericBaz> { func testTypeInParamGeneric2(a: #^TYPE_IN_FUNC_PARAM_GENERIC_2?check=TYPE_IN_FUNC_PARAM_GENERIC_2;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_FUNC_PARAM_GENERIC_2: Begin completions // TYPE_IN_FUNC_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_2: End completions struct TestTypeInParamGeneric3 { func testTypeInParamGeneric3< GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_3?check=TYPE_IN_FUNC_PARAM_GENERIC_3;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_FUNC_PARAM_GENERIC_3: Begin completions // TYPE_IN_FUNC_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_3: End completions struct TestTypeInParamGeneric4< StructGenericFoo : FooProtocol, StructGenericBar : FooProtocol & BarProtocol, StructGenericBaz> { func testTypeInParamGeneric4< GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_4?check=TYPE_IN_FUNC_PARAM_GENERIC_4;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_FUNC_PARAM_GENERIC_4: Begin completions // Generic parameters of the struct. // TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}} // Generic parameters of the function. // TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_4: End completions struct TestTypeInParamGeneric5<StructGenericFoo> { struct TestTypeInParamGeneric5a<StructGenericBar> { struct TestTypeInParamGeneric5b<StructGenericBaz> { func testTypeInParamGeneric5<GenericFoo>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_5?check=TYPE_IN_FUNC_PARAM_GENERIC_5;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } } } // TYPE_IN_FUNC_PARAM_GENERIC_5: Begin completions // Generic parameters of the containing structs. // TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}} // Generic parameters of the function. // TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // TYPE_IN_FUNC_PARAM_GENERIC_5: End completions struct TestTypeInConstructorParamGeneric1< StructGenericFoo : FooProtocol, StructGenericBar : FooProtocol & BarProtocol, StructGenericBaz> { init(a: #^TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1?check=TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1: Begin completions // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1: End completions struct TestTypeInConstructorParamGeneric2 { init<GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: #^TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2?check=TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2: Begin completions // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2: End completions struct TestTypeInConstructorParamGeneric3< StructGenericFoo : FooProtocol, StructGenericBar : FooProtocol & BarProtocol, StructGenericBaz> { init<GenericFoo : FooProtocol, GenericBar : FooProtocol & BarProtocol, GenericBaz>(a: #^TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3?check=TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3: Begin completions // Generic parameters of the struct. // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}} // Generic parameters of the constructor. // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}} // TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3: End completions // No tests for destructors: destructors don't have parameters. //===--- //===--- Test that we don't duplicate generic parameters. //===--- struct GenericStruct<T> { func foo() -> #^TYPE_IN_RETURN_GEN_PARAM_NO_DUP^# } class A<T> { var foo: #^TYPE_IVAR_GEN_PARAM_NO_DUP^# subscript(_ arg: Int) -> #^TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP^# } // TYPE_IN_RETURN_GEN_PARAM_NO_DUP: Begin completions // TYPE_IN_RETURN_GEN_PARAM_NO_DUP-DAG: Decl[GenericTypeParam]/Local: T[#T#]; name=T // TYPE_IN_RETURN_GEN_PARAM_NO_DUP-NOT: Decl[GenericTypeParam]/Local: T[#T#]; name=T // TYPE_IN_RETURN_GEN_PARAM_NO_DUP: End completions // TYPE_IVAR_GEN_PARAM_NO_DUP: Begin completions // TYPE_IVAR_GEN_PARAM_NO_DUP-DAG: Decl[GenericTypeParam]/Local: T[#T#]; name=T // TYPE_IVAR_GEN_PARAM_NO_DUP-NOT: Decl[GenericTypeParam]/Local: T[#T#]; name=T // TYPE_IVAR_GEN_PARAM_NO_DUP: End completions // TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP: Begin completions // TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP-DAG: Decl[GenericTypeParam]/Local: T[#T#]; name=T // TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP-NOT: Decl[GenericTypeParam]/Local: T[#T#]; name=T // TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP: End completions //===--- //===--- Test that we can complete types in variable declarations. //===--- func testTypeInLocalVarInFreeFunc1() { var localVar: #^TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInLocalVarInFreeFunc2() { struct NestedStruct {} class NestedClass {} enum NestedEnum { case NestedEnumX(Int) } typealias NestedTypealias = Int var localVar: #^TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2?check=TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2: Begin completions // TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[Struct]/Local: NestedStruct[#NestedStruct#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[Class]/Local: NestedClass[#NestedClass#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[Enum]/Local: NestedEnum[#NestedEnum#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[TypeAlias]/Local: NestedTypealias[#Int#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2: End completions class TestTypeInLocalVarInMemberFunc1 { struct NestedStruct {} class NestedClass {} enum NestedEnum { case NestedEnumX(Int) } typealias NestedTypealias = Int init() { var localVar: #^TYPE_IN_LOCAL_VAR_IN_CONSTRUCTOR_1?check=TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } deinit { var localVar: #^TYPE_IN_LOCAL_VAR_IN_DESTRUCTOR_1?check=TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func test() { var localVar: #^TYPE_IN_LOCAL_VAR_IN_INSTANCE_FUNC_1?check=TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } } // TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1: Begin completions // TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1: End completions var TypeInGlobalVar1: #^TYPE_IN_GLOBAL_VAR_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# //===--- //===--- Test that we can complete types in typealias declarations. //===--- typealias TypeInTypealias1 = #^TYPE_IN_TYPEALIAS_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# typealias TypeInTypealias2 = (#^TYPE_IN_TYPEALIAS_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func resyncParser0() {} typealias TypeInTypealias3 = ((#^TYPE_IN_TYPEALIAS_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func resyncParser1() {} //===--- //===--- Test that we can complete types in associated type declarations. //===--- protocol AssocType1 { associatedtype AssocType = #^TYPE_IN_ASSOC_TYPE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } //===--- //===--- Test that we can complete types in inheritance clause of associated type declarations. //===--- protocol AssocType1 { associatedtype AssocType : #^TYPE_IN_ASSOC_TYPE_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } //===--- //===--- Test that we can complete types in extension declarations. //===--- extension #^TYPE_IN_EXTENSION_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# //===--- //===--- Test that we can complete types in the extension inheritance clause. //===--- extension TypeInExtensionInheritance1 : #^TYPE_IN_EXTENSION_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# extension TypeInExtensionInheritance2 : #^TYPE_IN_EXTENSION_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } extension TypeInExtensionInheritance3 : FooProtocol, #^TYPE_IN_EXTENSION_INHERITANCE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } //===--- //===--- Test that we can complete types in the struct inheritance clause. //===--- struct TypeInStructInheritance1 : #^TYPE_IN_STRUCT_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# struct TypeInStructInheritance2 : , #^TYPE_IN_STRUCT_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# struct TypeInStructInheritance3 : FooProtocol, #^TYPE_IN_STRUCT_INHERITANCE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# // FIXME: 'check' shold be 'WITH_GLOBAL_TYPES' struct TypeInStructInheritance4 : FooProtocol., #^TYPE_IN_STRUCT_INHERITANCE_4?check=WITH_GLOBAL_TYPES_EXPR^# struct TypeInStructInheritance5 : #^TYPE_IN_STRUCT_INHERITANCE_5?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } struct TypeInStructInheritance6 : , #^TYPE_IN_STRUCT_INHERITANCE_6?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } struct TypeInStructInheritance7 : FooProtocol, #^TYPE_IN_STRUCT_INHERITANCE_7?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } // FIXME: 'check' shold be 'WITH_GLOBAL_TYPES' struct TypeInStructInheritance8 : FooProtocol., #^TYPE_IN_STRUCT_INHERITANCE_8?check=WITH_GLOBAL_TYPES_EXPR^# { } //===--- //===--- Test that we can complete types in the class inheritance clause. //===--- class TypeInClassInheritance1 : #^TYPE_IN_CLASS_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } class TypeInClassInheritance2 : #^TYPE_IN_CLASS_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# //===--- //===--- Test that we can complete types in the enum inheritance clause. //===--- enum TypeInEnumInheritance1 : #^TYPE_IN_ENUM_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# enum TypeInEnumInheritance2 : #^TYPE_IN_ENUM_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } //===--- //===--- Test that we can complete types in the protocol inheritance clause. //===--- protocol TypeInProtocolInheritance1 : #^TYPE_IN_PROTOCOL_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# protocol TypeInProtocolInheritance2 : #^TYPE_IN_PROTOCOL_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# { } //===--- //===--- Test that we can complete types in tuple types. //===--- func testTypeInTupleType1() { var localVar: (#^TYPE_IN_TUPLE_TYPE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInTupleType2() { var localVar: (a: #^TYPE_IN_TUPLE_TYPE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInTupleType3() { var localVar: (Int, #^TYPE_IN_TUPLE_TYPE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInTupleType4() { var localVar: (a: Int, #^TYPE_IN_TUPLE_TYPE_4?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInTupleType5() { var localVar: (Int, a: #^TYPE_IN_TUPLE_TYPE_5?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInTupleType6() { var localVar: (a:, #^TYPE_IN_TUPLE_TYPE_6?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInTupleType7() { var localVar: (a: b: #^TYPE_IN_TUPLE_TYPE_7?xfail=FIXME^# } //===--- //===--- Test that we can complete types in function types. //===--- func testTypeInFunctionType1() { var localVar: #^TYPE_IN_FUNCTION_TYPE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# -> } func testTypeInFunctionType2() { var localVar: (#^TYPE_IN_FUNCTION_TYPE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#) -> () } func testTypeInFunctionType3() { var localVar: () -> #^TYPE_IN_FUNCTION_TYPE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInFunctionType4() { var localVar: (Int) -> #^TYPE_IN_FUNCTION_TYPE_4?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInFunctionType5() { var localVar: (a: Int) -> #^TYPE_IN_FUNCTION_TYPE_5?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInFunctionType6() { var localVar: (a: Int, ) -> #^TYPE_IN_FUNCTION_TYPE_6?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } //===--- //===--- Test that we can complete types in protocol compositions. //===--- func testTypeInProtocolComposition1() { var localVar: protocol<#^TYPE_IN_PROTOCOL_COMPOSITION_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInProtocolComposition2() { var localVar: protocol<, #^TYPE_IN_PROTOCOL_COMPOSITION_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } func testTypeInProtocolComposition3() { var localVar: protocol<FooProtocol, #^TYPE_IN_PROTOCOL_COMPOSITION_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } //===--- //===--- Test that we can complete types from extensions and base classes. //===--- class VarBase1 { var instanceVarBase1: #^TYPE_IN_INSTANCE_VAR_1?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func paramNestedTypesBase1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_1?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func localVarBaseTest1() { var localVar: #^TYPE_IN_LOCAL_VAR_1?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // Define types after all tests to test delayed parsing of decls. struct BaseNestedStruct {} class BaseNestedClass {} enum BaseNestedEnum { case BaseEnumX(Int) } typealias BaseNestedTypealias = Int } extension VarBase1 { var instanceVarBaseExt1: #^TYPE_IN_INSTANCE_VAR_2?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func paramNestedTypesBaseExt1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_2?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func localVarBaseExtTest1() { var localVar: #^TYPE_IN_LOCAL_VAR_2?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // Define types after all tests to test delayed parsing of decls. struct BaseExtNestedStruct {} class BaseExtNestedClass {} enum BaseExtNestedEnum { case BaseExtEnumX(Int) } typealias BaseExtNestedTypealias = Int } // VAR_BASE_1_TYPES: Begin completions // From VarBase1 // VAR_BASE_1_TYPES-DAG: Decl[Struct]/CurrNominal: BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}} // VAR_BASE_1_TYPES-DAG: Decl[Class]/CurrNominal: BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}} // VAR_BASE_1_TYPES-DAG: Decl[Enum]/CurrNominal: BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}} // VAR_BASE_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: BaseNestedTypealias[#Int#]{{; name=.+$}} // From VarBase1 extension // VAR_BASE_1_TYPES-DAG: Decl[Struct]/CurrNominal: BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}} // VAR_BASE_1_TYPES-DAG: Decl[Class]/CurrNominal: BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}} // VAR_BASE_1_TYPES-DAG: Decl[Enum]/CurrNominal: BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}} // VAR_BASE_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: BaseExtNestedTypealias[#Int#]{{; name=.+$}} // VAR_BASE_1_TYPES: End completions // VAR_BASE_1_TYPES_INCONTEXT: Begin completions // From VarBase1 // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: BaseNestedStruct[#BaseNestedStruct#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: BaseNestedClass[#BaseNestedClass#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: BaseNestedEnum[#BaseNestedEnum#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: BaseNestedTypealias[#Int#]{{; name=.+$}} // From VarBase1 extension // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: BaseExtNestedStruct[#BaseExtNestedStruct#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: BaseExtNestedClass[#BaseExtNestedClass#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: BaseExtNestedEnum[#BaseExtNestedEnum#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: BaseExtNestedTypealias[#Int#]{{; name=.+$}} // VAR_BASE_1_TYPES_INCONTEXT: End completions // VAR_BASE_1_NO_DOT_TYPES: Begin completions // From VarBase1 // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Struct]/CurrNominal: .BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Class]/CurrNominal: .BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Enum]/CurrNominal: .BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BaseNestedTypealias[#Int#]{{; name=.+$}} // From VarBase1 extension // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Struct]/CurrNominal: .BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Class]/CurrNominal: .BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Enum]/CurrNominal: .BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BaseExtNestedTypealias[#Int#]{{; name=.+$}} // VAR_BASE_1_NO_DOT_TYPES: End completions class VarDerived1 : VarBase1 { var instanceVarDerived1 : #^TYPE_IN_INSTANCE_VAR_3?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func paramNestedTypesDerived1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_3?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func localVarDerivedTest1() { var localVar : #^TYPE_IN_LOCAL_VAR_3?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // Define types after all tests to test delayed parsing of decls. struct DerivedNestedStruct {} class DerivedNestedClass {} enum DerivedNestedEnum { case DerivedEnumX(Int) } typealias DerivedNestedTypealias = Int } extension VarDerived1 { var instanceVarDerivedExt1 : #^TYPE_IN_INSTANCE_VAR_4?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func paramNestedTypesDerivedExt1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_4?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func localVarDerivedExtTest1() { var localVar : #^TYPE_IN_LOCAL_VAR_4?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } // Define types after all tests to test delayed parsing of decls. struct DerivedExtNestedStruct {} class DerivedExtNestedClass {} enum DerivedExtNestedEnum { case DerivedExtEnumX(Int) } typealias DerivedExtNestedTypealias = Int } // VAR_DERIVED_1_TYPES: Begin completions // From VarBase1 // VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/Super: BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Class]/Super: BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/Super: BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/Super: BaseNestedTypealias[#Int#]{{; name=.+$}} // From VarBase1 extension // VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/Super: BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Class]/Super: BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/Super: BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/Super: BaseExtNestedTypealias[#Int#]{{; name=.+$}} // From VarDerived1 // VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/CurrNominal: DerivedNestedStruct[#VarDerived1.DerivedNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Class]/CurrNominal: DerivedNestedClass[#VarDerived1.DerivedNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/CurrNominal: DerivedNestedEnum[#VarDerived1.DerivedNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: DerivedNestedTypealias[#Int#]{{; name=.+$}} // From VarDerived1 extension // VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/CurrNominal: DerivedExtNestedStruct[#VarDerived1.DerivedExtNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Class]/CurrNominal: DerivedExtNestedClass[#VarDerived1.DerivedExtNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/CurrNominal: DerivedExtNestedEnum[#VarDerived1.DerivedExtNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: DerivedExtNestedTypealias[#Int#]{{; name=.+$}} // VAR_DERIVED_1_TYPES: End completions // VAR_DERIVED_1_TYPES_INCONTEXT: Begin completions // From VarBase1 // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/Super: BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/Super: BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/Super: BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/Super: BaseNestedTypealias[#Int#]{{; name=.+$}} // From VarBase1 extension // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/Super: BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/Super: BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/Super: BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/Super: BaseExtNestedTypealias[#Int#]{{; name=.+$}} // From VarDerived1 // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: DerivedNestedStruct[#DerivedNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: DerivedNestedClass[#DerivedNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: DerivedNestedEnum[#DerivedNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: DerivedNestedTypealias[#Int#]{{; name=.+$}} // From VarDerived1 extension // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: DerivedExtNestedStruct[#DerivedExtNestedStruct#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: DerivedExtNestedClass[#DerivedExtNestedClass#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: DerivedExtNestedEnum[#DerivedExtNestedEnum#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: DerivedExtNestedTypealias[#Int#]{{; name=.+$}} // VAR_DERIVED_1_TYPES_INCONTEXT: End completions //===--- //===--- Test that we can complete based on user-provided type-identifier. //===--- func testTypeIdentifierBase1(a: VarBase1.#^TYPE_IDENTIFIER_BASE_1?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierBase2(a: Int, b: VarBase1.#^TYPE_IDENTIFIER_BASE_2?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierBase3(a: unknown_type, b: VarBase1.#^TYPE_IDENTIFIER_BASE_3?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierBase4(a: , b: VarBase1.#^TYPE_IDENTIFIER_BASE_4?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierBaseNoDot1(a: VarBase1#^TYPE_IDENTIFIER_BASE_NO_DOT_1?check=VAR_BASE_1_NO_DOT_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierBaseNoDot2() { var localVar : protocol<VarBase1#^TYPE_IDENTIFIER_BASE_NO_DOT_2?check=VAR_BASE_1_NO_DOT_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } typealias testTypeIdentifierBaseNoDot3 = VarBase1#^TYPE_IDENTIFIER_BASE_NO_DOT_3?check=VAR_BASE_1_NO_DOT_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierDerived1(a: VarDerived1.#^TYPE_IDENTIFIER_DERIVED_1?check=VAR_DERIVED_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierDerived2() { var localVar : protocol<VarDerived1.#^TYPE_IDENTIFIER_DERIVED_2?check=VAR_DERIVED_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } typealias testTypeIdentifierDerived3 = VarDerived1.#^TYPE_IDENTIFIER_DERIVED_3?check=VAR_DERIVED_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# func testTypeIdentifierGeneric1< GenericFoo : FooProtocol >(a: GenericFoo.#^TYPE_IDENTIFIER_GENERIC_1?check=TYPE_IDENTIFIER_GENERIC_1;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# // TYPE_IDENTIFIER_GENERIC_1: Begin completions // TYPE_IDENTIFIER_GENERIC_1-NEXT: Decl[AssociatedType]/CurrNominal: FooTypeAlias1{{; name=.+$}} // TYPE_IDENTIFIER_GENERIC_1-NEXT: Keyword/None: Type[#GenericFoo.Type#] // TYPE_IDENTIFIER_GENERIC_1-NEXT: End completions func testTypeIdentifierGeneric2< GenericFoo : FooProtocol & BarProtocol >(a: GenericFoo.#^TYPE_IDENTIFIER_GENERIC_2?check=TYPE_IDENTIFIER_GENERIC_2;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# // TYPE_IDENTIFIER_GENERIC_2: Begin completions // TYPE_IDENTIFIER_GENERIC_2-NEXT: Decl[AssociatedType]/CurrNominal: BarTypeAlias1{{; name=.+$}} // TYPE_IDENTIFIER_GENERIC_2-NEXT: Decl[AssociatedType]/CurrNominal: FooTypeAlias1{{; name=.+$}} // TYPE_IDENTIFIER_GENERIC_2-NEXT: Keyword/None: Type[#GenericFoo.Type#] // TYPE_IDENTIFIER_GENERIC_2-NEXT: End completions func testTypeIdentifierGeneric3< GenericFoo>(a: GenericFoo.#^TYPE_IDENTIFIER_GENERIC_3^# // TYPE_IDENTIFIER_GENERIC_3: Begin completions // TYPE_IDENTIFIER_GENERIC_3-NEXT: Keyword/None: Type[#GenericFoo.Type#] // TYPE_IDENTIFIER_GENERIC_3-NOT: Keyword/CurrNominal: self[#GenericFoo#] // TYPE_IDENTIFIER_GENERIC_3-NEXT: End completions func testTypeIdentifierIrrelevant1() { var a: Int #^TYPE_IDENTIFIER_IRRELEVANT_1^# } // TYPE_IDENTIFIER_IRRELEVANT_1: Begin completions // TYPE_IDENTIFIER_IRRELEVANT_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // TYPE_IDENTIFIER_IRRELEVANT_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // TYPE_IDENTIFIER_IRRELEVANT_1: End completions //===--- //===--- Test that we can complete types in 'as' cast. //===--- func testAsCast1(a: Int) { a as #^INSIDE_AS_CAST_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# } //===--- //===--- Test that we can complete generic typealiases. //===--- func testGenericTypealias1() { typealias MyPair<T> = (T, T) let x: #^GENERIC_TYPEALIAS_1^# } // FIXME: should we use the alias name in the annotation? // GENERIC_TYPEALIAS_1: Decl[TypeAlias]/Local: MyPair[#(T, T)#]; func testGenericTypealias2() { typealias MyPair<T> = (T, T) let x: MyPair<#^GENERIC_TYPEALIAS_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#> } // In generic argument struct GenStruct<T> { } let a : GenStruct<#^GENERIC_ARGS_TOPLEVEL_VAR?check=WITH_GLOBAL_TYPES^# func foo1(x: GenStruct<#^GENERIC_ARGS_TOPLEVEL_PARAM?check=WITH_GLOBAL_TYPES^# func foo2() -> GenStruct<#^GENERIC_ARGS_TOPLEVEL_RETURN?check=WITH_GLOBAL_TYPES^# class _TestForGenericArg_ { let a : GenStruct<#^GENERIC_ARGS_MEMBER_VAR?check=WITH_GLOBAL_TYPES^# func foo1(x: GenStruct<#^GENERIC_ARGS_MEMBER_PARAM?check=WITH_GLOBAL_TYPES^# func foo2() -> GenStruct<#^GENERIC_ARGS_MEMBER_RETURN?check=WITH_GLOBAL_TYPES^# } func _testForGenericArg_() { let a : GenStruct<#^GENERIC_ARGS_LOCAL_VAR?check=WITH_GLOBAL_TYPES^# func foo1(x: GenStruct<#^GENERIC_ARGS_LOCAL_PARAM?check=WITH_GLOBAL_TYPES^# func foo2() -> GenStruct<#^GENERIC_ARGS_LOCAL_RETURN?check=WITH_GLOBAL_TYPES^# } func testProtocol() { let _: FooProtocol.#^PROTOCOL_DOT_1^# // PROTOCOL_DOT_1: Begin completions, 3 items // PROTOCOL_DOT_1-DAG: Decl[AssociatedType]/CurrNominal: FooTypeAlias1; name=FooTypeAlias1 // PROTOCOL_DOT_1-DAG: Keyword/None: Protocol[#FooProtocol.Protocol#]; name=Protocol // PROTOCOL_DOT_1-DAG: Keyword/None: Type[#FooProtocol.Type#]; name=Type // PROTOCOL_DOT_1: End completions } //===--- //===--- Test we can complete unbound generic types //===--- public final class Task<Success> { public enum Inner { public typealias Failure = Int case success(Success) case failure(Failure) } } extension Task.Inner { public init(left error: Failure) { fatalError() } } extension Task.Inner.#^UNBOUND_DOT_1?check=UNBOUND_DOT^# {} func testUnbound(x: Task.Inner.#^UNBOUND_DOT_2?check=UNBOUND_DOT^#) {} // UNBOUND_DOT: Begin completions // UNBOUND_DOT-DAG: Decl[TypeAlias]/CurrNominal: Failure[#Int#]; name=Failure // UNBOUND_DOT-DAG: Keyword/None: Type[#Task.Inner.Type#]; name=Type // UNBOUND_DOT: End completions protocol MyProtocol {} struct OuterStruct<U> { class Inner<V>: MyProtocol {} } func testUnbound2(x: OuterStruct<Int>.Inner.#^UNBOUND_DOT_3^#) {} // UNBOUND_DOT_3: Begin completions // UNBOUND_DOT_3-DAG: Keyword/None: Type[#OuterStruct<Int>.Inner.Type#]; name=Type // UNBOUND_DOT_3: End completions // rdar://problem/67102794 struct HasProtoAlias { typealias ProtoAlias = FooProtocol } extension FooStruct: HasProtoAlias.#^EXTENSION_INHERITANCE_1?check=EXTENSION_INHERITANCE^# {} struct ContainExtension { extension FooStruct: HasProtoAlias.#^EXTENSION_INHERITANCE_2?check=EXTENSION_INHERITANCE^# {} } // EXTENSION_INHERITANCE: Begin completions, 2 items // EXTENSION_INHERITANCE-DAG: Decl[TypeAlias]/CurrNominal: ProtoAlias[#FooProtocol#]; // EXTENSION_INHERITANCE-DAG: Keyword/None: Type[#HasProtoAlias.Type#]; // EXTENSION_INHERITANCE: End completions var _: (() -> #^IN_POSTFIX_BASE_1?check=WITH_GLOBAL_TYPES^#)? var _: (() -> #^IN_POSTFIX_BASE_2?check=WITH_GLOBAL_TYPES^#)! var _: (() -> #^IN_POSTFIX_BASE_3?check=WITH_GLOBAL_TYPES^#)[1] var _: (() -> #^IN_POSTFIX_BASE_4?check=WITH_GLOBAL_TYPES^#).Protocol var _: (() -> #^IN_POSTFIX_BASE_5?check=WITH_GLOBAL_TYPES^#).Type struct HaveNested { struct Nested {} } var _: HaveNested.#^IN_POSTFIX_BASE_MEMBER_1?check=POSTFIX_BASE_MEMBER^#? var _: HaveNested.#^IN_POSTFIX_BASE_MEMBER_2?check=POSTFIX_BASE_MEMBER^#! var _: HaveNested.#^IN_POSTFIX_BASE_MEMBER_3?check=POSTFIX_BASE_MEMBER^#[1] var _: HaveNested.#^IN_POSTFIX_BASE_MEMBER_4?check=POSTFIX_BASE_MEMBER^#.Protocol var _: HaveNested.#^IN_POSTFIX_BASE_MEMBER_5?check=POSTFIX_BASE_MEMBER^#.Type // POSTFIX_BASE_MEMBER: Begin completions, 2 items // POSTFIX_BASE_MEMBER-DAG: Decl[Struct]/CurrNominal: Nested[#HaveNested.Nested#]; // POSTFIX_BASE_MEMBER-DAG: Keyword/None: Type[#HaveNested.Type#]; // POSTFIX_BASE_MEMBER: End completions
apache-2.0
ngageoint/mage-ios
Mage/LocationDataStore.swift
1
5902
// // LocationDataStore.swift // MAGE // // Created by Daniel Barela on 7/14/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation class LocationDataStore: NSObject { var tableView: UITableView; var scheme: MDCContainerScheming?; var locations: Locations?; weak var actionsDelegate: UserActionsDelegate?; var emptyView: UIView? public init(tableView: UITableView, actionsDelegate: UserActionsDelegate?, emptyView: UIView? = nil, scheme: MDCContainerScheming?) { self.scheme = scheme; self.tableView = tableView; self.actionsDelegate = actionsDelegate; self.emptyView = emptyView super.init(); self.tableView.dataSource = self; self.tableView.delegate = self; } func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) { self.scheme = containerScheme; } func startFetchController(locations: Locations? = nil) { if (locations == nil) { self.locations = Locations.forAllUsers(); } else { self.locations = locations; } self.locations?.delegate = self; do { try self.locations?.fetchedResultsController.performFetch() } catch { print("Error fetching locations \(error) \(error.localizedDescription)") } self.tableView.reloadData(); } func updatePredicates() { self.locations?.fetchedResultsController.fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: Locations.getPredicatesForLocations() as! [NSPredicate]); do { try self.locations?.fetchedResultsController.performFetch() } catch { print("Error fetching users \(error) \(error.localizedDescription)") } self.tableView.reloadData(); } } extension LocationDataStore: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo: NSFetchedResultsSectionInfo? = self.locations?.fetchedResultsController.sections?[section]; let number = sectionInfo?.numberOfObjects ?? 0; if number == 0 { tableView.backgroundView = emptyView } else { tableView.backgroundView = nil } return number } func numberOfSections(in tableView: UITableView) -> Int { return self.locations?.fetchedResultsController.sections?.count ?? 0; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(cellClass: PersonTableViewCell.self, forIndexPath: indexPath); configure(cell: cell, at: indexPath); return cell; } func configure(cell: PersonTableViewCell, at indexPath: IndexPath) { if let controller = self.locations?.fetchedResultsController as? NSFetchedResultsController<Location> { let location: Location = controller.object(at: indexPath) cell.configure(location: location, actionsDelegate: actionsDelegate, scheme: scheme); } } } extension LocationDataStore: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude; } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude; } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(); } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return UIView(); } } extension LocationDataStore: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: if let insertIndexPath = newIndexPath { self.tableView.insertRows(at: [insertIndexPath], with: .fade); } break; case .delete: if let deleteIndexPath = indexPath { self.tableView.deleteRows(at: [deleteIndexPath], with: .fade); } break; case .update: if let updateIndexPath = indexPath { self.tableView.reloadRows(at: [updateIndexPath], with: .none); } break; case .move: if let deleteIndexPath = indexPath { self.tableView.deleteRows(at: [deleteIndexPath], with: .fade); } if let insertIndexPath = newIndexPath { self.tableView.insertRows(at: [insertIndexPath], with: .fade); } break; default: break; } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade); break; case .delete: self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade); break; default: break; } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates(); } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates(); } }
apache-2.0
DivineDominion/mac-licensing-fastspring-cocoafob
Shared Tests/URLQueryLicenseParserTests.swift
1
1844
// Copyright (c) 2015-2019 Christian Tietze // // See the file LICENSE for copying permission. import Cocoa import XCTest @testable import MyNewApp class URLQueryLicenseParserTests: XCTestCase { let service = URLQueryLicenseParser() func testParse_WithEmptyQuery_ReturnsNil() { XCTAssertNil(service.parse(query: "")) } func testParse_WithoutNameAndLicenseCode_ReturnsNil() { XCTAssertNil(service.parse(query: "bogus=info")) } let licensee = "Sm9obiBBcHBsZXNlZWQ=" // John Appleseed func testParse_WithNameOnly_ReturnsNil() { XCTAssertNil(service.parse(query: "name=\(licensee)")) } func testParse_WithLicenseCodeOnly_ReturnsNil() { XCTAssertNil(service.parse(query: "licenseCode=foo")) } func testParse_WithUnencodedNameAndLicenseCode_ReturnsNil() { XCTAssertNil(service.parse(query: "name=unencoded&licenseCode=foo")) } func testParse_CompleteQuery_ReturnsLicense() { let query = "name=\(licensee)&licenseCode=the-license-code" let result = service.parse(query: query) XCTAssertNotNil(result) if let license = result { XCTAssertEqual(license.name, "John Appleseed") XCTAssertEqual(license.licenseCode, "the-license-code") } } func testParse_CompleteQueryReversedAndWithOtherInfo_ReturnsLicense() { let query = "licenseCode=the-license-code&bogus=info&name=\(licensee)" let result = service.parse(query: query) XCTAssertNotNil(result) if let license = result { XCTAssertEqual(license.name, "John Appleseed") XCTAssertEqual(license.licenseCode, "the-license-code") } } }
mit
marcelmueller/MyWeight
MyWeight/Views/Style.swift
1
2033
// // Style.swift // MyWeight // // Created by Diogo on 09/10/16. // Copyright © 2016 Diogo Tridapalli. All rights reserved. // import UIKit public protocol StyleProvider { var backgroundColor: UIColor { get } var separatorColor: UIColor { get } var textColor: UIColor { get } var textLightColor: UIColor { get } var textInTintColor: UIColor { get } var tintColor: UIColor { get } var title1: UIFont { get } var title2: UIFont { get } var title3: UIFont { get } var body: UIFont { get } var callout: UIFont { get } var subhead: UIFont { get } var footnote: UIFont { get } var grid: CGFloat { get } } public struct Style: StyleProvider { public let backgroundColor: UIColor = Style.white public let separatorColor: UIColor = Style.lightGray public let textColor: UIColor = Style.black public let textLightColor: UIColor = Style.gray public let textInTintColor: UIColor = Style.lightGray public let tintColor: UIColor = Style.teal public let title1 = UIFont.systemFont(ofSize: 42, weight: UIFontWeightHeavy) public let title2 = UIFont.systemFont(ofSize: 28, weight: UIFontWeightSemibold) public let title3 = UIFont.systemFont(ofSize: 22, weight: UIFontWeightBold) public let body = UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium) public let callout = UIFont.systemFont(ofSize: 18, weight: UIFontWeightMedium) public let subhead = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium) public let footnote = UIFont.systemFont(ofSize: 13, weight: UIFontWeightMedium) public let grid: CGFloat = 8 static let teal = UIColor(red: 81/255, green: 203/255, blue: 212/255, alpha: 1) static let black = UIColor(red: 67/255, green: 70/255, blue: 75/255, alpha: 1) static let gray = UIColor(red: 168/255, green: 174/255, blue: 186/255, alpha: 1) static let lightGray = UIColor(red: 241/255, green: 243/255, blue: 246/255, alpha: 1) static let white = UIColor(white: 1, alpha: 1) }
mit
wongzigii/HidingNavigationBar
HidingNavigationBarSample/HidingNavigationBarSample/AppDelegate.swift
4
2168
// // AppDelegate.swift // HidingNavigationBarSample // // Created by Tristan Himmelman on 2015-05-01. // Copyright (c) 2015 Tristan Himmelman. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
sora0077/DribbbleKit
DribbbleKit/Sources/Shots/UpdateShot.swift
1
916
// // UpdateShot.swift // DribbbleKit // // Created by 林 達也 on 2017/04/19. // Copyright © 2017年 jp.sora0077. All rights reserved. // import Foundation import APIKit import Alter public struct UpdateShot<Data: ShotData>: PostRequest { public typealias Response = DribbbleKit.Response<Data> public var scope: OAuth.Scope? { return .upload } public var path: String { return "/shots/\(id.value)" } public var parameters: Any? { return [ "title": title, "description": description, "tags": tags, "team_id": teamId, "low_profile": lowProfile].cleaned } private let id: Shot.Identifier public var title: String? public var description: String? public var tags: [String]? public var teamId: Int? public var lowProfile: Bool? public init(id: Shot.Identifier) { self.id = id } }
mit
pattersongerald/DiscordKit
DiscordKit/Classes/VoiceState.swift
1
348
// // VoiceState.swift // Pods // // Created by Gerald Patterson on 5/18/16. // // import Foundation class VoiceState { var guild_id: String? var channel_id: String? var user_id: String? var session_id: String? var deaf: Bool? var mute: Bool? var self_deaf: Bool? var self_mute: Bool? var suppress: Bool? }
mit
sbennett912/SwiftGL
SwiftGL/Constants.swift
1
8969
// // Constants.swift // SwiftGL // // Created by Scott Bennett on 2014-06-17. // Copyright (c) 2014 Scott Bennett. All rights reserved. // #if os(OSX) import OpenGL.GL3 // glDebug(__FILE__, __LINE__) public func glDebug(filename: String, line: Int) { var error = glGetError() while error != GLenum(GL_NO_ERROR) { var errMsg: String switch error { case GL_INVALID_ENUM: errMsg = "GL_INVALID_ENUM" case GL_INVALID_VALUE: errMsg = "GL_INVALID_VALUE" case GL_INVALID_OPERATION: errMsg = "GL_INVALID_OPERATION" case GL_INVALID_FRAMEBUFFER_OPERATION: errMsg = "GL_INVALID_FRAMEBUFFER_OPERATION" case GL_OUT_OF_MEMORY: errMsg = "GL_OUT_OF_MEMORY" default: errMsg = String(format: "0x%2X", error) } print("ERROR: \(filename):\(line) - \(errMsg)") error = glGetError() } } // Boolean Constants public let GL_FALSE = GLboolean(OpenGL.GL_FALSE) public let GL_TRUE = GLboolean(OpenGL.GL_TRUE) // Error Constants public let GL_NO_ERROR = GLenum(OpenGL.GL_NO_ERROR) public let GL_INVALID_ENUM = GLenum(OpenGL.GL_INVALID_ENUM) public let GL_INVALID_VALUE = GLenum(OpenGL.GL_INVALID_VALUE) public let GL_INVALID_OPERATION = GLenum(OpenGL.GL_INVALID_OPERATION) public let GL_INVALID_FRAMEBUFFER_OPERATION = GLenum(OpenGL.GL_INVALID_FRAMEBUFFER_OPERATION) public let GL_OUT_OF_MEMORY = GLenum(OpenGL.GL_OUT_OF_MEMORY) // Clear Buffer Constants public let GL_COLOR_BUFFER_BIT = GLbitfield(OpenGL.GL_COLOR_BUFFER_BIT) public let GL_DEPTH_BUFFER_BIT = GLbitfield(OpenGL.GL_DEPTH_BUFFER_BIT) public let GL_STENCIL_BUFFER_BIT = GLbitfield(OpenGL.GL_STENCIL_BUFFER_BIT) // Primitive Type Constants public let GL_POINTS = GLenum(OpenGL.GL_POINTS) public let GL_LINES = GLenum(OpenGL.GL_LINES) public let GL_LINE_LOOP = GLenum(OpenGL.GL_LINE_LOOP) public let GL_LINE_STRIP = GLenum(OpenGL.GL_LINE_STRIP) public let GL_TRIANGLES = GLenum(OpenGL.GL_TRIANGLES) public let GL_TRIANGLE_FAN = GLenum(OpenGL.GL_TRIANGLE_FAN) public let GL_TRIANGLE_STRIP = GLenum(OpenGL.GL_TRIANGLE_STRIP) public let GL_QUADS = GLenum(OpenGL.GL_QUADS) // Shader Constants public let GL_VERTEX_SHADER = GLenum(OpenGL.GL_VERTEX_SHADER) public let GL_FRAGMENT_SHADER = GLenum(OpenGL.GL_FRAGMENT_SHADER) public let GL_GEOMETRY_SHADER = GLenum(OpenGL.GL_GEOMETRY_SHADER) // Vertex Buffer Object public let GL_ARRAY_BUFFER = GLenum(OpenGL.GL_ARRAY_BUFFER) public let GL_ELEMENT_ARRAY_BUFFER = GLenum(OpenGL.GL_ELEMENT_ARRAY_BUFFER) public let GL_DYNAMIC_DRAW = GLenum(OpenGL.GL_DYNAMIC_DRAW) public let GL_STATIC_DRAW = GLenum(OpenGL.GL_STATIC_DRAW) // Texture Constants public let GL_TEXTURE_2D = GLenum(OpenGL.GL_TEXTURE_2D) public let GL_TEXTURE0 = GLenum(OpenGL.GL_TEXTURE0) // Type Constants public let GL_BYTE = GLenum(OpenGL.GL_BYTE) public let GL_SHORT = GLenum(OpenGL.GL_SHORT) public let GL_INT = GLenum(OpenGL.GL_INT) public let GL_FLOAT = GLenum(OpenGL.GL_FLOAT) public let GL_DOUBLE = GLenum(OpenGL.GL_DOUBLE) public let GL_UNSIGNED_BYTE = GLenum(OpenGL.GL_UNSIGNED_BYTE) public let GL_UNSIGNED_SHORT = GLenum(OpenGL.GL_UNSIGNED_SHORT) public let GL_UNSIGNED_INT = GLenum(OpenGL.GL_UNSIGNED_INT) // Comparison Constants public let GL_NEVER = GLenum(OpenGL.GL_NEVER) public let GL_ALWAYS = GLenum(OpenGL.GL_ALWAYS) public let GL_EQUAL = GLenum(OpenGL.GL_EQUAL) public let GL_NOTEQUAL = GLenum(OpenGL.GL_NOTEQUAL) public let GL_LESS = GLenum(OpenGL.GL_LESS) public let GL_GREATER = GLenum(OpenGL.GL_GREATER) public let GL_LEQUAL = GLenum(OpenGL.GL_LEQUAL) public let GL_GEQUAL = GLenum(OpenGL.GL_GEQUAL) // Enable Constants public let GL_BLEND = GLenum(OpenGL.GL_BLEND) public let GL_DEPTH_TEST = GLenum(OpenGL.GL_DEPTH_TEST) public let GL_CULL_FACE = GLenum(OpenGL.GL_CULL_FACE) // Blend Constants public let GL_ZERO = GLenum(OpenGL.GL_ZERO) public let GL_ONE = GLenum(OpenGL.GL_ONE) public let GL_SRC_ALPHA = GLenum(OpenGL.GL_SRC_ALPHA) public let GL_ONE_MINUS_SRC_ALPHA = GLenum(OpenGL.GL_ONE_MINUS_SRC_ALPHA) // Cull Face Constants public let GL_FRONT = GLenum(OpenGL.GL_FRONT) public let GL_BACK = GLenum(OpenGL.GL_BACK) public let GL_FRONT_AND_BACK = GLenum(OpenGL.GL_FRONT_AND_BACK) #else import OpenGLES.ES2.gl // glDebug(__FILE__, __LINE__) public func glDebug(filename: String, line: Int) { var error = glGetError() while error != GLenum(GL_NO_ERROR) { var errMsg: String switch error { case GL_INVALID_ENUM: errMsg = "GL_INVALID_ENUM" case GL_INVALID_VALUE: errMsg = "GL_INVALID_VALUE" case GL_INVALID_OPERATION: errMsg = "GL_INVALID_OPERATION" case GL_INVALID_FRAMEBUFFER_OPERATION: errMsg = "GL_INVALID_FRAMEBUFFER_OPERATION" case GL_OUT_OF_MEMORY: errMsg = "GL_OUT_OF_MEMORY" case GL_STACK_UNDERFLOW: errMsg = "GL_STACK_UNDERFLOW" case GL_STACK_OVERFLOW: errMsg = "GL_STACK_OVERFLOW" default: errMsg = String(format: "0x%2X", error) } print("ERROR: \(filename):\(line) - \(errMsg)") error = glGetError() } } // Boolean Constants public let GL_FALSE = GLboolean(OpenGLES.GL_FALSE) public let GL_TRUE = GLboolean(OpenGLES.GL_TRUE) // Error Constants public let GL_NO_ERROR = GLenum(OpenGLES.GL_NO_ERROR) public let GL_INVALID_ENUM = GLenum(OpenGLES.GL_INVALID_ENUM) public let GL_INVALID_VALUE = GLenum(OpenGLES.GL_INVALID_VALUE) public let GL_INVALID_OPERATION = GLenum(OpenGLES.GL_INVALID_OPERATION) public let GL_INVALID_FRAMEBUFFER_OPERATION = GLenum(OpenGLES.GL_INVALID_FRAMEBUFFER_OPERATION) public let GL_OUT_OF_MEMORY = GLenum(OpenGLES.GL_OUT_OF_MEMORY) public let GL_STACK_UNDERFLOW = GLenum(OpenGLES.GL_STACK_UNDERFLOW) public let GL_STACK_OVERFLOW = GLenum(OpenGLES.GL_STACK_OVERFLOW) // Clear Buffer Constants public let GL_COLOR_BUFFER_BIT = GLbitfield(OpenGLES.GL_COLOR_BUFFER_BIT) public let GL_DEPTH_BUFFER_BIT = GLbitfield(OpenGLES.GL_DEPTH_BUFFER_BIT) public let GL_STENCIL_BUFFER_BIT = GLbitfield(OpenGLES.GL_STENCIL_BUFFER_BIT) // Primitive Type Constants public let GL_POINTS = GLenum(OpenGLES.GL_POINTS) public let GL_LINES = GLenum(OpenGLES.GL_LINES) public let GL_LINE_LOOP = GLenum(OpenGLES.GL_LINE_LOOP) public let GL_LINE_STRIP = GLenum(OpenGLES.GL_LINE_STRIP) public let GL_TRIANGLES = GLenum(OpenGLES.GL_TRIANGLES) public let GL_TRIANGLE_FAN = GLenum(OpenGLES.GL_TRIANGLE_FAN) public let GL_TRIANGLE_STRIP = GLenum(OpenGLES.GL_TRIANGLE_STRIP) // Shader Constants public let GL_VERTEX_SHADER = GLenum(OpenGLES.GL_VERTEX_SHADER) public let GL_FRAGMENT_SHADER = GLenum(OpenGLES.GL_FRAGMENT_SHADER) // Vertex Buffer Object public let GL_ARRAY_BUFFER = GLenum(OpenGLES.GL_ARRAY_BUFFER) public let GL_ELEMENT_ARRAY_BUFFER = GLenum(OpenGLES.GL_ELEMENT_ARRAY_BUFFER) public let GL_DYNAMIC_DRAW = GLenum(OpenGLES.GL_DYNAMIC_DRAW) public let GL_STATIC_DRAW = GLenum(OpenGLES.GL_STATIC_DRAW) // Texture Constants public let GL_TEXTURE_2D = GLenum(OpenGLES.GL_TEXTURE_2D) public let GL_TEXTURE0 = GLenum(OpenGLES.GL_TEXTURE0) // Type Constants public let GL_BYTE = GLenum(OpenGLES.GL_BYTE) public let GL_SHORT = GLenum(OpenGLES.GL_SHORT) public let GL_INT = GLenum(OpenGLES.GL_INT) public let GL_FLOAT = GLenum(OpenGLES.GL_FLOAT) public let GL_UNSIGNED_BYTE = GLenum(OpenGLES.GL_UNSIGNED_BYTE) public let GL_UNSIGNED_SHORT = GLenum(OpenGLES.GL_UNSIGNED_SHORT) public let GL_UNSIGNED_INT = GLenum(OpenGLES.GL_UNSIGNED_INT) // Comparison Constants public let GL_NEVER = GLenum(OpenGLES.GL_NEVER) public let GL_ALWAYS = GLenum(OpenGLES.GL_ALWAYS) public let GL_EQUAL = GLenum(OpenGLES.GL_EQUAL) public let GL_NOTEQUAL = GLenum(OpenGLES.GL_NOTEQUAL) public let GL_LESS = GLenum(OpenGLES.GL_LESS) public let GL_GREATER = GLenum(OpenGLES.GL_GREATER) public let GL_LEQUAL = GLenum(OpenGLES.GL_LEQUAL) public let GL_GEQUAL = GLenum(OpenGLES.GL_GEQUAL) // Enable Constants public let GL_BLEND = GLenum(OpenGLES.GL_BLEND) public let GL_DEPTH_TEST = GLenum(OpenGLES.GL_DEPTH_TEST) public let GL_CULL_FACE = GLenum(OpenGLES.GL_CULL_FACE) // Blend Constants public let GL_ZERO = GLenum(OpenGLES.GL_ZERO) public let GL_ONE = GLenum(OpenGLES.GL_ONE) public let GL_SRC_ALPHA = GLenum(OpenGLES.GL_SRC_ALPHA) public let GL_ONE_MINUS_SRC_ALPHA = GLenum(OpenGLES.GL_ONE_MINUS_SRC_ALPHA) // Cull Face Constants public let GL_FRONT = GLenum(OpenGLES.GL_FRONT) public let GL_BACK = GLenum(OpenGLES.GL_BACK) public let GL_FRONT_AND_BACK = GLenum(OpenGLES.GL_FRONT_AND_BACK) #endif
mit
AfricanSwift/TUIKit
TUIKit/dev-Termios-input .swift
1
7608
// // File: dev-Termios-input.swift // Created by: African Swift import Darwin import Foundation var terminal_descriptor: Int32 = -1 var terminal_original = termios() var terminal_settings = termios() /// Restore terminal to original settings func terminal_done() { if terminal_descriptor != -1 { tcsetattr(terminal_descriptor, TCSANOW, &terminal_original) } } // "Default" signal handler: restore terminal, then exit. func terminal_signal(_ signum: Int32) { if terminal_descriptor != -1 { tcsetattr(terminal_descriptor, TCSANOW, &terminal_original) } /* exit() is not async-signal safe, but _exit() is. * Use the common idiom of 128 + signal number for signal exits. * Alternative approach is to reset the signal to default handler, * and immediately raise() it. */ _exit(128 + signum) } func devTermios() { // Initialize terminal for non-canonical, non-echo mode, // that should be compatible with standard C I/O. // Returns 0 if success, nonzero errno otherwise. func terminal_init() -> Int32 { var act = sigaction() // Already initialized if terminal_descriptor != -1 { errno = 0 return errno } print("stderr", isatty(STDERR_FILENO)) print("stdin", isatty(STDIN_FILENO)) print("stdout", isatty(STDOUT_FILENO)) // Which standard stream is connected to our TTY? if isatty(STDERR_FILENO) != 0 { terminal_descriptor = STDERR_FILENO print("stderr connected") } else if isatty(STDIN_FILENO) != 0 { terminal_descriptor = STDIN_FILENO print("stdin connected") } else if isatty(STDOUT_FILENO) != 0 { terminal_descriptor = STDOUT_FILENO print("stdout connected") } else { errno = ENOTTY return errno } // Obtain terminal settings. if tcgetattr(terminal_descriptor, &terminal_original) != 0 || tcgetattr(terminal_descriptor, &terminal_settings) != 0 { errno = ENOTSUP return errno } // Disable buffering for terminal streams. if isatty(STDIN_FILENO) != 0 { setvbuf(stdin, nil, _IONBF, 0) } if isatty(STDERR_FILENO) != 0 { setvbuf(stderr, nil, _IONBF, 0) } // At exit() or return from main(), restore the original settings if atexit(terminal_done) != 0 { errno = ENOTSUP return errno } // Set new "default" handlers for typical signals, so that if this process is // killed by a signal, the terminal settings will still be restored first. sigemptyset(&act.sa_mask) act.__sigaction_u.__sa_handler = terminal_signal as (@convention(c) (Int32) -> Void) act.sa_flags = 0 // Break conditions var condition = sigaction(SIGHUP, &act, nil) != 0 || sigaction(SIGINT, &act, nil) != 0 || sigaction(SIGQUIT, &act, nil) != 0 || sigaction(SIGTERM, &act, nil) != 0 || sigaction(SIGPIPE, &act, nil) != 0 || sigaction(SIGALRM, &act, nil) != 0 #if SIGXCPU condition |= sigaction(SIGXCPU, &act, nil) != 0 #endif #if SIGXFSZ condition |= sigaction(SIGXFSZ, &act, nil) != 0 #endif #if SIGIO condition |= sigaction(SIGIO, &act, nil) != 0 #endif if condition { errno = ENOTSUP return errno } // Let BREAK cause a SIGINT in input terminal_settings.c_iflag &= ~UInt(IGNBRK) terminal_settings.c_iflag |= UInt(BRKINT) // Ignore framing and parity errors in input terminal_settings.c_iflag |= UInt(IGNPAR) terminal_settings.c_iflag &= ~UInt(PARMRK) // Do not strip eighth bit on input terminal_settings.c_iflag &= ~UInt(ISTRIP) // Do not do newline translation on input terminal_settings.c_iflag &= ~(UInt(INLCR) | UInt(IGNCR) | UInt(ICRNL)) #if IUCLC // Do not do uppercase-to-lowercase mapping on input terminal_settings.c_iflag &= ~UInt(IUCLC) #endif // Use 8-bit characters. This too may affect standard streams, // but any sane C library can deal with 8-bit characters terminal_settings.c_cflag &= ~UInt(CSIZE) terminal_settings.c_cflag |= UInt(CS8) // Enable receiver terminal_settings.c_cflag |= UInt(CREAD) // Let INTR/QUIT/SUSP/DSUSP generate the corresponding signals (CTRL-C, ....) terminal_settings.c_lflag &= ~UInt(ISIG) // Enable noncanonical mode. // This is the most important bit, as it disables line buffering etc terminal_settings.c_lflag &= ~UInt(ICANON) // Disable echoing input characters terminal_settings.c_lflag &= ~(UInt(ECHO) | UInt(ECHOE) | UInt(ECHOK) | UInt(ECHONL)) // Disable implementation-defined input processing terminal_settings.c_lflag &= ~UInt(IEXTEN) // To maintain best compatibility with normal behaviour of terminals, // we set TIME=0 and MAX=1 in noncanonical mode. This means that // read() will block until at least one byte is available. // terminal_settings.c_cc[VTIME] = 0 // terminal_settings.c_cc[VMIN] = 1 Ansi.Terminal.setc_cc(settings: &terminal_settings, index: VTIME, value: 0) Ansi.Terminal.setc_cc(settings: &terminal_settings, index: VMIN, value: 1) // Set the new terminal settings. // Note that we don't actually check which ones were successfully // set and which not, because there isn't much we can do about it. tcsetattr(terminal_descriptor, TCSANOW, &terminal_settings) // Done errno = 0 return errno } Ansi.Set.sendMouseXYOnButtonPressX11On().stdout() Ansi.Set.sgrMouseModeOn().stdout() Ansi.flush() if terminal_init() != 0 { if Darwin.errno == ENOTTY { fputs("This program requires a terminal.\n", stderr) } else { fputs("Cannot initialize terminal: \(strerror(errno))\n", stderr) } } var readFDS = fd_set() var timeValue = timeval() var result = "" while true { // Watch stdin (fd 0) to see when it has input. Swift_FD_ZERO(&readFDS) Swift_FD_SET(0, &readFDS) // Wait up to 5 milliseconds. timeValue.tv_sec = 0 timeValue.tv_usec = 5000 let retval = select(1, &readFDS, nil, nil, &timeValue) if retval == -1 { perror("select()") exit(EXIT_FAILURE) } else if retval != 0 { let c = getc(stdin) if c >= 33 && c <= 126 { // let format = String(format: "0x%02x = 0%03o = %3d = '%c'\n", c, c, c, c) // print(format) } else { // let format = String(format: "0x%02x = 0%03o = %3d\n", c, c, c) // print(format) } result += String(UnicodeScalar(Int(c))) // print(result) // if c == 3 || c == Q || c == q // Exit on CTRL-C if c == 3 { Ansi.Set.sendMouseXYOnButtonPressX11Off().stdout() Ansi.Set.sgrMouseModeOff().stdout() break } } else { if result.characters.count > 0 { if result.hasPrefix("\u{1b}") { debugPrint("\(result)") } else { print(result, terminator: "") } result = "" } // Triggered when select timed out // Add event code here: screen painting, etc... Thread.sleep(forTimeInterval: 0.1) } } //Thread.sleep(forTimeInterval: 10) Ansi.Set.sendMouseXYOnButtonPressX11Off().stdout() Ansi.Set.sgrMouseModeOff().stdout() // print(Ansi.Terminal.hasUnicodeSupport()) Ansi.Terminal.bell() }
mit
FabrizioBrancati/BFKit-Swift
Sources/BFKit/Apple/UIKit/UILabel+Extensions.swift
1
4473
// // UILabel+Extensions.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit // MARK: - UILabel extension /// This extesion adds some useful functions to UILabel. public extension UILabel { // MARK: - Functions /// Create an UILabel with the given parameters. /// /// - Parameters: /// - frame: Label frame. /// - text: Label text. /// - font: Label font. /// - color: Label text color. /// - alignment: Label text alignment. /// - lines: Label text lines. /// - shadowColor: Label text shadow color. convenience init(frame: CGRect, text: String, font: UIFont, color: UIColor, alignment: NSTextAlignment, lines: Int, shadowColor: UIColor = UIColor.clear) { self.init(frame: frame) self.font = font self.text = text backgroundColor = UIColor.clear textColor = color textAlignment = alignment numberOfLines = lines self.shadowColor = shadowColor } /// Create an UILabel with the given parameters. /// /// - Parameters: /// - frame: Label frame. /// - text: Label text. /// - font: Label font name. /// - size: Label font size. /// - color: Label text color. /// - alignment: Label text alignment. /// - lines: Label text lines. /// - shadowColor: Label text shadow color. convenience init(frame: CGRect, text: String, font: FontName, fontSize: CGFloat, color: UIColor, alignment: NSTextAlignment, lines: Int, shadowColor: UIColor = UIColor.clear) { self.init(frame: frame) self.font = UIFont(fontName: font, size: fontSize) self.text = text backgroundColor = UIColor.clear textColor = color textAlignment = alignment numberOfLines = lines self.shadowColor = shadowColor } /// Calculates height based on text, width and font. /// /// - Returns: Returns calculated height. func calculateHeight() -> CGFloat { guard let text = text else { return 0 } return UIFont.calculateHeight(width: frame.size.width, font: font, text: text) } /// Sets a custom font from a character at an index to character at another index. /// /// - Parameters: /// - font: New font to be setted. /// - fromIndex: The start index. /// - toIndex: The end index. func setFont(_ font: UIFont, fromIndex: Int, toIndex: Int) { guard let text = text else { return } attributedText = text.attributedString.font(font, range: NSRange(location: fromIndex, length: toIndex - fromIndex)) } /// Sets a custom font from a character at an index to character at another index. /// /// - Parameters: /// - font: New font to be setted. /// - fontSize: New font size. /// - fromIndex: The start index. /// - toIndex: The end index. func setFont(_ font: FontName, fontSize: CGFloat, fromIndex: Int, toIndex: Int) { guard let text = text, let font = UIFont(fontName: font, size: fontSize) else { return } attributedText = text.attributedString.font(font, range: NSRange(location: fromIndex, length: toIndex - fromIndex)) } }
mit
urbn/URBNAlert
Sources/URBNAlert/AlertController.swift
1
4111
// // AlertController.swift // Pods // // Created by Kevin Taniguchi on 5/22/17. // // import UIKit public class AlertController: NSObject { public static let shared = AlertController() public var alertStyler = AlertStyler() private var alertIsVisible = false private var queue: [AlertViewController] = [] private var alertWindow: UIWindow? public var presentingWindow = UIApplication.shared.currentWindow ?? UIWindow(frame: UIScreen.main.bounds) // MARK: Queueing public func addAlertToQueue(avc: AlertViewController) { queue.append(avc) showNextAlert() } public func showNextAlert() { guard let nextAVC = queue.first, !alertIsVisible else { return } nextAVC.dismissingHandler = {[weak self] wasTouchedOutside in guard let strongSelf = self else { return } if wasTouchedOutside { strongSelf.dismiss(alertViewController: nextAVC) } if strongSelf.queue.isEmpty { strongSelf.alertWindow?.resignKey() strongSelf.alertWindow?.isHidden = true strongSelf.alertWindow = nil strongSelf.presentingWindow.makeKey() } if nextAVC.alertConfiguration.presentationView != nil { nextAVC.view.removeFromSuperview() } } if let presentationView = nextAVC.alertConfiguration.presentationView { var rect = nextAVC.view.frame rect.size.width = presentationView.frame.size.width rect.size.height = presentationView.frame.size.height nextAVC.view.frame = rect nextAVC.alertConfiguration.presentationView?.addSubview(nextAVC.view) } else { NotificationCenter.default.addObserver(self, selector: #selector(resignActive(note:)), name: Notification.Name(rawValue: "UIWindowDidBecomeKeyNotification"), object: nil) setupAlertWindow() alertWindow?.rootViewController = nextAVC alertWindow?.makeKeyAndVisible() } NSObject.cancelPreviousPerformRequests(withTarget: self) if !nextAVC.alertConfiguration.isActiveAlert, let duration = nextAVC.alertConfiguration.duration { perform(#selector(dismiss(alertViewController:)), with: nextAVC, afterDelay: TimeInterval(duration)) } } private func setupAlertWindow() { if alertWindow == nil { alertWindow = UIWindow(frame: UIScreen.main.bounds) } alertWindow?.windowLevel = UIWindow.Level.alert alertWindow?.isHidden = false alertWindow?.accessibilityIdentifier = "alertWindow" NotificationCenter.default.addObserver(self, selector: #selector(resignActive) , name: Notification.Name(rawValue: "UIWindowDidBecomeKeyNotification") , object: nil) } func popQueueAndShowNextIfNecessary() { alertIsVisible = false if !queue.isEmpty { _ = queue.removeFirst() } showNextAlert() } /// Conveinence to close alerts that are visible or in queue public func dismissAllAlerts() { queue.forEach { (avc) in avc.dismissAlert(sender: self) } } @objc func dismiss(alertViewController: AlertViewController) { alertIsVisible = false alertViewController.dismissAlert(sender: self) } /** * Called when a new window becomes active. * Specifically used to detect new alertViews or actionSheets so we can dismiss ourselves **/ @objc func resignActive(note: Notification) { guard let noteWindow = note.object as? UIWindow, noteWindow != alertWindow, noteWindow != presentingWindow else { return } if let nextAVC = queue.first { dismiss(alertViewController: nextAVC) } } } extension UIApplication { var currentWindow: UIWindow? { return windows.first(where: { $0.isKeyWindow }) } }
mit
haawa799/StrokeDrawingView
Example/ViewController.swift
1
1481
// // ViewController.swift // Example // // Created by Andrii Kharchyshyn on 5/2/17. // Copyright © 2017 @haawa799. All rights reserved. // import UIKit import StrokeDrawingView class ViewController: UIViewController { let kanji = Kanji(kanji: "数") var shouldPlay = true @IBOutlet weak var strokedView: StrokeDrawingView! { didSet { self.strokedView.dataSource = self } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if shouldPlay == true { strokedView.playForever(delayBeforeEach: 2) shouldPlay = false } } } extension ViewController: StrokeDrawingViewDataSource { func sizeOfDrawing() -> CGSize { return CGSize(width: 109, height: 109) } func numberOfStrokes() -> Int { return kanji.bezierPathes.count } func pathForIndex(index: Int) -> UIBezierPath { let path = kanji.bezierPathes[index] path.lineWidth = 3 return path } func animationDurationForStroke(index: Int) -> CFTimeInterval { return 0.5 } func colorForStrokeAtIndex(index: Int) -> UIColor { switch index { case 0...5: return kanji.color0 case 5...8: return kanji.color1 default: return kanji.color2 } } func colorForUnderlineStrokes() -> UIColor? { return UIColor.lightGray } }
mit
ls1intum/sReto
Source/sReto/Core/InTransfer.swift
1
3204
// // InTransfer.swift // sReto // // Created by Julian Asamer on 26/07/14. // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // 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 /** * An InTransfer represents a data transfer from a remote peer to the local peer. The connection class generates InTransfer instances when a remote peer sends data. */ open class InTransfer: Transfer { // MARK: Events // Called when the transfer completes with the full data received. Buffers the data in memory until the transfer is complete. Alternative to onPartialData. If both are set, onPartialData is used. open var onCompleteData: ((Transfer, Data) -> ())? = nil // Called whenever data is received. This method may be called multiple times, i.e. the data is not the full transfer. Exclusive alternative to onCompleteData. open var onPartialData: ((Transfer, Data) -> ())? = nil // MARK: Internal func updateWithReceivedData(_ data: Data) { if let onPartialData = self.onPartialData { onPartialData(self, data) } else if self.onCompleteData != nil { if self.dataBuffer == nil { self.dataBuffer = NSMutableData(capacity: self.length) } dataBuffer?.append(data) } else { log(.high, error: "You need to set either onCompleteData or onPartialData on incoming transfers (affected instance: \(self))") } if onCompleteData != nil && onPartialData != nil { log(.medium, warning: "You set both onCompleteData and onPartialData in \(self). Only onPartialData will be used.") } self.updateProgress(data.count) } var dataBuffer: NSMutableData? = nil override open func cancel() { self.manager?.cancel(self) } override func confirmEnd() { self.dataBuffer = nil self.onCompleteData = nil self.onPartialData = nil super.confirmEnd() } override func confirmCompletion() { if let data = self.dataBuffer { self.onCompleteData?(self, data as Data) } super.confirmCompletion() } }
mit
openbuild-sheffield/jolt
Sources/OpenbuildRepository/func.loadConnectionsFromPlist.swift
1
2055
import Foundation import PerfectLib public func loadConnectionsFromPlist(path: String) -> [String: ModuleConnectionDetail]{ var moduleConnectionDetails: [String: ModuleConnectionDetail] = [:] print("READING module connection details from file: \(path)") do { let configURL = URL(fileURLWithPath: path) let configData = try Data(contentsOf:configURL) let configDictionary = try PropertyListSerialization.propertyList(from: configData, options: [], format: nil) as! [String:Any] let dataConnectionsDictionary = configDictionary["dataConnections"] as! [String: [[String: Any]]] for (type, connections) in dataConnectionsDictionary { for connection in connections { guard let namedConnection = connection["name"] else { print("No name for connection: "); print(connection); exit(0) } guard let stores = connection["stores"] else { print("No stores for connection: "); print(connection); exit(0) } for store in stores as! [[String: String]]{ guard let db = store["db"] else { print("No db in store \(connection) : \(store)") exit(0) } guard let name = store["name"] else { print("No name in store \(connection) : \(store)") exit(0) } let key = type + (namedConnection as! String) + name moduleConnectionDetails[key] = ModuleConnectionDetail( type: type, namedConnection: namedConnection as! String, db: db ) } } } } catch { print("Failed to load config file") exit(0) } return moduleConnectionDetails }
gpl-2.0
ps2/rileylink_ios
MinimedKit/GlucoseEvents/RelativeTimestampedGlucoseEvent.swift
1
340
// // RelativeTimestampedGlucoseEvent.swift // RileyLink // // Created by Timothy Mecklem on 10/16/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation /// An event that requires timestamp information from a ReferenceTimestampGlucoseEvent public protocol RelativeTimestampedGlucoseEvent: GlucoseEvent { }
mit
JadenGeller/Orderly
Tests/OrderlyTests/SortedArray.swift
1
2124
// // SortedArray.swift // // // Created by Jaden Geller on 3/28/17. // // import XCTest import Orderly class SortedArrayTests: XCTestCase { func testIsSorted() { XCTAssertTrue([-60, 1, 2, 3, 3, 3, 5, 6, 10000].isSorted()) XCTAssertFalse([61, -60, 1, 2, 3, 3, 3, 5, 6, 10000].isSorted()) XCTAssertFalse([1, 2, 3, 3, 3, 5, 6, -10].isSorted()) XCTAssertFalse([1, 2, 3, 3, 3, 5, 6, 5].isSorted()) XCTAssertFalse([1, 2, 3, 2, 3, 5, 6].isSorted()) } func testInsertionIndex() { let arr = SortedArray(sorting: [1, 2, 5, 6, 6, 10, 12]) XCTAssertEqual(0, arr.insertionIndex(of: -100)) XCTAssertEqual(0, arr.insertionIndex(of: 0)) XCTAssertEqual(0, arr.insertionIndex(of: 1)) XCTAssertEqual(1, arr.insertionIndex(of: 2)) XCTAssertEqual(2, arr.insertionIndex(of: 3)) XCTAssertEqual(2, arr.insertionIndex(of: 4)) XCTAssertEqual(2, arr.insertionIndex(of: 5)) XCTAssertEqual(3, arr.insertionIndex(of: 6)) XCTAssertEqual(3, arr.insertionIndex(of: 6, for: .least)) XCTAssertEqual(3, arr.insertionIndex(of: 6, for: .least)) XCTAssertEqual(5, arr.insertionIndex(of: 6, for: .greatest)) XCTAssertEqual(7, arr.insertionIndex(of: 100)) } func testInsert() { var arr = SortedArray(sorting: [1, 2, 5, 6, 6, 10, 12]) arr.insert(3) arr.insert(6) arr.insert(0) XCTAssertEqual([0, 1, 2, 3, 5, 6, 6, 6, 10, 12], Array(arr)) arr.insert(contentsOf: 7...11) XCTAssertEqual([0, 1, 2, 3, 5, 6, 6, 6, 7, 8, 9, 10, 10, 11, 12], Array(arr)) } func testInsertSortedArray() { let arr = SortedArray(sorting: [1, 2, 3, 5, 10, 12, 13]) let sortedBar = SortedArray(sorting: [2, 3, 4, 6, 7, 8, 16]) let unsortedBar: Array = [2, 3, 4, 6, 7, 8, 16] var arrNormal = arr arrNormal.insert(contentsOf: unsortedBar) var arrOptimized = arr arrOptimized.insert(contentsOf: sortedBar) XCTAssertTrue(arrNormal == arrOptimized) } }
mit
SteveBarnegren/SBAutoLayout
Example/SBAutoLayout/ExampleItem.swift
1
1482
// // ExampleItem.swift // SBAutoLayout // // Created by Steven Barnegren on 18/10/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import UIKit struct ExampleItem { enum TextPosition { case center case centerInView(viewNumber: Int) case aboveView(viewNumber: Int) case belowView(viewNumber: Int) case leftOfView(viewNumber: Int) case rightOfView(viewNumber: Int) } let numberOfViews: Int let layoutActions: [AutoLayoutAction] let textPosition: TextPosition var text: String { var string = String() for (index, layoutAction) in layoutActions.enumerated() { string.append(layoutAction.name()) if index != layoutActions.count-1 { string.append("\n") } } return string } init(numberOfViews: Int, textPosition: TextPosition, layoutActions: [AutoLayoutAction]) { self.layoutActions = layoutActions self.textPosition = textPosition self.numberOfViews = numberOfViews } func nameAndColorForView(number: Int) -> (name: String, color: UIColor) { let array: [(name: String, color: UIColor)] = [ ("BlueView", UIColor(red: 0.333, green: 0.675, blue: 0.937, alpha: 1)), ("OrangeView", UIColor.orange), ] return array[number] } }
mit
sadwx/SuxiNumberInputView
SuxiNumberInputView/Classes/SuxiNumberInputViewDelegate.swift
1
334
// // SuxiNumberInputViewDelegate.swift // SuxiNumberInputView // // Created by Simon on 02/08/2017. // Copyright © 2017 Simon. All rights reserved. // import Foundation public protocol SuxiNumberInputViewDelegate: class { func suxiNumberInputView(_ inputView: SuxiNumberInputView, pressedKey keyCode: SuxiNumberKeyCode) }
mit
nubbel/swift-tensorflow
Sources/op_performance_data.pb.swift
1
33056
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: tensorflow/core/grappler/costs/op_performance_data.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ // Copyright 2017 The TensorFlow Authors. 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 SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// Description of an operation as well as the parameters expected to impact its /// performance. public struct Tensorflow_OpInfo: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".OpInfo" /// The operation name. There may be custom parameters in attrs. public var op: String { get {return _storage._op} set {_uniqueStorage()._op = newValue} } /// Custom parameters impacting the behavior of the op. public var attr: Dictionary<String,Tensorflow_AttrValue> { get {return _storage._attr} set {_uniqueStorage()._attr = newValue} } public var inputs: [Tensorflow_OpInfo.TensorProperties] { get {return _storage._inputs} set {_uniqueStorage()._inputs = newValue} } /// Optional description of the op outputs public var outputs: [Tensorflow_OpInfo.TensorProperties] { get {return _storage._outputs} set {_uniqueStorage()._outputs = newValue} } /// Device on which the operation is run. public var device: Tensorflow_DeviceProperties { get {return _storage._device ?? Tensorflow_DeviceProperties()} set {_uniqueStorage()._device = newValue} } /// Returns true if `device` has been explicitly set. public var hasDevice: Bool {return _storage._device != nil} /// Clears the value of `device`. Subsequent reads from it will return its default value. public mutating func clearDevice() {_storage._device = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() /// Input data types, shapes and values if known. public struct TensorProperties: SwiftProtobuf.Message { public static let protoMessageName: String = Tensorflow_OpInfo.protoMessageName + ".TensorProperties" public var dtype: Tensorflow_DataType { get {return _storage._dtype} set {_uniqueStorage()._dtype = newValue} } public var shape: Tensorflow_TensorShapeProto { get {return _storage._shape ?? Tensorflow_TensorShapeProto()} set {_uniqueStorage()._shape = newValue} } /// Returns true if `shape` has been explicitly set. public var hasShape: Bool {return _storage._shape != nil} /// Clears the value of `shape`. Subsequent reads from it will return its default value. public mutating func clearShape() {_storage._shape = nil} public var value: Tensorflow_TensorProto { get {return _storage._value ?? Tensorflow_TensorProto()} set {_uniqueStorage()._value = newValue} } /// Returns true if `value` has been explicitly set. public var hasValue: Bool {return _storage._value != nil} /// Clears the value of `value`. Subsequent reads from it will return its default value. public mutating func clearValue() {_storage._value = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularEnumField(value: &_storage._dtype) case 2: try decoder.decodeSingularMessageField(value: &_storage._shape) case 3: try decoder.decodeSingularMessageField(value: &_storage._value) default: break } } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if _storage._dtype != .dtInvalid { try visitor.visitSingularEnumField(value: _storage._dtype, fieldNumber: 1) } if let v = _storage._shape { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } if let v = _storage._value { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } } try unknownFields.traverse(visitor: &visitor) } fileprivate var _storage = _StorageClass.defaultInstance } public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &_storage._op) case 2: try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,Tensorflow_AttrValue>.self, value: &_storage._attr) case 3: try decoder.decodeRepeatedMessageField(value: &_storage._inputs) case 4: try decoder.decodeSingularMessageField(value: &_storage._device) case 5: try decoder.decodeRepeatedMessageField(value: &_storage._outputs) default: break } } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if !_storage._op.isEmpty { try visitor.visitSingularStringField(value: _storage._op, fieldNumber: 1) } if !_storage._attr.isEmpty { try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufString,Tensorflow_AttrValue>.self, value: _storage._attr, fieldNumber: 2) } if !_storage._inputs.isEmpty { try visitor.visitRepeatedMessageField(value: _storage._inputs, fieldNumber: 3) } if let v = _storage._device { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } if !_storage._outputs.isEmpty { try visitor.visitRepeatedMessageField(value: _storage._outputs, fieldNumber: 5) } } try unknownFields.traverse(visitor: &visitor) } fileprivate var _storage = _StorageClass.defaultInstance } public struct Tensorflow_NormalDistribution: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".NormalDistribution" public var mu: Double = 0 public var sigma: Double = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularDoubleField(value: &self.mu) case 2: try decoder.decodeSingularDoubleField(value: &self.sigma) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.mu != 0 { try visitor.visitSingularDoubleField(value: self.mu, fieldNumber: 1) } if self.sigma != 0 { try visitor.visitSingularDoubleField(value: self.sigma, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } } public struct Tensorflow_LogNormalDistribution: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".LogNormalDistribution" public var mu: Double = 0 public var sigma: Double = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularDoubleField(value: &self.mu) case 2: try decoder.decodeSingularDoubleField(value: &self.sigma) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.mu != 0 { try visitor.visitSingularDoubleField(value: self.mu, fieldNumber: 1) } if self.sigma != 0 { try visitor.visitSingularDoubleField(value: self.sigma, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } } /// Performance data for tensorflow operations public struct Tensorflow_OpPerformance: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".OpPerformance" /// The op public var op: Tensorflow_OpInfo { get {return _storage._op ?? Tensorflow_OpInfo()} set {_uniqueStorage()._op = newValue} } /// Returns true if `op` has been explicitly set. public var hasOp: Bool {return _storage._op != nil} /// Clears the value of `op`. Subsequent reads from it will return its default value. public mutating func clearOp() {_storage._op = nil} /// The node name (optional). Makes it easier to associate the performance data /// with a specific graph node. public var node: String { get {return _storage._node} set {_uniqueStorage()._node = newValue} } /// Temporary memory used by this node (in bytes). public var temporaryMemorySize: Int64 { get {return _storage._temporaryMemorySize} set {_uniqueStorage()._temporaryMemorySize = newValue} } /// Time it takes to run the op (in nanoseconds). public var computeCost: Int64 { get {return _storage._computeCost} set {_uniqueStorage()._computeCost = newValue} } /// Analytical compute cost (in nanoseconds). public var computeTime: Int64 { get {return _storage._computeTime} set {_uniqueStorage()._computeTime = newValue} } /// Analytical memory access cost (in nanoseconds). public var memoryTime: Int64 { get {return _storage._memoryTime} set {_uniqueStorage()._memoryTime = newValue} } /// Percentage of theoretical compute performance. public var computeEfficiency: Double { get {return _storage._computeEfficiency} set {_uniqueStorage()._computeEfficiency = newValue} } /// Percentage of theoretical memory performance. public var memoryEfficiency: Double { get {return _storage._memoryEfficiency} set {_uniqueStorage()._memoryEfficiency = newValue} } /// Expected execution time, modeled using one of 2 possible distributions. public var executionTime: OneOf_ExecutionTime? { get {return _storage._executionTime} set {_uniqueStorage()._executionTime = newValue} } public var executionTimeNormal: Tensorflow_NormalDistribution { get { if case .executionTimeNormal(let v)? = _storage._executionTime {return v} return Tensorflow_NormalDistribution() } set {_uniqueStorage()._executionTime = .executionTimeNormal(newValue)} } public var executionTimeLogNormal: Tensorflow_LogNormalDistribution { get { if case .executionTimeLogNormal(let v)? = _storage._executionTime {return v} return Tensorflow_LogNormalDistribution() } set {_uniqueStorage()._executionTime = .executionTimeLogNormal(newValue)} } public var opMemory: Tensorflow_OpPerformance.OpMemory { get {return _storage._opMemory ?? Tensorflow_OpPerformance.OpMemory()} set {_uniqueStorage()._opMemory = newValue} } /// Returns true if `opMemory` has been explicitly set. public var hasOpMemory: Bool {return _storage._opMemory != nil} /// Clears the value of `opMemory`. Subsequent reads from it will return its default value. public mutating func clearOpMemory() {_storage._opMemory = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() /// Expected execution time, modeled using one of 2 possible distributions. public enum OneOf_ExecutionTime: Equatable { case executionTimeNormal(Tensorflow_NormalDistribution) case executionTimeLogNormal(Tensorflow_LogNormalDistribution) public static func ==(lhs: Tensorflow_OpPerformance.OneOf_ExecutionTime, rhs: Tensorflow_OpPerformance.OneOf_ExecutionTime) -> Bool { switch (lhs, rhs) { case (.executionTimeNormal(let l), .executionTimeNormal(let r)): return l == r case (.executionTimeLogNormal(let l), .executionTimeLogNormal(let r)): return l == r default: return false } } } /// Memory usage data for a tensorflow operation. public struct OpMemory: SwiftProtobuf.Message { public static let protoMessageName: String = Tensorflow_OpPerformance.protoMessageName + ".OpMemory" /// The output information may have memory usage and output shapes. public var outputMemory: [Int64] = [] /// Temporary memory allocated by this node. public var hostTempMemory: Int64 = 0 public var deviceTempMemory: Int64 = 0 /// The persisted_memory doesn't include outputs. public var hostPersistentMemory: Int64 = 0 public var devicePersistentMemory: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeRepeatedInt64Field(value: &self.outputMemory) case 2: try decoder.decodeSingularInt64Field(value: &self.hostTempMemory) case 3: try decoder.decodeSingularInt64Field(value: &self.deviceTempMemory) case 4: try decoder.decodeSingularInt64Field(value: &self.hostPersistentMemory) case 5: try decoder.decodeSingularInt64Field(value: &self.devicePersistentMemory) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.outputMemory.isEmpty { try visitor.visitPackedInt64Field(value: self.outputMemory, fieldNumber: 1) } if self.hostTempMemory != 0 { try visitor.visitSingularInt64Field(value: self.hostTempMemory, fieldNumber: 2) } if self.deviceTempMemory != 0 { try visitor.visitSingularInt64Field(value: self.deviceTempMemory, fieldNumber: 3) } if self.hostPersistentMemory != 0 { try visitor.visitSingularInt64Field(value: self.hostPersistentMemory, fieldNumber: 4) } if self.devicePersistentMemory != 0 { try visitor.visitSingularInt64Field(value: self.devicePersistentMemory, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } } public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularMessageField(value: &_storage._op) case 2: try decoder.decodeSingularInt64Field(value: &_storage._temporaryMemorySize) case 3: try decoder.decodeSingularInt64Field(value: &_storage._computeCost) case 4: try decoder.decodeSingularDoubleField(value: &_storage._computeEfficiency) case 5: try decoder.decodeSingularStringField(value: &_storage._node) case 6: try decoder.decodeSingularInt64Field(value: &_storage._computeTime) case 7: try decoder.decodeSingularInt64Field(value: &_storage._memoryTime) case 8: try decoder.decodeSingularDoubleField(value: &_storage._memoryEfficiency) case 9: try decoder.decodeSingularMessageField(value: &_storage._opMemory) case 10: var v: Tensorflow_NormalDistribution? if let current = _storage._executionTime { try decoder.handleConflictingOneOf() if case .executionTimeNormal(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {_storage._executionTime = .executionTimeNormal(v)} case 11: var v: Tensorflow_LogNormalDistribution? if let current = _storage._executionTime { try decoder.handleConflictingOneOf() if case .executionTimeLogNormal(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {_storage._executionTime = .executionTimeLogNormal(v)} default: break } } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if let v = _storage._op { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if _storage._temporaryMemorySize != 0 { try visitor.visitSingularInt64Field(value: _storage._temporaryMemorySize, fieldNumber: 2) } if _storage._computeCost != 0 { try visitor.visitSingularInt64Field(value: _storage._computeCost, fieldNumber: 3) } if _storage._computeEfficiency != 0 { try visitor.visitSingularDoubleField(value: _storage._computeEfficiency, fieldNumber: 4) } if !_storage._node.isEmpty { try visitor.visitSingularStringField(value: _storage._node, fieldNumber: 5) } if _storage._computeTime != 0 { try visitor.visitSingularInt64Field(value: _storage._computeTime, fieldNumber: 6) } if _storage._memoryTime != 0 { try visitor.visitSingularInt64Field(value: _storage._memoryTime, fieldNumber: 7) } if _storage._memoryEfficiency != 0 { try visitor.visitSingularDoubleField(value: _storage._memoryEfficiency, fieldNumber: 8) } if let v = _storage._opMemory { try visitor.visitSingularMessageField(value: v, fieldNumber: 9) } switch _storage._executionTime { case .executionTimeNormal(let v)?: try visitor.visitSingularMessageField(value: v, fieldNumber: 10) case .executionTimeLogNormal(let v)?: try visitor.visitSingularMessageField(value: v, fieldNumber: 11) case nil: break } } try unknownFields.traverse(visitor: &visitor) } fileprivate var _storage = _StorageClass.defaultInstance } /// A collection of OpPerformance data points. public struct Tensorflow_OpPerformanceList: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".OpPerformanceList" public var opPerformance: [Tensorflow_OpPerformance] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeRepeatedMessageField(value: &self.opPerformance) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.opPerformance.isEmpty { try visitor.visitRepeatedMessageField(value: self.opPerformance, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "tensorflow" extension Tensorflow_OpInfo: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "op"), 2: .same(proto: "attr"), 3: .same(proto: "inputs"), 5: .same(proto: "outputs"), 4: .same(proto: "device"), ] fileprivate class _StorageClass { var _op: String = String() var _attr: Dictionary<String,Tensorflow_AttrValue> = [:] var _inputs: [Tensorflow_OpInfo.TensorProperties] = [] var _outputs: [Tensorflow_OpInfo.TensorProperties] = [] var _device: Tensorflow_DeviceProperties? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _op = source._op _attr = source._attr _inputs = source._inputs _outputs = source._outputs _device = source._device } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public func _protobuf_generated_isEqualTo(other: Tensorflow_OpInfo) -> Bool { if _storage !== other._storage { let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_storage, other_storage) in if _storage._op != other_storage._op {return false} if _storage._attr != other_storage._attr {return false} if _storage._inputs != other_storage._inputs {return false} if _storage._outputs != other_storage._outputs {return false} if _storage._device != other_storage._device {return false} return true } if !storagesAreEqual {return false} } if unknownFields != other.unknownFields {return false} return true } } extension Tensorflow_OpInfo.TensorProperties: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "dtype"), 2: .same(proto: "shape"), 3: .same(proto: "value"), ] fileprivate class _StorageClass { var _dtype: Tensorflow_DataType = .dtInvalid var _shape: Tensorflow_TensorShapeProto? = nil var _value: Tensorflow_TensorProto? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _dtype = source._dtype _shape = source._shape _value = source._value } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public func _protobuf_generated_isEqualTo(other: Tensorflow_OpInfo.TensorProperties) -> Bool { if _storage !== other._storage { let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_storage, other_storage) in if _storage._dtype != other_storage._dtype {return false} if _storage._shape != other_storage._shape {return false} if _storage._value != other_storage._value {return false} return true } if !storagesAreEqual {return false} } if unknownFields != other.unknownFields {return false} return true } } extension Tensorflow_NormalDistribution: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "mu"), 2: .same(proto: "sigma"), ] public func _protobuf_generated_isEqualTo(other: Tensorflow_NormalDistribution) -> Bool { if self.mu != other.mu {return false} if self.sigma != other.sigma {return false} if unknownFields != other.unknownFields {return false} return true } } extension Tensorflow_LogNormalDistribution: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "mu"), 2: .same(proto: "sigma"), ] public func _protobuf_generated_isEqualTo(other: Tensorflow_LogNormalDistribution) -> Bool { if self.mu != other.mu {return false} if self.sigma != other.sigma {return false} if unknownFields != other.unknownFields {return false} return true } } extension Tensorflow_OpPerformance: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "op"), 5: .same(proto: "node"), 2: .standard(proto: "temporary_memory_size"), 3: .standard(proto: "compute_cost"), 6: .standard(proto: "compute_time"), 7: .standard(proto: "memory_time"), 4: .standard(proto: "compute_efficiency"), 8: .standard(proto: "memory_efficiency"), 10: .standard(proto: "execution_time_normal"), 11: .standard(proto: "execution_time_log_normal"), 9: .standard(proto: "op_memory"), ] fileprivate class _StorageClass { var _op: Tensorflow_OpInfo? = nil var _node: String = String() var _temporaryMemorySize: Int64 = 0 var _computeCost: Int64 = 0 var _computeTime: Int64 = 0 var _memoryTime: Int64 = 0 var _computeEfficiency: Double = 0 var _memoryEfficiency: Double = 0 var _executionTime: Tensorflow_OpPerformance.OneOf_ExecutionTime? var _opMemory: Tensorflow_OpPerformance.OpMemory? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _op = source._op _node = source._node _temporaryMemorySize = source._temporaryMemorySize _computeCost = source._computeCost _computeTime = source._computeTime _memoryTime = source._memoryTime _computeEfficiency = source._computeEfficiency _memoryEfficiency = source._memoryEfficiency _executionTime = source._executionTime _opMemory = source._opMemory } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public func _protobuf_generated_isEqualTo(other: Tensorflow_OpPerformance) -> Bool { if _storage !== other._storage { let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_storage, other_storage) in if _storage._op != other_storage._op {return false} if _storage._node != other_storage._node {return false} if _storage._temporaryMemorySize != other_storage._temporaryMemorySize {return false} if _storage._computeCost != other_storage._computeCost {return false} if _storage._computeTime != other_storage._computeTime {return false} if _storage._memoryTime != other_storage._memoryTime {return false} if _storage._computeEfficiency != other_storage._computeEfficiency {return false} if _storage._memoryEfficiency != other_storage._memoryEfficiency {return false} if _storage._executionTime != other_storage._executionTime {return false} if _storage._opMemory != other_storage._opMemory {return false} return true } if !storagesAreEqual {return false} } if unknownFields != other.unknownFields {return false} return true } } extension Tensorflow_OpPerformance.OpMemory: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "output_memory"), 2: .standard(proto: "host_temp_memory"), 3: .standard(proto: "device_temp_memory"), 4: .standard(proto: "host_persistent_memory"), 5: .standard(proto: "device_persistent_memory"), ] public func _protobuf_generated_isEqualTo(other: Tensorflow_OpPerformance.OpMemory) -> Bool { if self.outputMemory != other.outputMemory {return false} if self.hostTempMemory != other.hostTempMemory {return false} if self.deviceTempMemory != other.deviceTempMemory {return false} if self.hostPersistentMemory != other.hostPersistentMemory {return false} if self.devicePersistentMemory != other.devicePersistentMemory {return false} if unknownFields != other.unknownFields {return false} return true } } extension Tensorflow_OpPerformanceList: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "op_performance"), ] public func _protobuf_generated_isEqualTo(other: Tensorflow_OpPerformanceList) -> Bool { if self.opPerformance != other.opPerformance {return false} if unknownFields != other.unknownFields {return false} return true } }
mit
EvsenevDev/SmartReceiptsiOS
SmartReceipts/ViewControllers/TripTitleView/TripTitleView.swift
2
1036
// // TripTitleView.swift // SmartReceipts // // Created by Bogdan Evsenev on 23.12.2019. // Copyright © 2019 Will Baumann. All rights reserved. // import Foundation class TripTitleView: UIView { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var arrrowImageView: UIImageView! @IBOutlet private weak var subtitleLabel: UILabel! @IBOutlet private weak var widthConstraint: NSLayoutConstraint! override var tintColor: UIColor! { didSet { titleLabel.textColor = tintColor arrrowImageView.tintColor = tintColor subtitleLabel.textColor = tintColor.withAlphaComponent(0.5) } } func set(title: String, subtitle: String?) { titleLabel.text = title subtitleLabel.text = subtitle subtitleLabel.isHidden = subtitle == nil titleLabel.sizeToFit() subtitleLabel.sizeToFit() widthConstraint.constant = max(titleLabel.bounds.width, subtitleLabel.bounds.width) + UI_MARGIN_16 } }
agpl-3.0
binarylevel/Tinylog-iOS
Tinylog/Extensions/String+TinylogiOSAdditions.swift
1
1187
// // String+TinylogiOSAdditions.swift // Tinylog // // Created by Spiros Gerokostas on 18/10/15. // Copyright © 2015 Spiros Gerokostas. All rights reserved. // import UIKit extension String { func length() -> Int { return self.characters.count } func trim() -> String { return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) } func substring(location:Int, length:Int) -> String! { return (self as NSString).substringWithRange(NSMakeRange(location, length)) } subscript(index: Int) -> String! { get { return self.substring(index, length: 1) } } func location(other: String) -> Int { return (self as NSString).rangeOfString(other).location } func contains(other: String) -> Bool { return (self as NSString).containsString(other) } // http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-contains-a-numeric-value func isNumeric() -> Bool { return (self as NSString).rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).location == NSNotFound } }
mit
realm-demos/realm-loginkit
RealmLoginKit Apple/RealmLoginKit/Extensions/Realm+RLMSupport.swift
1
2319
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 Realm extension RLMRealm { @nonobjc public class func schemaVersion(at url: URL, usingEncryptionKey key: Data? = nil) throws -> UInt64 { var error: NSError? let version = __schemaVersion(at: url, encryptionKey: key, error: &error) guard version != RLMNotVersioned else { throw error! } return version } public func objects<T: RLMObject>(ofType: T.Type, where predicateFormat: String, _ args: CVarArg...) -> RLMResults<T> { return T.objects(in: self, with: NSPredicate(format: predicateFormat, arguments: getVaList(args))) as! RLMResults<T> } } public final class RLMIterator: IteratorProtocol { private var iteratorBase: NSFastEnumerationIterator internal init(collection: RLMCollection) { iteratorBase = NSFastEnumerationIterator(collection) } public func next() -> RLMObject? { return iteratorBase.next() as! RLMObject? } } // Sequence conformance for RLMArray and RLMResults is provided by RLMCollection's // `makeIterator()` implementation. extension RLMArray: Sequence {} extension RLMResults: Sequence {} extension RLMCollection { // Support Sequence-style enumeration public func makeIterator() -> RLMIterator { return RLMIterator(collection: self) } } extension RLMCollection { // Swift query convenience functions public func indexOfObject(where predicateFormat: String, _ args: CVarArg...) -> UInt { return indexOfObject(with: NSPredicate(format: predicateFormat, arguments: getVaList(args))) } }
apache-2.0
cafielo/iOS_BigNerdRanch_5th
Chap3_WorldTrotter/WorldTrotter/ViewController.swift
1
509
// // ViewController.swift // WorldTrotter // // Created by Joonwon Lee on 7/17/16. // Copyright © 2016 Joonwon Lee. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
damoyan/BYRClient
FromScratch/ImagePlayer.swift
1
2550
// // ImageInfo.swift // FromScratch // // Created by Yu Pengyang on 1/11/16. // Copyright © 2016 Yu Pengyang. All rights reserved. // import UIKit class ImagePlayer { private var currentIndex = 0 private let decoder: ImageDecoder private var link = CADisplayLink() private var curImage: UIImage? private var buffer = [Int: UIImage]() private var block: ((UIImage?) -> ())? private var time: NSTimeInterval = 0 private var miss = false private var queue = NSOperationQueue() private var lock = OS_SPINLOCK_INIT init(decoder: ImageDecoder, block: (UIImage?) -> ()) { self.decoder = decoder self.block = block self.link = CADisplayLink(target: WeakReferenceProxy(target: self), selector: "step:") link.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) if let image = decoder.firstFrame { block(image) } } @objc private func step(link: CADisplayLink) { let nextIndex = (currentIndex + 1) % decoder.frameCount if !miss { time += link.duration var delay = decoder.imageDurationAtIndex(currentIndex) if time < delay { return } time -= delay delay = decoder.imageDurationAtIndex(nextIndex) if time > delay { time = delay } } OSSpinLockLock(&lock) let image = buffer[nextIndex] OSSpinLockUnlock(&lock) if let image = image { curImage = image currentIndex = nextIndex miss = false } else { miss = true } if !miss { block?(image) } if queue.operationCount > 0 { return } queue.addOperationWithBlock { [weak self] () -> Void in guard let this = self else { return } for i in 0...(nextIndex + 1) { OSSpinLockLock(&this.lock) let cached = this.buffer[i] OSSpinLockUnlock(&this.lock) if cached != nil { continue } if let image = this.decoder.imageAtIndex(i) { OSSpinLockLock(&this.lock) this.buffer[i] = image OSSpinLockUnlock(&this.lock) } } } } func stop() { print("stop") block = nil link.invalidate() } deinit { link.invalidate() print("deinit ImagePlayer") } }
mit
firebase/firebase-ios-sdk
FirebaseRemoteConfigSwift/Tests/SwiftAPI/Constants.swift
1
1901
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// String constants used for testing. enum Constants { static let key1 = "Key1" static let jedi = "Jedi" static let sith = "Sith_Lord" static let value1 = "Value1" static let obiwan = "Obi-Wan" static let yoda = "Yoda" static let darthSidious = "Darth Sidious" static let stringKey = "myString" static let stringValue = "string contents" static let intKey = "myInt" static let intValue: Int = 123 static let floatKey = "myFloat" static let floatValue: Float = 42.75 static let doubleValue: Double = 42.75 static let decimalKey = "myDecimal" static let decimalValue: Decimal = 375.785 static let trueKey = "myTrue" static let falseKey = "myFalse" static let dataKey = "myData" static let dataValue: Data = "data".data(using: .utf8)! static let arrayKey = "fruits" static let arrayValue: [String] = ["mango", "pineapple", "papaya"] static let dictKey = "platforms" static let dictValue: [String: String] = [ "iOS": "14.0", "macOS": "14.0", "tvOS": "10.0", "watchOS": "6.0", ] static let jsonKey = "Recipe" static let jsonValue: [String: AnyHashable] = [ "recipeName": "PB&J", "ingredients": ["bread", "peanut butter", "jelly"], "cookTime": 7, ] static let nonJsonKey = "notJSON" static let nonJsonValue = "notJSON" }
apache-2.0
codeswimmer/SwiftCommon
SwiftCommon/SwiftCommon/Source/GCD.swift
1
1825
// // GCD.swift // SwiftCommon // // Created by Keith Ermel on 7/5/14. // Copyright (c) 2014 Keith Ermel. All rights reserved. // import Foundation public class GCD { public typealias DQueue = dispatch_queue_t public typealias DTime = dispatch_time_t public typealias GCDAction = () -> Void public typealias DelayCompletion = ()->Void // MARK: Async public class func asyncOnMainQueue(action: GCDAction) {dispatch_async(mainQueue, action)} public class func asyncOnQueue(queue: DQueue, action: GCDAction) {dispatch_async(queue, action)} public class func performWithDelayMillis(delay: Int64, action: GCDAction) { dispatch_after(timeWith(delay), mainQueue, {action()}) } public class func performWithDelayMillis(delay: Int64, action: GCDAction, completion: DelayCompletion?) { dispatch_after(timeWith(delay), mainQueue, { action() if let completionHandler = completion { completionHandler() } }) } // MARK: Queue Creation public class func createSerialQueue(label: String) -> DQueue { return dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL) } public class func createConcurrentQueue(label: String) -> DQueue { return dispatch_queue_create(label, DISPATCH_QUEUE_CONCURRENT) } // MARK: Utilities public class func isMainQueue() -> Bool {return NSThread.isMainThread()} public class func timeWith(millis: Int64) -> DTime {return dispatch_time(timeNow, millis * nanoPerMS)} // MARK: Constants public class var mainQueue: DQueue! {return dispatch_get_main_queue()} class var timeNow: DTime {return DISPATCH_TIME_NOW} class var nanoPerMS: Int64 {return Int64(NSEC_PER_MSEC)} }
mit
tirtawn/EGSwiftConnectFour
swiftConnectFour/AppDelegate.swift
1
2168
// // AppDelegate.swift // swiftConnectFour // // Created by Eric Gu on 10/31/14. // Copyright (c) 2014 Eric Gu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
Econa77/SwiftFontName
Example/Example/SystemFontsViewController.swift
2
1275
// // SystemFontsViewController.swift // Example // // Created by MORITANAOKI on 2015/07/18. // Copyright (c) 2015年 molabo. All rights reserved. // import UIKit class SystemFontsViewController: UITableViewController { let viewModel = SystemFontsViewModel() override func viewDidLoad() { super.viewDidLoad() } } extension SystemFontsViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return count(viewModel.families) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count(viewModel.families[section].fonts) } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.families[section].name } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let family = viewModel.families[indexPath.section] let font = family.fonts[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell cell.textLabel?.text = font.name cell.textLabel?.font = font.font return cell } }
mit
jphacks/TK_21
ios/jphack3/AppDelegate.swift
1
2147
// // AppDelegate.swift // jphack3 // // Created by Shoma Saito on 2015/11/29. // Copyright © 2015年 eyes,japan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
blinker13/Terminal
Sources/Block.swift
1
360
public struct Block : Command { public let name:String public let description:String public let handler:(Arguments) -> Void public init(name:String, description:String, handler:(Arguments) -> Void) { (self.name, self.description, self.handler) = (name, description, handler) } public func run(with arguments: Arguments) { handler(arguments) } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/15645-swift-sourcemanager-getmessage.swift
11
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing return m( { case { enum b { class d { deinit { class case ,
mit
natecook1000/swift-compiler-crashes
crashes-fuzzing/24900-swift-typebase-getmembersubstitutions.swift
7
215
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where B:e{class a<d{class f let a=f
mit
AdamSliwakowski/TypedTableView
TypedTableViewExample/AppDelegate.swift
1
2162
// // AppDelegate.swift // TypedTableView // // Created by Adam Śliwakowski on 20.12.2015. // Copyright © 2015 AdamSliwakowski. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
barankaraoguzzz/FastOnBoarding
Example/FOView/AppDelegate.swift
1
2216
// // AppDelegate.swift // FOView // // Created by baran.karaoguz@ogr.sakarya.edu.tr on 04/04/2018. // Copyright (c) 2018 baran.karaoguz@ogr.sakarya.edu.tr. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
Egibide-DAM/swift
02_ejemplos/10_varios/03_conversion_tipos/03_downcasting.playground/Contents.swift
1
1259
class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] // the type of "library" is inferred to be [MediaItem] // ------ for item in library { if let movie = item as? Movie { print("Movie: \(movie.name), dir. \(movie.director)") } else if let song = item as? Song { print("Song: \(song.name), by \(song.artist)") } } // Movie: Casablanca, dir. Michael Curtiz // Song: Blue Suede Shoes, by Elvis Presley // Movie: Citizen Kane, dir. Orson Welles // Song: The One And Only, by Chesney Hawkes // Song: Never Gonna Give You Up, by Rick Astley
apache-2.0
abaca100/Nest
iOS-NestDK/HomeStore.swift
1
593
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `HomeStore` class is a simple singleton class which holds a home manager and the current selected home. */ import HomeKit /// A static, singleton class which holds a home manager and the current home. class HomeStore: NSObject { static let sharedStore = HomeStore() // MARK: Properties /// The current 'selected' home. var home: HMHome? /// The singleton home manager. var homeManager = HMHomeManager() }
apache-2.0
BoxJeon/funjcam-ios
Domain/Usecase/TestSupport/SearchProviderUsecaseMock.swift
1
418
import Entity import Usecase public final class SearchProviderUsecaseMock: SearchProviderUsecase { public var searchProvider: SearchProvider public init(searchProvider: SearchProvider) { self.searchProvider = searchProvider } public func query() -> SearchProvider { return self.searchProvider } public func mutate(_ newValue: SearchProvider) { self.searchProvider = newValue } }
mit
minsOne/DigitClockInSwift
MainFeature/MainFeature/Dependencies/Clock/Clock/Source/TimerService.swift
1
992
// // TimerService.swift // Clock // // Created by minsone on 2019/12/01. // Copyright © 2019 minsone. All rights reserved. // import Foundation import ClockTimer import Library protocol TimerServiciable { func setSpaceViewTimerRecevier(receiver: SpaceViewScheduledTimerReceivable) func setClockScheduledTimerReceiver(receiver: ClockScheduledTimerReceivable) func startClockTimer() func startSpaceViewTimer() func stopSpaceViewTimer() } class TimerService { var clockTimer: ClockScheduledTimerable? var spaceViewTimer: SpaceViewScheduledTimerable? init() {} func setSpaceViewTimerRecevier(receiver: SpaceViewScheduledTimerReceivable) { self.spaceViewTimer?.receiver = receiver } func setClockScheduledTimerReceiver(receiver: ClockScheduledTimerReceivable) { self.clockTimer?.receiver = receiver } func startClockTimer() { if let timer = clockTimer { timer.stop() } } }
mit
dasmer/RelativeFit
RelativeFit/DeltaTableViewCell.swift
1
799
import UIKit import RelativeFitDataKit @objc(DeltaTableViewCell) public class DeltaTableViewCell: UITableViewCell { class func height() -> Int { return 90; } @IBOutlet weak var deltaValueLabel: UILabel! @IBOutlet weak var todayValueLabel: UILabel! @IBOutlet weak var yesterdayValueLabel: UILabel! @IBOutlet weak var todayTitleLabel: UILabel! @IBOutlet weak var yesterdayTitleLabel: UILabel! public override func awakeFromNib() { deltaValueLabel?.textColor = UIColor.fit_emeraldColor() todayValueLabel?.textColor = UIColor.fit_greyColor() yesterdayValueLabel?.textColor = UIColor.fit_greyColor() todayTitleLabel?.textColor = UIColor.fit_greyColor() yesterdayTitleLabel?.textColor = UIColor.fit_greyColor() } }
mit
AppTown/OpenWeather
OpenWeather/OpenWeather/ForecastTableViewCell.swift
1
528
// // ForecastTableViewCell.swift // OpenWeather // // Created by Dario Banno on 29/05/2017. // Copyright © 2017 AppTown. All rights reserved. // import UIKit class ForecastTableViewCell: UITableViewCell { @IBOutlet weak var dateTimeLabel: UILabel! @IBOutlet weak var temperatureMinLabel: UILabel! @IBOutlet weak var temperatureMaxLabel: UILabel! @IBOutlet weak var iconLabel: UILabel! { didSet { iconLabel.font = UIFont(name: "WeatherIcons-Regular", size: 20) } } }
bsd-3-clause
nghialv/Hakuba
Hakuba/Source/Cell/CellModel.swift
1
1645
// // CellModel.swift // Example // // Created by Le VanNghia on 3/4/16. // // import UIKit protocol CellModelDelegate: class { func bumpMe(with type: ItemBumpType, animation: UITableViewRowAnimation) func getOffscreenCell(by identifier: String) -> Cell func tableViewWidth() -> CGFloat func deselectCell(at indexPath: IndexPath, animated: Bool) } open class CellModel { weak var delegate: CellModelDelegate? open let reuseIdentifier: String open var height: CGFloat open var selectionHandler: ((Cell) -> Void)? open internal(set) var indexPath: IndexPath = .init(row: 0, section: 0) open var editable = false open var editingStyle: UITableViewCellEditingStyle = .none open var shouldHighlight = true public init<T: Cell & CellType>(cell: T.Type, height: CGFloat = UITableViewAutomaticDimension, selectionHandler: ((Cell) -> Void)? = nil) { self.reuseIdentifier = cell.reuseIdentifier self.height = height self.selectionHandler = selectionHandler } @discardableResult open func bump(_ animation: UITableViewRowAnimation = .none) -> Self { delegate?.bumpMe(with: .reload(indexPath), animation: animation) return self } open func deselect(_ animated: Bool) { delegate?.deselectCell(at: indexPath, animated: animated) } } // MARK - Internal methods extension CellModel { func setup(indexPath: IndexPath, delegate: CellModelDelegate) { self.indexPath = indexPath self.delegate = delegate } func didSelect(cell: Cell) { selectionHandler?(cell) } }
mit
startry/SwViewCapture
Example/Example/STViewDemoController.swift
1
1563
// // STViewDemoController.swift // STViewCapture // // Created by chenxing.cx on 10/28/2015. // Copyright (c) 2015 startry.com All rights reserved. // import UIKit import SwViewCapture class STViewDemoController: UIViewController { // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.yellow navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Capture", style: UIBarButtonItemStyle.plain, target: self, action: #selector(STViewDemoController.didCaptureBtnClicked(_:))) // Add Some Color View for Capture let orangeView = UIView(frame: CGRect(x: 100, y: 100, width: 20, height: 50)) let redView = UIView(frame: CGRect(x: 150, y: 200, width: 100, height: 100)) let headImage = UIImage(named: "demo_2") let headImageView = UIImageView(frame: CGRect(x: 30, y: 300, width: headImage!.size.width, height: headImage!.size.height)) headImageView.image = headImage orangeView.backgroundColor = UIColor.orange redView.backgroundColor = UIColor.red view.addSubview(orangeView) view.addSubview(redView) view.addSubview(headImageView) } // MARK: Events @objc func didCaptureBtnClicked(_ button: UIButton){ view.swCapture { (capturedImage) -> Void in let vc = ImageViewController(image: capturedImage!) self.navigationController?.pushViewController(vc, animated: true) } } }
mit
shiLiJie/LJWeiBo
LJ微博/LJ微博/DiscoverViewController.swift
1
610
// // DiscoverViewController.swift // LJ微博 // // Created by slj on 15/10/7. // Copyright © 2015年 slj. All rights reserved. // import UIKit class DiscoverViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() loginView?.setupInfo(false, imageName: "visitordiscover_image_message", message: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
Matzo/Kamishibai
Example/Kamishibai/SecondViewController.swift
1
1136
// // SecondViewController.swift // Kamishibai // // Created by Keisuke Matsuo on 2017/08/12. // // import UIKit class SecondViewController: UIViewController { @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a kamishibaiboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ static func create() -> SecondViewController { let vc = UIStoryboard.init(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: String(describing: SecondViewController.self)) as! SecondViewController return vc } }
mit
rudkx/swift
test/Interop/Cxx/reference/reference-silgen.swift
1
3311
// RUN: %target-swift-emit-sil -I %S/Inputs -enable-cxx-interop %s | %FileCheck %s import Reference func getCxxRef() -> UnsafeMutablePointer<CInt> { return getStaticIntRef() } // CHECK: sil hidden @$s4main9getCxxRefSpys5Int32VGyF : $@convention(thin) () -> UnsafeMutablePointer<Int32> // CHECK: [[REF:%.*]] = function_ref @{{_Z15getStaticIntRefv|\?getStaticIntRef@@YAAEAHXZ}} : $@convention(c) () -> UnsafeMutablePointer<Int32> // CHECK: apply [[REF]]() : $@convention(c) () -> UnsafeMutablePointer<Int32> func getConstCxxRef() -> UnsafePointer<CInt> { return getConstStaticIntRef() } // CHECK: sil hidden @$s4main14getConstCxxRefSPys5Int32VGyF : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[REF:%.*]] = function_ref @{{_Z20getConstStaticIntRefv|\?getConstStaticIntRef@@YAAEBHXZ}} : $@convention(c) () -> UnsafePointer<Int32> // CHECK: apply [[REF]]() : $@convention(c) () -> UnsafePointer<Int32> func getCxxRvalueRef() -> UnsafeMutablePointer<CInt> { return getStaticIntRvalueRef() } // CHECK: sil hidden @$s4main15getCxxRvalueRefSpys5Int32VGyF : $@convention(thin) () -> UnsafeMutablePointer<Int32> // CHECK: [[REF:%.*]] = function_ref @{{_Z21getStaticIntRvalueRefv|\?getStaticIntRvalueRef@@YA\$\$QEAHXZ}} : $@convention(c) () -> UnsafeMutablePointer<Int32> // CHECK: apply [[REF]]() : $@convention(c) () -> UnsafeMutablePointer<Int32> func getConstCxxRvalueRef() -> UnsafePointer<CInt> { return getConstStaticIntRvalueRef() } // CHECK: sil hidden @$s4main20getConstCxxRvalueRefSPys5Int32VGyF : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[REF:%.*]] = function_ref @{{_Z26getConstStaticIntRvalueRefv|\?getConstStaticIntRvalueRef@@YA\$\$QEBHXZ}} : $@convention(c) () -> UnsafePointer<Int32> // CHECK: apply [[REF]]() : $@convention(c) () -> UnsafePointer<Int32> func setCxxRef() { var val: CInt = 21 setStaticIntRef(&val) } // CHECK: sil hidden @$s4main9setCxxRefyyF : $@convention(thin) () -> () // CHECK: [[REF:%.*]] = function_ref @{{_Z15setStaticIntRefRi|\?setStaticIntRef@@YAXAEAH@Z}} : $@convention(c) (@inout Int32) -> () // CHECK: apply [[REF]](%{{[0-9]+}}) : $@convention(c) (@inout Int32) -> () func setCxxConstRef() { let val: CInt = 21 setConstStaticIntRef(val) } // CHECK: sil hidden @$s4main14setCxxConstRefyyF : $@convention(thin) () -> () // CHECK: [[REF:%.*]] = function_ref @{{_Z20setConstStaticIntRefRKi|\?setConstStaticIntRef@@YAXAEBH@Z}} : $@convention(c) (@in Int32) -> () // CHECK: apply [[REF]](%{{[0-9]+}}) : $@convention(c) (@in Int32) -> () func setCxxRvalueRef() { var val: CInt = 21 setStaticIntRvalueRef(&val) } // CHECK: sil hidden @$s4main15setCxxRvalueRefyyF : $@convention(thin) () -> () // CHECK: [[REF:%.*]] = function_ref @{{_Z21setStaticIntRvalueRefOi|\?setStaticIntRvalueRef@@YAX\$\$QEAH@Z}} : $@convention(c) (@inout Int32) -> () // CHECK: apply [[REF]](%{{[0-9]+}}) : $@convention(c) (@inout Int32) -> () func setCxxConstRvalueRef() { let val: CInt = 21 setConstStaticIntRvalueRef(val) } // CHECK: sil hidden @$s4main20setCxxConstRvalueRefyyF : $@convention(thin) () -> () // CHECK: [[REF:%.*]] = function_ref @{{_Z26setConstStaticIntRvalueRefOKi|\?setConstStaticIntRvalueRef@@YAX\$\$QEBH@Z}} : $@convention(c) (@in Int32) -> () // CHECK: apply [[REF]](%{{[0-9]+}}) : $@convention(c) (@in Int32) -> ()
apache-2.0
rajusa420/DataStructures
DataStructures/DataStructures/LinkedList.swift
1
5063
// // Created by Raj on 2019-01-13. // Copyright (c) 2019 Rajusa. All rights reserved. // import Foundation class SwLinkedListNode { var data: NSObject?; fileprivate var next: SwLinkedListNode?; init(data: NSObject) { self.data = data; } init(data: NSObject, next: SwLinkedListNode) { self.data = data; self.next = next; } } public class SwLinkedList : NSObject, DataCollection, DataCollectionDebug { var head: SwLinkedListNode?; var tail: SwLinkedListNode?; var nodeCount: UInt = 0; public class func newInstance() -> SwLinkedList { return SwLinkedList() } public func count() -> UInt { return self.nodeCount; } public func add(_ object: NSObject!) { let newNode = SwLinkedListNode(data: object); if let tail = self.tail { tail.next = newNode; } self.tail = newNode; if self.head == nil { self.head = newNode; } self.nodeCount += 1; } public func removeFirstObject() -> NSObject? { guard let head = self.head else { return nil; } if let tail = self.tail { if tail === head { self.tail = nil; } } self.head = head.next; self.nodeCount -= 1; return head.data; } public func removeLastObject() -> NSObject? { guard let head = self.head else { return nil; } var current : SwLinkedListNode? = head; if let tail = self.tail { if tail === head { self.head = nil; self.tail = nil; self.nodeCount = 0; return current!.data; } } while current != nil { if (current!.next === self.tail) { let lastNode : SwLinkedListNode? = current!.next; current!.next = nil; self.tail = current; self.nodeCount -= 1; return lastNode!.data; } current = current!.next; } return nil; } public func remove(_ object: NSObject!) -> NSObject! { guard let head = self.head else { return nil; } var previous : SwLinkedListNode? = nil; var current : SwLinkedListNode? = head; while current != nil { if (current!.data == object) { if head === current { self.head = current!.next; } if self.tail === current { self.tail = previous; } if previous != nil { previous!.next = current!.next; } return current!.data; } previous = current; current = current!.next; } return nil; } public func removeAllObjects() { guard let head = self.head else { return; } // Note: We need to go through and release one object at a time // else we get a stack overflow var current : SwLinkedListNode? = head; while current != nil { let next: SwLinkedListNode? = current!.next; current!.data = nil; current!.next = nil; current = next; } self.head = nil; self.tail = nil; self.nodeCount = 0; } public func contains(_ object: NSObject) -> Bool { guard let head = self.head else { return false; } var current : SwLinkedListNode? = head; while current != nil { if (current!.data == object) { return true; } current = current!.next; } return false; } public func getFirstObject() -> NSObject? { guard let head = self.head else { return nil; } return head.data; } public func getLastObject() -> NSObject? { guard let tail = self.tail else { return nil; } return tail.data; } public func getObjectAt(_ index: UInt) -> NSObject? { guard let head = self.head else { return nil; } var current : SwLinkedListNode? = head; var position : UInt = 0; while current != nil { if (position == index) { return current!.data; } position += 1; current = current!.next; } return nil; } public func printAllObjects(withDataType dataType: AnyClass) { guard let head = self.head else { return; } var current: SwLinkedListNode? = head; while current != nil { if current?.data.self is NSNumber { let data: NSNumber = current?.data as! NSNumber; NSLog("%@", data.stringValue); } current = current?.next; } } }
gpl-3.0
uptech/Constraid
Tests/ConstraidTests/FlushWithEdgesTests.swift
1
11779
import XCTest @testable import Constraid class FlushWithEdgesTests: XCTestCase { func testFlushWithLeadingEdgeOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withLeadingEdgeOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints.first! XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testFlushWithTrailingEdgeOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withTrailingEdgeOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints.first! XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintOne.constant, -10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testFlushWithTopEdgeOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withTopEdgeOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints.first! XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testFlushWithBottomEdgeOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withBottomEdgeOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints.first! XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintOne.constant, -10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testFlushWithVerticalEdgesOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withVerticalEdgesOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints.first! let constraintTwo = viewOne.constraints.last! XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintTwo.constant, -10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testFlushWithHorizontalEdgesOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withHorizontalEdgesOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints.first! let constraintTwo = viewOne.constraints.last! XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintTwo.constant, -10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } func testFlushWithEdgesOf() { let viewOne = View() let viewTwo = View() viewOne.addSubview(viewTwo) let proxy = viewOne.constraid.flush(withEdgesOf: viewTwo, times: 2.0, insetBy: 10.0, priority: Constraid.LayoutPriority(rawValue: 500)) let constraints = proxy.constraintCollection proxy.activate() let constraintOne = viewOne.constraints[0] let constraintTwo = viewOne.constraints[1] let constraintThree = viewOne.constraints[2] let constraintFour = viewOne.constraints[3] XCTAssertEqual(constraints, viewOne.constraints) XCTAssertEqual(constraintOne.isActive, true) XCTAssertEqual(constraintOne.firstItem as! View, viewOne) XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.relation, LayoutRelation.equal) XCTAssertEqual(constraintOne.secondItem as! View, viewTwo) XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.top) XCTAssertEqual(constraintOne.constant, 10.0) XCTAssertEqual(constraintOne.multiplier, 2.0) XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(constraintTwo.isActive, true) XCTAssertEqual(constraintTwo.firstItem as! View, viewOne) XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal) XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo) XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.bottom) XCTAssertEqual(constraintTwo.constant, -10.0) XCTAssertEqual(constraintTwo.multiplier, 2.0) XCTAssertEqual(constraintTwo.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(constraintThree.isActive, true) XCTAssertEqual(constraintThree.firstItem as! View, viewOne) XCTAssertEqual(constraintThree.firstAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintThree.relation, LayoutRelation.equal) XCTAssertEqual(constraintThree.secondItem as! View, viewTwo) XCTAssertEqual(constraintThree.secondAttribute, LayoutAttribute.leading) XCTAssertEqual(constraintThree.constant, 10.0) XCTAssertEqual(constraintThree.multiplier, 2.0) XCTAssertEqual(constraintThree.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(constraintFour.isActive, true) XCTAssertEqual(constraintFour.firstItem as! View, viewOne) XCTAssertEqual(constraintFour.firstAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintFour.relation, LayoutRelation.equal) XCTAssertEqual(constraintFour.secondItem as! View, viewTwo) XCTAssertEqual(constraintFour.secondAttribute, LayoutAttribute.trailing) XCTAssertEqual(constraintFour.constant, -10.0) XCTAssertEqual(constraintFour.multiplier, 2.0) XCTAssertEqual(constraintFour.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500))) XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false) } }
mit
AwesomeDennis/DXPhotoPicker
DXPhotoPicker/Classes/Views/DXTapDetectingImageView.swift
1
2202
// // DXTapDetectingImageView.swift // DXPhotosPickerDemo // Inspired by MWTapDetectingImageView github:https://github.com/mwaterfall/MWPhotoBrowser // Created by Ding Xiao on 15/10/14. // Copyright © 2015年 Dennis. All rights reserved. // // A swift version of MWTapDetectingImageView import UIKit @objc protocol DXTapDetectingImageViewDelegate: NSObjectProtocol { @objc optional func imageView(_: DXTapDetectingImageView?, singleTapDetected touch: UITouch?) @objc optional func imageView(_: DXTapDetectingImageView?, doubleTapDetected touch: UITouch?) @objc optional func imageView(_: DXTapDetectingImageView?, tripleTapDetected touch: UITouch?) } class DXTapDetectingImageView: UIImageView, DXTapDetectingImageViewDelegate { weak var tapDelegate: DXTapDetectingImageViewDelegate? // MARK: initialize override init(frame: CGRect) { super.init(frame: frame) self.isUserInteractionEnabled = true } override init(image: UIImage?) { super.init(image: image) self.isUserInteractionEnabled = true } override init(image: UIImage?, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) self.isUserInteractionEnabled = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: touch events override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { func handleSingleTap(touch: UITouch?) { self.tapDelegate?.imageView?(self, singleTapDetected: touch) } func handleDoubleTap(touch: UITouch?) { tapDelegate?.imageView?(self, doubleTapDetected: touch) } func handleTripleTap(touch: UITouch?) { tapDelegate?.imageView?(self, tripleTapDetected: touch) } let touch = touches.first let tapcount = touch?.tapCount switch(tapcount!) { case 1: handleSingleTap(touch: touch) case 2: handleDoubleTap(touch: touch) case 3: handleTripleTap(touch: touch) default: break } } }
mit
KeithPiTsui/Pavers
Pavers/Sources/CryptoSwift/BlockMode/PCBC.swift
2
1923
// // PCBM.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // Propagating Cipher Block Chaining (PCBC) // struct PCBCModeWorker: BlockModeWorker { let cipherOperation: CipherOperationOnBlock private let iv: ArraySlice<UInt8> private var prev: ArraySlice<UInt8>? init(iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) { self.iv = iv self.cipherOperation = cipherOperation } mutating func encrypt(_ plaintext: ArraySlice<UInt8>) -> Array<UInt8> { guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { return Array(plaintext) } prev = xor(plaintext, ciphertext.slice) return ciphertext } mutating func decrypt(_ ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { guard let plaintext = cipherOperation(ciphertext) else { return Array(ciphertext) } let result: Array<UInt8> = xor(prev ?? iv, plaintext) prev = xor(plaintext.slice, ciphertext) return result } }
mit
ahoppen/swift
test/IRGen/dynamic_replaceable_coroutine.swift
11
975
// RUN: %target-swift-frontend -module-name A -enable-implicit-dynamic -emit-ir %s | %FileCheck %s extension Int { public struct Thing { var _int: Int init(_ int: Int) { self._int = int } } public var thing: Thing { get { Thing(self) } // Make sure the initialization of `thing` is after the dynamic replacement // check. Coro splitting does not like memsets before the coro.begin. // CHECK: define{{.*}} swiftcc { i8*, %TSi1AE5ThingV* } @"$sSi1AE5thingSiAAE5ThingVvM" // CHECK: call i8* @swift_getFunctionReplacement // CHECK: br // CHECK: original_entry: // CHECK: [[FRAMEPTR:%.*]] = bitcast i8* %0 to // CHECK: [[THING:%.*]] = getelementptr inbounds {{.*}}* [[FRAMEPTR]], i32 0 // CHECK: [[THING2:%.*]] = bitcast %TSi1AE5ThingV* [[THING]] to i8* // CHECK: call void @llvm.memset{{.*}}(i8* {{.*}} [[THING2]] // CHECK: ret _modify { var thing = Thing(self) yield &thing } } }
apache-2.0
ontouchstart/swift3-playground
Drawing Sounds.playgroundbook/Contents/Chapters/Document1.playgroundchapter/Pages/Exercise1.playgroundpage/Contents.swift
1
3209
//#-hidden-code // // Contents.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // //#-end-hidden-code /*: Configure and play your own instruments! Follow the code comments below to find tips for modifying the audio loop and instruments to make new sounds. */ //#-hidden-code //#-code-completion(everything, hide) //#-code-completion(currentmodule, show) //#-code-completion(module, show, Swift) //#-code-completion(module, show, Drawing_Sounds_Sources) //#-code-completion(identifier, show, if, func, var, let, ., =, <=, >=, <, >, ==, !=, +, -, true, false, &&, ||, !, *, /, (, )) //#-code-completion(identifier, hide, leftSoundProducer(), rightSoundProducer(), SoundProducer, viewController, storyBoard, SoundBoard, MusicViewController, Instrument, ClampedInteger, AudioPlayerEngine, connect(_:)) import UIKit import PlaygroundSupport let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main) let viewController = storyBoard.instantiateInitialViewController() as! MusicViewController PlaygroundPage.current.liveView = viewController // Note: These functions are not following Swift conventions but are instead trying to mimic the feel of a class for a beginner audience. /// Creates an electric guitar. func ElectricGuitar() -> Instrument { let instrument = Instrument(kind: .electricGuitar) instrument.connect(viewController.engine!) instrument.defaultVelocity = 64 return instrument } /// Creates a bass guitar. func Bass() -> Instrument { let instrument = Instrument(kind: .bass) instrument.connect(viewController.engine!) instrument.defaultVelocity = 64 return instrument } //#-end-hidden-code //#-editable-code // Try other types of loops! let loop = Loop(type: LoopType.aboveAndBeyond) // Numbers in this playground can be from 0 to 100. Increase the volume to hear the loop. loop.volume = 0 loop.play() // This code configures the instrument keyboard on the left. //#-end-editable-code func leftSoundProducer() -> SoundProducer { //#-editable-code // Try changing the instrument to ElectricGuitar(). let instrument = Bass() instrument.defaultVelocity = 80 // Try changing the type or values for xEffect, which changes the sound depending on where you touch the keyboard. instrument.xEffect = InstrumentTweak(type: InstrumentTweakType.velocity, effectFrom: 50, to: 100) // Try another filter, such as multiEcho. instrument.filter = InstrumentFilter(type: InstrumentFilterType.cathedral) return instrument //#-end-editable-code } //#-editable-code // This code configures the voice keyboard on the right. //#-end-editable-code func rightSoundProducer() -> SoundProducer { //#-editable-code // Put your own words here. let speech = Speech(words: "Here's to the crazy ones.") speech.defaultSpeed = 30 speech.defaultVolume = 60 // Try changing the type to speed to see how it impacts the sound. speech.xEffect = SpeechTweak(type: SpeechTweakType.pitch, effectFrom: 0, to: 100) return speech //#-end-editable-code } //#-hidden-code viewController.makeLeftSoundProducer = leftSoundProducer viewController.makeRightSoundProducer = rightSoundProducer //#-end-hidden-code
mit