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
zorn/Expenses
_FINAL/Expenses/Expense.swift
1
140
import Foundation class Expense : NSObject { let name: String init(name: String) { self.name = name; } }
mit
raymondshadow/SwiftDemo
SwiftApp/StudyNote/StudyNote/RxSwift/custom/model/SNStuInfoModel.swift
1
1288
// // SNStuInfoModel.swift // StudyNote // // Created by 邬勇鹏 on 2018/9/21. // Copyright © 2018年 Raymond. All rights reserved. // import UIKit class SNStuInfoModel: NSObject { @objc dynamic var baseInfo: SNStuBaseInfoModel = SNStuBaseInfoModel() @objc dynamic var scoreInfo: SNStuScoreInfoModel = SNStuScoreInfoModel() } class SNStuBaseInfoModel: NSObject { @objc dynamic var id: Int @objc dynamic var name: String @objc dynamic var age: Int @objc dynamic var address: String override init() { self.id = 0 self.name = "" self.age = 0 self.address = "" } convenience init(id: Int, name: String, age: Int, address: String) { self.init() self.id = id self.name = name self.age = age self.address = address } } class SNStuScoreInfoModel: NSObject { @objc dynamic var math: Int = 0 @objc dynamic var english: Int = 0 @objc dynamic var china: Int = 0 override init() { super.init() } convenience init(math: Int, english: Int, china: Int) { self.init() self.math = math self.english = english self.china = china } }
apache-2.0
iMetalk/TCZDemo
RealmTest-swift-/Pods/RealmSwift/RealmSwift/Sync.swift
5
29955
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 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 import Realm.Private import Foundation /** An object representing a Realm Object Server user. - see: `RLMSyncUser` */ public typealias SyncUser = RLMSyncUser /** An immutable data object representing information retrieved from the Realm Object Server about a particular user. - see: `RLMSyncUserInfo` */ public typealias SyncUserInfo = RLMSyncUserInfo /** A singleton which configures and manages the Realm Object Server synchronization-related functionality. - see: `RLMSyncManager` */ public typealias SyncManager = RLMSyncManager extension SyncManager { /// The sole instance of the singleton. public static var shared: SyncManager { return __shared() } } /** A session object which represents communication between the client and server for a specific Realm. - see: `RLMSyncSession` */ public typealias SyncSession = RLMSyncSession /** A closure type for a closure which can be set on the `SyncManager` to allow errors to be reported to the application. - see: `RLMSyncErrorReportingBlock` */ public typealias ErrorReportingBlock = RLMSyncErrorReportingBlock /** A closure type for a closure which is used by certain APIs to asynchronously return a `SyncUser` object to the application. - see: `RLMUserCompletionBlock` */ public typealias UserCompletionBlock = RLMUserCompletionBlock /** An error associated with the SDK's synchronization functionality. All errors reported by an error handler registered on the `SyncManager` are of this type. - see: `RLMSyncError` */ public typealias SyncError = RLMSyncError /** An error associated with network requests made to the authentication server. This type of error may be returned in the callback block to `SyncUser.logIn()` upon certain types of failed login attempts (for example, if the request is malformed or if the server is experiencing an issue). - see: `RLMSyncAuthError` */ public typealias SyncAuthError = RLMSyncAuthError /** An error associated with retrieving or modifying user permissions to access a synchronized Realm. - see: `RLMSyncPermissionError` */ public typealias SyncPermissionError = RLMSyncPermissionError /** An enum which can be used to specify the level of logging. - see: `RLMSyncLogLevel` */ public typealias SyncLogLevel = RLMSyncLogLevel /** An enum representing the different states a sync management object can take. - see: `RLMSyncManagementObjectStatus` */ public typealias SyncManagementObjectStatus = RLMSyncManagementObjectStatus /** A data type whose values represent different authentication providers that can be used with the Realm Object Server. - see: `RLMIdentityProvider` */ public typealias Provider = RLMIdentityProvider public extension SyncError { /// Given a client reset error, extract and return the recovery file path and the reset closure. public func clientResetInfo() -> (String, () -> Void)? { if code == SyncError.clientResetError, let recoveryPath = userInfo[kRLMSyncPathOfRealmBackupCopyKey] as? String, let block = _nsError.__rlmSync_clientResetBlock() { return (recoveryPath, block) } return nil } /// Given a permission denied error, extract and return the reset closure. public func deleteRealmUserInfo() -> (() -> Void)? { return _nsError.__rlmSync_deleteRealmBlock() } } /** A `SyncConfiguration` represents configuration parameters for Realms intended to sync with a Realm Object Server. */ public struct SyncConfiguration { /// The `SyncUser` who owns the Realm that this configuration should open. public let user: SyncUser /** The URL of the Realm on the Realm Object Server that this configuration should open. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. */ public let realmURL: URL /** A policy that determines what should happen when all references to Realms opened by this configuration go out of scope. */ internal let stopPolicy: RLMSyncStopPolicy /** Whether the SSL certificate of the Realm Object Server should be validated. */ public let enableSSLValidation: Bool internal init(config: RLMSyncConfiguration) { self.user = config.user self.realmURL = config.realmURL self.stopPolicy = config.stopPolicy self.enableSSLValidation = config.enableSSLValidation } func asConfig() -> RLMSyncConfiguration { let config = RLMSyncConfiguration(user: user, realmURL: realmURL) config.stopPolicy = stopPolicy config.enableSSLValidation = enableSSLValidation return config } /** Initialize a sync configuration with a user and a Realm URL. Additional settings can be optionally specified. Descriptions of these settings follow. `enableSSLValidation` is true by default. It can be disabled for debugging purposes. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. - warning: NEVER disable SSL validation for a system running in production. */ public init(user: SyncUser, realmURL: URL, enableSSLValidation: Bool = true) { self.user = user self.realmURL = realmURL self.stopPolicy = .afterChangesUploaded self.enableSSLValidation = enableSSLValidation } } /// A `SyncCredentials` represents data that uniquely identifies a Realm Object Server user. public struct SyncCredentials { public typealias Token = String internal var token: Token internal var provider: Provider internal var userInfo: [String: Any] /** Initialize new credentials using a custom token, authentication provider, and user information dictionary. In most cases, the convenience initializers should be used instead. */ public init(customToken token: Token, provider: Provider, userInfo: [String: Any] = [:]) { self.token = token self.provider = provider self.userInfo = userInfo } internal init(_ credentials: RLMSyncCredentials) { self.token = credentials.token self.provider = credentials.provider self.userInfo = credentials.userInfo } /// Initialize new credentials using a Facebook account token. public static func facebook(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(facebookToken: token)) } /// Initialize new credentials using a Google account token. public static func google(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(googleToken: token)) } /// Initialize new credentials using a CloudKit account token. public static func cloudKit(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(cloudKitToken: token)) } /// Initialize new credentials using a Realm Object Server username and password. public static func usernamePassword(username: String, password: String, register: Bool = false) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(username: username, password: password, register: register)) } /// Initialize new credentials using a Realm Object Server access token. public static func accessToken(_ accessToken: String, identity: String) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(accessToken: accessToken, identity: identity)) } } extension RLMSyncCredentials { internal convenience init(_ credentials: SyncCredentials) { self.init(customToken: credentials.token, provider: credentials.provider, userInfo: credentials.userInfo) } } extension SyncUser { /** Given credentials and a server URL, log in a user and asynchronously return a `SyncUser` object which can be used to open `Realm`s and retrieve `SyncSession`s. */ public static func logIn(with credentials: SyncCredentials, server authServerURL: URL, timeout: TimeInterval = 30, onCompletion completion: @escaping UserCompletionBlock) { return SyncUser.__logIn(with: RLMSyncCredentials(credentials), authServerURL: authServerURL, timeout: timeout, onCompletion: completion) } /// A dictionary of all valid, logged-in user identities corresponding to their `SyncUser` objects. public static var all: [String: SyncUser] { return __allUsers() } /** The logged-in user. `nil` if none exists. Only use this property if your application expects no more than one logged-in user at any given time. - warning: Throws an Objective-C exception if more than one logged-in user exists. */ public static var current: SyncUser? { return __current() } /** Returns an instance of the Management Realm owned by the user. This Realm can be used to control access permissions for Realms managed by the user. This includes granting other users access to Realms. */ public func managementRealm() throws -> Realm { var config = Realm.Configuration.fromRLMRealmConfiguration(.managementConfiguration(for: self)) guard let permissionChangeClass = NSClassFromString("RealmSwift.SyncPermissionChange") as? Object.Type else { fatalError("Internal error: could not build `SyncPermissionChange` metaclass from string.") } config.objectTypes = [permissionChangeClass, SyncPermissionOffer.self, SyncPermissionOfferResponse.self] return try Realm(configuration: config) } /** Returns an instance of the Permission Realm owned by the user. This read-only Realm contains `SyncPermission` objects reflecting the synchronized Realms and permission details this user has access to. */ @available(*, deprecated, message: "Use SyncUser.retrievePermissions()") public func permissionRealm() throws -> Realm { var config = Realm.Configuration.fromRLMRealmConfiguration(.permissionConfiguration(for: self)) config.objectTypes = [SyncPermission.self] return try Realm(configuration: config) } } /** A value which represents a permission granted to a user to interact with a Realm. These values are passed into APIs on `SyncUser`, and returned from `SyncPermissionResults`. - see: `RLMSyncPermissionValue` */ public typealias SyncPermissionValue = RLMSyncPermissionValue /** An enumeration describing possible access levels. - see: `RLMSyncAccessLevel` */ public typealias SyncAccessLevel = RLMSyncAccessLevel /** A collection of `SyncPermissionValue`s that represent the permissions that have been configured on all the Realms that some user is allowed to administer. - see: `RLMSyncPermissionResults` */ public typealias SyncPermissionResults = RLMSyncPermissionResults #if swift(>=3.1) extension SyncPermissionResults: RandomAccessCollection { public subscript(index: Int) -> SyncPermissionValue { return object(at: index) } public func index(after i: Int) -> Int { return i + 1 } public var startIndex: Int { return 0 } public var endIndex: Int { return count } } #else extension SyncPermissionResults { /// Return the first permission value in the results, or `nil` if /// the results are empty. public var first: SyncPermissionValue? { return count > 0 ? object(at: 0) : nil } /// Return the last permission value in the results, or `nil` if /// the results are empty. public var last: SyncPermissionValue? { return count > 0 ? object(at: count - 1) : nil } } extension SyncPermissionResults: Sequence { public struct Iterator: IteratorProtocol { private let iteratorBase: NSFastEnumerationIterator fileprivate init(results: SyncPermissionResults) { iteratorBase = NSFastEnumerationIterator(results) } public func next() -> SyncPermissionValue? { return iteratorBase.next() as! SyncPermissionValue? } } public func makeIterator() -> SyncPermissionResults.Iterator { return Iterator(results: self) } } #endif /** This model is used to reflect permissions. It should be used in conjunction with a `SyncUser`'s Permission Realm. You can only read this Realm. Use the objects in Management Realm to make request for modifications of permissions. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ @available(*, deprecated, message: "Use `SyncPermissionValue`") public final class SyncPermission: Object { /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The ID of the affected user by the permission. @objc public dynamic var userId = "" /// The path to the realm. @objc public dynamic var path = "" /// Whether the affected user is allowed to read from the Realm. @objc public dynamic var mayRead = false /// Whether the affected user is allowed to write to the Realm. @objc public dynamic var mayWrite = false /// Whether the affected user is allowed to manage the access rights for others. @objc public dynamic var mayManage = false /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "Permission" } } /** This model is used for requesting changes to a Realm's permissions. It should be used in conjunction with a `SyncUser`'s Management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ @available(*, deprecated, message: "Use `SyncUser.applyPermission()` and `SyncUser.revokePermission()`") public final class SyncPermissionChange: Object { /// The globally unique ID string of this permission change object. @objc public dynamic var id = UUID().uuidString /// The date this object was initially created. @objc public dynamic var createdAt = Date() /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. @objc public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { return SyncManagementObjectStatus(statusCode: statusCode) } /// The remote URL to the realm. @objc public dynamic var realmUrl = "*" /// The identity of a user affected by this permission change. @objc public dynamic var userId = "*" /// Define read access. Set to `true` or `false` to update this value. Leave unset /// to preserve the existing setting. public let mayRead = RealmOptional<Bool>() /// Define write access. Set to `true` or `false` to update this value. Leave unset /// to preserve the existing setting. public let mayWrite = RealmOptional<Bool>() /// Define management access. Set to `true` or `false` to update this value. Leave /// unset to preserve the existing setting. public let mayManage = RealmOptional<Bool>() /** Construct a permission change object used to change the access permissions for a user on a Realm. - parameter realmURL: The Realm URL whose permissions settings should be changed. Use `*` to change the permissions of all Realms managed by the Management Realm's `SyncUser`. - parameter userID: The user or users who should be granted these permission changes. Use `*` to change the permissions for all users. - parameter mayRead: Define read access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayWrite: Define write access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayManage: Define management access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. */ public convenience init(realmURL: String, userID: String, mayRead: Bool?, mayWrite: Bool?, mayManage: Bool?) { self.init() self.realmUrl = realmURL self.userId = userID self.mayRead.value = mayRead self.mayWrite.value = mayWrite self.mayManage.value = mayManage } /// :nodoc: override public class func primaryKey() -> String? { return "id" } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionChange" } } /** This model is used for offering permission changes to other users. It should be used in conjunction with a `SyncUser`'s Management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ public final class SyncPermissionOffer: Object { /// The globally unique ID string of this permission offer object. @objc public dynamic var id = UUID().uuidString /// The date this object was initially created. @objc public dynamic var createdAt = Date() /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. @objc public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { return SyncManagementObjectStatus(statusCode: statusCode) } /// A token which uniquely identifies this offer. Generated by the server. @objc public dynamic var token: String? /// The remote URL to the realm. @objc public dynamic var realmUrl = "" /// Whether this offer allows the receiver to read from the Realm. @objc public dynamic var mayRead = false /// Whether this offer allows the receiver to write to the Realm. @objc public dynamic var mayWrite = false /// Whether this offer allows the receiver to manage the access rights for others. @objc public dynamic var mayManage = false /// When this token will expire and become invalid. @objc public dynamic var expiresAt: Date? /** Construct a permission offer object used to offer permission changes to other users. - parameter realmURL: The URL to the Realm on which to apply these permission changes to, once the offer is accepted. - parameter expiresAt: When this token will expire and become invalid. Pass `nil` if this offer should not expire. - parameter mayRead: Grant or revoke read access. - parameter mayWrite: Grant or revoked read-write access. - parameter mayManage: Grant or revoke administrative access. */ public convenience init(realmURL: String, expiresAt: Date?, mayRead: Bool, mayWrite: Bool, mayManage: Bool) { self.init() self.realmUrl = realmURL self.expiresAt = expiresAt self.mayRead = mayRead self.mayWrite = mayWrite self.mayManage = mayManage } /// :nodoc: override public class func indexedProperties() -> [String] { return ["token"] } /// :nodoc: override public class func primaryKey() -> String? { return "id" } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionOffer" } } /** This model is used to apply permission changes defined in the permission offer object represented by the specified token, which was created by another user's `SyncPermissionOffer` object. It should be used in conjunction with a `SyncUser`'s Management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ public final class SyncPermissionOfferResponse: Object { /// The globally unique ID string of this permission offer response object. @objc public dynamic var id = UUID().uuidString /// The date this object was initially created. @objc public dynamic var createdAt = Date() /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. @objc public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { return SyncManagementObjectStatus(statusCode: statusCode) } /// The received token which uniquely identifies another user's `SyncPermissionOffer`. @objc public dynamic var token = "" /// The remote URL to the realm on which these permission changes were applied. @objc public dynamic var realmUrl: String? /** Construct a permission offer response object used to apply permission changes defined in the permission offer object represented by the specified token, which was created by another user's `SyncPermissionOffer` object. - parameter token: The received token which uniquely identifies another user's `SyncPermissionOffer`. */ public convenience init(token: String) { self.init() self.token = token } /// :nodoc: override public class func primaryKey() -> String? { return "id" } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionOfferResponse" } } fileprivate extension SyncManagementObjectStatus { fileprivate init(statusCode: RealmOptional<Int>) { guard let statusCode = statusCode.value else { self = .notProcessed return } if statusCode == 0 { self = .success } else { self = .error } } } public extension SyncSession { /** The transfer direction (upload or download) tracked by a given progress notification block. Progress notification blocks can be registered on sessions if your app wishes to be informed how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. */ public enum ProgressDirection { /// For monitoring upload progress. case upload /// For monitoring download progress. case download } /** The desired behavior of a progress notification block. Progress notification blocks can be registered on sessions if your app wishes to be informed how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. */ public enum ProgressMode { /** The block will be called forever, or until it is unregistered by calling `ProgressNotificationToken.stop()`. Notifications will always report the latest number of transferred bytes, and the most up-to-date number of total transferrable bytes. */ case reportIndefinitely /** The block will, upon registration, store the total number of bytes to be transferred. When invoked, it will always report the most up-to-date number of transferrable bytes out of that original number of transferrable bytes. When the number of transferred bytes reaches or exceeds the number of transferrable bytes, the block will be unregistered. */ case forCurrentlyOutstandingWork } /** A token corresponding to a progress notification block. Call `stop()` on the token to stop notifications. If the notification block has already been automatically stopped, calling `stop()` does nothing. `stop()` should be called before the token is destroyed. */ public typealias ProgressNotificationToken = RLMProgressNotificationToken /** A struct encapsulating progress information, as well as useful helper methods. */ public struct Progress { /// The number of bytes that have been transferred. public let transferredBytes: Int /** The total number of transferrable bytes (bytes that have been transferred, plus bytes pending transfer). If the notification block is tracking downloads, this number represents the size of the changesets generated by all other clients using the Realm. If the notification block is tracking uploads, this number represents the size of the changesets representing the local changes on this client. */ public let transferrableBytes: Int /// The fraction of bytes transferred out of all transferrable bytes. If this value is 1, /// no bytes are waiting to be transferred (either all bytes have already been transferred, /// or there are no bytes to be transferred in the first place). public var fractionTransferred: Double { if transferrableBytes == 0 { return 1 } let percentage = Double(transferredBytes) / Double(transferrableBytes) return percentage > 1 ? 1 : percentage } /// Whether all pending bytes have already been transferred. public var isTransferComplete: Bool { return transferredBytes >= transferrableBytes } fileprivate init(transferred: UInt, transferrable: UInt) { transferredBytes = Int(transferred) transferrableBytes = Int(transferrable) } } /** Register a progress notification block. If the session has already received progress information from the synchronization subsystem, the block will be called immediately. Otherwise, it will be called as soon as progress information becomes available. Multiple blocks can be registered with the same session at once. Each block will be invoked on a side queue devoted to progress notifications. The token returned by this method must be retained as long as progress notifications are desired, and the `stop()` method should be called on it when notifications are no longer needed and before the token is destroyed. If no token is returned, the notification block will never be called again. There are a number of reasons this might be true. If the session has previously experienced a fatal error it will not accept progress notification blocks. If the block was configured in the `forCurrentlyOutstandingWork` mode but there is no additional progress to report (for example, the number of transferrable bytes and transferred bytes are equal), the block will not be called again. - parameter direction: The transfer direction (upload or download) to track in this progress notification block. - parameter mode: The desired behavior of this progress notification block. - parameter block: The block to invoke when notifications are available. - returns: A token which must be held for as long as you want notifications to be delivered. - see: `ProgressDirection`, `Progress`, `ProgressNotificationToken` */ public func addProgressNotification(for direction: ProgressDirection, mode: ProgressMode, block: @escaping (Progress) -> Void) -> ProgressNotificationToken? { return __addProgressNotification(for: (direction == .upload ? .upload : .download), mode: (mode == .reportIndefinitely ? .reportIndefinitely : .forCurrentlyOutstandingWork)) { transferred, transferrable in block(Progress(transferred: transferred, transferrable: transferrable)) } } }
mit
hollance/swift-algorithm-club
Bucket Sort/BucketSort.playground/Contents.swift
3
1732
// // BucketSort.playground // // Created by Barbara Rodeker on 4/4/16. // // 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. // // ////////////////////////////////////// // MARK: Extensions ////////////////////////////////////// extension Int: IntConvertible, Sortable { public func toInt() -> Int { return self } } ////////////////////////////////////// // MARK: Playing code ////////////////////////////////////// let input = [1, 2, 4, 6, 10, 5] var buckets = [Bucket<Int>(capacity: 15), Bucket<Int>(capacity: 15), Bucket<Int>(capacity: 15)] let sortedElements = bucketSort(input, distributor: RangeDistributor(), sorter: InsertionSorter(), buckets: buckets) print(sortedElements)
mit
manavgabhawala/swift
test/SILGen/retaining_globals.swift
2
2824
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/globals.h -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop // This test makes sure loading from globals properly retains/releases loads from globals. // NSString was the only real problem, as the compiler treats NSString globals specially. // The rest of these are just hedges against future changes. // From header: // globalString: __strong NSString* // globalObject: __strong NSObject* // globalID: __strong id // globalArray: __strong NSArray* // globalConstArray: __strong NSArray *const func main() { Globals.sharedInstance() // Initialize globals (dispatch_once) // CHECK: global_addr @globalConstArray : $*Optional<NSArray> // CHECK: global_addr @globalArray : $*Optional<NSArray> // CHECK: global_addr @globalId : $*Optional<AnyObject> // CHECK: global_addr @globalObject : $*Optional<NSObject> // CHECK: global_addr @globalString : $*NSString // CHECK: [[globalString:%.*]] = load [copy] {{%.*}} : $*NSString // CHECK: [[bridgeStringFunc:%.*]] = function_ref @{{.*}} : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: [[wrappedString:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[globalString]] : $NSString // CHECK: [[stringMetaType:%.*]] = metatype $@thin String.Type // CHECK: [[bridgedString:%.*]] = apply [[bridgeStringFunc]]([[wrappedString]], [[stringMetaType]]) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String let string = globalString // Problematic case, wasn't being retained // CHECK: [[load_1:%.*]] = load [copy] {{%.*}} : $*Optional<NSObject> let object = globalObject // CHECK: [[load_2:%.*]] = load [copy] {{%.*}} : $*Optional<AnyObject> let id = globalId // CHECK: [[load_3:%.*]] = load [copy] {{%.*}} : $*Optional<NSArray> let arr = globalArray // CHECK: [[load_4:%.*]] = load [copy] {{%.*}} : $*Optional<NSArray> let constArr = globalConstArray // Make sure there's no more copies // CHECK-NOT: load [copy] print(string as Any) print(object as Any) print(id as Any) print(arr as Any) print(constArr as Any) // CHECK: [[PRINT_FUN:%.*]] = function_ref @_TFs5printFTGSaP{{.*}} : $@convention(thin) (@owned Array<Any>, @owned String, @owned String) -> () // CHECK: apply [[PRINT_FUN]]({{.*}}) // CHECK: destroy_value [[load_4]] // CHECK: destroy_value [[load_3]] // CHECK: destroy_value [[load_2]] // CHECK: destroy_value [[load_1]] // CHECK: destroy_value [[bridgedString]] // Make sure there's no more destroys // CHECK-NOT: destroy_value // CHECK: } // end sil function '_TF17retaining_globals4mainFT_T_' } main() main() // Used to crash here, due to use-after-free. main() main() main() main()
apache-2.0
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/UIScrollViewSpec.swift
5
3876
import ReactiveSwift import ReactiveCocoa import UIKit import Quick import Nimble import enum Result.NoError private final class UIScrollViewDelegateForZooming: NSObject, UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return scrollView.subviews.first! } } class UIScrollViewSpec: QuickSpec { override func spec() { var scrollView: UIScrollView! weak var _scrollView: UIScrollView? beforeEach { scrollView = UIScrollView(frame: .zero) _scrollView = scrollView } afterEach { scrollView = nil expect(_scrollView).to(beNil()) } it("should accept changes from bindings to its content inset value") { scrollView.contentInset = .zero let (pipeSignal, observer) = Signal<UIEdgeInsets, NoError>.pipe() scrollView.reactive.contentInset <~ SignalProducer(pipeSignal) observer.send(value: UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)) expect(scrollView.contentInset) == UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4) observer.send(value: .zero) expect(scrollView.contentInset) == UIEdgeInsets.zero } it("should accept changes from bindings to its scroll indicator insets value") { scrollView.scrollIndicatorInsets = .zero let (pipeSignal, observer) = Signal<UIEdgeInsets, NoError>.pipe() scrollView.reactive.scrollIndicatorInsets <~ SignalProducer(pipeSignal) observer.send(value: UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)) expect(scrollView.scrollIndicatorInsets) == UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4) observer.send(value: .zero) expect(scrollView.scrollIndicatorInsets) == UIEdgeInsets.zero } it("should accept changes from bindings to its scroll enabled state") { scrollView.isScrollEnabled = true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() scrollView.reactive.isScrollEnabled <~ SignalProducer(pipeSignal) observer.send(value: true) expect(scrollView.isScrollEnabled) == true observer.send(value: false) expect(scrollView.isScrollEnabled) == false } it("should accept changes from bindings to its zoom scale value") { let contentView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) scrollView.addSubview(contentView) let delegate = UIScrollViewDelegateForZooming() scrollView.delegate = delegate scrollView.minimumZoomScale = 1 scrollView.maximumZoomScale = 5 scrollView.zoomScale = 1 let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe() scrollView.reactive.zoomScale <~ SignalProducer(pipeSignal) observer.send(value: 3) expect(scrollView.zoomScale) == 3 observer.send(value: 1) expect(scrollView.zoomScale) == 1 } it("should accept changes from bindings to its minimum zoom scale value") { scrollView.minimumZoomScale = 0 let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe() scrollView.reactive.minimumZoomScale <~ SignalProducer(pipeSignal) observer.send(value: 42) expect(scrollView.minimumZoomScale) == 42 observer.send(value: 0) expect(scrollView.minimumZoomScale) == 0 } it("should accept changes from bindings to its maximum zoom scale value") { scrollView.maximumZoomScale = 0 let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe() scrollView.reactive.maximumZoomScale <~ SignalProducer(pipeSignal) observer.send(value: 42) expect(scrollView.maximumZoomScale) == 42 observer.send(value: 0) expect(scrollView.maximumZoomScale) == 0 } it("should accept changes from bindings to its scrolls to top state") { scrollView.scrollsToTop = true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() scrollView.reactive.scrollsToTop <~ SignalProducer(pipeSignal) observer.send(value: true) expect(scrollView.scrollsToTop) == true observer.send(value: false) expect(scrollView.scrollsToTop) == false } } }
gpl-3.0
ben-ng/swift
validation-test/compiler_crashers_fixed/27592-swift-genericparamlist-addnestedarchetypes.swift
1
500
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck if true{}{struct A{struct S<T where g:a{class A{struct Q<h{{}enum A{enum b{var _=B<T struct B class B
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/07368-swift-sourcemanager-getmessage.swift
11
311
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b: A { class A { var d { switch x } protocol A : NSObject { } } class A { } enum S<T where g: T: f.c { var f = A? { class case c, struct
mit
cnoon/swift-compiler-crashes
crashes-duplicates/07679-swift-sourcemanager-getmessage.swift
11
240
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { protocol A { class d { extension A { var f = { { class case ,
mit
ConradoMateu/GOT-Challenge-Swift
GOT-Challenge-Swift/Modules/Details/Presenter/DetailsPresenter.swift
1
498
// // DetailsPresenter.swift // GOT-Challenge-Swift // // Created by Conrado Mateu Gisbert on 19/04/17. // Copyright © 2017 conradomateu. All rights reserved. // import Foundation class DetailsPresenter: DetailsPresentation { open var view: DetailsView? var character: Character! init(view: DetailsView, character: Character) { self.view = view self.character = character } func viewDidLoad() { view?.showDetails(forCharacter: character) } }
apache-2.0
aroyarexs/PASTA
Tests/PASTAViewTests.swift
1
1871
// // Created by Aaron Krämer on 23.08.17. // Copyright (c) 2017 Aaron Krämer. All rights reserved. // import Quick import Nimble @testable import PASTA class PASTAViewTests: QuickSpec { override func spec() { describe("a PASTA view") { let view = PASTAView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) context("hit by a point") { let subviewCountBeforeHitTest = view.subviews.count let point = CGPoint(x: 10, y: 10) let hitTestView = view.hitTest(point, with: nil) it("returns a view") { expect(hitTestView).toNot(beNil()) } it("has additional subview") { expect(view.subviews.count).to(equal(subviewCountBeforeHitTest+1)) } guard let marker = hitTestView as? PASTAMarker else { it("is a marker") { expect(hitTestView?.isKind(of: PASTAMarker.classForKeyedUnarchiver())).to(beTruthy()) } return } context("a second time at same position") { marker.radius = 10 let resultView = view.hitTest(point, with: nil) it("also returns a view") { expect(resultView).toNot(beNil()) expect(resultView?.isKind(of: PASTAMarker.classForKeyedUnarchiver())).to(beTruthy()) } it("equals previous view") { expect(resultView == marker).to(beTrue()) } it("has no additional subview") { expect(view.subviews.count).to(equal(subviewCountBeforeHitTest+1)) } } } } } }
mit
son11592/STKeyboard
Example/Tests/Tests.swift
1
760
import UIKit import XCTest import STKeyboard 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
rringham/swift-promises
promises/AppDelegate.swift
1
3231
// // AppDelegate.swift // promises // // Created by Rob Ringham on 6/7/14. // Copyright (c) 2014, Rob Ringham // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> 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
leizh007/HiPDA
HiPDA/HiPDA/General/Categories/String+Emoji.swift
1
3101
// // String+Emoji.swift // HiPDA // // Created by leizh007 on 2017/6/15. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation // https://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji extension UnicodeScalar { var isEmoji: Bool { switch value { case 0x1F600...0x1F64F, // Emoticons 0x1F300...0x1F5FF, // Misc Symbols and Pictographs 0x1F680...0x1F6FF, // Transport and Map 0x2600...0x26FF, // Misc symbols 0x2700...0x27BF, // Dingbats 0xFE00...0xFE0F, // Variation Selectors 0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs 65024...65039, // Variation selector 8400...8447: // Combining Diacritical Marks for Symbols return true default: return false } } var isZeroWidthJoiner: Bool { return value == 8205 } } extension String { var glyphCount: Int { let richText = NSAttributedString(string: self) let line = CTLineCreateWithAttributedString(richText) return CTLineGetGlyphCount(line) } var isSingleEmoji: Bool { return glyphCount == 1 && containsEmoji } var containsEmoji: Bool { return unicodeScalars.contains { $0.isEmoji } } var containsOnlyEmoji: Bool { return !isEmpty && !unicodeScalars.contains(where: { !$0.isEmoji && !$0.isZeroWidthJoiner }) } // The next tricks are mostly to demonstrate how tricky it can be to determine emoji's // If anyone has suggestions how to improve this, please let me know var emojiString: String { return emojiScalars.map { String($0) }.reduce("", +) } var emojis: [String] { var scalars: [[UnicodeScalar]] = [] var currentScalarSet: [UnicodeScalar] = [] var previousScalar: UnicodeScalar? for scalar in emojiScalars { if let prev = previousScalar, !prev.isZeroWidthJoiner && !scalar.isZeroWidthJoiner { scalars.append(currentScalarSet) currentScalarSet = [] } currentScalarSet.append(scalar) previousScalar = scalar } scalars.append(currentScalarSet) return scalars.map { $0.map{ String($0) } .reduce("", +) } } fileprivate var emojiScalars: [UnicodeScalar] { var chars: [UnicodeScalar] = [] var previous: UnicodeScalar? for cur in unicodeScalars { if let previous = previous, previous.isZeroWidthJoiner && cur.isEmoji { chars.append(previous) chars.append(cur) } else if cur.isEmoji { chars.append(cur) } previous = cur } return chars } }
mit
davejlin/treehouse
swift/swift3/RestaurantReviews/RestaurantReviews/YelpSearchController.swift
1
7349
// // YelpSearchController.swift // RestaurantReviews // // Created by Pasan Premaratne on 5/9/17. // Copyright © 2017 Treehouse. All rights reserved. // import UIKit import MapKit class YelpSearchController: UIViewController { // MARK: - Properties let searchController = UISearchController(searchResultsController: nil) @IBOutlet weak var tableView: UITableView! @IBOutlet weak var mapView: MKMapView! let dataSource = YelpSearchResultsDataSource() lazy var locationManager: LocationManager = { return LocationManager(delegate: self, permissionsDelegate: nil) }() lazy var client: YelpClient = { let yelpAccount = YelpAccount.loadFromKeychain() let oauthToken = yelpAccount!.accessToken return YelpClient(oauthToken: oauthToken) }() var coordinate: Coordinate? { didSet { if let coordinate = coordinate { showNearbyRestaurants(at: coordinate) } } } let queue = OperationQueue() var isAuthorized: Bool { let isAuthorizedWithYelpToken = YelpAccount.isAuthorized let isAuthorizedForLocation = LocationManager.isAuthorized return isAuthorizedWithYelpToken && isAuthorizedForLocation } override func viewDidLoad() { super.viewDidLoad() setupSearchBar() setupTableView() } override func viewDidAppear(_ animated: Bool) { if isAuthorized { locationManager.requestLocation() } else { checkPermissions() } } // MARK: - Table View func setupTableView() { self.tableView.dataSource = dataSource self.tableView.delegate = self } func showNearbyRestaurants(at coordinate: Coordinate) { client.search(withTerm: "", at: coordinate) { [weak self] result in switch result { case .success(let businesses): self?.dataSource.update(with: businesses) self?.tableView.reloadData() let annotations: [MKPointAnnotation] = businesses.map { business in let point = MKPointAnnotation() point.coordinate = CLLocationCoordinate2D(latitude: business.location.latitude, longitude: business.location.longitude) point.title = business.name point.subtitle = business.isClosed ? "Closed" : "Open" return point } self?.mapView.addAnnotations(annotations) case .failure(let error): print(error) } } } // MARK: - Search func setupSearchBar() { self.navigationItem.titleView = searchController.searchBar searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchResultsUpdater = self } // MARK: - Permissions /// Checks (1) if the user is authenticated against the Yelp API and has an OAuth /// token and (2) if the user has authorized location access for whenInUse tracking. func checkPermissions() { let isAuthorizedWithToken = YelpAccount.isAuthorized let isAuthorizedForLocation = LocationManager.isAuthorized let permissionsController = PermissionsController(isAuthorizedForLocation: isAuthorizedForLocation, isAuthorizedWithToken: isAuthorizedWithToken) present(permissionsController, animated: true, completion: nil) } } // MARK: - UITableViewDelegate extension YelpSearchController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let business = dataSource.object(at: indexPath) let detailsOperation = YelpBusinessDetailsOperation(business: business, client: self.client) let reviewsOperation = YelpBusinessReviewsOperation(business: business, client: client) reviewsOperation.addDependency(detailsOperation) reviewsOperation.completionBlock = { DispatchQueue.main.async { self.dataSource.update(business, at: indexPath) self.performSegue(withIdentifier: "showBusiness", sender: nil) } } queue.addOperation(detailsOperation) queue.addOperation(reviewsOperation) } } // MARK: - Search Results extension YelpSearchController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard let searchTerm = searchController.searchBar.text, let coordinate = coordinate else { return } if !searchTerm.isEmpty { client.search(withTerm: searchTerm, at: coordinate) { [weak self] result in switch result { case .success(let businesses): self?.dataSource.update(with: businesses) self?.tableView.reloadData() self?.mapView.removeAnnotations(self!.mapView.annotations) let annotations: [MKPointAnnotation] = businesses.map { business in let point = MKPointAnnotation() point.coordinate = CLLocationCoordinate2D(latitude: business.location.latitude, longitude: business.location.longitude) point.title = business.name point.subtitle = business.isClosed ? "Closed" : "Open" return point } self?.mapView.addAnnotations(annotations) case .failure(let error): print(error) } } } } } // MARK: - Navigation extension YelpSearchController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showBusiness" { if let indexPath = tableView.indexPathForSelectedRow { let business = dataSource.object(at: indexPath) let detailController = segue.destination as! YelpBusinessDetailController detailController.business = business detailController.dataSource.updateData(business.reviews) } } } } // MARK: - Location Manager Delegate extension YelpSearchController: LocationManagerDelegate { func obtainedCoordinates(_ coordinate: Coordinate) { self.coordinate = coordinate adjustMap(with: coordinate) } func failedWithError(_ error: LocationError) { print(error) } } // MARK: - MapKit extension YelpSearchController { func adjustMap(with coordinate: Coordinate) { let coordinate2D = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude) let span = MKCoordinateRegionMakeWithDistance(coordinate2D, 2500, 2500).span let region = MKCoordinateRegion(center: coordinate2D, span: span) mapView.setRegion(region, animated: true) } }
unlicense
gottsohn/ios-swift-boiler
IOSSwiftBoilerTests/WebViewControllerTests.swift
1
2422
// // WebViewControllerTests.swift // IOSSwiftBoiler // // Created by Godson Ukpere on 3/17/16. // Copyright © 2016 Godson Ukpere. All rights reserved. // import XCTest @testable import IOSSwiftBoiler class WebViewControllerTests: XCTestCase { var webViewController:WebViewController! var timer:NSTimer! var asyncExpectation:XCTestExpectation! override func setUp() { super.setUp() webViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(Const.ID_WEB_VIEW_CONTROLLER) as! WebViewController } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. webViewController = nil super.tearDown() } func testViews() { XCTAssertNil(webViewController.webView) XCTAssertNil(webViewController.progressView) _ = webViewController.view XCTAssertNotNil(webViewController.webView) XCTAssertNotNil(webViewController.progressView) } func testWebViewNoLoad() { XCTAssertNil(webViewController.url) XCTAssertNil(webViewController.labelText) _ = webViewController.view XCTAssertEqual(webViewController.progressView.progress, 0.0) } func testWebViewLoad() { asyncExpectation = expectationWithDescription("server responded") XCTAssertNil(webViewController.url) XCTAssertNil(webViewController.labelText) webViewController.url = "http://blog.godson.com.ng" _ = webViewController.view timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(WebViewControllerTests.checkProgress), userInfo: nil, repeats: false) waitForExpectationsWithTimeout(15, handler: nil) } func checkProgress() { XCTAssertNotNil(webViewController.progressView) XCTAssert(webViewController.progressView.hidden, "Progress View should be hidden") XCTAssertEqual(webViewController.progressView.progress, 1.0) timer.invalidate() asyncExpectation.fulfill() } 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
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/MainListViewController.swift
1
5475
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class MainListViewController: UITableViewController { var footerHeight : CGFloat = 200.0 var tableData : [(name:String, cell:UITableViewCell.Type, controller:UIViewController.Type)] { return [("DemoCell", DemoCell.self, DemoViewController.self), ("LibraryCell", LibraryCell.self, LibraryListViewController.self), ("AboutCell", AboutCell.self, UIViewController.self)] } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func viewDidLoad() { for item in self.tableData { self.tableView.register(item.cell, forCellReuseIdentifier: item.name) } self.view.backgroundColor = UIColor.sldsBackgroundColor(.colorBackgroundRowSelected) self.tableView.separatorStyle = .none self.navigationController?.navigationBar.isTranslucent = false self.navigationController?.navigationBar.tintColor = UIColor.sldsTextColor(.colorTextButtonBrand) self.navigationController?.navigationBar.barTintColor = UIColor.sldsFill(.brandActive) self.navigationController?.navigationBar.backIndicatorImage = UIImage.sldsUtilityIcon(.chevronleft, withSize:SLDSSquareIconUtilityMedium) self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage.sldsUtilityIcon(.chevronleft, withSize: SLDSSquareIconUtilityMedium).withAlignmentRectInsets(UIEdgeInsetsMake(0, 0, -1, 0)) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.sldsFont(.regular, with: .medium)] self.title = "Lightning Design System" self.tableView.alwaysBounceVertical = false } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let rowHeight = (self.view.frame.height - tableView.contentInset.top) / CGFloat(tableData.count) if indexPath.row < tableData.count - 1 { return rowHeight + 70 } return rowHeight - 140 } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func numberOfSections(in tableView: UITableView) -> Int { return 1 } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: tableData[indexPath.row].name) return cell! } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if indexPath.row == tableData.count - 1 { return nil } return indexPath } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controllerClass = tableData[indexPath.row].controller let controller = controllerClass.init() self.navigationController?.show(controller, sender: self) } }
bsd-3-clause
kzaher/RxSwift
RxCocoa/macOS/NSTextField+Rx.swift
7
2690
// // NSTextField+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 5/17/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(macOS) import Cocoa import RxSwift /// Delegate proxy for `NSTextField`. /// /// For more information take a look at `DelegateProxyType`. open class RxTextFieldDelegateProxy : DelegateProxy<NSTextField, NSTextFieldDelegate> , DelegateProxyType , NSTextFieldDelegate { /// Typed parent object. public weak private(set) var textField: NSTextField? /// Initializes `RxTextFieldDelegateProxy` /// /// - parameter textField: Parent object for delegate proxy. init(textField: NSTextField) { self.textField = textField super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self) } public static func registerKnownImplementations() { self.register { RxTextFieldDelegateProxy(textField: $0) } } fileprivate let textSubject = PublishSubject<String?>() // MARK: Delegate methods open func controlTextDidChange(_ notification: Notification) { let textField: NSTextField = castOrFatalError(notification.object) let nextValue = textField.stringValue self.textSubject.on(.next(nextValue)) _forwardToDelegate?.controlTextDidChange?(notification) } // MARK: Delegate proxy methods /// For more information take a look at `DelegateProxyType`. open class func currentDelegate(for object: ParentObject) -> NSTextFieldDelegate? { object.delegate } /// For more information take a look at `DelegateProxyType`. open class func setCurrentDelegate(_ delegate: NSTextFieldDelegate?, to object: ParentObject) { object.delegate = delegate } } extension Reactive where Base: NSTextField { /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy<NSTextField, NSTextFieldDelegate> { RxTextFieldDelegateProxy.proxy(for: self.base) } /// Reactive wrapper for `text` property. public var text: ControlProperty<String?> { let delegate = RxTextFieldDelegateProxy.proxy(for: self.base) let source = Observable.deferred { [weak textField = self.base] in delegate.textSubject.startWith(textField?.stringValue) }.take(until: self.deallocated) let observer = Binder(self.base) { (control, value: String?) in control.stringValue = value ?? "" } return ControlProperty(values: source, valueSink: observer.asObserver()) } } #endif
mit
meetkei/KxUI
KxUI/View/Button/KUUnderlineLabelButton.swift
1
1959
// // Copyright (c) 2016 Keun young Kim <app@meetkei.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @IBDesignable open class KUUnderlineLabelButton: UIButton { open override func prepareForInterfaceBuilder() { setupView() } open override func awakeFromNib() { super.awakeFromNib() setupView() } open override func layoutSubviews() { super.layoutSubviews() setupView() } func setupView() { if let _ = title(for: .normal), let label = titleLabel { var frame = label.frame frame.origin.y = frame.maxY frame.size.height = 0.5 let view = UIView(frame: frame) view.backgroundColor = titleColor(for: .normal) view.isUserInteractionEnabled = false addSubview(view) } } }
mit
HongliYu/firefox-ios
UITests/LoginInputTests.swift
1
5243
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import EarlGrey @testable import Client class LoginInputTests: KIFTestCase { fileprivate var webRoot: String! fileprivate var profile: Profile! override func setUp() { super.setUp() profile = (UIApplication.shared.delegate as! AppDelegate).profile! webRoot = SimplePageServer.start() BrowserUtils.configEarlGrey() BrowserUtils.dismissFirstRunUI() } override func tearDown() { _ = profile.logins.wipe().value BrowserUtils.resetToAboutHome() BrowserUtils.clearPrivateData() super.tearDown() } func enterUrl(url: String) { EarlGrey.selectElement(with: grey_accessibilityID("url")).perform(grey_tap()) EarlGrey.selectElement(with: grey_accessibilityID("address")).perform(grey_replaceText(url)) EarlGrey.selectElement(with: grey_accessibilityID("address")).perform(grey_typeText("\n")) } func waitForLoginDialog(text: String, appears: Bool = true) { var success = false var failedReason = "Failed to display dialog" if appears == false { failedReason = "Dialog still displayed" } let saveLoginDialog = GREYCondition(name: "Check login dialog appears", block: { var errorOrNil: NSError? let matcher = grey_allOf([grey_accessibilityLabel(text), grey_sufficientlyVisible()]) EarlGrey.selectElement(with: matcher) .assert(grey_notNil(), error: &errorOrNil) if appears == true { success = errorOrNil == nil } else { success = errorOrNil != nil } return success }).wait(withTimeout: 10) GREYAssertTrue(saveLoginDialog, reason: failedReason) } func testLoginFormDisplaysNewSnackbar() { let url = "\(webRoot!)/loginForm.html" let username = "test@user.com" enterUrl(url: url) tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText("password", intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?") EarlGrey.selectElement(with: grey_accessibilityID("SaveLoginPrompt.dontSaveButton")).perform(grey_tap()) } func testLoginFormDisplaysUpdateSnackbarIfPreviouslySaved() { let url = "\(webRoot!)/loginForm.html" let username = "test@user.com" let password1 = "password1" let password2 = "password2" enterUrl(url: url) tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password1, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?") EarlGrey.selectElement(with: grey_accessibilityID("SaveLoginPrompt.saveLoginButton")) .perform(grey_tap()) tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password2, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") waitForLoginDialog(text: "Update login \(username) for \(self.webRoot!)?") EarlGrey.selectElement(with: grey_accessibilityID("UpdateLoginPrompt.updateButton")) .perform(grey_tap()) } func testLoginFormDoesntOfferSaveWhenEmptyPassword() { let url = "\(webRoot!)/loginForm.html" let username = "test@user.com" enterUrl(url: url) tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText("", intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?", appears: false) } func testLoginFormDoesntOfferUpdateWhenEmptyPassword() { let url = "\(webRoot!)/loginForm.html" let username = "test@user.com" let password1 = "password1" let password2 = "" enterUrl(url: url) tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password1, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?") EarlGrey.selectElement(with: grey_accessibilityID("SaveLoginPrompt.saveLoginButton")) .perform(grey_tap()) tester().enterText(username, intoWebViewInputWithName: "username") tester().enterText(password2, intoWebViewInputWithName: "password") tester().tapWebViewElementWithAccessibilityLabel("submit_btn") waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?", appears: false) } }
mpl-2.0
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/ZKillboardInteractor.swift
2
972
// // ZKillboardInteractor.swift // Neocom // // Created by Artem Shimanski on 11/15/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData class ZKillboardInteractor: TreeInteractor { typealias Presenter = ZKillboardPresenter typealias Content = Void weak var presenter: Presenter? required init(presenter: Presenter) { self.presenter = presenter } var api = Services.api.current func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> { return .init(()) } private var didChangeAccountObserver: NotificationObserver? func configure() { didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in _ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in self?.presenter?.view?.present(presentation, animated: true) } } } }
lgpl-2.1
RedRoma/Lexis
Code/Lexis/WordViewController+Sharing.swift
1
4687
// // WordViewController+Sharing.swift // Lexis // // Created by Wellington Moreno on 9/24/16. // Copyright © 2016 RedRoma, Inc. All rights reserved. // import AromaSwiftClient import Foundation import LexisDatabase import Archeota import UIKit /** Determines the size of the card created and shared. */ private let shareSize = CGSize(width: 500, height: 500) extension WordViewController { var isPhone: Bool { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone } var isPad: Bool { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad } func share(word: LexisWord, in view: UIView, expanded: Bool = true) { LOG.info("Sharing word: \(word)") AromaClient.beginMessage(withTitle: "Sharing Word") .addBody("Word:").addLine() .addBody("\(word)") .withPriority(.medium) .send() guard let shareViewController = self.storyboard?.instantiateViewController(withIdentifier: "SimpleShareViewController") as? SimpleShareViewController else { LOG.warn("Could not instantiate ShareViewController") return } shareViewController.word = word shareViewController.view.frame = CGRect(origin: CGPoint.zero, size: shareSize) shareViewController.view.setNeedsDisplay() shareViewController.view.layoutIfNeeded() guard let image = shareViewController.view.screenshot() else { return } guard let controller = self.createShareController(word: word, andImage: image, expanded: expanded) else { return } if self.isPhone { self.navigationController?.present(controller, animated: true, completion: nil) } else if self.isPad { // Change Rect to position Popover controller.modalPresentationStyle = .popover guard let popover = controller.popoverPresentationController else { return } popover.permittedArrowDirections = .any popover.sourceView = view self.navigationController?.present(controller, animated: true, completion: nil) } } private func createShareController(word: LexisWord, andImage image: UIImage, expanded: Bool) -> UIActivityViewController? { let text: String if expanded { text = word.forms.map() { return $0.capitalizingFirstCharacter() }.joined(separator: ", ") } else { text = (word.forms.first?.capitalizingFirstCharacter()) ?? "" } // let's add a String and an NSURL let activityViewController = UIActivityViewController( activityItems: [text, image], applicationActivities: nil) activityViewController.completionWithItemsHandler = { (activity, success, items, error) in let activity = activity?.rawValue ?? "" if success { AromaClient.beginMessage(withTitle:"Lexis Shared") .withPriority(.high) .addBody("Word:").addLine() .addBody(word.description).addLine(2) .addBody("To Activity: ").addLine() .addBody("\(activity)") .send() } else if let error = error { AromaClient.beginMessage(withTitle:"Lexis Share Failed") .withPriority(.high) .addBody("Word:").addLine() .addBody(word.description).addLine(3) .addBody("\(error)") .send() } else { AromaClient.beginMessage(withTitle:"Lexis Share Canceled") .withPriority(.low) .addBody("Word:").addLine() .addBody(word.description).addLine(3) .addBody("\(error)") .send() } } return activityViewController } } fileprivate extension UIView { func screenshot() -> UIImage? { UIGraphicsBeginImageContextWithOptions(self.frame.size, self.isOpaque, 0.0) guard let context = UIGraphicsGetCurrentContext() else { return nil } layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
apache-2.0
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Scenes/SignIn/Worker/SignInWorker.swift
1
258
// // SignInWorker.swift // CleanStore // // Created by hoi on 16/6/17. // Copyright (c) 2017 hoi. All rights reserved. // import UIKit class SignInWorker { // MARK: - Business Logic func doSomeWork() { // TODO: Do the work } }
mit
hooman/swift
test/SourceKit/CursorInfo/cursor_some_type.swift
4
3793
public protocol Proto { associatedtype Assoc func method() -> Assoc } public class Base {} public class Derived: Base, Proto { public func method() -> Int {} } public struct S { public func foo<T>(x: T) -> some Base & Proto { return Derived() } } func test(value: S) { let _ = value.foo(x: 12) } // RUN: %sourcekitd-test -req=cursor -pos=13:15 %s -- %s -module-name Test | %FileCheck %s -check-prefix=DECLSITE // DECLSITE: source.lang.swift.decl.function.method.instance (13:15-13:27) // DECLSITE-NEXT: foo(x:) // DECLSITE-NEXT: s:4Test1SV3foo1xQrx_tlF // DECLSITE-NEXT: source.lang.swift // DECLSITE-NEXT: <T> (S) -> (T) -> some Base & Proto // DECLSITE-NEXT: $s1xQrx_tcluD // DECLSITE-NEXT: <Declaration>public func foo&lt;T&gt;(x: <Type usr=[[T_USR:.*]]>T</Type>) -&gt; some <Type usr=[[Base_USR:.*]]>Base</Type> &amp; <Type usr=[[Proto_USR:.*]]>Proto</Type></Declaration> // DECLSITE-NEXT: <decl.function.method.instance><syntaxtype.keyword>public</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>&lt;<decl.generic_type_param usr=[[T_USR]]><decl.generic_type_param.name>T</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr=[[T_USR]]>T</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><syntaxtype.keyword>some</syntaxtype.keyword> <ref.class usr=[[Base_USR]]>Base</ref.class> &amp; <ref.protocol usr=[[Proto_USR]]>Proto</ref.protocol></decl.function.returntype></decl.function.method.instance> // RUN: %sourcekitd-test -req=cursor -pos=13:43 %s -- %s -module-name Test | %FileCheck %s -check-prefix=PROTO_AFTER_SOME // PROTO_AFTER_SOME: source.lang.swift.ref.protocol (1:17-1:22) // PROTO_AFTER_SOME-NEXT: Proto // PROTO_AFTER_SOME-NEXT: s:4Test5ProtoP // PROTO_AFTER_SOME-NEXT: source.lang.swift // PROTO_AFTER_SOME-NEXT: Proto.Protocol // PROTO_AFTER_SOME-NEXT: $s4Test5Proto_pmD // PROTO_AFTER_SOME-NEXT: <Declaration>public protocol Proto</Declaration> // PROTO_AFTER_SOME-NEXT: <decl.protocol><syntaxtype.keyword>public</syntaxtype.keyword> <syntaxtype.keyword>protocol</syntaxtype.keyword> <decl.name>Proto</decl.name></decl.protocol> // RUN: %sourcekitd-test -req=cursor -pos=19:17 %s -- %s -module-name Test | %FileCheck %s -check-prefix=USESITE // USESITE: source.lang.swift.ref.function.method.instance (13:15-13:27) // USESITE-NEXT: foo(x:) // USESITE-NEXT: s:4Test1SV3foo1xQrx_tlF // USESITE-NEXT: source.lang.swift // USESITE-NEXT: <T> (S) -> (T) -> some Base & Proto // USESITE-NEXT: $s1xQrx_tcluD // USESITE-NEXT: <Container>$s4Test1SVD</Container> // USESITE-NEXT: <Declaration>public func foo&lt;T&gt;(x: <Type usr="s:4Test1SV3foo1xQrx_tlFQO1Txmfp">T</Type>) -&gt; some <Type usr=[[Base_USR:.*]]>Base</Type> &amp; <Type usr=[[Proto_USR:.*]]>Proto</Type></Declaration> // USESITE-NEXT: <decl.function.method.instance><syntaxtype.keyword>public</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>&lt;<decl.generic_type_param usr="s:4Test1SV3foo1xQrx_tlFQO1Txmfp"><decl.generic_type_param.name>T</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:4Test1SV3foo1xQrx_tlFQO1Txmfp">T</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><syntaxtype.keyword>some</syntaxtype.keyword> <ref.class usr=[[Base_USR]]>Base</ref.class> &amp; <ref.protocol usr=[[Proto_USR]]>Proto</ref.protocol></decl.function.returntype></decl.function.method.instance>
apache-2.0
swipe-org/swipe
core/SwipePage.swift
2
28798
// // SwipePage.swift // Swipe // // Created by satoshi on 6/3/15. // Copyright (c) 2015 Satoshi Nakajima. All rights reserved. // #if os(OSX) import Cocoa import AVFoundation #else import UIKit import AVFoundation import MediaPlayer #endif extension UIResponder { private weak static var _currentFirstResponder: UIResponder? = nil public class func currentFirstResponder() -> UIResponder? { UIResponder._currentFirstResponder = nil UIApplication.shared.sendAction(#selector(UIResponder.findFirstResponder(sender:)), to: nil, from: nil, for: nil) return UIResponder._currentFirstResponder } @objc internal func findFirstResponder(sender: Any) { UIResponder._currentFirstResponder = self } } private func MyLog(_ text:String, level:Int = 0) { let s_verbosLevel = 0 if level <= s_verbosLevel { print(text) } } protocol SwipePageDelegate: NSObjectProtocol { func dimension(_ page:SwipePage) -> CGSize func scale(_ page:SwipePage) -> CGSize func prototypeWith(_ name:String?) -> [String:Any]? func pageTemplateWith(_ name:String?) -> SwipePageTemplate? func pathWith(_ name:String?) -> Any? #if !os(OSX) // REVIEW func speak(_ utterance:AVSpeechUtterance) func stopSpeaking() #endif func currentPageIndex() -> Int func parseMarkdown(_ markdowns:[String]) -> NSAttributedString func baseURL() -> URL? func voice(_ k:String?) -> [String:Any] func languageIdentifier() -> String? func tapped() } extension Notification.Name { static let SwipePageDidStartPlaying = Notification.Name("SwipePageDidStartPlaying") static let SwipePageDidFinishPlaying = Notification.Name("SwipePageDidFinishPlaying") static let SwipePageShouldStartAutoPlay = Notification.Name("SwipePageShouldStartAutoPlay") static let SwipePageShouldPauseAutoPlay = Notification.Name("SwipePageShouldPauseAutoPlay") } class SwipePage: SwipeView, SwipeElementDelegate { // Debugging static var objectCount = 0 var accessCount = 0 var completionCount = 0 // Public properties let index:Int var pageTemplate:SwipePageTemplate? weak var delegate:SwipePageDelegate! // Public Lazy Properties lazy var fixed:Bool = { let ret = (self.transition != "scroll") //NSLog("SWPage fixed = \(self.transition) \(ret), \(self.index)") return self.transition != "scroll" }() lazy var replace:Bool = { return self.transition == "replace" }() // Private properties private var fSeeking = false private var fEntered = false private var cPlaying = 0 private var cDebug = 0 private var fPausing = false private var offsetPaused:CGFloat? // Private lazy properties // Private properties allocated in loadView (we need to clean up in unloadView) #if !os(OSX) private var utterance:AVSpeechUtterance? #endif private var viewVideo:UIView? // Special layer to host auto-play video layers private var viewAnimation:UIView? private var aniLayer:CALayer? private var audioPlayer:AVAudioPlayer? init(index:Int, info:[String:Any], delegate:SwipePageDelegate) { self.index = index self.delegate = delegate self.pageTemplate = delegate.pageTemplateWith(info["template"] as? String) if self.pageTemplate == nil { self.pageTemplate = delegate.pageTemplateWith(info["scene"] as? String) if self.pageTemplate != nil { MyLog("SwPage DEPRECATED 'scene'; use 'template'") } } super.init(info: SwipeParser.inheritProperties(info, baseObject: pageTemplate?.pageTemplateInfo)) SwipePage.objectCount += 1 } func unloadView() { #if !os(tvOS) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) #endif SwipeTimer.cancelAll() if let view = self.view { MyLog("SWPage unloading @\(index)", level: 2) view.removeFromSuperview() for c in children { if let element = c as? SwipeElement { element.clear() // PARANOIA (extra effort to clean up everything) } } children.removeAll() self.view = nil self.viewVideo = nil self.viewAnimation = nil #if !os(OSX) self.utterance = nil #endif self.audioPlayer = nil } } deinit { MyLog("SWPage deinit \(index) \(accessCount) \(completionCount)", level: 1) if self.autoplay { NotificationCenter.default.post(name: .SwipePageShouldPauseAutoPlay, object: self) } SwipePage.objectCount -= 1 } static func checkMemoryLeak() { //assert(SwipePage.objectCount == 0) if SwipePage.objectCount > 0 { NSLog("SWPage memory leak detected ###") } } // Private lazy properties private lazy var backgroundColor:CGColor = { if let value = self.info["bc"] { return SwipeParser.parseColor(value) } return UIColor.white.cgColor }() private lazy var transition:String = { if let value = self.info["transition"] as? String { return value } return (self.animation == "scroll") ? "replace": "scroll" // default }() private lazy var fps:Int = { if let value = self.info["fps"] as? Int { return value } return 60 // default }() private lazy var animation:String = { if let value = self.info["play"] as? String { return value } if let value = self.info["animation"] as? String { NSLog("SWPage DEPRECATED 'animation'; use 'play'") return value } return "auto" // default }() private lazy var autoplay:Bool = { return self.animation == "auto" || self.animation == "always" }() private lazy var always:Bool = { return self.animation == "always" }() private lazy var scroll:Bool = { return self.animation == "scroll" }() private lazy var vibrate:Bool = { if let value = self.info["vibrate"] as? Bool { return value } return false }() private lazy var duration:CGFloat = { if let value = self.info["duration"] as? CGFloat { return value } return 0.2 }() private lazy var fRepeat:Bool = { if let value = self.info["repeat"] as? Bool { return value } return false }() private lazy var rewind:Bool = { if let value = self.info["rewind"] as? Bool { return value } return false }() func setTimeOffsetWhileDragging(_ offset:CGFloat) { if self.scroll { fEntered = false // stops the element animation CATransaction.begin() CATransaction.setDisableActions(true) assert(self.viewAnimation != nil, "must have self.viewAnimation") assert(self.viewVideo != nil, "must have viewVideo") self.aniLayer?.timeOffset = CFTimeInterval(offset) for c in children { if let element = c as? SwipeElement { element.setTimeOffsetTo(offset) } } CATransaction.commit() } } func willLeave(_ fAdvancing:Bool) { MyLog("SWPage willLeave @\(index) \(fAdvancing)", level: 2) #if !os(OSX) if let _ = self.utterance { delegate.stopSpeaking() prepareUtterance() // recreate a new utterance to avoid reusing itt } #endif } func pause(_ fForceRewind:Bool) { fPausing = true if let player = self.audioPlayer { player.stop() } NotificationCenter.default.post(name: .SwipePageShouldPauseAutoPlay, object: self) // auto rewind if self.rewind || fForceRewind { prepareToPlay() } } func didLeave(_ fGoingBack:Bool) { fEntered = false self.pause(fGoingBack) MyLog("SWPage didLeave @\(index) \(fGoingBack)", level: 2) } func willEnter(_ fForward:Bool) { MyLog("SWPage willEnter @\(index) \(fForward)", level: 2) if self.autoplay && fForward || self.always { prepareToPlay() } if fForward && self.scroll { playAudio() } } private func playAudio() { if let player = audioPlayer { player.currentTime = 0.0 player.play() } #if !os(OSX) if let utterance = self.utterance { delegate.speak(utterance) } if self.vibrate { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } #endif } func didEnter(_ fForward:Bool) { fEntered = true accessCount += 1 if fForward && self.autoplay || self.always || self.fRepeat { autoPlay(false) } else if self.hasRepeatElement() { autoPlay(true) } MyLog("SWPage didEnter @\(index) \(fForward)", level: 2) } func prepare() { if scroll { prepareToPlay(index > self.delegate.currentPageIndex()) } else { if index < self.delegate.currentPageIndex() { prepareToPlay(rewind) } } } private func prepareToPlay(_ fForward:Bool = true) { CATransaction.begin() CATransaction.setDisableActions(true) self.aniLayer?.timeOffset = fForward ? 0.0 : 1.0 for c in children { if let element = c as? SwipeElement { element.setTimeOffsetTo(fForward ? 0.0 : 1.0) } } CATransaction.commit() self.offsetPaused = nil } func play() { // REVIEW: Remove this block once we detect the end of speech if let _ = self.utterance { delegate.stopSpeaking() prepareUtterance() // recreate a new utterance to avoid reusing it } self.autoPlay(false) } private func autoPlay(_ fElementRepeat:Bool) { fPausing = false if !fElementRepeat { playAudio() NotificationCenter.default.post(name: .SwipePageShouldStartAutoPlay, object: self) } assert(self.viewAnimation != nil, "must have self.viewAnimation") assert(self.viewVideo != nil, "must have viewVideo") if let offset = self.offsetPaused { timerTick(offset, fElementRepeat: fElementRepeat) } else { timerTick(0.0, fElementRepeat: fElementRepeat) } self.cDebug += 1 self.cPlaying += 1 self.didStartPlayingInternal() } private func timerTick(_ offset:CGFloat, fElementRepeat:Bool) { var fElementRepeatNext = fElementRepeat // NOTE: We don't want to add [unowned self] because the timer will fire anyway. // During the shutdown sequence, the loop will stop when didLeave was called. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1000 * NSEC_PER_MSEC / UInt64(self.fps))) / Double(NSEC_PER_SEC), execute: { () -> Void in var offsetForNextTick:CGFloat? if self.fEntered && !self.fPausing { var nextOffset = offset + 1.0 / self.duration / CGFloat(self.fps) if nextOffset < 1.0 { offsetForNextTick = nextOffset } else { nextOffset = 1.0 if self.fRepeat { self.playAudio() offsetForNextTick = 0.0 } else if self.hasRepeatElement() { offsetForNextTick = 0.0 fElementRepeatNext = true } } CATransaction.begin() CATransaction.setDisableActions(true) if !fElementRepeatNext { self.aniLayer?.timeOffset = CFTimeInterval(nextOffset) } for c in self.children { if let element = c as? SwipeElement { element.setTimeOffsetTo(nextOffset, fAutoPlay: true) } } CATransaction.commit() } if let value = offsetForNextTick { self.timerTick(value, fElementRepeat: fElementRepeatNext) } else { self.offsetPaused = self.fPausing ? offset : nil self.cPlaying -= 1 self.cDebug -= 1 self.didFinishPlayingInternal() } }) } // Returns the list of URLs of required resouces for this element (including children) lazy var resourceURLs:[URL:String] = { var urls = [URL:String]() let baseURL = self.delegate.baseURL() for key in ["audio"] { if let src = self.info[key] as? String, let url = URL.url(src, baseURL: baseURL) { urls[url] = "" } } if let elementsInfo = self.info["elements"] as? [[String:Any]] { let scaleDummy = CGSize(width: 0.1, height: 0.1) for e in elementsInfo { let element = SwipeElement(info: e, scale:scaleDummy, parent:self, delegate:self) for (url, prefix) in element.resourceURLs { urls[url as URL] = prefix } } } if let pageTemplate = self.pageTemplate { for (url, prefix) in pageTemplate.resourceURLs { urls[url as URL] = prefix } } return urls }() lazy var prefetcher:SwipePrefetcher = { return SwipePrefetcher(urls:self.resourceURLs) }() func loadView(_ callback:(()->(Void))?) -> UIView { MyLog("SWPage loading @\(index)", level: 2) assert(self.view == nil, "loadView self.view must be nil") let view = InternalView(wrapper: self, frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)) view.clipsToBounds = true self.view = view let viewVideo = UIView(frame: view.bounds) self.viewVideo = viewVideo let viewAnimation = UIView(frame: view.bounds) self.viewAnimation = viewAnimation #if os(OSX) let layer = view.makeBackingLayer() let aniLayer = viewAnimation.makeBackingLayer() #else let layer = view.layer let aniLayer = viewAnimation.layer #endif self.aniLayer = aniLayer let dimension = delegate.dimension(self) var transform = CATransform3DIdentity transform.m34 = -1 / dimension.width // default eyePosition is canvas width if let eyePosition = info["eyePosition"] as? CGFloat { transform.m34 = -1 / (dimension.width * eyePosition) } aniLayer.sublayerTransform = transform viewVideo.layer.sublayerTransform = transform view.addSubview(viewVideo) view.addSubview(viewAnimation) //view.tag = 100 + index // for debugging only layer.backgroundColor = self.backgroundColor if animation != "never" { aniLayer.speed = 0 // to manually specify the media timing aniLayer.beginTime = 0 // to manually specify the media timing aniLayer.fillMode = CAMediaTimingFillMode.forwards } #if os(OSX) viewAnimation.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable] #else viewVideo.autoresizingMask = [.flexibleWidth, .flexibleHeight] viewAnimation.autoresizingMask = [.flexibleWidth, .flexibleHeight] #endif //viewAnimation.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 0.2) self.prefetcher.start { (completed:Bool, _:[URL], _:[NSError]) -> Void in if completed { if self.view != nil { // NOTE: We are intentionally ignoring fetch errors (of network resources) here. if let eventsInfo = self.info["events"] as? [String:Any] { self.eventHandler.parse(eventsInfo) } self.loadSubviews() callback?() } } } setupGestureRecognizers() #if !os(tvOS) NotificationCenter.default.addObserver(self, selector: #selector(SwipePage.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SwipePage.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) #endif if let actions = eventHandler.actionsFor("load") { DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { self.execute(self, actions: actions) } } return view } #if !os(tvOS) @objc func keyboardWillShow(notification: Notification) { if let info = notification.userInfo { if let kbFrame = info[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect { if let fr = findFirstResponder() { let frFrame = fr.view!.frame let myFrame = self.view!.frame //let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as NSTimeInterval //UIView.animateWithDuration(0.25, delay: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.view!.frame = CGRect(x: 0, y: myFrame.origin.y - max(0, (frFrame.origin.y + frFrame.size.height) - (myFrame.size.height - kbFrame.size.height)), width: myFrame.size.height, height: myFrame.size.height) // }, completion: nil) } } } } @objc func keyboardWillHide(notification: Notification) { if let _ = notification.userInfo { if findFirstResponder() != nil { let myFrame = self.view!.frame //let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber as NSTimeInterval //UIView.animateWithDuration(0.25, delay: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.view!.frame = CGRect(x: 0, y: 0, width: myFrame.size.height, height: myFrame.size.height) // }, completion: nil) } } } #endif private func loadSubviews() { let scale = delegate.scale(self) let dimension = delegate.dimension(self) if let value = self.info["audio"] as? String, let url = URL.url(value, baseURL: self.delegate.baseURL()), let urlLocal = self.prefetcher.map(url) { do { audioPlayer = try AVAudioPlayer(contentsOf: urlLocal) audioPlayer?.prepareToPlay() } catch let error as NSError { NSLog("SWPage audio error \(error)") } } prepareUtterance() if let elementsInfo = self.info["elements"] as? [[String:Any]] { for e in elementsInfo { let element = SwipeElement(info: e, scale:scale, parent:self, delegate:self) if let subview = element.loadView(dimension) { if (self.autoplay || !self.scroll) && element.isVideoElement() { // HACK: video element can not be played normally if it is added to the animation layer, which has the speed property zero. self.viewVideo!.addSubview(subview) } else { self.viewAnimation!.addSubview(subview) } children.append(element) } } // for e in elementsInfo } } private func prepareUtterance() { // REVIEW: Disabled for OSX for now #if !os(OSX) if let speech = self.info["speech"] as? [String:Any], let text = parseText(self, info: speech, key: "text") { let voice = self.delegate.voice(speech["voice"] as? String) let utterance = AVSpeechUtterance(string: text) // BCP-47 code if let lang = voice["lang"] as? String { // HACK: Work-around an iOS9 bug // http://stackoverflow.com/questions/30794082/how-do-we-solve-an-axspeechassetdownloader-error-on-ios // https://forums.developer.apple.com/thread/19079?q=AVSpeechSynthesisVoice let voices = AVSpeechSynthesisVoice.speechVoices() var theVoice:AVSpeechSynthesisVoice? for voice in voices { //NSLog("SWPage lang=\(voice.language)") if lang == voice.language { theVoice = voice break; } } if let voice = theVoice { utterance.voice = voice } else { NSLog("SWPage Voice for \(lang) is not available (iOS9 bug)") } // utterance.voice = AVSpeechSynthesisVoice(language: lang) } if let pitch = voice["pitch"] as? Float { if pitch >= 0.5 && pitch < 2.0 { utterance.pitchMultiplier = pitch } } if let rate = voice["rate"] as? Float { if rate >= 0.0 && rate <= 1.0 { utterance.rate = AVSpeechUtteranceMinimumSpeechRate + (AVSpeechUtteranceDefaultSpeechRate - AVSpeechUtteranceMinimumSpeechRate) * rate } else if rate > 1.0 && rate <= 2.0 { utterance.rate = AVSpeechUtteranceDefaultSpeechRate + (AVSpeechUtteranceMaximumSpeechRate - AVSpeechUtteranceDefaultSpeechRate) * (rate - 1.0) } } self.utterance = utterance } #endif } // <SwipeElementDelegate> method func addedResourceURLs(_ urls:[URL:String], callback:@escaping () -> Void) { self.prefetcher.append(urls) { (completed:Bool, _:[URL], _:[NSError]) -> Void in if completed { callback() } } } func prototypeWith(_ name:String?) -> [String:Any]? { return delegate.prototypeWith(name) } // <SwipeElementDelegate> method func pathWith(_ name:String?) -> Any? { return delegate.pathWith(name) } // <SwipeElementDelegate> method func shouldRepeat(_ element:SwipeElement) -> Bool { return fEntered && self.fRepeat } // <SwipeElementDelegate> method func onAction(_ element:SwipeElement) { if let action = element.action { MyLog("SWPage onAction \(action)", level: 2) if action == "play" { //prepareToPlay() //autoPlay() play() } } } // <SwipeElementDelegate> method func didStartPlaying(_ element:SwipeElement) { didStartPlayingInternal() } // <SwipeElementDelegate> method func didFinishPlaying(_ element:SwipeElement, completed:Bool) { if completed { completionCount += 1 } didFinishPlayingInternal() } // <SwipeElementDelegate> method func baseURL() -> URL? { return delegate.baseURL() } // <SwipeElementDelegate> method func pageIndex() -> Int { return index } // <SwipeElementDelegate> method func localizedStringForKey(_ key:String) -> String? { if let strings = self.info["strings"] as? [String:Any], let texts = strings[key] as? [String:Any] { return SwipeParser.localizedString(texts, langId: delegate.languageIdentifier()) } return nil } // <SwipeElementDelegate> method func languageIdentifier() -> String? { return delegate.languageIdentifier() } func parseText(_ originator: SwipeNode, info:[String:Any], key:String) -> String? { guard let value = info[key] else { return nil } if let text = value as? String { return text } if let ref = value as? [String:Any], let key = ref["ref"] as? String, let text = localizedStringForKey(key) { return text } return nil } private func didStartPlayingInternal() { cPlaying += 1 if cPlaying==1 { //NSLog("SWPage didStartPlaying @\(index)") NotificationCenter.default.post(name: .SwipePageDidStartPlaying, object: self) } } private func didFinishPlayingInternal() { assert(cPlaying > 0, "didFinishPlaying going negative! @\(index)") cPlaying -= 1 if cPlaying == 0 { NotificationCenter.default.post(name: .SwipePageDidFinishPlaying, object: self) } } #if !os(OSX) func speak(_ utterance:AVSpeechUtterance) { delegate.speak(utterance) } #endif func parseMarkdown(_ element:SwipeElement, markdowns:[String]) -> NSAttributedString { return self.delegate.parseMarkdown(markdowns) } func map(_ url:URL) -> URL? { return self.prefetcher.map(url) } func isPlaying() -> Bool { let fPlaying = cPlaying > 0 //assert(fPlaying == self.isPlayingOld()) return fPlaying } /* private func isPlayingOld() -> Bool { for element in elements { if element.isPlaying() { return true } } return false } */ func hasRepeatElement() -> Bool { for c in children { if let element = c as? SwipeElement { if element.isRepeatElement() { return true } } } return false } // SwipeView override func tapped() { self.delegate.tapped() } // SwipeNode override func getValue(_ originator: SwipeNode, info: [String:Any]) -> Any? { var name = "*" if let val = info["id"] as? String { name = val } // first try own page property if (name == "*" || self.name.caseInsensitiveCompare(name) == .orderedSame) { if let attribute = info["property"] as? String { return getPropertyValue(originator, property: attribute) } else if let attributeInfo = info["property"] as? [String:Any] { return getPropertiesValue(originator, info: attributeInfo) } } for c in children { if let e = c as? SwipeElement { if name == "*" || e.name.caseInsensitiveCompare(name) == .orderedSame { if let attribute = info["property"] as? String { return e.getPropertyValue(originator, property: attribute) } else if let attributeInfo = info["property"] as? [String:Any] { return e.getPropertiesValue(originator, info: attributeInfo) } } } } return nil } override func updateElement(_ originator: SwipeNode, name: String, up: Bool, info: [String:Any]) -> Bool { // Find named element and update for c in children { if let e = c as? SwipeElement { if e.name.caseInsensitiveCompare(name) == .orderedSame { e.update(originator, info: info) return true } } } return false } override func appendList(_ originator: SwipeNode, name: String, up: Bool, info: [String : Any]) -> Bool { // Find named element and update for c in children { if let e = c as? SwipeElement { if e.name.caseInsensitiveCompare(name) == .orderedSame { e.appendList(originator, info: info) return true } } } return false } }
mit
sgr-ksmt/SUSwiftSugar
SUSwiftSugar/Protocols/FilePathConvertible.swift
1
508
// // FilePathConvertible.swift import Foundation public protocol FilePathConvertible { var filePath: String { get } var fileURL: NSURL { get } } extension String: FilePathConvertible { public var filePath: String { return self } public var fileURL: NSURL { return NSURL(fileURLWithPath: self) } } extension NSURL: FilePathConvertible { public var filePath: String { return self.path! } public var fileURL: NSURL { return self } }
mit
tutsplus/iOS-AVFoundation-StarterProject
MP3Player/ViewController.swift
2
1076
// // ViewController.swift // MP3Player // // Created by James Tyner on 7/5/15. // Copyright (c) 2015 James Tyner. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var mp3Player:MP3Player? var timer:NSTimer? @IBOutlet weak var trackName: UILabel! @IBOutlet weak var trackTime: UILabel! @IBOutlet weak var progressBar: UIProgressView! override func viewDidLoad() { super.viewDidLoad() } @IBAction func playSong(sender: AnyObject) { } @IBAction func stopSong(sender: AnyObject) { } @IBAction func pauseSong(sender: AnyObject) { } @IBAction func playNextSong(sender: AnyObject) { } @IBAction func setVolume(sender: UISlider) { } @IBAction func playPreviousSong(sender: AnyObject) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bsd-2-clause
dymx101/BallDown
BallDown/Extension/SKNodeExtension.swift
1
631
// // SKNodeExtension.swift // BallDown // // Copyright (c) 2015 ones. All rights reserved. // import Foundation import SpriteKit extension SKNode { var bind: AnyObject? { get { return self.userData?.objectForKey("@bind") } set { if newValue == nil { self.userData?.removeObjectForKey("@bind") } else { if self.userData == nil { self.userData = NSMutableDictionary() } self.userData!.setValue(newValue, forKey: "@bind") } } } }
mit
firebase/quickstart-ios
database/DatabaseExampleSwiftUI/DatabaseExample/Shared/Models/UserViewModel.swift
1
2150
// // Copyright (c) 2021 Google 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 SwiftUI import FirebaseAuth class UserViewModel: ObservableObject { @AppStorage("isSignedIn") var isSignedIn = false @Published var email = "" @Published var password = "" @Published var alert = false @Published var alertMessage = "" private func showAlertMessage(message: String) { alertMessage = message alert.toggle() } func login() { // check if all fields are inputted correctly if email.isEmpty || password.isEmpty { showAlertMessage(message: "Neither email nor password can be empty.") return } // sign in with email and password Auth.auth().signIn(withEmail: email, password: password) { result, err in if let err = err { self.alertMessage = err.localizedDescription self.alert.toggle() } else { self.isSignedIn = true } } } func signUp() { // check if all fields are inputted correctly if email.isEmpty || password.isEmpty { showAlertMessage(message: "Neither email nor password can be empty.") return } // sign up with email and password Auth.auth().createUser(withEmail: email, password: password) { result, err in if let err = err { self.alertMessage = err.localizedDescription self.alert.toggle() } else { self.login() } } } func logout() { do { try Auth.auth().signOut() isSignedIn = false email = "" password = "" } catch { print("Error signing out.") } } } let user = UserViewModel()
apache-2.0
mobgeek/swift
Swift em 4 Semanas/Playgrounds/Semana 3/5-Inicialização.playground/Contents.swift
2
3737
// Playground - noun: a place where you can play import UIKit // Initializers struct CelsiusTeste { var temperatura:Double = 35.0 //Uma outra opção seria usar o init() para inicializar temperatura. O resultado seria o mesmo. // init() { // // temperatura = 35.0 // // } } var c = CelsiusTeste() println("A temperatura padrão é \(c.temperatura)") //Customizando inicialização - Parâmetros de Inicialização struct Celsius { var temperaturaEmCelsius: Double = 0.0 init(deFahrenheit fahrenheit: Double) { temperaturaEmCelsius = (fahrenheit - 32) / 1.8 } init(deKelvin kelvin: Double) { temperaturaEmCelsius = kelvin - 273.15 } } //Não esquecer que definindo pontoDeEbulição e pontoDoCongelamento como constantes, todas as propriedades são consideradas constantes, por se tratar de uma estrutura (Tipo Valor) let pontoDeEbulição = Celsius(deFahrenheit: 212.0) let pontoDeCongelamento = Celsius(deKelvin: 273.15) //Quando nomes externos para os parâmetros dos initializers não são informados, Swift irá considerar o nome como local e externo struct Cor { let vermelho, verde, azul: Double init(vermelho: Double, verde: Double, azul: Double) { self.vermelho = vermelho self.verde = verde self.azul = azul } init(branco: Double) { vermelho = branco verde = branco azul = branco } } let magenta = Cor(vermelho: 1.0, verde: 0.0, azul: 1.0) let meioCinza = Cor(branco: 0.5) //let verdão = Cor(0.0, 1.0, 0.0) //erro, nomes externos não foram informados //Ignorando o Nome Externo struct Celsius2 { var temperaturaEmCelsius: Double = 0.0 //Basta usar o _ antes do parâmetro para não precisar usar mais nome externo init(_ celsius: Double) { temperaturaEmCelsius = celsius } } let temperaturaDoCorpo = Celsius2(37.0) //nome externo foi ignorado //Customizando inciaialização - Propriedades Opcionais class PerguntaEnquete { var texto: String var resposta: String? //inicializada com nil, logo, não é preciso usá-la em algum init init(texto: String) { self.texto = texto } func pergunta() { println(texto) } } let perguntaGeek = PerguntaEnquete(texto: "Você se considera um Geek?") perguntaGeek.pergunta() perguntaGeek.resposta = "Hm. Acho que sim :-)" perguntaGeek.resposta! //Lembrando que é preciso forçar o desempacotamento (F.U.) //Propriedades Constantes: //mudando a propriedade texto da classe PerguntaEnquete de variável para constante, ela poderá ter seu valor alterado apenas dentro de algum initializer //Inicializadores Padrão //Relembrando: Em Estruturas, ao fornecer ou não valores padrão para todas as propriedades, Swift fornece um Incializador de Membro. //Agora, tanto Classes e Estruturas, ao terem todas as suas propriedades inicializadas com algum valor padrão, Swift fornecerá um Inicializador Padrão para elas. E nas Estruturas além de ter o Inicializador Padrão, terá o de Membro. //Em Classes class ListaDeCompras { var nome: String? var quantidade = 1 var comprado = false } var item = ListaDeCompras() //Inicializador Padrão // Em estruturas struct Resolução { var largura = 0.0 var altura = 0.0 } var fullHD1 = Resolução(largura: 1920, altura: 1080) //Inicializador de Membro var novaResolução = Resolução() //Inicializador Padrão
mit
lemanhtien/MTSlideToOpen
MTSlideToOpen/AppDelegate.swift
1
2176
// // AppDelegate.swift // MTSlideToOpen // // Created by Martin Lee on 10/12/17. // Copyright © 2017 Martin Le. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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
DylanModesitt/Picryption_iOS
Picryption/AppDelegate.swift
1
4771
// // AppDelegate.swift // Picryption // // Created by Dylan Modesitt on 4/21/17. // Copyright © 2017 Modesitt Systems. All rights reserved. // import UIKit import CoreData @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:. // Saves changes in the application's managed object context before the application terminates. if #available(iOS 10.0, *) { self.saveContext() } else { // Fallback on earlier versions } } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Picryption") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support @available(iOS 10.0, *) func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
xmkevinchen/CKMessagesKit
CKMessagesKit/Sources/View/Layout/CKViewLayout.swift
1
617
// // CKMessageLayout.swift // CKMessagesViewController // // Created by Kevin Chen on 8/26/16. // Copyright © 2016 Kevin Chen. All rights reserved. // import CoreGraphics /// A type that can layout itself and its contents public protocol CKViewLayout { /// The type of the leaf content elements in this layout. associatedtype Content /// Lay out this layout and all of its contained layouts within `rect`. func layout(in rect: CGRect) /// Return all of the leaf content elements contained in this layout and its descendants. var contents: [Content] { get } }
mit
varkor/firefox-ios
Client/Frontend/Menu/AppMenuConfiguration.swift
1
16746
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared enum AppMenuAction: String { case OpenNewNormalTab = "OpenNewNormalTab" case OpenNewPrivateTab = "OpenNewPrivateTab" case FindInPage = "FindInPage" case ToggleBrowsingMode = "ToggleBrowsingMode" case ToggleBookmarkStatus = "ToggleBookmarkStatus" case OpenSettings = "OpenSettings" case CloseAllTabs = "CloseAllTabs" case OpenHomePage = "OpenHomePage" case SetHomePage = "SetHomePage" case SharePage = "SharePage" case OpenTopSites = "OpenTopSites" case OpenBookmarks = "OpenBookmarks" case OpenHistory = "OpenHistory" case OpenReadingList = "OpenReadingList" case ShowImageMode = "ShowImageMode" case HideImageMode = "HideImageMode" case ShowNightMode = "ShowNightMode" case HideNightMode = "HideNightMode" } struct AppMenuConfiguration: MenuConfiguration { internal private(set) var menuItems = [MenuItem]() internal private(set) var menuToolbarItems: [MenuToolbarItem]? internal private(set) var numberOfItemsInRow: Int = 0 private(set) var isPrivateMode: Bool = false init(appState: AppState) { menuItems = menuItemsForAppState(appState) menuToolbarItems = menuToolbarItemsForAppState(appState) numberOfItemsInRow = numberOfMenuItemsPerRowForAppState(appState) isPrivateMode = appState.ui.isPrivate() } func menuForState(appState: AppState) -> MenuConfiguration { return AppMenuConfiguration(appState: appState) } func toolbarColor() -> UIColor { return isPrivateMode ? UIConstants.MenuToolbarBackgroundColorPrivate : UIConstants.MenuToolbarBackgroundColorNormal } func toolbarTintColor() -> UIColor { return isPrivateMode ? UIConstants.MenuToolbarTintColorPrivate : UIConstants.MenuToolbarTintColorNormal } func menuBackgroundColor() -> UIColor { return isPrivateMode ? UIConstants.MenuBackgroundColorPrivate : UIConstants.MenuBackgroundColorNormal } func menuTintColor() -> UIColor { return isPrivateMode ? UIConstants.MenuToolbarTintColorPrivate : UIConstants.MenuBackgroundColorPrivate } func menuFont() -> UIFont { return UIFont.systemFontOfSize(11) } func menuIcon() -> UIImage? { return isPrivateMode ? UIImage(named:"bottomNav-menu-pbm") : UIImage(named:"bottomNav-menu") } func minMenuRowHeight() -> CGFloat { return 65.0 } func shadowColor() -> UIColor { return isPrivateMode ? UIColor.darkGrayColor() : UIColor.lightGrayColor() } func selectedItemTintColor() -> UIColor { return UIConstants.MenuSelectedItemTintColor } private func numberOfMenuItemsPerRowForAppState(appState: AppState) -> Int { switch appState.ui { case .TabTray: return 4 default: return 3 } } // the items should be added to the array according to desired display order private func menuItemsForAppState(appState: AppState) -> [MenuItem] { var menuItems = [MenuItem]() switch appState.ui { case .Tab(let tabState): menuItems.append(AppMenuConfiguration.FindInPageMenuItem) if #available(iOS 9, *) { menuItems.append(tabState.desktopSite ? AppMenuConfiguration.RequestMobileMenuItem : AppMenuConfiguration.RequestDesktopMenuItem) } if !HomePageAccessors.isButtonInMenu(appState) { menuItems.append(AppMenuConfiguration.SharePageMenuItem) } else if HomePageAccessors.hasHomePage(appState) { menuItems.append(AppMenuConfiguration.OpenHomePageMenuItem) } else { menuItems.append(AppMenuConfiguration.SetHomePageMenuItem) } menuItems.append(AppMenuConfiguration.NewTabMenuItem) if #available(iOS 9, *) { menuItems.append(AppMenuConfiguration.NewPrivateTabMenuItem) } menuItems.append(tabState.isBookmarked ? AppMenuConfiguration.RemoveBookmarkMenuItem : AppMenuConfiguration.AddBookmarkMenuItem) if NoImageModeHelper.isNoImageModeAvailable(appState) { if NoImageModeHelper.isNoImageModeActivated(appState) { menuItems.append(AppMenuConfiguration.ShowImageModeMenuItem) } else { menuItems.append(AppMenuConfiguration.HideImageModeMenuItem) } } if NightModeAccessors.isNightModeAvailable(appState) { if NightModeAccessors.isNightModeActivated(appState) { menuItems.append(AppMenuConfiguration.ShowNightModeItem) } else { menuItems.append(AppMenuConfiguration.HideNightModeItem) } } menuItems.append(AppMenuConfiguration.SettingsMenuItem) case .HomePanels, .Loading: menuItems.append(AppMenuConfiguration.NewTabMenuItem) if #available(iOS 9, *) { menuItems.append(AppMenuConfiguration.NewPrivateTabMenuItem) } if HomePageAccessors.isButtonInMenu(appState) && HomePageAccessors.hasHomePage(appState) { menuItems.append(AppMenuConfiguration.OpenHomePageMenuItem) } if NoImageModeHelper.isNoImageModeAvailable(appState) { if NoImageModeHelper.isNoImageModeActivated(appState) { menuItems.append(AppMenuConfiguration.ShowImageModeMenuItem) } else { menuItems.append(AppMenuConfiguration.HideImageModeMenuItem) } } if NightModeAccessors.isNightModeAvailable(appState) { if NightModeAccessors.isNightModeActivated(appState) { menuItems.append(AppMenuConfiguration.ShowNightModeItem) } else { menuItems.append(AppMenuConfiguration.HideNightModeItem) } } menuItems.append(AppMenuConfiguration.SettingsMenuItem) case .TabTray: menuItems.append(AppMenuConfiguration.NewTabMenuItem) if #available(iOS 9, *) { menuItems.append(AppMenuConfiguration.NewPrivateTabMenuItem) } menuItems.append(AppMenuConfiguration.CloseAllTabsMenuItem) menuItems.append(AppMenuConfiguration.SettingsMenuItem) } return menuItems } // the items should be added to the array according to desired display order private func menuToolbarItemsForAppState(appState: AppState) -> [MenuToolbarItem]? { let menuToolbarItems: [MenuToolbarItem]? switch appState.ui { case .Tab, .TabTray: menuToolbarItems = [AppMenuConfiguration.TopSitesMenuToolbarItem, AppMenuConfiguration.BookmarksMenuToolbarItem, AppMenuConfiguration.HistoryMenuToolbarItem, AppMenuConfiguration.ReadingListMenuToolbarItem] default: menuToolbarItems = nil } return menuToolbarItems } } // MARK: Static helper access function extension AppMenuConfiguration { private static var NewTabMenuItem: MenuItem { return AppMenuItem(title: NewTabTitleString, action: MenuAction(action: AppMenuAction.OpenNewNormalTab.rawValue), icon: "menu-NewTab", privateModeIcon: "menu-NewTab-pbm") } @available(iOS 9, *) private static var NewPrivateTabMenuItem: MenuItem { return AppMenuItem(title: NewPrivateTabTitleString, action: MenuAction(action: AppMenuAction.OpenNewPrivateTab.rawValue), icon: "menu-NewPrivateTab", privateModeIcon: "menu-NewPrivateTab-pbm") } private static var AddBookmarkMenuItem: MenuItem { return AppMenuItem(title: AddBookmarkTitleString, action: MenuAction(action: AppMenuAction.ToggleBookmarkStatus.rawValue), icon: "menu-Bookmark", privateModeIcon: "menu-Bookmark-pbm", selectedIcon: "menu-RemoveBookmark", animation: JumpAndSpinAnimator()) } private static var RemoveBookmarkMenuItem: MenuItem { return AppMenuItem(title: RemoveBookmarkTitleString, action: MenuAction(action: AppMenuAction.ToggleBookmarkStatus.rawValue), icon: "menu-RemoveBookmark", privateModeIcon: "menu-RemoveBookmark") } private static var FindInPageMenuItem: MenuItem { return AppMenuItem(title: FindInPageTitleString, action: MenuAction(action: AppMenuAction.FindInPage.rawValue), icon: "menu-FindInPage", privateModeIcon: "menu-FindInPage-pbm") } @available(iOS 9, *) private static var RequestDesktopMenuItem: MenuItem { return AppMenuItem(title: ViewDesktopSiteTitleString, action: MenuAction(action: AppMenuAction.ToggleBrowsingMode.rawValue), icon: "menu-RequestDesktopSite", privateModeIcon: "menu-RequestDesktopSite-pbm") } @available(iOS 9, *) private static var RequestMobileMenuItem: MenuItem { return AppMenuItem(title: ViewMobileSiteTitleString, action: MenuAction(action: AppMenuAction.ToggleBrowsingMode.rawValue), icon: "menu-ViewMobile", privateModeIcon: "menu-ViewMobile-pbm") } private static var HideImageModeMenuItem: MenuItem { return AppMenuItem(title: Strings.MenuNoImageModeTurnOnLabel, action: MenuAction(action: AppMenuAction.HideImageMode.rawValue), icon: "menu-NoImageMode", privateModeIcon: "menu-NoImageMode-pbm") } private static var ShowImageModeMenuItem: MenuItem { return AppMenuItem(title: Strings.MenuNoImageModeTurnOffLabel, action: MenuAction(action: AppMenuAction.ShowImageMode.rawValue), icon: "menu-NoImageMode-Engaged", privateModeIcon: "menu-NoImageMode-Engaged") } private static var HideNightModeItem: MenuItem { return AppMenuItem(title: Strings.MenuNightModeTurnOnLabel, action: MenuAction(action: AppMenuAction.HideNightMode.rawValue), icon: "menu-NightMode", privateModeIcon: "menu-NightMode-pbm") } private static var ShowNightModeItem: MenuItem { return AppMenuItem(title: Strings.MenuNightModeTurnOffLabel, action: MenuAction(action: AppMenuAction.ShowNightMode.rawValue), icon: "menu-NightMode-Engaged", privateModeIcon: "menu-NightMode-Engaged") } private static var SettingsMenuItem: MenuItem { return AppMenuItem(title: SettingsTitleString, action: MenuAction(action: AppMenuAction.OpenSettings.rawValue), icon: "menu-Settings", privateModeIcon: "menu-Settings-pbm") } private static var CloseAllTabsMenuItem: MenuItem { return AppMenuItem(title: CloseAllTabsTitleString, action: MenuAction(action: AppMenuAction.CloseAllTabs.rawValue), icon: "menu-CloseTabs", privateModeIcon: "menu-CloseTabs-pbm") } private static var OpenHomePageMenuItem: MenuItem { return AppMenuItem(title: OpenHomePageTitleString, action: MenuAction(action: AppMenuAction.OpenHomePage.rawValue), icon: "menu-Home", privateModeIcon: "menu-Home-pbm", selectedIcon: "menu-Home-Engaged") } private static var SetHomePageMenuItem: MenuItem { return AppMenuItem(title: SetHomePageTitleString, action: MenuAction(action: AppMenuAction.SetHomePage.rawValue), icon: "menu-Home", privateModeIcon: "menu-Home-pbm", selectedIcon: "menu-Home-Engaged") } private static var SharePageMenuItem: MenuItem { return AppMenuItem(title: SharePageTitleString, action: MenuAction(action: AppMenuAction.SharePage.rawValue), icon: "menu-Send", privateModeIcon: "menu-Send-pbm", selectedIcon: "menu-Send-Engaged") } private static var TopSitesMenuToolbarItem: MenuToolbarItem { return AppMenuToolbarItem(title: TopSitesTitleString, action: MenuAction(action: AppMenuAction.OpenTopSites.rawValue), icon: "menu-panel-TopSites") } private static var BookmarksMenuToolbarItem: MenuToolbarItem { return AppMenuToolbarItem(title: BookmarksTitleString, action: MenuAction(action: AppMenuAction.OpenBookmarks.rawValue), icon: "menu-panel-Bookmarks") } private static var HistoryMenuToolbarItem: MenuToolbarItem { return AppMenuToolbarItem(title: HistoryTitleString, action: MenuAction(action: AppMenuAction.OpenHistory.rawValue), icon: "menu-panel-History") } private static var ReadingListMenuToolbarItem: MenuToolbarItem { return AppMenuToolbarItem(title: ReadingListTitleString, action: MenuAction(action: AppMenuAction.OpenReadingList.rawValue), icon: "menu-panel-ReadingList") } static let NewTabTitleString = NSLocalizedString("Menu.NewTabAction.Title", value: "New Tab", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to open a new tab") static let NewPrivateTabTitleString = NSLocalizedString("Menu.NewPrivateTabAction.Title", value: "New Private Tab", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to open a new private tab.") static let AddBookmarkTitleString = NSLocalizedString("Menu.AddBookmarkAction.Title", value: "Add Bookmark", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to create a bookmark for the current website.") static let RemoveBookmarkTitleString = NSLocalizedString("Menu.RemoveBookmarkAction.Title", value: "Remove Bookmark", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to delete an existing bookmark for the current website.") static let FindInPageTitleString = NSLocalizedString("Menu.FindInPageAction.Title", value: "Find In Page", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to open the toolbar to search for text within the current page.") static let ViewDesktopSiteTitleString = NSLocalizedString("Menu.ViewDekstopSiteAction.Title", value: "Request Desktop Site", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to request the desktop version of the current website.") static let ViewMobileSiteTitleString = NSLocalizedString("Menu.ViewMobileSiteAction.Title", value: "Request Mobile Site", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to request the mobile version of the current website.") static let SettingsTitleString = NSLocalizedString("Menu.OpenSettingsAction.Title", value: "Settings", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to open the Settings menu.") static let CloseAllTabsTitleString = NSLocalizedString("Menu.CloseAllTabsAction.Title", value: "Close All Tabs", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to close all tabs currently open.") static let OpenHomePageTitleString = NSLocalizedString("Menu.OpenHomePageAction.Title", value: "Home", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to navigate to the home page.") static let SetHomePageTitleString = NSLocalizedString("Menu.SetHomePageAction.Title", value: "Set Homepage", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to set the homepage if none is currently set.") static let SharePageTitleString = NSLocalizedString("Menu.SendPageAction.Title", value: "Send", tableName: "Menu", comment: "Label for the button, displayed in the menu, used to open the share dialog.") static let TopSitesTitleString = NSLocalizedString("Menu.OpenTopSitesAction.AccessibilityLabel", value: "Top Sites", tableName: "Menu", comment: "Accessibility label for the button, displayed in the menu, used to open the Top Sites home panel.") static let BookmarksTitleString = NSLocalizedString("Menu.OpenBookmarksAction.AccessibilityLabel", value: "Bookmarks", tableName: "Menu", comment: "Accessibility label for the button, displayed in the menu, used to open the Bbookmarks home panel.") static let HistoryTitleString = NSLocalizedString("Menu.OpenHistoryAction.AccessibilityLabel", value: "History", tableName: "Menu", comment: "Accessibility label for the button, displayed in the menu, used to open the History home panel.") static let ReadingListTitleString = NSLocalizedString("Menu.OpenReadingListAction.AccessibilityLabel", value: "Reading List", tableName: "Menu", comment: "Accessibility label for the button, displayed in the menu, used to open the Reading list home panel.") static let MenuButtonAccessibilityLabel = NSLocalizedString("Toolbar.Menu.AccessibilityLabel", value: "Menu", comment: "Accessibility label for the Menu button.") }
mpl-2.0
rlasante/Swift-Trip-Tracker
LocationTracker/TripManager.swift
1
4691
// // LocationManager.swift // LocationTracker // // Created by Ryan LaSante on 11/1/15. // Copyright © 2015 rlasante. All rights reserved. // import UIKit import CoreData import CoreLocation import ReactiveCocoa class TripManager: NSObject, CLLocationManagerDelegate { static let sharedInstance = TripManager() private let (speedSignal, speedObserver) = Signal<CLLocationSpeed, NoError>.pipe() private let (tripSignal, tripObserver) = Signal<Trip, NoError>.pipe() var trips = [Trip]() var currentTrip: Trip? private lazy var locationManager: CLLocationManager = { let manager = CLLocationManager() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestWhenInUseAuthorization() return manager }() private lazy var managedObjectContext: NSManagedObjectContext = { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate return appDelegate.managedObjectContext }() private func saveContext() { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.saveContext() } private override init() { super.init() loadSavedTrips() tripSignal.observeNext {[weak self] (trip) -> () in self?.trips.append(trip) self?.saveTrip(trip) } } func startTracking() { guard CLLocationManager.locationServicesEnabled() else { return } currentTrip = Trip() locationManager.startUpdatingLocation() } func stopTracking() { guard CLLocationManager.locationServicesEnabled() else { return } locationManager.stopUpdatingLocation() if let trip = currentTrip where !trip.locations.isEmpty { tripObserver.sendNext(trip) } currentTrip = nil speedObserver.sendNext(0) } func currentSpeedSignal() -> Signal<CLLocationSpeed, NoError> { // Returns the signal that sends the current speed in meters per second return speedSignal } func completedTripSignal() -> Signal<Trip, NoError> { return tripSignal } private func loadSavedTrips() { let fetchRequest = NSFetchRequest(entityName: "Trip") do { let results = try self.managedObjectContext.executeFetchRequest(fetchRequest) let tripObjects = results as! [NSManagedObject] for tripObject in tripObjects { trips.append(Trip(object: tripObject)) } } catch let error as NSError { print("Unable to fetch \(error). \(error.userInfo)") } } private func saveTrip(trip: Trip) { let tripEntity = NSEntityDescription.entityForName("Trip", inManagedObjectContext: self.managedObjectContext) let tripObject = NSManagedObject(entity: tripEntity!, insertIntoManagedObjectContext: self.managedObjectContext) let locations = getLocationEntities(trip) if locations.count > 0 { tripObject.setValue(Set(locations), forKey: "locations") } self.saveContext() } private func getLocationEntities(trip: Trip) -> [NSManagedObject] { var managedLocations = [NSManagedObject]() for location in trip.locations { let locationEntity = NSEntityDescription.entityForName("Location", inManagedObjectContext: self.managedObjectContext) let locationObject = NSManagedObject(entity: locationEntity!, insertIntoManagedObjectContext: self.managedObjectContext) locationObject.setValue(NSNumber(double: location.altitude), forKey: "altitude") locationObject.setValue(NSNumber(double: location.course), forKey: "course") locationObject.setValue(NSNumber(double: location.coordinate.latitude), forKey: "lat") locationObject.setValue(NSNumber(double: location.coordinate.longitude), forKey: "long") locationObject.setValue(NSNumber(double: location.horizontalAccuracy), forKey: "horizontalAccuracy") locationObject.setValue(NSNumber(double: location.verticalAccuracy), forKey: "verticalAccuracy") locationObject.setValue(NSNumber(double: location.speed), forKey: "speed") locationObject.setValue(location.timestamp, forKey: "timestamp") managedLocations.append(locationObject) } return managedLocations } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let trip = currentTrip { let trimmedLocations = locations.filter { (location) -> Bool in let tripBeforeLocation = trip.createdAt.compare(location.timestamp) == .OrderedAscending return tripBeforeLocation && location.horizontalAccuracy < 50.0 } trip.addLocations(trimmedLocations) if !trimmedLocations.isEmpty { speedObserver.sendNext(trimmedLocations.last!.speed) } } } }
mit
joe22499/JKCalendar
Sources/JKCalendarScrollView.swift
1
6964
// // JKCalendarScrollView.swift // // Copyright © 2017 Joe Ciou. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public class JKCalendarScrollView: UIScrollView { public let calendar: JKCalendar = JKCalendar(frame: CGRect.zero) public weak var nativeDelegate: UIScrollViewDelegate? public var startsCollapsed: Bool = false private var first = true private var rotating = false override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { super.delegate = self calendar.interactionObject = self NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil) } override open func layoutSubviews() { super.layoutSubviews() layoutSubviewsHandler() } func layoutSubviewsHandler() { if first || rotating{ var calendarSize: CGSize! let footerHeight = calendar.delegate?.heightOfFooterView?(in: calendar) ?? 0 if frame.width > frame.height { let height = ((calendar.isTopViewDisplayed ? calendar.topView.frame.height: 0) + calendar.weekView.frame.height + frame.width * 0.35 + footerHeight).rounded() calendarSize = CGSize(width: frame.width, height: height) } else { let height = ((calendar.isTopViewDisplayed ? calendar.topView.frame.height: 0) + calendar.weekView.frame.height + frame.width * 0.65 + footerHeight).rounded() calendarSize = CGSize(width: frame.width, height: height) } calendar.frame = CGRect(x: 0, y: frame.origin.y, width: calendarSize.width, height: calendarSize.height) contentInset = UIEdgeInsets(top: calendarSize.height, left: 0, bottom: 0, right: 0) scrollIndicatorInsets = UIEdgeInsets(top: calendarSize.height, left: 0, bottom: 0, right: 0) contentOffset = CGPoint(x: 0, y: -calendarSize.height) rotating = false if first { superview?.insertSubview(calendar, aboveSubview: self) first = false } } } @objc func rotated() { if !first { rotating = true layoutSubviewsHandler() } } } extension JKCalendarScrollView: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { var value = calendar.frame.height + contentOffset.y if value > calendar.collapsedMaximum { value = calendar.collapsedMaximum } else if value < 0 { value = 0 } calendar.collapsedValue = value nativeDelegate?.scrollViewDidScroll?(scrollView) } public func scrollViewDidZoom(_ scrollView: UIScrollView) { nativeDelegate?.scrollViewDidZoom?(scrollView) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { nativeDelegate?.scrollViewWillBeginDragging?(scrollView) } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let value = (targetContentOffset.pointee.y + calendar.bounds.height) / calendar.collapsedMaximum if value < 1 { targetContentOffset.pointee.y = (value > 0.5 ? calendar.collapsedMaximum : 0) - calendar.bounds.height } nativeDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { nativeDelegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate) } public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { nativeDelegate?.scrollViewWillBeginDecelerating?(scrollView) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { nativeDelegate?.scrollViewDidEndDecelerating?(scrollView) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { nativeDelegate?.scrollViewDidEndScrollingAnimation?(scrollView) } public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return nativeDelegate?.viewForZooming?(in: scrollView) } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { nativeDelegate?.scrollViewWillBeginZooming?(scrollView, with: view) } public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { nativeDelegate?.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale) } public func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return nativeDelegate?.scrollViewShouldScrollToTop?(scrollView) != nil ? nativeDelegate!.scrollViewShouldScrollToTop!(scrollView): true } public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { nativeDelegate?.scrollViewDidScrollToTop?(scrollView) } }
mit
andrebocchini/SwiftChatty
SwiftChatty/Responses/Messages/GetMessageCountResponse.swift
1
535
// // GetMessageCountResponse.swift // SwiftChatty // // Created by Andre Bocchini on 1/24/16. // Copyright © 2016 Andre Bocchini. All rights reserved.// import Freddy /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451692 public struct GetMessageCountResponse { public let total: Int public let unread: Int } extension GetMessageCountResponse: MappableResponse { public init(json: JSON) throws { self.total = try json.decode(at: "total") self.unread = try json.decode(at: "unread") } }
mit
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/QR Login/Helpers/QRLoginInternetConnectionChecker.swift
1
351
import Foundation struct QRLoginInternetConnectionChecker: QRLoginConnectionChecker { var connectionAvailable: Bool { let appDelegate = WordPressAppDelegate.shared guard let connectionAvailable = appDelegate?.connectionAvailable, connectionAvailable == true else { return false } return true } }
gpl-2.0
bjarkehs/Rex
Source/UIKit/UIBarButtonItem.swift
1
1168
// // UIBarButtonItem.swift // Rex // // Created by Bjarke Hesthaven Søndergaard on 24/07/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit extension UIBarButtonItem { /// Exposes a property that binds an action to bar button item. The action is set as /// a target of the button. When property changes occur the previous action is /// overwritten. This also binds the enabled state of the action to the `rex_enabled` /// property on the button. public var rex_action: MutableProperty<CocoaAction> { return associatedObject(self, key: &actionKey) { [weak self] _ in let initial = CocoaAction.rex_disabled let property = MutableProperty(initial) property.producer.start(Observer(next: { next in self?.target = next self?.action = CocoaAction.selector })) if let strongSelf = self { strongSelf.rex_enabled <~ property.producer.flatMap(.Latest) { $0.rex_enabledProducer } } return property } } } private var actionKey: UInt8 = 0
mit
ioscreator/ioscreator
IOSSendEmailTutorial/IOSSendEmailTutorial/ViewController.swift
1
1902
// // ViewController.swift // IOSSendEmailTutorial // // Created by Arthur Knopper on 08/02/2020. // Copyright © 2020 Arthur Knopper. All rights reserved. // import UIKit import MessageUI class ViewController: UIViewController, MFMailComposeViewControllerDelegate, UITextFieldDelegate, UITextViewDelegate { @IBOutlet weak var subject: UITextField! @IBOutlet weak var body: UITextView! @IBAction func sendMail(_ sender: Any) { let picker = MFMailComposeViewController() picker.mailComposeDelegate = self if let subjectText = subject.text { picker.setSubject(subjectText) } picker.setMessageBody(body.text, isHTML: true) present(picker, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() subject.delegate = self body.delegate = self if !MFMailComposeViewController.canSendMail() { print("Mail services are not available") return } } // MFMailComposeViewControllerDelegate // 1 func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } // UITextFieldDelegate // 2 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // UITextViewDelegate // 3 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { body.text = textView.text if text == "\n" { textView.resignFirstResponder() return false } return true } }
mit
hanzhuzi/XRCustomProgressView
XRCustomProgressView/Classes/Views/MainCustomTableViewCell.swift
1
1542
// // MainCustomTableViewCell.swift // XRCustomProgressView // // Created by xuran on 2017/10/1. // Copyright © 2017年 xuran. All rights reserved. // import UIKit class MainCustomTableViewCell: UITableViewCell { var yearEarningsPrecentView: XRCirclePercentProgressView! var paillarProgressView: XRPaillarProgressView! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) yearEarningsPrecentView = XRCirclePercentProgressView(frame: .zero) self.contentView.addSubview(yearEarningsPrecentView) paillarProgressView = XRPaillarProgressView(frame: CGRect.zero) self.contentView.addSubview(paillarProgressView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() yearEarningsPrecentView.frame = CGRect(x: 20, y: (self.contentView.frame.size.height - 110.0) * 0.5, width: 110, height: 110) paillarProgressView.frame = CGRect(x: yearEarningsPrecentView.frame.maxX + 20, y: (self.contentView.frame.size.height - 18) * 0.5, width: 180, height: 18) } 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
studyYF/YueShiJia
YueShiJia/YueShiJia/Classes/Home/Models/YFSpecialGoodsItem.swift
1
3890
// // YFAdvetiseItem.swift // YueShiJia // // Created by YangFan on 2017/5/12. // Copyright © 2017年 YangFan. All rights reserved. // import UIKit class YFSpecialGoodsItem: NSObject { var special_sum: Int? var special_share_url: String? var special_image: String? var news_special: [News_Special]? var special_tis: String? var special_id: String? var special_title: String? var special_stitle: String? init(dict: [String: Any]) { special_sum = dict["special_sum"] as? Int special_share_url = dict["special_share_url"] as? String special_image = dict["special_image"] as? String special_id = dict["special_id"] as? String special_title = dict["special_title"] as? String special_stitle = dict["special_stitle"] as? String if let array = dict["news_special"] as? NSArray { news_special = [News_Special]() for good in array { news_special?.append(News_Special(dict: good as! [String : Any])) } } } } class News_Special: NSObject { var object_font: String? var special_type: Int? var goods_list: [Goods_List]? init(dict: [String: Any]) { object_font = dict["object_font"] as? String special_type = dict["special_type"] as? Int if let array = dict["goods_list"] as? NSArray { goods_list = [Goods_List]() for good in array { goods_list?.append(Goods_List(dict: good as! [String : Any])) } } } } class Goods_List: NSObject { var is_presell: String? var sole_flag: Bool? var is_fcode: String? var if_favorites: Int? var is_own_shop: String? var goods_jingle: String? var goods_marketprice: String? var group_flag: Bool? var specif_set: String? var goods_image: String? var goods_name: String? var goods_salenum: String? var store_id: String? var evaluation_good_star: String? var goods_image_long: String? var store_name: String? var store_logo: String? var tag_print: String? var evaluation_count: String? var goods_custom: String? var goods_image_url: String? var xianshi_flag: Bool? var goods_price: String? var goods_id: String? var have_gift: String? var is_virtual: String? init(dict: [String: Any]) { is_presell = dict[""] as? String sole_flag = dict["sole_flag"] as? Bool is_fcode = dict["is_fcode"] as? String if_favorites = dict["if_favorites"] as? Int is_own_shop = dict["is_own_shop"] as? String goods_jingle = dict["goods_jingle"] as? String goods_marketprice = dict["goods_marketprice"] as? String group_flag = dict["group_flag"] as? Bool specif_set = dict["specif_set"] as? String goods_image = dict["goods_image"] as? String goods_name = dict["goods_name"] as? String goods_salenum = dict["goods_salenum"] as? String store_id = dict["store_id"] as? String evaluation_good_star = dict["evaluation_good_star"] as? String goods_image_long = dict["goods_image_long"] as? String store_name = dict["store_name"] as? String store_logo = dict["store_logo"] as? String tag_print = dict["tag_print"] as? String evaluation_count = dict["evaluation_count"] as? String goods_custom = dict["goods_custom"] as? String goods_image_url = dict["goods_image_url"] as? String xianshi_flag = dict["xianshi_flag"] as? Bool goods_price = dict["goods_price"] as? String goods_id = dict["goods_id"] as? String have_gift = dict["have_gift"] as? String is_virtual = dict["is_virtual"] as? String } }
apache-2.0
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/Etc/AlbumModel.swift
1
2705
// // AlbumModel.swift // bitboylabs-ios-base // // Created by 조백근 on 2016. 10. 18.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import RealmSwift class AlbumModel: NSObject { let realm = try! Realm() var albums: [[String: String]] let onGetData: Foundation.Notification = Foundation.Notification(name: NSNotification.Name(rawValue: "onGetData"), object: nil) override init() { self.albums = [] super.init() } func getAlbums(_ term: String){ NotificationCenter.default.post(onGetData) } func perseRealm<T: Album>(_ collection: Results<T>) -> [[String: String]] { var returnAlbums: [[String : String]] = [] for i in 0 ..< collection.count { returnAlbums.append(parseRealmToDict(collection[i])) } returnAlbums = returnAlbums.reversed() return returnAlbums } func contains(_ collectionId: String) -> Bool { var flag: Bool = false for i in 0 ..< self.albums.count { if(self.albums[i]["collectionId"] == collectionId) { flag = true } } return flag } func save(_ newAlbum: [String: String]) { } func destroy(_ collectionId: String) { } func addRealm<T: Album>(_ model: T, selectedAlbum: [String: String]) { model.id = selectedAlbum["collectionId"]! model.collectionName = selectedAlbum["collectionName"]! model.imageUrl = selectedAlbum["imageUrl"]! model.artistName = selectedAlbum["artistName"]! try! realm.write { realm.add(model, update: true) self.getAlbums("") } } func removeRealm<T: Album>(_ model: T) { try! realm.write { realm.delete(model) self.getAlbums("") } } func deleteError(_ collectionId: String) { print("Error: \(collectionId) not found") } func parseRealmToDict<T: Album>(_ model: T) -> [String: String] { return [ "collectionId": String(describing: model["id"]!), "collectionName": String(describing: model["collectionName"]!), "artistName": String(describing: model["artistName"]!), "imageUrl": String(describing: model["imageUrl"]!) ] } func setModelProp(_ model: [String: String]) -> [String: String] { return [ "collectionId": String(model["collectionId"]!), "collectionName": String(model["collectionName"]!), "artistName": String(model["artistName"]!), "imageUrl": String(model["imageUrl"]!) ] } }
mit
kdawgwilk/vapor
Tests/Vapor/ControllerTests.swift
1
6464
import XCTest @testable import Vapor private class TestController: DropletInitializable, Resource { required init(droplet: Droplet) { } var lock: ( index: Int, store: Int, show: Int, replace: Int, modify: Int, destroy: Int, destroyAll: Int, options: Int, optionsAll: Int ) = (0, 0, 0, 0, 0, 0, 0, 0, 0) func index(request: Request) throws -> Vapor.ResponseRepresentable { lock.index += 1 return "index" } func store(request: Request) throws -> Vapor.ResponseRepresentable { lock.store += 1 return "store" } func show(request: Request, item: String) throws -> Vapor.ResponseRepresentable { lock.show += 1 return "show" } func replace(request: Request, item: String) throws -> Vapor.ResponseRepresentable { lock.replace += 1 return "update" } func modify(request: Request, item: String) throws -> Vapor.ResponseRepresentable { lock.modify += 1 return "modify" } func destroy(request: Request, item: String) throws -> Vapor.ResponseRepresentable { lock.destroy += 1 return "destroy" } func destroy(request: Request) throws -> Vapor.ResponseRepresentable { lock.destroyAll += 1 return "destroy all" } func options(request: Request) throws -> Vapor.ResponseRepresentable { lock.optionsAll += 1 return "options all" } func options(request: Request, item: String) throws -> Vapor.ResponseRepresentable { lock.options += 1 return "options all" } } private class TestActionController: DefaultInitializable { static var helloRunCount = 0 let person: String init(person: String) { self.person = person } required init() { self.person = "World" } func hello(_ request: Request) throws -> Vapor.ResponseRepresentable { TestActionController.helloRunCount += 1 return "Hello, \(person)!" } } class ControllerTests: XCTestCase { static let allTests = [ ("testController", testController), ("testControllerActionRouting_withFactory", testControllerActionRouting_withFactory), ("testControllerActionRouting_withDefaultInitializable", testControllerActionRouting_withDefaultInitializable), ("testControllerActionRouting_withDropletInitializable", testControllerActionRouting_withDropletInitializable), ("testControllerMethodsHit", testControllerMethodsHit) ] func testController() throws { let drop = Droplet() let instance = TestController(droplet: drop) drop.resource("foo", makeControllerWith: { return instance }) let fooIndex = try Request(method: .get, path: "foo") if let handler = drop.router.route(fooIndex) { do { let _ = try handler.respond(to: fooIndex) XCTAssert(instance.lock.index == 1, "foo.index Lock not correct") } catch { XCTFail("foo.index handler failed") } } else { XCTFail("No handler found for foo.index") } } func testControllerActionRouting_withFactory() throws { TestActionController.helloRunCount = 0 let drop = Droplet() drop.add(.get, path: "/hello", action: TestActionController.hello) { TestActionController(person: "Tanner") } let request = try Request(method: .get, path: "hello") guard let handler = drop.router.route(request) else { XCTFail("No handler found for TestActionController.hello") return } let _ = try handler.respond(to: request) XCTAssertEqual(TestActionController.helloRunCount, 1) } func testControllerActionRouting_withDefaultInitializable() throws { TestActionController.helloRunCount = 0 let drop = Droplet() drop.add(.get, path: "/hello", action: TestActionController.hello) let request = try Request(method: .get, path: "hello") guard let handler = drop.router.route(request) else { XCTFail("No handler found for TestActionController.hello") return } let _ = try handler.respond(to: request) XCTAssertEqual(TestActionController.helloRunCount, 1) } func testControllerActionRouting_withDropletInitializable() throws { TestActionController.helloRunCount = 0 let drop = Droplet() drop.add(.get, path: "/hello", action: TestActionController.hello) let request = try Request(method: .get, path: "hello") guard let handler = drop.router.route(request) else { XCTFail("No handler found for TestController.hello") return } let _ = try handler.respond(to: request) XCTAssertEqual(TestActionController.helloRunCount, 1) } func testControllerMethodsHit() throws { let drop = Droplet() // Need single instance to test let testInstance = TestController(droplet: drop) let factory: (Void) -> TestController = { print("blahblah : \(testInstance)"); return testInstance } drop.resource("/test", makeControllerWith: factory) func handleRequest(req: Request) throws { guard let handler = drop.router.route(req) else { return } let _ = try handler.respond(to: req) } let arrayRequests: [Request] = try [.get, .post, .delete].map { return try Request(method: $0, path: "/test", host: "0.0.0.0") } try arrayRequests.forEach(handleRequest) XCTAssert(testInstance.lock.index == 1) XCTAssert(testInstance.lock.store == 1) XCTAssert(testInstance.lock.destroyAll == 1) XCTAssert(testInstance.lock.show == 0) XCTAssert(testInstance.lock.replace == 0) XCTAssert(testInstance.lock.modify == 0) XCTAssert(testInstance.lock.destroy == 0) let individualRequests: [Request] = try [.get, .post, .put, .patch, .delete].map { return try Request(method: $0, path: "test/123", host: "0.0.0.0") } try individualRequests.forEach(handleRequest) XCTAssert(testInstance.lock.show == 1) XCTAssert(testInstance.lock.replace == 1) XCTAssert(testInstance.lock.modify == 1) XCTAssert(testInstance.lock.destroy == 1) } }
mit
natecook1000/swift
test/IRGen/objc.swift
1
4710
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo // CHECK: [[TYPE:%swift.type]] = type // CHECK: [[BLAMMO:%T4objc6BlammoC]] = type // CHECK: [[MYBLAMMO:%T4objc8MyBlammoC]] = type // CHECK: [[TEST2:%T4objc5Test2C]] = type // CHECK: [[OBJC:%objc_object]] = type // CHECK: [[ID:%T4objc2idV]] = type <{ %AnyObject }> // CHECK: [[GIZMO:%TSo5GizmoC]] = type // CHECK: [[RECT:%TSo4RectV]] = type // CHECK: [[FLOAT:%TSf]] = type // CHECK: @"\01L_selector_data(bar)" = private global [4 x i8] c"bar\00", section "__TEXT,__objc_methname,cstring_literals", align 1 // CHECK: @"\01L_selector(bar)" = private externally_initialized global i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(bar)", i64 0, i64 0), section "__DATA,__objc_selrefs,literal_pointers,no_dead_strip", align 8 // CHECK: @"$SSo4RectVMn" = linkonce_odr hidden constant // CHECK: @"$SSo4RectVN" = linkonce_odr hidden constant // CHECK: @"\01L_selector_data(acquiesce)" // CHECK-NOT: @"\01L_selector_data(disharmonize)" // CHECK: @"\01L_selector_data(eviscerate)" struct id { var data : AnyObject } // Exporting something as [objc] doesn't make it an ObjC class. @objc class Blammo { } // Class and methods are [objc] by inheritance. class MyBlammo : Blammo { func foo() {} // CHECK: define hidden swiftcc void @"$S4objc8MyBlammoC3fooyyF"([[MYBLAMMO]]* swiftself) {{.*}} { // CHECK: call {{.*}} @swift_release // CHECK: ret void } // Class and methods are [objc] by inheritance. class Test2 : Gizmo { func foo() {} // CHECK: define hidden swiftcc void @"$S4objc5Test2C3fooyyF"([[TEST2]]* swiftself) {{.*}} { // CHECK: call {{.*}} @objc_release // CHECK: ret void @objc dynamic func bar() {} } // Test @nonobjc. class Contrarian : Blammo { @objc func acquiesce() {} @nonobjc func disharmonize() {} @nonobjc func eviscerate() {} } class Octogenarian : Contrarian { // Override of @nonobjc is @objc again unless made @nonobjc. @nonobjc override func disharmonize() {} // Override of @nonobjc can be @objc. @objc override func eviscerate() {} } @_silgen_name("unknown") func unknown(_ x: id) -> id // CHECK: define hidden swiftcc %objc_object* @"$S4objc5test0{{[_0-9a-zA-Z]*}}F"(%objc_object*) // CHECK-NOT: call {{.*}} @swift_unknownObjectRetain // CHECK: call {{.*}} @swift_unknownObjectRetain // CHECK-NOT: call {{.*}} @swift_unknownObjectRelease // CHECK: call {{.*}} @swift_unknownObjectRelease // CHECK: ret %objc_object* func test0(_ arg: id) -> id { var x : id x = arg unknown(x) var y = x return y } func test1(_ cell: Blammo) {} // CHECK: define hidden swiftcc void @"$S4objc5test1{{[_0-9a-zA-Z]*}}F"([[BLAMMO]]*) {{.*}} { // CHECK-NEXT: entry // CHECK-NEXT: alloca // CHECK-NEXT: bitcast // CHECK-NEXT: store // CHECK-NEXT: store // CHECK-NEXT: ret void // FIXME: These ownership convention tests should become SILGen tests. func test2(_ v: Test2) { v.bar() } func test3() -> NSObject { return Gizmo() } // Normal message send with argument, no transfers. func test5(_ g: Gizmo) { Gizmo.inspect(g) } // The argument to consume: is __attribute__((ns_consumed)). func test6(_ g: Gizmo) { Gizmo.consume(g) } // fork is __attribute__((ns_consumes_self)). func test7(_ g: Gizmo) { g.fork() } // clone is __attribute__((ns_returns_retained)). func test8(_ g: Gizmo) { g.clone() } // duplicate has an object returned at +0. func test9(_ g: Gizmo) { g.duplicate() } func test10(_ g: Gizmo, r: Rect) { Gizmo.run(with: r, andGizmo:g); } // Force the emission of the Rect metadata. func test11_helper<T>(_ t: T) {} // NSRect's metadata needs to be uniqued at runtime using getForeignTypeMetadata. // CHECK-LABEL: define hidden swiftcc void @"$S4objc6test11yySo4RectVF" // CHECK: call swiftcc %swift.metadata_response @swift_getForeignTypeMetadata(i64 %0, {{.*}} @"$SSo4RectVN" func test11(_ r: Rect) { test11_helper(r) } class WeakObjC { weak var obj: NSObject? weak var id: AnyObject? init() { var foo = obj var bar: AnyObject? = id } } // rdar://17528908 // CHECK: i32 1, !"Objective-C Version", i32 2} // CHECK: i32 1, !"Objective-C Image Info Version", i32 0} // CHECK: i32 1, !"Objective-C Image Info Section", !"__DATA,__objc_imageinfo,regular,no_dead_strip"} // 1536 == (6 << 8). 6 is the Swift ABI version. // CHECK: i32 4, !"Objective-C Garbage Collection", i32 1536} // CHECK: i32 1, !"Swift Version", i32 6}
apache-2.0
endpress/PopNetwork
PopNetwork/Source/Client.swift
1
1376
// // SessionHttpClient.swift // PopNetwork // // Created by apple on 12/7/16. // Copyright © 2016 zsc. All rights reserved. // import Foundation /// the client protocol used to sent request and handle data protocol Client { func send<T: PopRequest>(popRequest: T, dataHandler: @escaping DataHandler) } /// a session client use session to sent request protocol SessionClient: Client { var session: URLSession { get } var sessionDelegate: SessionDelegate { get } } extension SessionClient { var session: URLSession { return SessionSingleton.default } var sessionDelegate: SessionDelegate { return SessionDelegate.default } func send<T: PopRequest>(popRequest: T, dataHandler: @escaping DataHandler) { let parameterEncoder = ParameterEncoder() let encodeError = PopError.error(reason: "ParameterEncoder encode function failed") guard let request = parameterEncoder.encode(popRequest: popRequest) else { return dataHandler(Result.Faliure(error: encodeError)) } let task = session.dataTask(with: request) sessionDelegate[task] = Response(dataHandler: dataHandler) task.resume() } } struct SessionSingleton { static let `default` = URLSession(configuration: .default, delegate: SessionDelegate.default, delegateQueue: nil) }
apache-2.0
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Domain Events/Events/EventFeedbackReady.swift
1
388
extension DomainEvent { struct EventFeedbackReady { var identifier: EventIdentifier var feedback: EventFeedback var delegate: EventFeedbackDelegate var rating: Int { return feedback.starRating } var eventFeedback: String { return feedback.feedback } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/19778-swift-constraints-constraintsystem-getfixedtyperecursive.swift
11
209
// 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 { deinit { var : Int = (T: B? {
mit
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 22/SportsStore/SportsStore/ProductDataStore.swift
4
3803
import Foundation final class ProductDataStore { var callback:((Product) -> Void)?; private var networkQ:dispatch_queue_t private var uiQ:dispatch_queue_t; lazy var products:[Product] = self.loadData(); init() { networkQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0); uiQ = dispatch_get_main_queue(); } private func loadData() -> [Product] { var products = [Product](); for product in productData { var p:Product = LowStockIncreaseDecorator(product: product); if (p.category == "Soccer") { p = SoccerDecreaseDecorator(product: p); } dispatch_async(self.networkQ, {() in StockServerFactory.getStockServer().getStockLevel(p.name, callback: { name, stockLevel in p.stockLevel = stockLevel; dispatch_async(self.uiQ, {() in if (self.callback != nil) { self.callback!(p); } }) }); }); products.append(p); } return products; } private var productData:[Product] = [ ProductComposite(name: "Running Pack", description: "Complete Running Outfit", category: "Running", stockLevel: 10, products: Product.createProduct("Shirt", description: "Running Shirt", category: "Running", price: 42, stockLevel: 10), Product.createProduct("Shorts", description: "Running Shorts", category: "Running", price: 30, stockLevel: 10), Product.createProduct("Shoes", description: "Running Shoes", category: "Running", price: 120, stockLevel: 10), ProductComposite(name: "Headgear", description: "Hat, etc", category: "Running", stockLevel: 10, products: Product.createProduct("Hat", description: "Running Hat", category: "Running", price: 10, stockLevel: 10), Product.createProduct("Sunglasses", description: "Glasses", category: "Running", price: 10, stockLevel: 10)) ), Product.createProduct("Kayak", description:"A boat for one person", category:"Watersports", price:275.0, stockLevel:0), Product.createProduct("Lifejacket", description:"Protective and fashionable", category:"Watersports", price:48.95, stockLevel:0), Product.createProduct("Soccer Ball", description:"FIFA-approved size and weight", category:"Soccer", price:19.5, stockLevel:0), Product.createProduct("Corner Flags", description:"Give your playing field a professional touch", category:"Soccer", price:34.95, stockLevel:0), Product.createProduct("Stadium", description:"Flat-packed 35,000-seat stadium", category:"Soccer", price:79500.0, stockLevel:0), Product.createProduct("Thinking Cap", description:"Improve your brain efficiency", category:"Chess", price:16.0, stockLevel:0), Product.createProduct("Unsteady Chair", description:"Secretly give your opponent a disadvantage", category: "Chess", price: 29.95, stockLevel:0), Product.createProduct("Human Chess Board", description:"A fun game for the family", category:"Chess", price:75.0, stockLevel:0), Product.createProduct("Bling-Bling King", description:"Gold-plated, diamond-studded King", category:"Chess", price:1200.0, stockLevel:0)]; }
mit
Zuikyo/ZIKRouter
ZRouterTests/BSubview.swift
1
2541
// // BSubview.swift // ZRouterTests // // Created by zuik on 2018/4/28. // Copyright © 2018 zuik. All rights reserved. // import UIKit import ZRouter import ZIKRouter import ZIKRouter.Internal class BSubview: UIView { var title: String? } protocol BSubviewInput: class { var title: String? { get set } } extension BSubview: ZIKRoutableView, BSubviewInput { } extension RoutableView where Protocol == BSubviewInput { init() { self.init(declaredProtocol: Protocol.self) } } protocol BSubviewModuleInput: class { var title: String? { get set } func makeDestinationCompletion(_ block: @escaping (BSubviewInput) -> Void) } extension RoutableViewModule where Protocol == BSubviewModuleInput { init() { self.init(declaredProtocol: Protocol.self) } } class BSubviewModuleConfiguration: ZIKViewRouteConfiguration, BSubviewModuleInput { var completion: ((BSubviewInput) -> Void)? var title: String? func makeDestinationCompletion(_ block: @escaping (BSubviewInput) -> Void) { completion = block } override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! BSubviewModuleConfiguration copy.title = self.title return copy } } class BSubviewRouter: ZIKViewRouter<BSubview, BSubviewModuleConfiguration> { override class func registerRoutableDestination() { registerView(BSubview.self) if !TEST_BLOCK_ROUTE { register(RoutableView<BSubviewInput>()) register(RoutableViewModule<BSubviewModuleInput>()) } } override class func defaultRouteConfiguration() -> BSubviewModuleConfiguration { return BSubviewModuleConfiguration() } override class func supportedRouteTypes() -> ZIKViewRouteTypeMask { return .viewDefault } override func destination(with configuration: BSubviewModuleConfiguration) -> BSubview? { if TestConfig.routeShouldFail { return nil } return BSubview() } override func prepareDestination(_ destination: BSubview, configuration: BSubviewModuleConfiguration) { if let title = configuration.title { destination.title = title } } override func didFinishPrepareDestination(_ destination: BSubview, configuration: BSubviewModuleConfiguration) { if let completion = configuration.completion { completion(destination) configuration.completion = nil } } }
mit
tsc000/SCCycleScrollView
SCCycleScrollView/SCCycleScrollView/CustomCell/CustomCollectionViewCell.swift
1
1131
// // CustomCollectionViewCell.swift // SCCycleScrollView // // Created by tongshichao on 2018/11/28. // Copyright © 2018 童世超. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) initial() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initial() { imageView.frame = CGRect(x: 5, y: 5, width: self.frame.width - 10, height: self.frame.height - 10) titleLabel.center = imageView.center } private lazy var titleLabel: UILabel! = { let titleLabel = UILabel() titleLabel.text = "自定义ell" titleLabel.textAlignment = .left contentView.addSubview(titleLabel) titleLabel.sizeToFit() return titleLabel }() private lazy var imageView: UIImageView! = { let imageView = UIImageView() imageView.backgroundColor = UIColor.orange contentView.addSubview(imageView) return imageView }() }
mit
huangboju/Moots
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Post/PostDetailHeader.swift
1
917
// // PostDetailHeader.swift // RedditOs // // Created by Thomas Ricouard on 10/07/2020. // import SwiftUI import Backend import KingfisherSwiftUI struct PostDetailHeader: View { let listing: SubredditPost var body: some View { HStack { Text(listing.title) .font(.title) .lineLimit(5) .multilineTextAlignment(.leading) .truncationMode(.tail) if let url = listing.thumbnailURL, url.pathExtension != "jpg", url.pathExtension != "png" { KFImage(url) .frame(width: 80, height: 60) .aspectRatio(contentMode: .fit) .cornerRadius(8) } Spacer() } } } struct PostDetailHeader_Previews: PreviewProvider { static var previews: some View { PostDetailHeader(listing: static_listing) } }
mit
snazzware/Mergel
HexMatch/HexMap/HexCell.swift
2
9324
// // HexCell.swift // HexMatch // // Created by Josh McKee on 1/12/16. // Copyright © 2016 Josh McKee. All rights reserved. // import Foundation enum HexCellDirection { case north, south, northEast, northWest, southEast, southWest static let allDirections = [north, south, northEast, northWest, southEast, southWest] } enum MergeStyle : String { case Liner = "Liner" case Cluster = "Cluster" } class HexCell : NSObject, NSCoding { //var x: Int //var y: Int var position: HCPosition var isVoid = false var mergeStyle: MergeStyle = .Cluster var hexMap: HexMap var _hexPiece: HexPiece? var hexPiece: HexPiece? { get { return self._hexPiece } set { // unlink any existing piece if (self._hexPiece != nil) { self._hexPiece!.hexCell = nil } // update value self._hexPiece = newValue // link to new piece if (self._hexPiece != nil) { self._hexPiece!.hexCell = self // map is no longer blank self.hexMap.isBlank = false } } } init(_ map: HexMap, _ x: Int, _ y: Int) { self.position = HCPosition(x, y) self.hexMap = map } func getCellByDirection(_ direction: HexCellDirection) -> HexCell? { switch direction { case HexCellDirection.north: return self.north case HexCellDirection.south: return self.south case HexCellDirection.southEast: return self.southEast case HexCellDirection.southWest: return self.southWest case HexCellDirection.northEast: return self.northEast case HexCellDirection.northWest: return self.northWest } } var north:HexCell? { get { return self.hexMap.cell(self.position.north) } } var northEast:HexCell? { get { return self.hexMap.cell(self.position.northEast) } } var northWest:HexCell? { get { return self.hexMap.cell(self.position.northWest) } } var south:HexCell? { get { return self.hexMap.cell(self.position.south) } } var southEast:HexCell? { get { return self.hexMap.cell(self.position.southEast) } } var southWest:HexCell? { get { return self.hexMap.cell(self.position.southWest) } } override var description: String { return "HexCell \(self.position)" } /** Determines if this cell will accept a given HexPiece - Parameters: - hexPiece: The piece to be tested - Returns: True if this cell will accept the piece, false otherwise */ func willAccept(_ hexPiece: HexPiece) -> Bool { return self.isOpen() } func isOpen() -> Bool { return (!self.isVoid && self.hexPiece == nil) } /** Recursively checks for valid merges in every direction for a given HexPiece, skipping cells which have already been checked as part of the current recursion. */ func getClusterMerges(_ hexPiece: HexPiece, _ visitedCells: [HexCell]) -> [HexPiece] { var merges: [HexPiece] = Array() var localVisitedCells = visitedCells for direction in HexCellDirection.allDirections { let targetCell = self.getCellByDirection(direction) if (targetCell != nil && !localVisitedCells.contains(targetCell!)) { localVisitedCells.append(targetCell!) if (targetCell != nil && targetCell!.hexPiece != nil && targetCell!.hexPiece!.canMergeWithPiece(hexPiece) && hexPiece.canMergeWithPiece(targetCell!.hexPiece!)) { merges.append(targetCell!.hexPiece!) merges += targetCell!.getClusterMerges(hexPiece, localVisitedCells) } } } return merges } /** Iterates over each direction from this cell, looking for runs of pieces which canMergeWithPiece(hexPiece) is true. If a merge is detected, the function recurses to detect further matches with the incremented value piece. - Parameters: - hexPiece: The piece to be tested - Returns: Set of HexPieces which would be merged (if any), or empty if none */ func getWouldMergeWith(_ hexPiece: HexPiece) -> [HexPiece] { var merges: [HexPiece] = Array() // Number of same pieces we found searching all directions var samePieceCount = 0 let firstValue = hexPiece.getMinMergeValue() let lastValue = hexPiece.getMaxMergeValue() var neighborValues: [Int] = Array() // Get values of all of our neighbors, for iteration, where value is between our piece's firstValue and lastValue for direction in HexCellDirection.allDirections { let targetCell = self.getCellByDirection(direction) if (targetCell != nil && targetCell!.hexPiece != nil && !neighborValues.contains(targetCell!.hexPiece!.value) && (firstValue <= targetCell!.hexPiece!.value && lastValue >= targetCell!.hexPiece!.value)) { neighborValues.append(targetCell!.hexPiece!.value) } } // Sort ascending neighborValues = neighborValues.sorted { $0 < $1 } // Get last (largest) value var value = neighborValues.popLast() // Loop over possible values for the piece being placed, starting with highest, until we find a merge while (samePieceCount<2 && value != nil) { merges.removeAll() samePieceCount = 0 hexPiece.value = value! switch (self.mergeStyle) { case .Liner: // Iterate over all directions, following each direction as long as there is a matching piece value for direction in HexCellDirection.allDirections { var targetCell = self.getCellByDirection(direction) while (targetCell != nil && targetCell!.hexPiece != nil && targetCell!.hexPiece!.canMergeWithPiece(hexPiece) && hexPiece.canMergeWithPiece(targetCell!.hexPiece!)) { merges.append(targetCell!.hexPiece!) samePieceCount += 1 targetCell = targetCell!.getCellByDirection(direction) } } break case .Cluster: var visitedCells: [HexCell] = Array() // Prevent visiting self visitedCells.append(self) // Recurse and find merges merges += self.getClusterMerges(hexPiece, visitedCells) samePieceCount = merges.count break } value = neighborValues.popLast() } // If we didn't get at least two of the same piece, clear our merge array if (samePieceCount < 2) { merges.removeAll() } else { // If we DID get at least two, recurse with the new piece if (hexPiece.value<HexMapHelper.instance.maxPieceValue) { if (hexPiece is WildcardHexPiece) { // create a copy if we're dealing with a wildcard let mergedPiece = HexPiece() mergedPiece.value = hexPiece.value+1 merges += self.getWouldMergeWith(mergedPiece) } else { // try next merge with updated value hexPiece.updateValueForMergeTest() merges += self.getWouldMergeWith(hexPiece) hexPiece.rollbackValueForMergeTest() } } } return merges } required convenience init?(coder decoder: NSCoder) { let x = decoder.decodeInteger(forKey: "x") let y = decoder.decodeInteger(forKey: "y") let hexMap = (decoder.decodeObject(forKey: "hexMap") as? HexMap)! self.init(hexMap, x, y) self.isVoid = decoder.decodeBool(forKey: "isVoid") self.mergeStyle = MergeStyle(rawValue: (decoder.decodeObject(forKey: "mergeStyle") as! String))! self.hexPiece = (decoder.decodeObject(forKey: "hexPiece") as? HexPiece) } func encode(with coder: NSCoder) { coder.encode(self.position.x, forKey: "x") coder.encode(self.position.y, forKey: "y") coder.encode(self.hexMap, forKey: "hexMap") coder.encode(self.isVoid, forKey: "isVoid") coder.encode(self.mergeStyle.rawValue, forKey: "mergeStyle") coder.encode(self.hexPiece, forKey: "hexPiece") } }
mit
huonw/swift
validation-test/compiler_crashers_fixed/01852-swift-constraints-constraintsystem-getconstraintlocator.swift
65
461
// 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 // RUN: not %target-swift-frontend %s -typecheck class a)) { } var f = a() protocol A { func a) typealias f : a
apache-2.0
noppoMan/aws-sdk-swift
Sources/Soto/Services/MigrationHubConfig/MigrationHubConfig_Error.swift
1
3024
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for MigrationHubConfig public struct MigrationHubConfigErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case dryRunOperation = "DryRunOperation" case internalServerError = "InternalServerError" case invalidInputException = "InvalidInputException" case serviceUnavailableException = "ServiceUnavailableException" case throttlingException = "ThrottlingException" } private let error: Code public let context: AWSErrorContext? /// initialize MigrationHubConfig public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// You do not have sufficient access to perform this action. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// Exception raised to indicate that authorization of an action was successful, when the DryRun flag is set to true. public static var dryRunOperation: Self { .init(.dryRunOperation) } /// Exception raised when an internal, configuration, or dependency error is encountered. public static var internalServerError: Self { .init(.internalServerError) } /// Exception raised when the provided input violates a policy constraint or is entered in the wrong format or data type. public static var invalidInputException: Self { .init(.invalidInputException) } /// Exception raised when a request fails due to temporary unavailability of the service. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } /// The request was denied due to request throttling. public static var throttlingException: Self { .init(.throttlingException) } } extension MigrationHubConfigErrorType: Equatable { public static func == (lhs: MigrationHubConfigErrorType, rhs: MigrationHubConfigErrorType) -> Bool { lhs.error == rhs.error } } extension MigrationHubConfigErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
dpereira411/GCTabView
GCTabView-swift/AppDelegate.swift
1
518
// // AppDelegate.swift // GCTabView-swift // // Created by Daniel Pereira on 13/11/14. // Copyright (c) 2014 Daniel Pereira. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
mit
grpc/grpc-swift
Sources/GRPC/ClientCalls/LazyEventLoopPromise.swift
1
3420
/* * 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 NIOConcurrencyHelpers import NIOCore extension EventLoop { internal func makeLazyPromise<Value>(of: Value.Type = Value.self) -> LazyEventLoopPromise<Value> { return LazyEventLoopPromise(on: self) } } /// A `LazyEventLoopPromise` is similar to an `EventLoopPromise` except that the underlying /// `EventLoopPromise` promise is only created if it is required. That is, when the future result /// has been requested and the promise has not yet been completed. /// /// Note that all methods **must** be called from its `eventLoop`. internal struct LazyEventLoopPromise<Value> { private enum State { // No future has been requested, no result has been delivered. case idle // No future has been requested, but this result have been delivered. case resolvedResult(Result<Value, Error>) // A future has been request; the promise may or may not contain a result. case unresolvedPromise(EventLoopPromise<Value>) // A future was requested, it's also been resolved. case resolvedFuture(EventLoopFuture<Value>) } private var state: State private let eventLoop: EventLoop fileprivate init(on eventLoop: EventLoop) { self.state = .idle self.eventLoop = eventLoop } /// Get the future result of this promise. internal mutating func getFutureResult() -> EventLoopFuture<Value> { self.eventLoop.preconditionInEventLoop() switch self.state { case .idle: let promise = self.eventLoop.makePromise(of: Value.self) self.state = .unresolvedPromise(promise) return promise.futureResult case let .resolvedResult(result): let future: EventLoopFuture<Value> switch result { case let .success(value): future = self.eventLoop.makeSucceededFuture(value) case let .failure(error): future = self.eventLoop.makeFailedFuture(error) } self.state = .resolvedFuture(future) return future case let .unresolvedPromise(promise): return promise.futureResult case let .resolvedFuture(future): return future } } /// Succeed the promise with the given value. internal mutating func succeed(_ value: Value) { self.completeWith(.success(value)) } /// Fail the promise with the given error. internal mutating func fail(_ error: Error) { self.completeWith(.failure(error)) } /// Complete the promise with the given result. internal mutating func completeWith(_ result: Result<Value, Error>) { self.eventLoop.preconditionInEventLoop() switch self.state { case .idle: self.state = .resolvedResult(result) case let .unresolvedPromise(promise): promise.completeWith(result) self.state = .resolvedFuture(promise.futureResult) case .resolvedResult, .resolvedFuture: () } } }
apache-2.0
jpush/jchat-swift
JChat/Src/UserModule/ViewController/JCRegisterInfoViewController.swift
1
9255
// // JCRegisterInfoViewController.swift // JChat // // Created by JIGUANG on 2017/5/12. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import JMessage class JCRegisterInfoViewController: UIViewController { var username: String! var password: String! //MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() _init() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.setStatusBarStyle(.lightContent, animated: false) self.navigationController?.setNavigationBarHidden(false, animated: false) } private lazy var nicknameTextField: UITextField = { var textField = UITextField() textField.addTarget(self, action: #selector(textFieldDidChanged(_ :)), for: .editingChanged) textField.clearButtonMode = .whileEditing textField.placeholder = "请输入昵称" textField.font = UIFont.systemFont(ofSize: 16) textField.frame = CGRect(x: 38 + 40 + 15, y: 64 + 40 + 80 + 40, width: self.view.width - 76 - 38, height: 40) return textField }() fileprivate lazy var avatorView: UIImageView = { var avatorView = UIImageView() avatorView.isUserInteractionEnabled = true avatorView.frame = CGRect(x: self.view.centerX - 40, y: 64 + 40, width: 80, height: 80) avatorView.image = UIImage.loadImage("com_icon_upload") let tapGR = UITapGestureRecognizer(target: self, action: #selector(_tapHandler)) avatorView.addGestureRecognizer(tapGR) return avatorView }() private lazy var registerButton: UIButton = { var button = UIButton() button.backgroundColor = UIColor(netHex: 0x2DD0CF) let button_y = 64 + 40 + 80 + 40 + 40 + 38 let button_width = Int(self.view.width - 76) button.frame = CGRect(x: 38, y: button_y, width: button_width, height: 40) button.setTitle("完成", for: .normal) button.layer.cornerRadius = 3.0 button.layer.masksToBounds = true button.addTarget(self, action: #selector(_userRegister), for: .touchUpInside) return button }() fileprivate lazy var tipsLabel: UILabel = { let tipsLabel = UILabel() tipsLabel.frame = CGRect(x: 38, y: 64 + 40 + 80 + 40 + 11 , width: 40, height: 18) tipsLabel.text = "昵称" tipsLabel.font = UIFont.systemFont(ofSize: 16) tipsLabel.textColor = UIColor(netHex: 0x999999) return tipsLabel }() fileprivate lazy var usernameLine: UILabel = { var line = UILabel() line.backgroundColor = UIColor(netHex: 0xD2D2D2) line.alpha = 0.4 line.frame = CGRect(x: 38, y: self.nicknameTextField.y + 40, width: self.view.width - 76, height: 2) return line }() fileprivate lazy var imagePicker: UIImagePickerController = { var picker = UIImagePickerController() picker.sourceType = .camera picker.cameraCaptureMode = .photo picker.delegate = self return picker }() fileprivate var image: UIImage? //MARK: - private func private func _init() { self.title = "补充信息" view.backgroundColor = .white navigationController?.setNavigationBarHidden(false, animated: false) navigationController?.interactivePopGestureRecognizer?.isEnabled = true nicknameTextField.addTarget(self, action: #selector(textFieldDidChanged(_ :)), for: .editingChanged) view.addSubview(avatorView) view.addSubview(nicknameTextField) view.addSubview(registerButton) view.addSubview(tipsLabel) view.addSubview(usernameLine) let tap = UITapGestureRecognizer(target: self, action: #selector(_tapView)) view.addGestureRecognizer(tap) } @objc func textFieldDidChanged(_ textField: UITextField) { if textField.markedTextRange == nil { let text = textField.text! if text.count > 30 { let range = (text.startIndex ..< text.index(text.startIndex, offsetBy: 30)) //let range = Range<String.Index>(text.startIndex ..< text.index(text.startIndex, offsetBy: 30)) let subText = text.substring(with: range) textField.text = subText } } } @objc func _tapView() { view.endEditing(true) } @objc func _tapHandler() { view.endEditing(true) let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: " 从相册中选择", "拍照") actionSheet.tag = 1001 actionSheet.show(in: self.view) } //MARK: - click event @objc func _userRegister() { MBProgressHUD_JChat.showMessage(message: "保存中", toView: self.view) userLogin(withUsername: self.username, password: self.password) } private func userLogin(withUsername: String, password: String) { JMSGUser.login(withUsername: self.username, password: self.password) { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error == nil { self.setupNickname() self.uploadImage() UserDefaults.standard.set(self.username, forKey: kLastUserName) UserDefaults.standard.set(self.username, forKey: kCurrentUserName) let appDelegate = UIApplication.shared.delegate let window = appDelegate?.window! window?.rootViewController = JCMainTabBarController() } else { MBProgressHUD_JChat.show(text: "登录失败", view: self.view) } } } private func setupNickname() { JMSGUser.updateMyInfo(withParameter: self.nicknameTextField.text!, userFieldType: .fieldsNickname) { (resultObject, error) -> Void in if error == nil { NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateUserInfo), object: nil) } else { print("error:\(String(describing: error?.localizedDescription))") } } } private func uploadImage() { if let image = image { let imageData = image.jpegData(compressionQuality: 0.8) JMSGUser.updateMyInfo(withParameter: imageData!, userFieldType: .fieldsAvatar, completionHandler: { (result, error) in if error == nil { let avatorData = NSKeyedArchiver.archivedData(withRootObject: imageData!) UserDefaults.standard.set(avatorData, forKey: kLastUserAvator) NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateUserInfo), object: nil) } }) } else { UserDefaults.standard.removeObject(forKey: kLastUserAvator) } } } extension JCRegisterInfoViewController: UIActionSheetDelegate { func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { switch buttonIndex { case 1: // 从相册中选择 let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary let temp_mediaType = UIImagePickerController.availableMediaTypes(for: picker.sourceType) picker.mediaTypes = temp_mediaType! picker.modalTransitionStyle = .coverVertical self.present(picker, animated: true, completion: nil) case 2: // 拍照 present(imagePicker, animated: true, completion: nil) default: break } } } extension JCRegisterInfoViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { // MARK: - UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) var image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage? image = image?.fixOrientation() self.image = image avatorView.image = image picker.dismiss(animated: true, completion: nil) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
mit
melvitax/AFDateHelper
Documentation/Playground.playground/Pages/Adjusting Dates.xcplaygroundpage/Contents.swift
1
860
//: [Previous](@previous) import DateHelper /*: # Adjusting Dates Provides two functions for adjusting dates */ /*: **1. adjust(_ component:, offset:)** `func adjust(_ component:DateComponentType, offset:Int) -> Date ` */ Date().adjust(.second, offset: 110) Date().adjust(.minute, offset: 60) Date().adjust(.hour, offset: 2) Date().adjust(.day, offset: 1) Date().adjust(.weekday, offset: 2) Date().adjust(.nthWeekday, offset: 1) Date().adjust(.week, offset: 1) Date().adjust(.month, offset: 1) Date().adjust(.year, offset: 1) /*: ### Component types * second * minute * hour * day * weekday * nthWeekday * week * month * year */ /*: --- 2. adjust(hour:minute:second:) `func adjust(hour: Int?, minute: Int?, second: Int?, day: Int? = nil, month: Int? = nil) -> Date ` */ Date().adjust(hour: 12, minute: 0, second: 0) //: [Next](@next)
mit
grpc/grpc-swift
Performance/QPSBenchmark/Sources/QPSBenchmark/Runtime/NIO/NIOQPSClientImpl.swift
1
10908
/* * 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 Atomics import BenchmarkUtils import Foundation import GRPC import Logging import NIOConcurrencyHelpers import NIOCore import NIOPosix /// Client to make a series of asynchronous calls. final class NIOQPSClientImpl<RequestMakerType: NIORequestMaker>: NIOQPSClient { private let eventLoopGroup: MultiThreadedEventLoopGroup private let threadCount: Int private let logger = Logger(label: "NIOQPSClientImpl") private let channelRepeaters: [ChannelRepeater] private var statsPeriodStart: DispatchTime private var cpuStatsPeriodStart: CPUTime /// Initialise a client to send requests. /// - parameters: /// - config: Config from the driver specifying how the client should behave. init(config: Grpc_Testing_ClientConfig) throws { // Parse possible invalid targets before code with side effects. let serverTargets = try config.parsedServerTargets() precondition(serverTargets.count > 0) // Setup threads let threadCount = config.threadsToUse() self.threadCount = threadCount self.logger.info("Sizing NIOQPSClientImpl", metadata: ["threads": "\(threadCount)"]) let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: threadCount) self.eventLoopGroup = eventLoopGroup // Start recording stats. self.statsPeriodStart = grpcTimeNow() self.cpuStatsPeriodStart = getResourceUsage() let requestMessage = try NIOQPSClientImpl .makeClientRequest(payloadConfig: config.payloadConfig) // Start the requested number of channels. self.channelRepeaters = (0 ..< Int(config.clientChannels)).map { channelNumber in ChannelRepeater( target: serverTargets[channelNumber % serverTargets.count], requestMessage: requestMessage, config: config, eventLoop: eventLoopGroup.next() ) } // Start the train. for channelRepeater in self.channelRepeaters { channelRepeater.start() } } /// Send current status back to the driver process. /// - parameters: /// - reset: Should the stats reset after being sent. /// - context: Calling context to allow results to be sent back to the driver. func sendStatus(reset: Bool, context: StreamingResponseCallContext<Grpc_Testing_ClientStatus>) { let currentTime = grpcTimeNow() let currentResourceUsage = getResourceUsage() var result = Grpc_Testing_ClientStatus() result.stats.timeElapsed = (currentTime - self.statsPeriodStart).asSeconds() result.stats.timeSystem = currentResourceUsage.systemTime - self.cpuStatsPeriodStart .systemTime result.stats.timeUser = currentResourceUsage.userTime - self.cpuStatsPeriodStart.userTime result.stats.cqPollCount = 0 // Collect stats from each of the channels. var latencyHistogram = Histogram() var statusCounts = StatusCounts() for channelRepeater in self.channelRepeaters { let stats = channelRepeater.getStats(reset: reset) try! latencyHistogram.merge(source: stats.latencies) statusCounts.merge(source: stats.statuses) } result.stats.latencies = Grpc_Testing_HistogramData(from: latencyHistogram) result.stats.requestResults = statusCounts.toRequestResultCounts() self.logger.info("Sending client status") _ = context.sendResponse(result) if reset { self.statsPeriodStart = currentTime self.cpuStatsPeriodStart = currentResourceUsage } } /// Shutdown the service. /// - parameters: /// - callbackLoop: Which eventloop should be called back on completion. /// - returns: A future on the `callbackLoop` which will succeed on completion of shutdown. func shutdown(callbackLoop: EventLoop) -> EventLoopFuture<Void> { let stoppedFutures = self.channelRepeaters.map { repeater in repeater.stop() } let allStopped = EventLoopFuture.andAllComplete(stoppedFutures, on: callbackLoop) return allStopped.flatMap { _ in let promise: EventLoopPromise<Void> = callbackLoop.makePromise() self.eventLoopGroup.shutdownGracefully { error in if let error = error { promise.fail(error) } else { promise.succeed(()) } } return promise.futureResult } } /// Make a request which can be sent to the server. private static func makeClientRequest(payloadConfig: Grpc_Testing_PayloadConfig) throws -> Grpc_Testing_SimpleRequest { if let payload = payloadConfig.payload { switch payload { case .bytebufParams: throw GRPCStatus(code: .invalidArgument, message: "Byte buffer not supported.") case let .simpleParams(simpleParams): var result = Grpc_Testing_SimpleRequest() result.responseType = .compressable result.responseSize = simpleParams.respSize result.payload.type = .compressable let size = Int(simpleParams.reqSize) let body = Data(count: size) result.payload.body = body return result case .complexParams: throw GRPCStatus( code: .invalidArgument, message: "Complex params not supported." ) } } else { // Default - simple proto without payloads. var result = Grpc_Testing_SimpleRequest() result.responseType = .compressable result.responseSize = 0 result.payload.type = .compressable return result } } /// Class to manage a channel. Repeatedly makes requests on that channel and records what happens. private class ChannelRepeater { private let channel: GRPCChannel private let eventLoop: EventLoop private let maxPermittedOutstandingRequests: Int private let stats: StatsWithLock /// Succeeds after a stop has been requested and all outstanding requests have completed. private var stopComplete: EventLoopPromise<Void> private let running = ManagedAtomic<Bool>(false) private let outstanding = ManagedAtomic<Int>(0) private var requestMaker: RequestMakerType init( target: ConnectionTarget, requestMessage: Grpc_Testing_SimpleRequest, config: Grpc_Testing_ClientConfig, eventLoop: EventLoop ) { self.eventLoop = eventLoop // 'try!' is fine; it'll only throw if we can't make an SSL context // TODO: Support TLS if requested. self.channel = try! GRPCChannelPool.with( target: target, transportSecurity: .plaintext, eventLoopGroup: eventLoop ) let logger = Logger(label: "ChannelRepeater") let client = Grpc_Testing_BenchmarkServiceNIOClient(channel: self.channel) self.maxPermittedOutstandingRequests = Int(config.outstandingRpcsPerChannel) self.stopComplete = eventLoop.makePromise() self.stats = StatsWithLock() self.requestMaker = RequestMakerType( config: config, client: client, requestMessage: requestMessage, logger: logger, stats: self.stats ) } /// Launch as many requests as allowed on the channel. Must only be called once. private func launchRequests() { // The plan here is: // - store the max number of outstanding requests in an atomic // - start that many requests asynchronously // - when a request finishes it will either start a new request or decrement the // the atomic counter (if we've been told to stop) // - if the counter drops to zero we're finished. let exchangedRunning = self.running.compareExchange( expected: false, desired: true, ordering: .relaxed ) precondition(exchangedRunning.exchanged, "launchRequests should only be called once") // We only decrement the outstanding count when running has been changed back to false. let exchangedOutstanding = self.outstanding.compareExchange( expected: 0, desired: self.maxPermittedOutstandingRequests, ordering: .relaxed ) precondition(exchangedOutstanding.exchanged, "launchRequests should only be called once") for _ in 0 ..< self.maxPermittedOutstandingRequests { self.requestMaker.makeRequest().whenComplete { _ in self.makeRequest() } } } private func makeRequest() { if self.running.load(ordering: .relaxed) { self.requestMaker.makeRequest().whenComplete { _ in self.makeRequest() } } else if self.outstanding.loadThenWrappingDecrement(ordering: .relaxed) == 1 { self.stopIsComplete() } // else we're no longer running but not all RPCs have finished. } /// Get stats for sending to the driver. /// - parameters: /// - reset: Should the stats reset after copying. /// - returns: The statistics for this channel. func getStats(reset: Bool) -> Stats { return self.stats.copyData(reset: reset) } /// Start sending requests to the server. func start() { self.launchRequests() } private func stopIsComplete() { // Close the connection then signal done. self.channel.close().cascade(to: self.stopComplete) } /// Stop sending requests to the server. /// - returns: A future which can be waited on to signal when all activity has ceased. func stop() -> EventLoopFuture<Void> { self.requestMaker.requestStop() self.running.store(false, ordering: .relaxed) return self.stopComplete.futureResult } } } /// Create an asynchronous client of the requested type. /// - parameters: /// - config: Description of the client required. /// - returns: The client created. func makeAsyncClient(config: Grpc_Testing_ClientConfig) throws -> NIOQPSClient { switch config.rpcType { case .unary: return try NIOQPSClientImpl<NIOUnaryRequestMaker>(config: config) case .streaming: return try NIOQPSClientImpl<NIOPingPongRequestMaker>(config: config) case .streamingFromClient: throw GRPCStatus(code: .unimplemented, message: "Client Type not implemented") case .streamingFromServer: throw GRPCStatus(code: .unimplemented, message: "Client Type not implemented") case .streamingBothWays: throw GRPCStatus(code: .unimplemented, message: "Client Type not implemented") case .UNRECOGNIZED: throw GRPCStatus(code: .invalidArgument, message: "Unrecognised client rpc type") } }
apache-2.0
lp1994428/TextKitch
TextKitchen/TextKitchen/classes/Ingredients/Recommend/View/IngreSceneLsitCell.swift
1
1524
// // IngreSceneLsitCell.swift // TextKitchen // // Created by 罗平 on 2016/10/28. // Copyright © 2016年 罗平. All rights reserved. // import UIKit class IngreSceneLsitCell: UITableViewCell { var jumpClosure:IngreJumpClosure? var listModel:IngreRecommendWidgeList?{ didSet{ config(listModel?.title) } } @IBOutlet weak var titleLabel: UILabel! func config(text:String?) { titleLabel.text = text } override func awakeFromNib() { super.awakeFromNib() // Initialization code let g = UITapGestureRecognizer(target: self, action: #selector(tapClick)) addGestureRecognizer(g) } func tapClick() { if jumpClosure != nil && listModel?.title_link != nil{ jumpClosure!((listModel?.title_link)!) } } class func createSceneList(tableView:UITableView,index:NSIndexPath,listModel:IngreRecommendWidgeList?)-> IngreSceneLsitCell{ let cellId = "IngreSceneLsitCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? IngreSceneLsitCell if nil == cell{ cell = NSBundle.mainBundle().loadNibNamed("IngreSceneLsitCell", owner: nil, options: nil).last as? IngreSceneLsitCell } cell?.listModel = listModel return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
IBM-Bluemix/hear-the-buzz
client/hear-the-buzz/JSONParser.swift
1
2519
// Copyright 2015 IBM Corp. 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 class JSONParser { func titlesFromJSON(data: NSData) -> [Tweet] { var titles = [String]() var tweetsData = [Tweet]() do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) let tweets = json["tweets"] as? [[String: AnyObject]] for tweet in tweets! { if let message = tweet["message"] as? [String: AnyObject], body = message["body"] as? String { titles.append(body) let tweetData:Tweet = Tweet(); tweetData.message = body tweetData.message = tweetData.message.stringByReplacingOccurrencesOfString("\n", withString: "") if let link = message["link"] as? String { tweetData.link = link } if let actor = message["actor"] as? [String: AnyObject], displayName = actor["displayName"] as? String { tweetData.authorName = displayName if var image = actor["image"] as? String { image = image.stringByReplacingOccurrencesOfString("_normal", withString: "") tweetData.authorPictureUrl = image } } tweetsData.append(tweetData) } } } catch { let logger = IMFLogger(forName:"hear-the-buzz") IMFLogger.setLogLevel(IMFLogLevel.Info) logger.logInfoWithMessages("Error when parsing JSON from Twitter: \(error)") } return tweetsData } }
apache-2.0
breadwallet/breadwallet-ios
breadwallet/src/Platform/BRWebViewController.swift
1
17784
// // BRWebViewController.swift // BreadWallet // // Created by Samuel Sutch on 12/10/15. // Copyright (c) 2016-2019 Breadwinner AG. All rights reserved. // import Foundation import UIKit import WebKit open class BRWebViewController: UIViewController, WKNavigationDelegate, BRWebSocketClient { var wkProcessPool: WKProcessPool var webView: WKWebView? var bundleName: String var server = BRHTTPServer() var debugEndpoint: String? var mountPoint: String var walletAuthenticator: TransactionAuthenticator var didClose: (() -> Void)? // bonjour debug endpoint establishment - this will configure the debugEndpoint // over bonjour if debugOverBonjour is set to true. this MUST be set to false // for production deploy targets let debugOverBonjour = false let bonjourBrowser = Bonjour() var debugNetService: NetService? // didLoad should be set to true within didLoadTimeout otherwise a view will be shown which // indicates some error. this is to prevent the white-screen-of-death where there is some // javascript exception (or other error) that prevents the content from loading var didLoad = false var didAppear = false var didLoadTimeout = 2500 // we are also a socket server which sends didview/didload events to the listening client(s) var sockets = [String: BRWebSocket]() // this is the data that occasionally gets sent to the above connected sockets var webViewInfo: [String: Any] { return [ "visible": didAppear, "loaded": didLoad ] } var indexUrl: URL { return URL(string: "http://127.0.0.1:\(server.port)\(mountPoint)")! } // Sometimes the webview will open partner widgets. This is the list of hosts the webview will allow. private let hostAllowList: [String] = ["trade-ui.sandbox.coinify.com", "trade-ui.coinify.com", "coinify.lon.netverify.com", "coinify-sandbox.lon.netverify.com", "pay.testwyre.com", "pay.sendwyre.com"] private let messageUIPresenter = MessageUIPresenter() private var notificationObservers = [String: NSObjectProtocol]() private var system: CoreSystem? init(bundleName: String, mountPoint: String = "/", walletAuthenticator: TransactionAuthenticator, system: CoreSystem? = nil) { wkProcessPool = WKProcessPool() self.bundleName = bundleName self.mountPoint = mountPoint self.walletAuthenticator = walletAuthenticator self.system = system super.init(nibName: nil, bundle: nil) if debugOverBonjour { setupBonjour() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { notificationObservers.values.forEach { observer in NotificationCenter.default.removeObserver(observer) } stopServer() } override open func loadView() { didLoad = false let config = WKWebViewConfiguration() config.processPool = wkProcessPool config.allowsInlineMediaPlayback = false config.allowsAirPlayForMediaPlayback = false config.mediaTypesRequiringUserActionForPlayback = .all config.allowsPictureInPictureMediaPlayback = false let request = URLRequest(url: indexUrl) view = UIView(frame: CGRect.zero) view.backgroundColor = .darkBackground webView = WKWebView(frame: CGRect.zero, configuration: config) webView?.navigationDelegate = self webView?.backgroundColor = .darkBackground webView?.isOpaque = false // prevents white background flash before web content is rendered webView?.alpha = 0.0 _ = webView?.load(request) webView?.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth] webView?.scrollView.contentInsetAdjustmentBehavior = .never view.addSubview(webView!) let center = NotificationCenter.default notificationObservers[UIApplication.didBecomeActiveNotification.rawValue] = center.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] (_) in self?.didAppear = true if let info = self?.webViewInfo { self?.sendToAllSockets(data: info) } } notificationObservers[UIApplication.willResignActiveNotification.rawValue] = center.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] (_) in self?.didAppear = false if let info = self?.webViewInfo { self?.sendToAllSockets(data: info) } } self.messageUIPresenter.presenter = self } override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) edgesForExtendedLayout = .all self.beginDidLoadCountdown() self.navigationController?.setNavigationBarHidden(true, animated: false) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) didAppear = true sendToAllSockets(data: webViewInfo) } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) didAppear = false sendToAllSockets(data: webViewInfo) } // this should be called when the webview is expected to load content. if the content has not signaled // that is has loaded by didLoadTimeout then an alert will be shown allowing the user to back out // of the faulty webview fileprivate func beginDidLoadCountdown() { let timeout = DispatchTime.now() + .milliseconds(self.didLoadTimeout) DispatchQueue.main.asyncAfter(deadline: timeout) { [weak self] in guard let myself = self else { return } if myself.didAppear && !myself.didLoad { // if the webview did not load the first time lets refresh the bundle. occasionally the bundle // update can fail, so this update should fetch an entirely new copy let activity = BRActivityViewController(message: S.Webview.dismiss) myself.present(activity, animated: true, completion: nil) Backend.apiClient.updateBundles(completionHandler: { results in results.forEach({ _, err in if err != nil { print("[BRWebViewController] error updating bundle: \(String(describing: err))") } // give the webview another chance to load DispatchQueue.main.async { self?.refresh() } // XXX(sam): log this event so we know how frequently it happens DispatchQueue.main.asyncAfter(deadline: timeout) { Store.trigger(name: .showStatusBar) self?.dismiss(animated: true) { self?.notifyUserOfLoadFailure() if let didClose = self?.didClose { didClose() } } } }) }) } } } fileprivate func notifyUserOfLoadFailure() { if self.didAppear && !self.didLoad { let alert = UIAlertController.init( title: S.Alert.error, message: S.Webview.errorMessage, preferredStyle: .alert ) let action = UIAlertAction(title: S.Webview.dismiss, style: .default) { [weak self] _ in self?.closeNow() } alert.addAction(action) self.present(alert, animated: true, completion: nil) } } // signal to the presenter that the webview content successfully loaded fileprivate func webviewDidLoad() { didLoad = true UIView.animate(withDuration: 0.4) { self.webView?.alpha = 1.0 } sendToAllSockets(data: webViewInfo) } fileprivate func closeNow() { Store.trigger(name: .showStatusBar) let didClose = self.didClose dismiss(animated: true, completion: { if let didClose = didClose { didClose() } }) } open func startServer() { do { if !server.isStarted { try server.start() setupIntegrations() } } catch let e { print("\n\n\nSERVER ERROR! \(e)\n\n\n") } } open func stopServer() { if server.isStarted { server.stop() server.resetMiddleware() } } func navigate(to: String) { let js = "window.location = '\(to)';" webView?.evaluateJavaScript(js, completionHandler: { _, error in if let error = error { print("WEBVIEW navigate to error: \(String(describing: error))") } }) } // this will look on the network for any _http._tcp bonjour services whose name // contains th string "webpack" and will set our debugEndpoint to whatever that // resolves to. this allows us to debug bundles over the network without complicated setup fileprivate func setupBonjour() { _ = bonjourBrowser.findService("_http._tcp") { [weak self] (services) in for svc in services { if !svc.name.lowercased().contains("webpack") { continue } self?.debugNetService = svc svc.resolve(withTimeout: 1.0) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in guard let netService = self?.debugNetService else { return } self?.debugEndpoint = "http://\(netService.hostName ?? ""):\(netService.port)" print("[BRWebViewController] discovered bonjour debugging service \(String(describing: self?.debugEndpoint))") self?.server.resetMiddleware() self?.setupIntegrations() self?.refresh() } break } } } fileprivate func setupIntegrations() { // proxy api for signing and verification let apiProxy = BRAPIProxy(mountAt: "/_api", client: Backend.apiClient) server.prependMiddleware(middleware: apiProxy) // http router for native functionality let router = BRHTTPRouter() server.prependMiddleware(middleware: router) if let archive = AssetArchive(name: bundleName, apiClient: Backend.apiClient) { // basic file server for static assets let fileMw = BRHTTPFileMiddleware(baseURL: archive.extractedUrl, debugURL: UserDefaults.platformDebugURL) server.prependMiddleware(middleware: fileMw) // middleware to always return index.html for any unknown GET request (facilitates window.history style SPAs) let indexMw = BRHTTPIndexMiddleware(baseURL: fileMw.baseURL) server.prependMiddleware(middleware: indexMw) // enable debug if it is turned on if let debugUrl = debugEndpoint { let url = URL(string: debugUrl) fileMw.debugURL = url indexMw.debugURL = url } } // geo plugin provides access to onboard geo location functionality router.plugin(BRGeoLocationPlugin()) // camera plugin router.plugin(BRCameraPlugin(fromViewController: self)) // wallet plugin provides access to the wallet if let system = system { router.plugin(BRWalletPlugin(walletAuthenticator: walletAuthenticator, system: system)) } // link plugin which allows opening links to other apps router.plugin(BRLinkPlugin(fromViewController: self)) // kvstore plugin provides access to the shared replicated kv store router.plugin(BRKVStorePlugin(client: Backend.apiClient)) // GET /_close closes the browser modal router.get("/_close") { [weak self] (request, _) -> BRHTTPResponse in DispatchQueue.main.async { self?.closeNow() } return BRHTTPResponse(request: request, code: 204) } //GET /_email opens system email dialog // Status codes: // - 200: Presented email UI // - 400: No address param provided router.get("/_email") { [weak self] (request, _) -> BRHTTPResponse in if let email = request.query["address"], email.count == 1 { DispatchQueue.main.async { self?.messageUIPresenter.presentMailCompose(emailAddress: email[0]) } return BRHTTPResponse(request: request, code: 200) } else { return BRHTTPResponse(request: request, code: 400) } } //POST /_email opens system email dialog // Status codes: // - 200: Presented email UI // - 400: No params provided router.post("/_email") { [weak self] (request, _) -> BRHTTPResponse in guard let data = request.body(), let j = try? JSONSerialization.jsonObject(with: data, options: []), let json = j as? [String: String] else { return BRHTTPResponse(request: request, code: 400) } if let email = json["address"] { let subject = json["subject"] let body = json["body"] DispatchQueue.main.async { self?.messageUIPresenter.presentMailCompose(emailAddress: email, subject: subject, body: body) } return BRHTTPResponse(request: request, code: 200) } else { return BRHTTPResponse(request: request, code: 400) } } // GET /_didload signals to the presenter that the content successfully loaded router.get("/_didload") { [weak self] (request, _) -> BRHTTPResponse in DispatchQueue.main.async { self?.webviewDidLoad() } return BRHTTPResponse(request: request, code: 204) } // socket /_webviewinfo will send info about the webview state to client router.websocket("/_webviewinfo", client: self) router.printDebug() } open func preload() { _ = self.view // force webview loading } open func refresh() { let request = URLRequest(url: indexUrl) _ = webView?.load(request) } // MARK: - navigation delegate open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let isMainFrameOrWindow = navigationAction.targetFrame?.isMainFrame ?? true if let url = navigationAction.request.url, let host = url.host { // allow all local server targets if let port = (url as NSURL).port, (host == server.listenAddress || port.int32Value == Int32(server.port)) { return decisionHandler(.allow) } // allow iframe targets based on allow list if !isMainFrameOrWindow { return decisionHandler(.allow) } } print("[BRWebViewController disallowing navigation: \(navigationAction)") decisionHandler(.cancel) } // MARK: - socket delegate func sendTo(socket: BRWebSocket, data: [String: Any]) { do { let j = try JSONSerialization.data(withJSONObject: data, options: []) if let s = String(data: j, encoding: .utf8) { socket.request.queue.async { socket.send(s) } } } catch let e { print("LOCATION SOCKET FAILED ENCODE JSON: \(e)") } } func sendToAllSockets(data: [String: Any]) { for (_, s) in sockets { sendTo(socket: s, data: data) } } public func socketDidConnect(_ socket: BRWebSocket) { print("WEBVIEW SOCKET CONNECT \(socket.id)") sockets[socket.id] = socket sendTo(socket: socket, data: webViewInfo) } public func socketDidDisconnect(_ socket: BRWebSocket) { print("WEBVIEW SOCKET DISCONNECT \(socket.id)") sockets.removeValue(forKey: socket.id) } public func socket(_ socket: BRWebSocket, didReceiveText text: String) { print("WEBVIEW SOCKET RECV TEXT \(text)") } public func socket(_ socket: BRWebSocket, didReceiveData data: Data) { print("WEBVIEW SOCKET RECV TEXT \(data.hexString)") } }
mit
alexpersian/Spine
Spine/AudioBook.swift
1
181
// // AudioBook.swift // Spine // // Created by Alex Persian on 10/29/16. // Copyright © 2016 alexpersian. All rights reserved. // import Foundation class AudioBook { }
mit
monsterkodi/krkkl
krkkl/Cubes.swift
1
13796
/* 0000000 000 000 0000000 00000000 0000000 000 000 000 000 000 000 000 000 000 000 0000000 0000000 0000000 000 000 000 000 000 000 000 0000000 0000000 0000000 00000000 0000000 */ import AppKit enum Side: Int { case up = 0, right, left, down, backl, backr, none } enum ColorType: Int { case random=0, list, direction, num } enum Reset: Int { case random = 0, ping, wrap } class Cubes { var preset:[String: AnyObject]? var fps:Double = 60 var cpf:Double = 60 var cubeSize:(x: Int, y: Int) = (0, 0) var pos: (x: Int, y: Int) = (0, 0) var size: (x: Int, y: Int) = (0, 0) var center: (x: Int, y: Int) = (0, 0) var color_top:Double = 0 var color_left:Double = 0 var color_right:Double = 0 var lastDir:Int = 0 var nextDir:Int = 0 var dirIncr:Int = 0 var probSum:Double = 0 var probDir:[Double] = [0,0,0] var keepDir:[Double] = [0,0,0] var reset:Int = -1 // what happens when the screen border is touched: "random", "ping", "wrap" ("center") var cubeCount:Int = 0 var maxCubes:Int = 5000 var colorType = ColorType.list var colorFade:Float = 0 var colorInc:Float = 0 var colorIndex:Int = 0 var colorList:[NSColor] = [] var thisColor = colorRGB([0,0,0]) var nextColor = colorRGB([0,0,0]) var resetColor = colorRGB([0,0,0]) var rgbColor = colorRGB([0,0,0]) func isDone() -> Bool { return cubeCount >= maxCubes } func nextStep() { for _ in 0...Int(cpf) { drawNextCube() } } /* 0000000 00000000 000000000 000 000 00000000 000 000 000 000 000 000 000 0000000 0000000 000 000 000 00000000 000 000 000 000 000 000 0000000 00000000 000 0000000 000 */ func setup(_ preview: Bool, width: Int, height: Int) { color_top = randDblPref("color_top") color_left = randDblPref("color_left") color_right = randDblPref("color_right") dirIncr = randChoice("dir_inc") as! Int size.y = Int(randDblPref("rows")) / (preview ? 2 : 1) cubeSize.y = height/size.y if (cubeSize.y % 2 == 1) { cubeSize.y -= 1 } cubeSize.y = max(2, cubeSize.y) size.y = height/cubeSize.y cubeSize.x = Int(sin(Double.pi/3) * Double(cubeSize.y)) size.x = width/cubeSize.x colorInc = Float(randDblPref("color_fade")) maxCubes = Int(Double(size.y * size.y)*randDblPref("cube_amount")) reset = randChoice("reset") as! Int // _______________________ derivatives cpf = randDblPref("cpf") fps = doublePref("fps") center.x = size.x/2 center.y = size.y/2 pos = center // start at center colorFade = 0 colorIndex = 0 let colorLists = Defaults.stringListToColorLists(preset!["colors"] as! [String]) let colorListIndex = randint(colorLists.count) colorList = colorLists[colorListIndex] if (colorList.count == 0) { colorType = .random } else if (colorList.count == 1 && colorList[0].hex() == "#000000") { colorType = .direction } else { colorType = .list } thisColor = colorRGB([0,0,0]) switch colorType { case .random: nextColor = randColor() case .list: thisColor = colorList[0] nextColor = colorList[0] default: break } rgbColor = thisColor keepDir[Side.up.rawValue] = randDblPref("keep_up") keepDir[Side.left.rawValue] = randDblPref("keep_left") keepDir[Side.right.rawValue] = randDblPref("keep_right") probDir[Side.up.rawValue] = randDblPref("prob_up") probDir[Side.left.rawValue] = randDblPref("prob_left") probDir[Side.right.rawValue] = randDblPref("prob_right") probSum = probDir.reduce(0.0, { $0 + $1 }) cubeCount = 0 if true { print("") print("width \(width)") print("height \(height)") print("numx \(size.x)") print("numy \(size.y)") print("cube \(cubeSize.x) \(cubeSize.y)") print("maxCubes \(maxCubes)") print("fps \(fps)") print("cpf \(cpf)") print("keepDir \(keepDir)") print("probDir \(probDir)") print("probSum \(probSum)") print("colorInc \(colorInc)") print("colorList \(colorListIndex)") print("colorType \(colorTypeName(colorType))") print("reset \(reset)") } } /* 0000000 0000000 000 0000000 00000000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 0000000 000 000 000 000 000 000 000 000 0000000 0000000 0000000 0000000 000 000 */ func chooseNextColor() { switch colorType { case .random: colorFade += colorInc if colorFade >= 100 { colorFade -= 100 thisColor = nextColor nextColor = randColor() } rgbColor = thisColor.fadeTo(nextColor, fade:colorFade/100.0) case .list: colorFade += colorInc if colorFade >= 100 { colorFade -= 100 colorIndex = (colorIndex + 1) % colorList.count thisColor = nextColor nextColor = colorList[colorIndex] } rgbColor = thisColor.fadeTo(nextColor, fade:colorFade/100.0) case .direction: let ci = 0.02 + 0.05 * colorInc/100.0 var r = Float(rgbColor.red()) var g = Float(rgbColor.green()) var b = Float(rgbColor.blue()) let side:Side = Side(rawValue:nextDir)! switch side { case .up: b = clamp(b + ci, low: 0.0, high: 1.0) case .left: r = clamp(r + ci, low: 0.0, high: 1.0) case .right: g = clamp(g + ci, low: 0.0, high: 1.0) case .down: b = clamp(b - ci, low: 0.0, high: 1.0) case .backr: r = clamp(r - ci, low: 0.0, high: 1.0) case .backl: g = clamp(g - ci, low: 0.0, high: 1.0) default: break } if r+g+b < 0.3 { (r,g,b) = (0.1, 0.1, 0.1) } rgbColor = colorRGB([r,g,b]) default: break } } /* 0000000 000 000 0000000 00000000 000 000 000 000 000 000 000 000 000 0000000 0000000 000 000 000 000 000 000 0000000 0000000 0000000 00000000 */ func drawNextCube() { var skip = Side.none nextDir = lastDir if (randdbl() >= keepDir[lastDir%3]) { if dirIncr == 3 { switch randdbl() { case let (prob) where prob <= probDir[Side.up.rawValue]/probSum: nextDir = randint(2) == 0 ? Side.up.rawValue : Side.down.rawValue case let (prob) where (probDir[Side.up.rawValue]/probSum <= prob) && (prob <= probDir[Side.up.rawValue + Side.left.rawValue]/probSum): nextDir = randint(2) == 0 ? Side.left.rawValue : Side.backr.rawValue default: nextDir = randint(2) == 0 ? Side.right.rawValue : Side.backl.rawValue } } else { nextDir = (nextDir + dirIncr)%6 } } lastDir = nextDir let side:Side = Side(rawValue:nextDir)! switch side { case .up: pos.y += 1 case .right: if (pos.x%2)==1 { pos.y -= 1 } pos.x += 1 case .left: if (pos.x%2)==1 { pos.y -= 1 } pos.x -= 1 case .down: pos.y -= 1 if cubeCount > 0 { skip = .up } case .backl: if (pos.x%2)==0 { pos.y += 1 } pos.x -= 1 if cubeCount > 0 { skip = .right } case .backr: if (pos.x%2)==0 { pos.y += 1 } pos.x += 1 if cubeCount > 0 { skip = .left } default: break } if (pos.x < 1 || pos.y < 2 || pos.x > size.x-1 || pos.y > size.y-1) // if screen border is touched { skip = .none lastDir = randint(6) if reset == Reset.random.rawValue { pos.x = randint(size.x) pos.y = randint(size.y) } else if reset == Reset.wrap.rawValue { if (pos.x < 1) { pos.x = size.x-1 } else if (pos.x > size.x-1) { pos.x = 1 } if (pos.y < 2) { pos.y = size.y-2 } else if (pos.y > size.y-1) { pos.y = 2 } } else if reset == Reset.ping.rawValue { if (pos.x < 1) { switch side { case .left: lastDir = Side.backr.rawValue default: lastDir = Side.right.rawValue } pos.x = 1 } else if (pos.x > size.x-1) { switch side { case .backr: lastDir = Side.left.rawValue default: lastDir = Side.backl.rawValue } pos.x = size.x-1 } if (pos.y < 2) { switch side { case .left: lastDir = Side.backr.rawValue case .right: lastDir = Side.backl.rawValue default: lastDir = randflt()>0.5 ? Side.backl.rawValue : Side.backr.rawValue } pos.y = 2 } else if (pos.y > size.y-1) { switch side { case .backr: lastDir = Side.left.rawValue case .backl: lastDir = Side.right.rawValue default: lastDir = randflt()>0.5 ? Side.left.rawValue : Side.right.rawValue } pos.y = size.y-1 } } if colorType == ColorType.direction && reset == Reset.random.rawValue { rgbColor = colorRGB([0,0,0]) } } chooseNextColor() drawCube(skip) cubeCount += 1 } /* 0000000 00000000 0000000 000 000 000 000 000 000 000 000 000 0 000 000 000 0000000 000000000 000000000 000 000 000 000 000 000 000 000 0000000 000 000 000 000 00 00 */ func drawCube(_ skip: Side) { let w = cubeSize.x let h = cubeSize.y let s = h/2 let x = pos.x*w let y = (pos.x%2 == 0) ? (pos.y*h) : (pos.y*h - s) if skip != .up { rgbColor.scale(color_top).set() let path = NSBezierPath() path.move(to: NSPoint(x: x ,y: y)) path.line(to: NSPoint(x: x+w ,y: y+s)) path.line(to: NSPoint(x: x ,y: y+h)) path.line(to: NSPoint(x: x-w ,y: y+s)) path.fill() } if skip != .left { rgbColor.scale(color_left).set() let path = NSBezierPath() path.move(to: NSPoint(x: x ,y: y)) path.line(to: NSPoint(x: x-w ,y: y+s)) path.line(to: NSPoint(x: x-w ,y: y-s)) path.line(to: NSPoint(x: x ,y: y-h)) path.fill() } if skip != .right { rgbColor.scale(color_right).set() let path = NSBezierPath() path.move(to: NSPoint(x: x ,y: y)) path.line(to: NSPoint(x: x+w ,y: y+s)) path.line(to: NSPoint(x: x+w ,y: y-s)) path.line(to: NSPoint(x: x ,y: y-h)) path.fill() } } func randDblPref(_ key:String) -> Double { let dbls = doublesPref(key) return randdblrng(dbls[0], high: dbls[1]) } func randChoice(_ key:String) -> AnyObject { let values = Defaults.presetValueForKey(preset!, key: key) as! [Int] return values[randint(values.count)] as AnyObject } func doublePref(_ key:String) -> Double { return Defaults.presetValueForKey(preset!, key: key) as! Double } func doublesPref(_ key:String) -> [Double] { return Defaults.presetValueForKey(preset!, key: key) as! [Double] } func colorTypeName(_ colorType:ColorType) -> String { switch colorType { case .random: return "Random" case .list: return "List" case .direction: return "Direction" case .num: return "???" } } }
apache-2.0
avito-tech/Marshroute
Example/NavigationDemo/Common/Services/TouchEventObserver/TouchEventForwarder.swift
1
117
import UIKit protocol TouchEventForwarder: class { func forwardEvent(_ event: UIEvent, touches: Set<UITouch>) }
mit
seivan/ScalarArithmetic
TestsAndSample/Tests/TestsDoubleComparable.swift
1
4082
// // TestsDoubleComparable.swift // TestsAndSample // // Created by Seivan Heidari on 01/07/14. // Copyright (c) 2014 Seivan Heidari. All rights reserved. // import XCTest class TestsDoubleComparable: SuperTestsScalarComparable, ScalarComparableTesting { func testEqual() { XCTAssert(self.doubleValue == self.intValue); XCTAssert(self.doubleValue == self.cgFloatValue); XCTAssert(self.doubleValue == self.int16Value); XCTAssert(self.doubleValue == self.int32Value); XCTAssert(self.doubleValue == self.int64Value); XCTAssert(self.doubleValue == self.uInt16Value); XCTAssert(self.doubleValue == self.uInt16Value); XCTAssert(self.doubleValue == self.uInt16Value); } func testNotEqual() { XCTAssertFalse(self.doubleValue != self.intValue); XCTAssertFalse(self.doubleValue != self.cgFloatValue); XCTAssertFalse(self.doubleValue != self.int16Value); XCTAssertFalse(self.doubleValue != self.int32Value); XCTAssertFalse(self.doubleValue != self.int64Value); XCTAssertFalse(self.doubleValue != self.uInt16Value); XCTAssertFalse(self.doubleValue != self.uInt16Value); XCTAssertFalse(self.doubleValue != self.uInt16Value); } func testLessThanOrEqual() { XCTAssert(self.doubleValue <= self.intValue); XCTAssert(self.doubleValue <= self.cgFloatValue); XCTAssert(self.doubleValue <= self.int16Value); XCTAssert(self.doubleValue <= self.int32Value); XCTAssert(self.doubleValue <= self.int64Value); XCTAssert(self.doubleValue <= self.uInt16Value); XCTAssert(self.doubleValue <= self.uInt16Value); XCTAssert(self.doubleValue <= self.uInt16Value); self.doubleValue = -1 XCTAssert(self.doubleValue <= self.intValue); XCTAssert(self.doubleValue <= self.cgFloatValue); XCTAssert(self.doubleValue <= self.int16Value); XCTAssert(self.doubleValue <= self.int32Value); XCTAssert(self.doubleValue <= self.int64Value); XCTAssert(self.doubleValue <= self.uInt16Value); XCTAssert(self.doubleValue <= self.uInt16Value); XCTAssert(self.doubleValue <= self.uInt16Value); } func testLessThan() { self.doubleValue = -1 XCTAssert(self.doubleValue < self.intValue); XCTAssert(self.doubleValue < self.cgFloatValue); XCTAssert(self.doubleValue < self.int16Value); XCTAssert(self.doubleValue < self.int32Value); XCTAssert(self.doubleValue < self.int64Value); XCTAssert(self.doubleValue < self.uInt16Value); XCTAssert(self.doubleValue < self.uInt16Value); XCTAssert(self.doubleValue < self.uInt16Value); } func testGreaterThanOrEqual() { XCTAssert(self.doubleValue >= self.intValue); XCTAssert(self.doubleValue >= self.cgFloatValue); XCTAssert(self.doubleValue >= self.int16Value); XCTAssert(self.doubleValue >= self.int32Value); XCTAssert(self.doubleValue >= self.int64Value); XCTAssert(self.doubleValue >= self.uInt16Value); XCTAssert(self.doubleValue >= self.uInt16Value); XCTAssert(self.doubleValue >= self.uInt16Value); self.doubleValue = -1 XCTAssertFalse(self.doubleValue >= self.intValue); XCTAssertFalse(self.doubleValue >= self.cgFloatValue); XCTAssertFalse(self.doubleValue >= self.int16Value); XCTAssertFalse(self.doubleValue >= self.int32Value); XCTAssertFalse(self.doubleValue >= self.int64Value); XCTAssertFalse(self.doubleValue >= self.uInt16Value); XCTAssertFalse(self.doubleValue >= self.uInt16Value); XCTAssertFalse(self.doubleValue >= self.uInt16Value); } func testGreaterThan() { self.doubleValue = -1 XCTAssertFalse(self.doubleValue > self.intValue); XCTAssertFalse(self.doubleValue > self.cgFloatValue); XCTAssertFalse(self.doubleValue > self.int16Value); XCTAssertFalse(self.doubleValue > self.int32Value); XCTAssertFalse(self.doubleValue > self.int64Value); XCTAssertFalse(self.doubleValue > self.uInt16Value); XCTAssertFalse(self.doubleValue > self.uInt16Value); XCTAssertFalse(self.doubleValue > self.uInt16Value); } }
mit
justinmfischer/SwiftyAccordionCells
SwiftyAccordionCells/AppDelegate.swift
1
2191
// // AppDelegate.swift // SwiftyAccordionCells // // Created by Fischer, Justin on 9/24/15. // Copyright © 2015 Justin M Fischer. 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
swimmath27/GameOfGames
GameOfGames/ViewControllers/StartOlympicsViewController.swift
1
884
// // StartOlympicsViewController.swift // GameOfGames // // Created by Michael Lombardo on 6/21/16. // Copyright © 2016 Michael Lombardo. All rights reserved. // import UIKit class StartOlympicsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.layer.insertSublayer(UIHelper.getBackgroundGradient(), at: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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
4np/UitzendingGemist
UitzendingGemist/NPOEpisode+UI.swift
1
3198
// // NPOEpisode+UI.swift // UitzendingGemist // // Created by Jeroen Wesbeek on 31/07/16. // Copyright © 2016 Jeroen Wesbeek. All rights reserved. // import Foundation import UIKit import NPOKit extension NPOEpisode { public var watchedIndicator: String { // add (partically) watched indicator switch watched { case .unwatched: return UitzendingGemistConstants.unwatchedSymbol case .partially: return UitzendingGemistConstants.partiallyWatchedSymbol case .fully: return UitzendingGemistConstants.watchedSymbol } } func getDisplayName() -> String { var displayName = watchedIndicator // add the episode name if let name = self.name, !name.isEmpty { displayName += name } else if let name = self.program?.name, !name.isEmpty { displayName += name } else { displayName += String.unknownEpisodeName } return displayName } func getTime() -> String? { guard let broadcasted = self.broadcasted else { return nil } let formatter = DateFormatter() formatter.dateFormat = "HH:mm" return formatter.string(from: broadcasted) } func getNames() -> (programName: String, episodeNameAndInfo: String) { // define the program name var programName = watchedIndicator if let name = self.program?.name, !name.isEmpty { programName += name } else { programName += String.unknownProgramName } // define the episode name and time var elements = [String]() // add episode name if let name = self.name, !name.isEmpty { if let tempProgramName = program?.name { var tempName = name // replace program name tempName = tempName.replacingOccurrences(of: tempProgramName, with: "", options: .caseInsensitive, range: nil) // remove garbage from beginning of name if let regex = try? NSRegularExpression(pattern: "^([^a-z0-9]+)", options: .caseInsensitive) { let range = NSRange(0..<tempName.utf16.count) tempName = regex.stringByReplacingMatches(in: tempName, options: .withTransparentBounds, range: range, withTemplate: "") } // capitalize tempName = tempName.capitalized if !tempName.isEmpty { elements.append(tempName) } } else { elements.append(name) } } // add time if let time = getTime() { elements.append(time) } // add duration elements.append(self.duration.timeDisplayValue) let episodeName = elements.joined(separator: UitzendingGemistConstants.separator) return (programName: programName, episodeNameAndInfo: episodeName) } }
apache-2.0
milseman/swift
validation-test/compiler_crashers_fixed/25524-swift-constraints-constraintsystem-simplifytype.swift
65
462
// 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 // RUN: not %target-swift-frontend %s -typecheck c< let a{ class A class A let a{ enum b <c{{}class B { func a:A
apache-2.0
milseman/swift
stdlib/public/SDK/Dispatch/IO.swift
19
3890
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// public extension DispatchIO { public enum StreamType : UInt { case stream = 0 case random = 1 } public struct CloseFlags : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let stop = CloseFlags(rawValue: 1) } public struct IntervalFlags : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public init(nilLiteral: ()) { self.rawValue = 0 } public static let strictInterval = IntervalFlags(rawValue: 1) } public class func read(fromFileDescriptor: Int32, maxLength: Int, runningHandlerOn queue: DispatchQueue, handler: @escaping (_ data: DispatchData, _ error: Int32) -> Void) { __dispatch_read(fromFileDescriptor, maxLength, queue) { (data: __DispatchData, error: Int32) in handler(DispatchData(data: data), error) } } public class func write(toFileDescriptor: Int32, data: DispatchData, runningHandlerOn queue: DispatchQueue, handler: @escaping (_ data: DispatchData?, _ error: Int32) -> Void) { __dispatch_write(toFileDescriptor, data as __DispatchData, queue) { (data: __DispatchData?, error: Int32) in handler(data.flatMap { DispatchData(data: $0) }, error) } } public convenience init( type: StreamType, fileDescriptor: Int32, queue: DispatchQueue, cleanupHandler: @escaping (_ error: Int32) -> Void) { self.init(__type: type.rawValue, fd: fileDescriptor, queue: queue, handler: cleanupHandler) } @available(swift, obsoleted: 4) public convenience init( type: StreamType, path: UnsafePointer<Int8>, oflag: Int32, mode: mode_t, queue: DispatchQueue, cleanupHandler: @escaping (_ error: Int32) -> Void) { self.init(__type: type.rawValue, path: path, oflag: oflag, mode: mode, queue: queue, handler: cleanupHandler) } @available(swift, introduced: 4) public convenience init?( type: StreamType, path: UnsafePointer<Int8>, oflag: Int32, mode: mode_t, queue: DispatchQueue, cleanupHandler: @escaping (_ error: Int32) -> Void) { self.init(__type: type.rawValue, path: path, oflag: oflag, mode: mode, queue: queue, handler: cleanupHandler) } public convenience init( type: StreamType, io: DispatchIO, queue: DispatchQueue, cleanupHandler: @escaping (_ error: Int32) -> Void) { self.init(__type: type.rawValue, io: io, queue: queue, handler: cleanupHandler) } public func read(offset: off_t, length: Int, queue: DispatchQueue, ioHandler: @escaping (_ done: Bool, _ data: DispatchData?, _ error: Int32) -> Void) { __dispatch_io_read(self, offset, length, queue) { (done: Bool, data: __DispatchData?, error: Int32) in ioHandler(done, data.flatMap { DispatchData(data: $0) }, error) } } public func write(offset: off_t, data: DispatchData, queue: DispatchQueue, ioHandler: @escaping (_ done: Bool, _ data: DispatchData?, _ error: Int32) -> Void) { __dispatch_io_write(self, offset, data as __DispatchData, queue) { (done: Bool, data: __DispatchData?, error: Int32) in ioHandler(done, data.flatMap { DispatchData(data: $0) }, error) } } public func setInterval(interval: DispatchTimeInterval, flags: IntervalFlags = []) { __dispatch_io_set_interval(self, UInt64(interval.rawValue), flags.rawValue) } public func close(flags: CloseFlags = []) { __dispatch_io_close(self, flags.rawValue) } }
apache-2.0
alloyapple/GooseGtk
Tests/LinuxMain.swift
1
97
import XCTest @testable import GooseGtkTests XCTMain([ testCase(GooseGtkTests.allTests), ])
apache-2.0
lizhaojie001/-Demo-
RATreeView-master/Examples/RATreeViewBasicExampleSwift/TreeViewController.swift
1
6112
// // TreeViewController.swift // RATreeViewExamples // // Created by Rafal Augustyniak on 21/11/15. // Copyright © 2015 com.Augustyniak. All rights reserved. // import UIKit import RATreeView class TreeViewController: UIViewController, RATreeViewDelegate, RATreeViewDataSource { var treeView : RATreeView! var data : [DataObject] var editButton : UIBarButtonItem! convenience init() { self.init(nibName : nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { data = TreeViewController.commonInit() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { data = TreeViewController.commonInit() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() title = "Things" setupTreeView() updateNavigationBarButtons() } func setupTreeView() -> Void { treeView = RATreeView(frame: view.bounds) treeView.registerNib(UINib.init(nibName: "TreeTableViewCell", bundle: nil), forCellReuseIdentifier: "TreeTableViewCell") treeView.autoresizingMask = UIViewAutoresizing(rawValue:UIViewAutoresizing.FlexibleWidth.rawValue | UIViewAutoresizing.FlexibleHeight.rawValue) treeView.delegate = self; treeView.dataSource = self; treeView.treeFooterView = UIView() treeView.backgroundColor = UIColor.clearColor() view.addSubview(treeView) } func updateNavigationBarButtons() -> Void { let systemItem = treeView.editing ? UIBarButtonSystemItem.Done : UIBarButtonSystemItem.Edit; self.editButton = UIBarButtonItem.init(barButtonSystemItem: systemItem, target: self, action: "editButtonTapped:") self.navigationItem.rightBarButtonItem = self.editButton; } func editButtonTapped(sender : AnyObject) -> Void { treeView.setEditing(!treeView.editing, animated: true) updateNavigationBarButtons() } //MARK: RATreeView data source func treeView(treeView: RATreeView, numberOfChildrenOfItem item: AnyObject?) -> Int { if let item = item as? DataObject { return item.children.count } else { return self.data.count } } func treeView(treeView: RATreeView, child index: Int, ofItem item: AnyObject?) -> AnyObject { if let item = item as? DataObject { return item.children[index] } else { return data[index] as AnyObject } } func treeView(treeView: RATreeView, cellForItem item: AnyObject?) -> UITableViewCell { let cell = treeView.dequeueReusableCellWithIdentifier("TreeTableViewCell") as! TreeTableViewCell let item = item as! DataObject let level = treeView.levelForCellForItem(item) let detailsText = "Number of children \(item.children.count)" cell.selectionStyle = .None cell.setup(withTitle: item.name, detailsText: detailsText, level: level, additionalButtonHidden: false) cell.additionButtonActionBlock = { [weak treeView] cell in guard let treeView = treeView else { return; } let item = treeView.itemForCell(cell) as! DataObject let newItem = DataObject(name: "Added value") item.addChild(newItem) treeView.insertItemsAtIndexes(NSIndexSet.init(index: 0), inParent: item, withAnimation: RATreeViewRowAnimationNone); treeView.reloadRowsForItems([item], withRowAnimation: RATreeViewRowAnimationNone) } return cell } //MARK: RATreeView delegate func treeView(treeView: RATreeView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowForItem item: AnyObject) { guard editingStyle == .Delete else { return; } let item = item as! DataObject let parent = treeView.parentForItem(item) as? DataObject var index = 0 if let parent = parent { parent.children.indexOf({ dataObject in return dataObject === item })! parent.removeChild(item) } else { index = self.data.indexOf({ dataObject in return dataObject === item; })! self.data.removeAtIndex(index) } self.treeView.deleteItemsAtIndexes(NSIndexSet.init(index: index), inParent: parent, withAnimation: RATreeViewRowAnimationRight) if let parent = parent { self.treeView.reloadRowsForItems([parent], withRowAnimation: RATreeViewRowAnimationNone) } } } private extension TreeViewController { static func commonInit() -> [DataObject] { let phone1 = DataObject(name: "Phone 1") let phone2 = DataObject(name: "Phone 2") let phone3 = DataObject(name: "Phone 3") let phone4 = DataObject(name: "Phone 4") let phones = DataObject(name: "Phones", children: [phone1, phone2, phone3, phone4]) let notebook1 = DataObject(name: "Notebook 1") let notebook2 = DataObject(name: "Notebook 2") let computer1 = DataObject(name: "Computer 1", children: [notebook1, notebook2]) let computer2 = DataObject(name: "Computer 2") let computer3 = DataObject(name: "Computer 3") let computers = DataObject(name: "Computers", children: [computer1, computer2, computer3]) let cars = DataObject(name: "Cars") let bikes = DataObject(name: "Bikes") let houses = DataObject(name: "Houses") let flats = DataObject(name: "Flats") let motorbikes = DataObject(name: "motorbikes") let drinks = DataObject(name: "Drinks") let food = DataObject(name: "Food") let sweets = DataObject(name: "Sweets") let watches = DataObject(name: "Watches") let walls = DataObject(name: "Walls") return [phones, computers, cars, bikes, houses, flats, motorbikes, drinks, food, sweets, watches, walls] } }
apache-2.0
GRSource/GRTabBarController
Example/Controllers/GRThird_RootViewController.swift
1
3170
// // GRThird_RootViewController.swift // GRTabBarController // // Created by iOS_Dev5 on 2017/2/9. // Copyright © 2017年 GRSource. All rights reserved. // import UIKit class GRThird_RootViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "三" // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
shaps80/Peek
Pod/Classes/Helpers/Constraints.swift
1
3972
/* Copyright © 18/10/2017 Shaps Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit /// Defines a tuple of views that returns a constraint internal typealias Constraint = (UIView, UIView) -> NSLayoutConstraint extension NSLayoutConstraint { /// Returns this constraint with its priority updated /// /// - Parameter priority: The new priority for this constraint /// - Returns: Returns self. func with(priority: UILayoutPriority) -> NSLayoutConstraint { self.priority = priority return self } } /// Returns a constraint for the specified anchor /// /// - Parameters: /// - keyPath: A keyPath to the source and destination anchor /// - constant: The constant to apply to this constraint /// - priority: The priority to apply to this constraint /// - Returns: A newly configured constraint internal func equal<Axis, Anchor>(_ keyPath: KeyPath<UIView, Anchor>, constant: CGFloat = 0, priority: UILayoutPriority = .defaultHigh) -> Constraint where Anchor: NSLayoutAnchor<Axis> { return equal(keyPath, keyPath, constant: constant, priority: priority) } /// Returns a constraint for the specified anchors /// /// - Parameters: /// - keyPath: A keyPath to the source anchor /// - to: A keyPath to the destination anchor /// - constant: The constant to apply to this constraint /// - priority: The priority to apply to this constraint /// - Returns: A newly configured constraint internal func equal<Axis, Anchor>(_ keyPath: KeyPath<UIView, Anchor>, _ to: KeyPath<UIView, Anchor>, constant: CGFloat = 0, priority: UILayoutPriority = .defaultHigh) -> Constraint where Anchor: NSLayoutAnchor<Axis> { return { view, parent in view[keyPath: keyPath].constraint(equalTo: parent[keyPath: to], constant: constant).with(priority: priority) } } internal func sized<Anchor>(_ keyPath: KeyPath<UIView, Anchor>, constant: CGFloat, priority: UILayoutPriority = .defaultHigh) -> Constraint where Anchor: NSLayoutDimension { return { _, parent in parent[keyPath: keyPath].constraint(equalToConstant: constant).with(priority: priority) } } extension UIView { /// Adds view to otherView, and activates the associated constraints. This also ensures translatesAutoresizingMaskIntoConstraints is disabled. /// /// - Parameters: /// - other: The other view this view will be added to /// - constraints: The constraints to apply internal func addSubview(_ other: UIView, below view: UIView? = nil, constraints: [Constraint]) { if let view = view { insertSubview(other, belowSubview: view) } else { addSubview(other) } other.translatesAutoresizingMaskIntoConstraints = false pin(to: other, constraints: constraints) } internal func pin(to other: UIView, constraints: [Constraint]) { NSLayoutConstraint.activate(constraints.map { $0(self, other) }) } }
mit
ivlevAstef/DITranquillity
Samples/SampleDelegateAndObserver/SampleDelegateAndObserver/Delegate/PopUpViewController.swift
1
461
// // PopUpViewController.swift // SampleDelegateAndObserver // // Created by Alexander Ivlev on 08/09/16. // Copyright © 2016 Alexander Ivlev. All rights reserved. // import UIKit class PopUpViewController: UIViewController { weak var delegate: PopUpDelegate? = nil @IBAction func sliderValueChanged(_ sender: UISlider) { print("From PopUp: Slider value changed on: \(sender.value)") delegate?.sliderValueChanged(Int(sender.value)) } }
mit
tryswift/tryswiftdev
Sources/main.swift
1
1531
do { print("") let arguments = Process.arguments.dropFirst() guard let arg1 = arguments.first else { usage() throw Error.InvalidValue } guard let option = Options(argment: arg1) else { usage() throw Error.InvalidValue } guard let value1 = arguments.dropFirst().first else { usage() throw Error.InvalidValue } guard let value2 = arguments.dropFirst(2).first else { usage() throw Error.InvalidValue } switch option { case .DuplicateReadme: duplicateExistingReadme(existingReadmeDirctoryPath: value1, newReadmeDirectoryPath: value2) case .ReplaceStringsInReadme: replaceStringsInReadme(source: value1, target: value2) case .FindIt: guard value1 == "-name" else { // TODO: For now, support `-name` only. throw Error.UnsupportedOption } findFile(targetOption: "-name", targetName: value2) case .UpdateVersionStrings: try updateVersionStrings(configurationFileFullPath: value1, rootDirectoryPath: value2) case .InstallDevelopmentSnapshot: guard value1 == "-ds" || value1 == "--development-snapshot" else { throw Error.UnsupportedOption } downloadAndInstallSnapshot(snapshotVersion: "swift-DEVELOPMENT-SNAPSHOT-\(value2)") case .Usage: usage() } } catch let error as Error { print(error.description) } catch { // TODO: Error Handling print("Error!!") } print("")
mit
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/PolylineGraphicSpec.swift
1
5982
// // PolylineGraphicSpec.swift // SwiftyEcharts // // Created by Pluto Y on 02/08/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class PolylineGraphicSpec: QuickSpec { override func spec() { describe("For PolylineGraphic.Shape.Smooth") { let valValue: Float = 563.5626 let splineString = "spline" let valSmooth = PolylineGraphic.Shape.Smooth.val(valValue) let splineSmooth = PolylineGraphic.Shape.Smooth.spline it("needs to check the enum case jsonString") { expect(valSmooth.jsonString).to(equal("\(valValue)")) expect(splineSmooth.jsonString).to(equal(splineString.jsonString)) } } let pointShapeValue: [Point] = [[22%, 44%], [44%, 55%], [11%, 44%]] let smoothShapeValue = PolylineGraphic.Shape.Smooth.val(75.37) let smoothConstraintShapeValue = false let shape = PolylineGraphic.Shape() shape.point = pointShapeValue shape.smooth = smoothShapeValue shape.smoothConstraint = smoothConstraintShapeValue describe("For PolylineGraphic.Shape") { it("needs to check the jsonStrin") { let resultDic: [String: Jsonable] = [ "point": pointShapeValue, "smooth": smoothShapeValue, "smoothConstraint": smoothConstraintShapeValue ] expect(shape.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let shapeByEnums = PolylineGraphic.Shape( .point(pointShapeValue), .smooth(smoothShapeValue), .smoothConstraint(smoothConstraintShapeValue) ) expect(shapeByEnums.jsonString).to(equal(shape.jsonString)) } } describe("For PolylineGraphic") { let typeValue = GraphicType.polyline let idValue = "polylineGraphicIdValue" let actionValue = GraphicAction.remove let leftValue = Position.start let rightValue = Position.middle let bottomValue = Position.right let topValue = Position.insideBottom let boundingValue = GraphicBounding.raw let zValue: Float = 49575375 let zlevelValue: Float = 0.3746324823 let silentValue = true let invisibleValue = true let cursorValue = "polylineGraphicCursorValue" let draggableValue = false let progressiveValue = false let shapeValue = shape let styleValue = CommonGraphicStyle( .lineWidth(5.0), .shadowColor(Color.red), .shadowOffsetY(5.7364), .stroke(Color.green) ) let polylineGraphic = PolylineGraphic() polylineGraphic.id = idValue polylineGraphic.action = actionValue polylineGraphic.left = leftValue polylineGraphic.right = rightValue polylineGraphic.top = topValue polylineGraphic.bottom = bottomValue polylineGraphic.bounding = boundingValue polylineGraphic.z = zValue polylineGraphic.zlevel = zlevelValue polylineGraphic.silent = silentValue polylineGraphic.invisible = invisibleValue polylineGraphic.cursor = cursorValue polylineGraphic.draggable = draggableValue polylineGraphic.progressive = progressiveValue polylineGraphic.shape = shapeValue polylineGraphic.style = styleValue it("needs to check the typeValue") { expect(polylineGraphic.type.jsonString).to(equal(typeValue.jsonString)) } it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "type": typeValue, "id": idValue, "$action": actionValue, "left": leftValue, "right": rightValue, "top": topValue, "bottom": bottomValue, "bounding": boundingValue, "z": zValue, "zlevel": zlevelValue, "silent": silentValue, "invisible": invisibleValue, "cursor": cursorValue, "draggable": draggableValue, "progressive": progressiveValue, "shape": shapeValue, "style": styleValue ] expect(polylineGraphic.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let polylineGraphicByEnums = PolylineGraphic( .id(idValue), .action(actionValue), .left(leftValue), .right(rightValue), .top(topValue), .bottom(bottomValue), .bounding(boundingValue), .z(zValue), .zlevel(zlevelValue), .silent(silentValue), .invisible(invisibleValue), .cursor(cursorValue), .draggable(draggableValue), .progressive(progressiveValue), .shape(shapeValue), .style(styleValue) ) expect(polylineGraphicByEnums.jsonString).to(equal(polylineGraphicByEnums.jsonString)) } } } }
mit
apple/swift
test/decl/protocol/special/coding/enum_codable_member_type_lookup.swift
13
274
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // MARK: - Synthesized CodingKeys Enum // Enums which get synthesized Codable implementations should have visible // CodingKey enums during member type lookup. enum SynthesizedEnum : Codable { case value }
apache-2.0
apple/swift
test/Interpreter/objc_implementation_swift_client.swift
2
2799
// REQUIRES: rdar101543397 // // Build objc_implementation.framework // // RUN: %empty-directory(%t) // RUN: %empty-directory(%t/frameworks) // RUN: %empty-directory(%t/frameworks/objc_implementation.framework/Modules/objc_implementation.swiftmodule) // RUN: %empty-directory(%t/frameworks/objc_implementation.framework/Headers) // RUN: cp %S/Inputs/objc_implementation.modulemap %t/frameworks/objc_implementation.framework/Modules/module.modulemap // RUN: cp %S/Inputs/objc_implementation.h %t/frameworks/objc_implementation.framework/Headers // RUN: %target-build-swift-dylib(%t/frameworks/objc_implementation.framework/objc_implementation) -emit-module-path %t/frameworks/objc_implementation.framework/Modules/objc_implementation.swiftmodule/%module-target-triple.swiftmodule -module-name objc_implementation -F %t/frameworks -import-underlying-module -Xlinker -install_name -Xlinker %t/frameworks/objc_implementation.framework/objc_implementation %S/objc_implementation.swift // // Execute this file // // RUN: %empty-directory(%t/swiftmod) // RUN: %target-build-swift %s -module-cache-path %t/swiftmod/mcp -F %t/frameworks -o %t/swiftmod/a.out -module-name main // RUN: %target-codesign %t/swiftmod/a.out // RUN: %target-run %t/swiftmod/a.out | %FileCheck %s // // Execute again, without the swiftmodule this time // // RUN: mv %t/frameworks/objc_implementation.framework/Modules/objc_implementation.swiftmodule %t/frameworks/objc_implementation.framework/Modules/objc_implementation.swiftmodule.disabled // RUN: %empty-directory(%t/clangmod) // RUN: %target-build-swift %s -module-cache-path %t/clangmod/mcp -F %t/frameworks -o %t/clangmod/a.out -module-name main // RUN: %target-codesign %t/clangmod/a.out // RUN: %target-run %t/clangmod/a.out | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import objc_implementation ImplClass.runTests() // CHECK: someMethod = ImplClass.someMethod() // CHECK: implProperty = 0 // CHECK: implProperty = 42 // CHECK: someMethod = SwiftSubclass.someMethod() // CHECK: implProperty = 0 // CHECK: implProperty = 42 // CHECK: otherProperty = 1 // CHECK: otherProperty = 13 // CHECK: implProperty = 42 let impl = ImplClass() print(impl.someMethod(), impl.implProperty) // CHECK: ImplClass.someMethod() 0 class SwiftClientSubclass: ImplClass { override init() {} var otherProperty = 2 override func someMethod() -> String { "SwiftClientSubclass.someMethod()" } } let swiftClientSub = SwiftClientSubclass() print(swiftClientSub.someMethod()) // CHECK: SwiftClientSubclass.someMethod() print(swiftClientSub.implProperty, swiftClientSub.otherProperty) // CHECK: 0 2 swiftClientSub.implProperty = 3 swiftClientSub.otherProperty = 9 print(swiftClientSub.implProperty, swiftClientSub.otherProperty) // CHECK: 3 9
apache-2.0
calkinssean/TIY-Assignments
Day 16/1BeforeWeBegin copy.playground/Contents.swift
1
103
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" str
cc0-1.0
hooman/swift
test/SILGen/cf_members.swift
5
14652
// RUN: %target-swift-emit-silgen -I %S/../IDE/Inputs/custom-modules %s -enable-objc-interop -I %S/Inputs/usr/include | %FileCheck %s import ImportAsMember func makeMetatype() -> Struct1.Type { return Struct1.self } // CHECK-LABEL: sil [ossa] @$s10cf_members17importAsUnaryInityyF public func importAsUnaryInit() { // CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply var a = CCPowerSupply(dangerous: ()) let f: (()) -> CCPowerSupply = CCPowerSupply.init(dangerous:) a = f(()) } // CHECK-LABEL: sil [ossa] @$s10cf_members3foo{{[_0-9a-zA-Z]*}}F public func foo(_ x: Double) { // CHECK: bb0([[X:%.*]] : $Double): // CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBALVAR]] : $*Double // CHECK: [[ZZ:%.*]] = load [trivial] [[READ]] let zz = Struct1.globalVar // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBALVAR]] : $*Double // CHECK: assign [[ZZ]] to [[WRITE]] Struct1.globalVar = zz // CHECK: [[Z:%.*]] = project_box // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) var z = Struct1(value: x) // The metatype expression should still be evaluated even if it isn't // used. // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) z = makeMetatype().init(value: x) // CHECK: [[FN:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcfu_ : $@convention(thin) (Double) -> Struct1 // CHECK: [[A:%.*]] = thin_to_thick_function [[FN]] // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] let a: (Double) -> Struct1 = Struct1.init(value:) // CHECK: [[NEW_Z_VALUE:%.*]] = apply [[BORROWED_A]]([[X]]) // CHECK: end_borrow [[BORROWED_A]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] // CHECK: assign [[NEW_Z_VALUE]] to [[WRITE]] // CHECK: end_access [[WRITE]] z = a(x) // TODO: Support @convention(c) references that only capture thin metatype // let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:) // z = b(x) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1 // CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace // CHECK: apply [[FN]]([[WRITE]]) z.invert() // CHECK: [[WRITE:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[WRITE]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1 // CHECK: apply [[FN]]([[ZTMP]], [[X]]) z = z.translate(radians: x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu0_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]] // CHECK: [[BORROWED_C2:%.*]] = begin_borrow [[C_COPY]] let c: (Double) -> Struct1 = z.translate(radians:) // CHECK: apply [[BORROWED_C2]]([[X]]) // CHECK: destroy_value [[C_COPY]] // CHECK: end_borrow [[BORROWED_C]] z = c(x) // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu2_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THICK_BORROW:%.*]] = begin_borrow [[THICK]] // CHECK: apply [[THICK_BORROW]]([[ZVAL]]) // CHECK: end_borrow [[THICK_BORROW]] z = d(z)(x) // TODO: If we implement SE-0042, this should thunk the value Struct1 param // to a const* param to the underlying C symbol. // // let e: @convention(c) (Struct1, Double) -> Struct1 // = Struct1.translate(radians:) // z = e(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale // CHECK: apply [[FN]]([[ZVAL]], [[X]]) z = z.scale(x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu4_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]] // CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]] // CHECK: [[BORROWED_F2:%.*]] = begin_borrow [[F_COPY]] let f = z.scale // CHECK: apply [[BORROWED_F2]]([[X]]) // CHECK: destroy_value [[F_COPY]] // CHECK: end_borrow [[BORROWED_F]] z = f(x) // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu6_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: thin_to_thick_function [[THUNK]] let g = Struct1.scale // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] z = g(z)(x) // TODO: If we implement SE-0042, this should directly reference the // underlying C function. // let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale // z = h(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[ZVAL_2:%.*]] = load [trivial] [[ZTMP]] // CHECK: store [[ZVAL_2]] to [trivial] [[ZTMP_2:%.*]] : // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double // CHECK: apply [[GET]]([[ZTMP_2]]) _ = z.radius // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> () // CHECK: apply [[SET]]([[ZVAL]], [[X]]) z.radius = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.altitude // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1 // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> () // CHECK: apply [[SET]]([[WRITE]], [[X]]) z.altitude = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.magnitude // CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: apply [[FN]]() var y = Struct1.staticMethod() // CHECK: [[SELF:%.*]] = metatype // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFs5Int32VycSo10IAMStruct1Vmcfu8_ : $@convention(thin) (@thin Struct1.Type) -> @owned @callee_guaranteed () -> Int32 // CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]]) // CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]] // CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]] // CHECK: [[BORROWED_I2:%.*]] = begin_borrow [[I_COPY]] let i = Struct1.staticMethod // CHECK: apply [[BORROWED_I2]]() // CHECK: destroy_value [[I_COPY]] // CHECK: end_borrow [[BORROWED_I]] y = i() // TODO: Support @convention(c) references that only capture thin metatype // let j: @convention(c) () -> Int32 = Struct1.staticMethod // y = j() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = Struct1.property // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) Struct1.property = y // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = Struct1.getOnlyProperty // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = makeMetatype().property // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) makeMetatype().property = y // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = makeMetatype().getOnlyProperty // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> () // CHECK: apply [[FN]]([[X]], [[ZVAL]]) z.selfComesLast(x: x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] let k: (Double) -> () = z.selfComesLast(x:) k(x) let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] l(z)(x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:) // m(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> () // CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]]) z.selfComesThird(a: y, b: 0, x: x) let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:) n(y, 0, x) let o: (Struct1) -> (Int32, Float, Double) -> () = Struct1.selfComesThird(a:b:x:) o(z)(y, 0, x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let p: @convention(c) (Struct1, Int, Float, Double) -> () // = Struct1.selfComesThird(a:b:x:) // p(z, y, 0, x) } // CHECK: } // end sil function '$s10cf_members3foo{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcfu_ : $@convention(thin) (Double) -> Struct1 { // CHECK: bb0([[X:%.*]] : $Double): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu0_ADSdcfu1_ : $@convention(thin) (Double, Struct1) -> Struct1 { // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] : // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu4_ADSdcfu5_ : $@convention(thin) (Double, Struct1) -> Struct1 { // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFs5Int32VycSo10IAMStruct1Vmcfu8_ADycfu9_ : $@convention(thin) (@thin Struct1.Type) -> Int32 { // CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: [[RET:%.*]] = apply [[CFUNC]]() // CHECK: return [[RET]] // CHECK-LABEL:sil private [ossa] @$s10cf_members3fooyySdFySdcSo10IAMStruct1Vcfu10_ySdcfu11_ : $@convention(thin) (Double, Struct1) -> () { // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast // CHECK: apply [[CFUNC]]([[X]], [[SELF]]) // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFys5Int32V_SfSdtcSo10IAMStruct1Vcfu14_yAD_SfSdtcfu15_ : $@convention(thin) (Int32, Float, Double, Struct1) -> () { // CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird // CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]]) // CHECK-LABEL: sil [ossa] @$s10cf_members3bar{{[_0-9a-zA-Z]*}}F public func bar(_ x: Double) { // CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply let ps = CCPowerSupply(watts: x) // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator let fridge = CCRefrigerator(powerSupply: ps) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> () fridge.open() // CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply let ps2 = fridge.powerSupply // CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> () fridge.powerSupply = ps2 let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:) let _ = a(x) let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open b(fridge)() let c = fridge.open c() } // CHECK-LABEL: sil [ossa] @$s10cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F public func importGlobalVarsAsProperties() -> (Double, CCPowerSupply, CCPowerSupply?) { // CHECK: global_addr @kCCPowerSupplyDC // CHECK: global_addr @kCCPowerSupplyAC // CHECK: global_addr @kCCPowerSupplyDefaultPower return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC) }
apache-2.0
TouchInstinct/LeadKit
TIYandexMapUtils/Sources/Extensions/YMKScreenRect+CameraPositioning.swift
1
2970
// // Copyright (c) 2022 Touch Instinct // // 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 YandexMapsMobile public extension YMKScreenRect { func cameraPosition(in mapView: YMKMapView, insets: UIEdgeInsets) -> YMKCameraPosition? { let mapWindow: YMKMapWindow = mapView.mapWindow // mapWindow is IUO let center = YMKScreenPoint(x: (topLeft.x + bottomRight.x) / 2, y: (topLeft.y + bottomRight.y) / 2) guard let coordinatePoint = mapWindow.screenToWorld(with: center) else { return nil } let mapInsets: UIEdgeInsets if #available(iOS 11.0, *) { mapInsets = (insets + mapView.safeAreaInsets) * CGFloat(mapWindow.scaleFactor) } else { mapInsets = insets * CGFloat(mapWindow.scaleFactor) } let size = CGSize(width: mapWindow.width(), height: mapWindow.height()) guard let minScale = minScale(for: size, insets: mapInsets) else { return nil } let map = mapWindow.map let newZoom = map.cameraPosition.zoom + log2(minScale) let minZoom = map.getMinZoom() let maxZoom = map.getMaxZoom() return YMKCameraPosition(target: coordinatePoint, zoom: min(max(newZoom, minZoom), maxZoom), azimuth: 0, tilt: 0) } private func minScale(for mapSize: CGSize, insets: UIEdgeInsets) -> Float? { let width = CGFloat(abs(bottomRight.x - topLeft.x)) let height = CGFloat(abs(topLeft.y - bottomRight.y)) if width > 0 || height > 0 { let scaleX = mapSize.width / width - (insets.left + insets.right) / width let scaleY = mapSize.height / height - (insets.top + insets.bottom) / height return Float(min(scaleX, scaleY)) } return nil } }
apache-2.0
Reggian/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Utilities/Streams/DFUStreamHex.swift
3
3146
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ internal class DFUStreamHex : DFUStream { fileprivate(set) var currentPart = 1 fileprivate(set) var parts = 1 fileprivate(set) var currentPartType:UInt8 = 0 /// Firmware binaries fileprivate var binaries:Data /// The init packet content fileprivate var initPacketBinaries:Data? fileprivate var firmwareSize:UInt32 = 0 var size:DFUFirmwareSize { switch currentPartType { case FIRMWARE_TYPE_SOFTDEVICE: return DFUFirmwareSize(softdevice: firmwareSize, bootloader: 0, application: 0) case FIRMWARE_TYPE_BOOTLOADER: return DFUFirmwareSize(softdevice: 0, bootloader: firmwareSize, application: 0) // case FIRMWARE_TYPE_APPLICATION: default: return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: firmwareSize) } } var currentPartSize:DFUFirmwareSize { return size } init(urlToHexFile:URL, urlToDatFile:URL?, type:DFUFirmwareType) { let hexData = try? Data.init(contentsOf: urlToHexFile) binaries = IntelHex2BinConverter.convert(hexData) firmwareSize = UInt32(binaries.count) if let dat = urlToDatFile { initPacketBinaries = try? Data.init(contentsOf: dat) } self.currentPartType = type.rawValue } var data:Data { return binaries } var initPacket:Data? { return initPacketBinaries } func hasNextPart() -> Bool { return false } func switchToNextPart() { // do nothing } }
mit
lorentey/GlueKit
Sources/ValueMappingForValueField.swift
1
11005
// // SelectOperator.swift // GlueKit // // Created by Károly Lőrentey on 2015-12-06. // Copyright © 2015–2017 Károly Lőrentey. // extension ObservableValueType { /// Map is an operator that implements key path coding and observing. /// Given an observable parent and a key that selects an observable child component (a.k.a "field") of its value, /// `map` returns a new observable that can be used to look up and modify the field and observe its changes /// indirectly through the parent. /// /// @param key: An accessor function that returns a component of self (a field) that is itself observable. /// @returns A new observable that tracks changes to both self and the field returned by `key`. /// /// For example, take the model for a hypothetical group chat system below. /// ``` /// class Account { /// let name: Variable<String> /// let avatar: Variable<Image> /// } /// class Message { /// let author: Variable<Account> /// let text: Variable<String> /// } /// class Room { /// let latestMessage: AnyObservableValue<Message> /// let newMessages: Source<Message> /// let messages: ArrayVariable<Message> /// } /// let currentRoom: Variable<Room> /// ``` /// /// You can create an observable for the latest message in the current room with /// ```Swift /// let observable = currentRoom.map{$0.latestMessage} /// ``` /// Sinks connected to `observable.futureValues` will fire whenever the current room changes, or when a new /// message is posted in the current room. The observable can also be used to simply retrieve the latest /// message at any time. /// public func map<O: ObservableValueType>(_ key: @escaping (Value) -> O) -> AnyObservableValue<O.Value> { return ValueMappingForValueField(parent: self, key: key).anyObservableValue } } /// A source of changes for an Observable field. private final class ValueMappingForValueField<Parent: ObservableValueType, Field: ObservableValueType>: _BaseObservableValue<Field.Value> { typealias Value = Field.Value typealias Change = ValueChange<Value> struct ParentSink: OwnedSink { typealias Owner = ValueMappingForValueField<Parent, Field> unowned let owner: Owner let identifier = 1 func receive(_ update: ValueUpdate<Parent.Value>) { owner.applyParentUpdate(update) } } struct FieldSink: OwnedSink { typealias Owner = ValueMappingForValueField<Parent, Field> unowned let owner: Owner let identifier = 2 func receive(_ update: ValueUpdate<Field.Value>) { owner.applyFieldUpdate(update) } } let parent: Parent let key: (Parent.Value) -> Field private var currentValue: Field.Value? = nil private var field: Field? = nil override var value: Field.Value { if let v = currentValue { return v } return key(parent.value).value } init(parent: Parent, key: @escaping (Parent.Value) -> Field) { self.parent = parent self.key = key } override func activate() { precondition(currentValue == nil) let field = key(parent.value) self.currentValue = field.value subscribe(to: field) parent.add(ParentSink(owner: self)) } override func deactivate() { precondition(currentValue != nil) self.field!.remove(FieldSink(owner: self)) parent.remove(ParentSink(owner: self)) self.field = nil self.currentValue = nil } private func subscribe(to field: Field) { self.field?.remove(FieldSink(owner: self)) self.field = field field.add(FieldSink(owner: self)) } func applyParentUpdate(_ update: ValueUpdate<Parent.Value>) { switch update { case .beginTransaction: beginTransaction() case .change(let change): let field = key(change.new) let old = currentValue! let new = field.value currentValue = new sendChange(ValueChange(from: old, to: new)) subscribe(to: field) case .endTransaction: endTransaction() } } func applyFieldUpdate(_ update: ValueUpdate<Field.Value>) { switch update { case .beginTransaction: beginTransaction() case .change(let change): let old = currentValue! currentValue = change.new sendChange(ValueChange(from: old, to: change.new)) case .endTransaction: endTransaction() } } } extension ObservableValueType { public func flatMap<O: ObservableValueType>(_ key: @escaping (Value) -> O?) -> AnyObservableValue<O.Value?> { return ValueMappingForOptionalValueField(parent: self, key: key).anyObservableValue } } private final class ValueMappingForOptionalValueField<Parent: ObservableValueType, Field: ObservableValueType>: _BaseObservableValue<Field.Value?> { typealias Value = Field.Value? typealias Change = ValueChange<Value> struct ParentSink: OwnedSink { typealias Owner = ValueMappingForOptionalValueField<Parent, Field> unowned let owner: Owner let identifier = 1 func receive(_ update: ValueUpdate<Parent.Value>) { owner.applyParentUpdate(update) } } struct FieldSink: OwnedSink { typealias Owner = ValueMappingForOptionalValueField<Parent, Field> unowned let owner: Owner let identifier = 2 func receive(_ update: ValueUpdate<Field.Value>) { owner.applyFieldUpdate(update) } } let parent: Parent let key: (Parent.Value) -> Field? private var activated = false private var currentValue: Field.Value? = nil private var field: Field? = nil override var value: Value { if activated { return currentValue } return key(parent.value)?.value } init(parent: Parent, key: @escaping (Parent.Value) -> Field?) { self.parent = parent self.key = key } override func activate() { precondition(!activated) activated = true if let field = key(parent.value) { self.currentValue = field.value subscribe(to: field) } else { self.currentValue = nil } parent.add(ParentSink(owner: self)) } override func deactivate() { precondition(activated) self.field?.remove(FieldSink(owner: self)) parent.remove(ParentSink(owner: self)) self.field = nil self.currentValue = nil activated = false } private func subscribe(to field: Field) { self.field?.remove(FieldSink(owner: self)) self.field = field field.add(FieldSink(owner: self)) } func applyParentUpdate(_ update: ValueUpdate<Parent.Value>) { switch update { case .beginTransaction: beginTransaction() case .change(let change): let field = key(change.new) let old = currentValue let new = field?.value currentValue = new sendChange(ValueChange(from: old, to: new)) if let field = field { subscribe(to: field) } case .endTransaction: endTransaction() } } func applyFieldUpdate(_ update: ValueUpdate<Field.Value>) { switch update { case .beginTransaction: beginTransaction() case .change(let change): let old = currentValue currentValue = change.new sendChange(ValueChange(from: old, to: change.new)) case .endTransaction: endTransaction() } } } extension ObservableValueType { /// Map is an operator that implements key path coding and observing. /// Given an observable parent and a key that selects an observable child component (a.k.a "field") of its value, /// `map` returns a new observable that can be used to look up and modify the field and observe its changes /// indirectly through the parent. If the field is updatable, then the result will be, too. /// /// @param key: An accessor function that returns a component of self (a field) that is itself updatable. /// @returns A new updatable that tracks changes to both self and the field returned by `key`. /// /// For example, take the model for a hypothetical group chat system below. /// ``` /// class Account { /// let name: Variable<String> /// let avatar: Variable<Image> /// } /// class Message { /// let author: Variable<Account> /// let text: Variable<String> /// } /// class Room { /// let latestMessage: AnyObservableValue<Message> /// let messages: ArrayVariable<Message> /// let newMessages: Source<Message> /// } /// let currentRoom: Variable<Room> /// ``` /// /// You can create an updatable for the avatar image of the author of the latest message in the current room with /// ```Swift /// let updatable = currentRoom.map{$0.latestMessage}.map{$0.author}.map{$0.avatar} /// ``` /// Sinks connected to `updatable.futureValues` will fire whenever the current room changes, or when a new message is posted /// in the current room, or when the author of that message is changed, or when the current /// author changes their avatar. The updatable can also be used to simply retrieve the avatar at any time, /// or to update it. /// public func map<U: UpdatableValueType>(_ key: @escaping (Value) -> U) -> AnyUpdatableValue<U.Value> { return ValueMappingForUpdatableField<Self, U>(parent: self, key: key).anyUpdatableValue } } private final class ValueMappingForUpdatableField<Parent: ObservableValueType, Field: UpdatableValueType>: _AbstractUpdatableValue<Field.Value> { typealias Value = Field.Value private let _observable: ValueMappingForValueField<Parent, Field> init(parent: Parent, key: @escaping (Parent.Value) -> Field) { self._observable = ValueMappingForValueField<Parent, Field>(parent: parent, key: key) } override var value: Field.Value { get { return _observable.value } set { _observable.key(_observable.parent.value).value = newValue } } override func apply(_ update: Update<ValueChange<Field.Value>>) { return _observable.key(_observable.parent.value).apply(update) } override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Update<Change> { _observable.add(sink) } @discardableResult override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Update<Change> { return _observable.remove(sink) } }
mit
between40and2/XALG
frameworks/Framework-XALG-Tests/Linear/XALG_Tests_Stack.swift
1
618
// // XALG_Tests_Stack.swift // XALG // // Created by Juguang Xiao on 2/24/16. // import XCTest class XALG_Tests_Stack: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func test_stack_array() { var stack = XALG_DS_Stack__Array<Int>() stack.push(1) stack.push(2) // if let i2 = stack.pop() { // // } XCTAssertEqual(stack.pop()!, 2) XCTAssertEqual(stack.pop()!, 1) XCTAssertNil(stack.pop()) } }
mit
quran/quran-ios
Tests/QuranKitTests/QuarterTests.swift
1
2435
// // QuarterTests.swift // // // Created by Mohamed Afifi on 2021-12-11. // @testable import QuranKit import XCTest final class QuarterTests: XCTestCase { private let quran = Quran.madani func testQuarters() throws { let quarters = quran.quarters XCTAssertEqual(quarters.count, 240) XCTAssertEqual(quarters.first!.quarterNumber, 1) XCTAssertEqual(quarters.last!.quarterNumber, 240) XCTAssertEqual(quarters[21].quarterNumber, 22) XCTAssertEqual(quarters[0].description, "<Quarter value=1>") XCTAssertEqual(quarters[29].description, "<Quarter value=30>") XCTAssertEqual(quarters[1], quarters[0].next) XCTAssertEqual(quarters[29], quarters[28].next) XCTAssertEqual(quarters[29], quarters[27].next?.next) XCTAssertNil(quarters.last!.next) XCTAssertEqual(quarters[0], quarters[1].previous) XCTAssertEqual(quarters[28], quarters[29].previous) XCTAssertEqual(quarters[27], quarters[29].previous?.previous) XCTAssertNil(quarters[0].previous) XCTAssertTrue(quarters[3] == quarters[3]) XCTAssertTrue(quarters[3] < quarters[4]) XCTAssertTrue(quarters[3] > quarters[2]) XCTAssertEqual(quarters[0].firstVerse.sura.suraNumber, 1) XCTAssertEqual(quarters[0].firstVerse.ayah, 1) XCTAssertEqual(quarters[239].firstVerse.sura.suraNumber, 100) XCTAssertEqual(quarters[239].firstVerse.ayah, 9) XCTAssertEqual(quarters[8].firstVerse.sura.suraNumber, 2) XCTAssertEqual(quarters[8].firstVerse.ayah, 142) XCTAssertEqual(quarters[0].page.pageNumber, 1) XCTAssertEqual(quarters[7].page.pageNumber, 19) XCTAssertEqual(quarters[8].page.pageNumber, 22) XCTAssertEqual(quarters[239].page.pageNumber, 599) XCTAssertEqual(quarters[0].juz.juzNumber, 1) XCTAssertEqual(quarters[7].juz.juzNumber, 1) XCTAssertEqual(quarters[8].juz.juzNumber, 2) XCTAssertEqual(quarters[239].juz.juzNumber, 30) XCTAssertEqual(quarters[0].hizb.hizbNumber, 1) XCTAssertEqual(quarters[7].hizb.hizbNumber, 2) XCTAssertEqual(quarters[8].hizb.hizbNumber, 3) XCTAssertEqual(quarters[239].hizb.hizbNumber, 60) } func testQuartersJuzTime() { measure { let quarters = quran.quarters _ = Dictionary(grouping: quarters, by: \.juz) } } }
apache-2.0
pNre/Kingfisher
Tests/KingfisherTests/UIButtonExtensionTests.swift
2
7597
// // UIButtonExtensionTests.swift // Kingfisher // // Created by Wei Wang on 15/4/17. // // Copyright (c) 2018 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import XCTest @testable import Kingfisher class UIButtonExtensionTests: XCTestCase { var button: UIButton! override class func setUp() { super.setUp() LSNocilla.sharedInstance().start() } override class func tearDown() { super.tearDown() LSNocilla.sharedInstance().stop() } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. button = UIButton() KingfisherManager.shared.downloader = ImageDownloader(name: "testDownloader") cleanDefaultCache() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. LSNocilla.sharedInstance().clearStubs() button = nil cleanDefaultCache() super.tearDown() } func testDownloadAndSetImage() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! var progressBlockIsCalled = false cleanDefaultCache() button.kf.setImage(with: url, for: .highlighted, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> Void in progressBlockIsCalled = true }) { (image, error, cacheType, imageURL) -> Void in expectation.fulfill() XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.") XCTAssert(image != nil, "Downloaded image should exist.") XCTAssert(image! == testImage, "Downloaded image should be the same as test image.") XCTAssert(self.button.image(for: UIControl.State.highlighted)! == testImage, "Downloaded image should be already set to the image for state") XCTAssert(self.button.kf.webURL(for: .highlighted) == imageURL, "Web URL should equal to the downloaded url.") XCTAssert(cacheType == .none, "The cache type should be none here. This image was just downloaded. But now is: \(cacheType)") } waitForExpectations(timeout: 5, handler: nil) } func testDownloadAndSetBackgroundImage() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = Foundation.URL(string: URLString)! var progressBlockIsCalled = false button.kf.setBackgroundImage(with: url, for: .normal, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> Void in progressBlockIsCalled = true }) { (image, error, cacheType, imageURL) -> Void in expectation.fulfill() XCTAssert(progressBlockIsCalled, "progressBlock should be called at least once.") XCTAssert(image != nil, "Downloaded image should exist.") XCTAssert(image! == testImage, "Downloaded image should be the same as test image.") XCTAssert(self.button.backgroundImage(for: .normal)! == testImage, "Downloaded image should be already set to the image for state") XCTAssert(self.button.kf.backgroundWebURL(for: .normal) == imageURL, "Web URL should equal to the downloaded url.") XCTAssert(cacheType == .none, "cacheType should be .None since the image was just downloaded.") } waitForExpectations(timeout: 5, handler: nil) } func testCacnelImageTask() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] let stub = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)?.delay() let url = URL(string: URLString)! button.kf.setImage(with: url, for: UIControl.State.highlighted, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> Void in }) { (image, error, cacheType, imageURL) -> Void in XCTAssertNotNil(error) XCTAssertEqual(error?.code, NSURLErrorCancelled) expectation.fulfill() } delay(0.1) { self.button.kf.cancelImageDownloadTask() _ = stub!.go() } waitForExpectations(timeout: 5, handler: nil) } func testCacnelBackgroundImageTask() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] let stub = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData)?.delay() let url = URL(string: URLString)! button.kf.setBackgroundImage(with: url, for: UIControl.State(), placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> Void in XCTFail("Progress block should not be called.") }) { (image, error, cacheType, imageURL) -> Void in XCTAssertNotNil(error) XCTAssertEqual(error?.code, NSURLErrorCancelled) expectation.fulfill() } delay(0.1) { self.button.kf.cancelBackgroundImageDownloadTask() _ = stub!.go() } waitForExpectations(timeout: 5, handler: nil) } func testSettingNilURL() { let expectation = self.expectation(description: "wait for downloading image") let url: URL? = nil button.kf.setBackgroundImage(with: url, for: UIControl.State(), placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) -> Void in XCTFail("Progress block should not be called.") }) { (image, error, cacheType, imageURL) -> Void in XCTAssertNil(image) XCTAssertNil(error) XCTAssertEqual(cacheType, CacheType.none) XCTAssertNil(imageURL) expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } }
mit
vl4298/mah-income
Mah Income/Mah Income/TransitionAnimator/DimmingPresentationController.swift
1
303
// // DimmingPresentationController.swift // Mah Income // // Created by Van Luu on 4/17/17. // Copyright © 2017 Van Luu. All rights reserved. // import UIKit class DimmingPresentationController: UIPresentationController { override var shouldRemovePresentersView: Bool { return false } }
mit
onekiloparsec/SwiftAA
Sources/SwiftAA/ObjectBase.swift
2
1904
// // ObjectBase.swift // SwiftAA // // Created by Cédric Foellmi on 18/07/16. // MIT Licence. See LICENCE file. // import Foundation /// Base protocol used by all types of astronomical objects considered in SwiftAA, /// planets, moons, the Earth, the Sun etc. public protocol ObjectBase { /// The julian day at which one considers the object. var julianDay: JulianDay { get } /// A boolean indicating whether high precision (i.e. VSOP87 theory) must be used. var highPrecision: Bool { get } /// The object name var name: String { get } /// Creates an object instance /// /// - Parameters: /// - julianDay: The julian day at which one will consider the object /// - highPrecision: If true (default), the VSOP87 theory is used when relevant to increase precision /// significantly. Is probably computationally slower compared to low-precision algorithms. init(julianDay: JulianDay, highPrecision: Bool) } /// The base class of all objects (Planets, Sun, Moons etc.). open class Object : ObjectBase { /// The Julian Day at which the object is considered. public fileprivate(set) var julianDay: JulianDay /// The precision flag. public fileprivate(set) var highPrecision: Bool /// A convenience accesor returning the name of the object class. public var name: String { return String(describing: type(of: self)) } /// Creates a new instance of the object. /// /// - Parameters: /// - julianDay: The julian day at which one will consider the object /// - highPrecision: A optional boolean indicating whether high precision (i.e. VSOP87 theory) must be used. /// Default is true. public required init(julianDay: JulianDay, highPrecision: Bool = true) { self.julianDay = julianDay self.highPrecision = highPrecision } }
mit
wesleysadler/UniversalStoryboard
UniversalStoryboardTests/UniversalStoryboardTests.swift
1
940
// // UniversalStoryboardTests.swift // UniversalStoryboardTests // // Created by Wesley Sadler on 1/6/15. // Copyright (c) 2015 Digital Sadler. All rights reserved. // import UIKit import XCTest class UniversalStoryboardTests: 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
swixbase/filesystem
Tests/FilesystemTests/FileHandlerTests.swift
1
11184
/// Copyright 2017 Sergei Egorov /// /// 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 XCTest import Foundation @testable import Filesystem class FileHandlerTests: XCTestCase { let fsManager = FileSystem() let fileHandler = FileHandler() static var allTests : [(String, (FileHandlerTests) -> () throws -> Void)] { return [ ("testOpenFileForReading", testOpenFileForReading), ("testOpenFileForUpdating", testOpenFileForUpdating), ("testOpenFileForWriting", testOpenFileForWriting), ("testIsFileOpen", testIsFileOpen), ("testReadWholeFileAtPath", testReadWholeFileAtPath), ("testReadWholeFileAtFileDescriptor", testReadWholeFileAtFileDescriptor), ("testReadBytesOfFileAtPath", testReadBytesOfFileAtPath), ("testReadBytesOfFileAtFileDescriptor", testReadBytesOfFileAtFileDescriptor), ("testWriteContentInFileAtPath", testWriteContentInFileAtPath), ("testWriteContentInFileAtFileDescriptor", testWriteContentInFileAtFileDescriptor), ("testWriteContentInFileToEOFAtPath", testWriteContentInFileToEOFAtPath), ("testWriteContentInFileToEOFAtFileDescriptor", testWriteContentInFileToEOFAtFileDescriptor), ("testTruncateFileAtPath", testTruncateFileAtPath), ("testTruncateFileAtFileDescriptor", testTruncateFileAtFileDescriptor) ] } // MARK: - Helpers func createTestFile(atPath path: String) { let content = "abcdefghijklmnopqrstuvwxyz".data(using: .utf8)! fsManager.createFile(atPath: path, content: content) } func generateFileName() -> String { return "\(fsManager.workPath)/\(UUID().uuidString)" } func deleteTestFile(atPath path: String) { do { try fsManager.deleteObject(atPath: path) } catch let error as FileSystemError { XCTFail(error.description) } catch { XCTFail("Unhandled error") } } // MARK: - Tests func testOpenFileForReading() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let descriptor = try fileHandler.openFileForReading(atPath: testfilePath) XCTAssertNotNil(descriptor) try fileHandler.closeFile(descriptor: descriptor) deleteTestFile(atPath: testfilePath) } func testOpenFileForUpdating() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let descriptor = try fileHandler.openFileForUpdating(atPath: testfilePath) XCTAssertNotNil(descriptor) try fileHandler.closeFile(descriptor: descriptor) deleteTestFile(atPath: testfilePath) } func testOpenFileForWriting() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let descriptor = try fileHandler.openFileForWriting(atPath: testfilePath) XCTAssertNotNil(descriptor) try fileHandler.closeFile(descriptor: descriptor) deleteTestFile(atPath: testfilePath) } func testIsFileOpen() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let descriptor = try fileHandler.openFileForWriting(atPath: testfilePath) XCTAssertTrue(fileHandler.isFileOpen(descriptor: descriptor)) try fileHandler.closeFile(descriptor: descriptor) XCTAssertFalse(fileHandler.isFileOpen(descriptor: descriptor)) deleteTestFile(atPath: testfilePath) } func testReadWholeFileAtPath() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let data = try fileHandler.readWholeFile(atPath: testfilePath) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "abcdefghijklmnopqrstuvwxyz") deleteTestFile(atPath: testfilePath) } func testReadWholeFileAtFileDescriptor() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let descriptor = try fileHandler.openFileForReading(atPath: testfilePath) let data = try fileHandler.readWholeFile(atFileDescriptor: descriptor) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "abcdefghijklmnopqrstuvwxyz") deleteTestFile(atPath: testfilePath) } func testReadBytesOfFileAtPath() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let data = try fileHandler.readBytesOfFile(atPath: testfilePath, start: 3, end: 6) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "def") deleteTestFile(atPath: testfilePath) } func testReadBytesOfFileAtFileDescriptor() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let descriptor = try fileHandler.openFileForReading(atPath: testfilePath) let data = try fileHandler.readBytesOfFile(atFileDescriptor: descriptor, start: 6, end: 9) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "ghi") deleteTestFile(atPath: testfilePath) } func testWriteContentInFileAtPath() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let recordData: Data = "mlkjihgfedcba".data(using: .utf8)! let count = try fileHandler.writeContentInFile(atPath: testfilePath, offset: 13, content: recordData) let data = try fileHandler.readWholeFile(atPath: testfilePath) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "abcdefghijklmmlkjihgfedcba") XCTAssertEqual(recordData.count, Int(count)) deleteTestFile(atPath: testfilePath) } func testWriteContentInFileAtFileDescriptor() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let writeDescriptor = try fileHandler.openFileForWriting(atPath: testfilePath) let recordData = "zyxwvutsrqpon".data(using: .utf8)! let count = try fileHandler.writeContentInFile(atFileDescriptor: writeDescriptor, offset: 0, content: recordData) try fileHandler.closeFile(descriptor: writeDescriptor) let readDescriptor = try self.fileHandler.openFileForReading(atPath: testfilePath) let data = try fileHandler.readWholeFile(atFileDescriptor: readDescriptor) let content = String(data: data, encoding: .utf8)! try fileHandler.closeFile(descriptor: readDescriptor) XCTAssertEqual(content, "zyxwvutsrqponnopqrstuvwxyz") XCTAssertEqual(recordData.count, Int(count)) deleteTestFile(atPath: testfilePath) } func testWriteContentInFileToEOFAtPath() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let recordData = "1234567890".data(using: .utf8)! let count = try fileHandler.writeContentToEndOfFile(atPath: testfilePath, content: recordData) let data = try self.fileHandler.readWholeFile(atPath: testfilePath) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "abcdefghijklmnopqrstuvwxyz1234567890") XCTAssertEqual(recordData.count, Int(count)) deleteTestFile(atPath: testfilePath) } func testWriteContentInFileToEOFAtFileDescriptor() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let recordData = "0987654321".data(using: .utf8)! let writeDescriptor = try fileHandler.openFileForWriting(atPath: testfilePath) let count = try fileHandler.writeContentToEndOfFile(atFileDescriptor: writeDescriptor, content: recordData) try fileHandler.closeFile(descriptor: writeDescriptor) let readDescriptor = try self.fileHandler.openFileForReading(atPath: testfilePath) let data = try fileHandler.readWholeFile(atFileDescriptor: readDescriptor) let content = String(data: data, encoding: .utf8)! try fileHandler.closeFile(descriptor: readDescriptor) XCTAssertEqual(content, "abcdefghijklmnopqrstuvwxyz0987654321") XCTAssertEqual(recordData.count, Int(count)) deleteTestFile(atPath: testfilePath) } func testTruncateFileAtPath() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) try fileHandler.truncateFile(atPath: testfilePath, toOffset: 0) let data = try self.fileHandler.readWholeFile(atPath: testfilePath) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "") deleteTestFile(atPath: testfilePath) } func testTruncateFileAtFileDescriptor() throws { let testfilePath = generateFileName() createTestFile(atPath: testfilePath) XCTAssertTrue(fsManager.existsObject(atPath: testfilePath)) let writeDescriptor = try fileHandler.openFileForWriting(atPath: testfilePath) try fileHandler.truncateFile(atFileDescriptor: writeDescriptor, toOffset: 10) try fileHandler.closeFile(descriptor: writeDescriptor) let readDescriptor = try self.fileHandler.openFileForReading(atPath: testfilePath) let data = try fileHandler.readWholeFile(atFileDescriptor: readDescriptor) let content = String(data: data, encoding: .utf8)! try fileHandler.closeFile(descriptor: readDescriptor) XCTAssertEqual(content, "abcdefghij") deleteTestFile(atPath: testfilePath) } }
apache-2.0
herveperoteau/TracktionProto2
TracktionProto2/WatchConnectivity/WatchConnectivityLayer.swift
1
2090
// // TrackDataItem.swift // TracktionProto1 // // Created by Hervé PEROTEAU on 03/01/2016. // Copyright © 2016 Hervé PEROTEAU. All rights reserved. // import Foundation let infoEndSession = "END" let keyTrackSessionId = "tSId" let keyDateStart = "DS" let keyDateEnd = "DE" let keyTimeStamp = "TS" let keyAccelerationX = "X" let keyAccelerationY = "Y" let keyAccelerationZ = "Z" let keyInfo = "I" class TrackSession { var trackSessionId: Int = 0 var dateStart: Double = 0.0 var dateEnd: Double = 0.0 var info: String = "" static func fromDictionary(userInfo: [String : AnyObject]) -> TrackSession { let item = TrackSession() item.trackSessionId = userInfo[keyTrackSessionId] as! Int item.dateStart = userInfo[keyDateStart] as! Double item.dateEnd = userInfo[keyDateEnd] as! Double item.info = userInfo[keyInfo] as! String return item } func toDictionary() -> [String : AnyObject] { var userInfo = [String : AnyObject]() userInfo[keyTrackSessionId] = trackSessionId userInfo[keyDateStart] = dateStart userInfo[keyDateEnd] = dateEnd userInfo[keyInfo] = info return userInfo } } class TrackDataItem { var trackSessionId: Int = 0 var timeStamp: Double = 0.0 var accelerationX: Double = 0.0 var accelerationY: Double = 0 var accelerationZ: Double = 0 static func fromDictionary(userInfo: [String : AnyObject]) -> TrackDataItem { let item = TrackDataItem() item.trackSessionId = userInfo[keyTrackSessionId] as! Int item.timeStamp = userInfo[keyTimeStamp] as! Double item.accelerationX = userInfo[keyAccelerationX] as! Double item.accelerationY = userInfo[keyAccelerationY] as! Double item.accelerationZ = userInfo[keyAccelerationZ] as! Double return item } func toDictionary() -> [String : AnyObject] { var userInfo = [String : AnyObject]() userInfo[keyTrackSessionId] = trackSessionId userInfo[keyTimeStamp] = timeStamp userInfo[keyAccelerationX] = accelerationX userInfo[keyAccelerationY] = accelerationY userInfo[keyAccelerationZ] = accelerationZ return userInfo } }
mit
AirChen/ACSwiftDemoes
Target11-PorpertyAnimate/ViewController.swift
1
1334
// // ViewController.swift // Target11-PorpertyAnimate // // Created by Air_chen on 2016/11/6. // Copyright © 2016年 Air_chen. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var keyField: UITextField! @IBOutlet weak var btn: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. nameField.transform = CGAffineTransform.init(translationX: -100, y: 0) keyField.transform = CGAffineTransform.init(translationX: -200, y: 0) btn.transform = CGAffineTransform.init(scaleX: 2, y: 1) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.2, animations:{ self.nameField.transform = CGAffineTransform.identity self.keyField.transform = CGAffineTransform.identity }) UIView.animate(withDuration: 0.3, animations: { self.btn.transform = CGAffineTransform.identity }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
dipen30/Qmote
KodiRemote/Pods/UPnAtom/Source/AV Profile/Services/ContentDirectory1Objects.swift
1
8582
// // ContentDirectory1Object.swift // // Copyright (c) 2015 David Robles // // 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 Ono // MARK: ContentDirectory1Object /// TODO: For now rooting to NSObject to expose to Objective-C, see Github issue #16 open class ContentDirectory1Object: NSObject { open let objectID: String open let parentID: String open let title: String open let rawType: String open let albumArtURL: URL? init?(xmlElement: ONOXMLElement) { if let objectID = xmlElement.value(forAttribute: "id") as? String, let parentID = xmlElement.value(forAttribute: "parentID") as? String, let title = xmlElement.firstChild(withTag: "title").stringValue(), let rawType = xmlElement.firstChild(withTag: "class").stringValue() { self.objectID = objectID self.parentID = parentID self.title = title self.rawType = rawType if let albumArtURLString = xmlElement.firstChild(withTag: "albumArtURI")?.stringValue() { self.albumArtURL = URL(string: albumArtURLString) } else { albumArtURL = nil } } else { /// TODO: Remove default initializations to simply return nil, see Github issue #11 objectID = "" parentID = "" title = "" rawType = "" albumArtURL = nil super.init() return nil } super.init() } } extension ContentDirectory1Object: ExtendedPrintable { #if os(iOS) public var className: String { return "\(type(of: self))" } #elseif os(OSX) // NSObject.className actually exists on OSX! Who knew. override public var className: String { return "\(type(of: self))" } #endif override open var description: String { var properties = PropertyPrinter() properties.add("id", property: objectID) properties.add("parentID", property: parentID) properties.add("title", property: title) properties.add("class", property: rawType) properties.add("albumArtURI", property: albumArtURL?.absoluteString) return properties.description } } // MARK: - ContentDirectory1Container open class ContentDirectory1Container: ContentDirectory1Object { open let childCount: Int? override init?(xmlElement: ONOXMLElement) { self.childCount = Int(String(describing: xmlElement.value(forAttribute: "childCount"))) super.init(xmlElement: xmlElement) } } /// for objective-c type checking extension ContentDirectory1Object { public func isContentDirectory1Container() -> Bool { return self is ContentDirectory1Container } } /// overrides ExtendedPrintable protocol implementation extension ContentDirectory1Container { override public var className: String { return "\(type(of: self))" } override open var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) properties.add("childCount", property: "\(childCount)") return properties.description } } // MARK: - ContentDirectory1Item open class ContentDirectory1Item: ContentDirectory1Object { open let resourceURL: URL! override init?(xmlElement: ONOXMLElement) { /// TODO: Return nil immediately instead of waiting, see Github issue #11 if let resourceURLString = xmlElement.firstChild(withTag: "res").stringValue() { resourceURL = URL(string: resourceURLString) } else { resourceURL = nil } super.init(xmlElement: xmlElement) guard resourceURL != nil else { return nil } } } /// for objective-c type checking extension ContentDirectory1Object { public func isContentDirectory1Item() -> Bool { return self is ContentDirectory1Item } } /// overrides ExtendedPrintable protocol implementation extension ContentDirectory1Item { override public var className: String { return "\(type(of: self))" } override open var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) properties.add("resourceURL", property: resourceURL?.absoluteString) return properties.description } } // MARK: - ContentDirectory1VideoItem open class ContentDirectory1VideoItem: ContentDirectory1Item { open let bitrate: Int? open let duration: TimeInterval? open let audioChannelCount: Int? open let protocolInfo: String? open let resolution: CGSize? open let sampleFrequency: Int? open let size: Int? override init?(xmlElement: ONOXMLElement) { bitrate = Int(String(describing: xmlElement.firstChild(withTag: "res").value(forAttribute: "bitrate"))) if let durationString = xmlElement.firstChild(withTag: "res").value(forAttribute: "duration") as? String { let durationComponents = durationString.components(separatedBy: ":") var count: Double = 0 var duration: Double = 0 for durationComponent in durationComponents.reversed() { duration += (durationComponent as NSString).doubleValue * pow(60, count) count += 1 } self.duration = TimeInterval(duration) } else { self.duration = nil } audioChannelCount = Int(String(describing: xmlElement.firstChild(withTag: "res").value(forAttribute: "nrAudioChannels"))) protocolInfo = xmlElement.firstChild(withTag: "res").value(forAttribute: "protocolInfo") as? String if let resolutionComponents = (xmlElement.firstChild(withTag: "res").value(forAttribute: "resolution") as? String)?.components(separatedBy: "x"), let width = Int(String(describing: resolutionComponents.first)), let height = Int(String(describing: resolutionComponents.last)) { resolution = CGSize(width: width, height: height) } else { resolution = nil } sampleFrequency = Int(String(describing: xmlElement.firstChild(withTag: "res").value(forAttribute: "sampleFrequency"))) size = Int(String(describing: xmlElement.firstChild(withTag: "res").value(forAttribute: "size"))) super.init(xmlElement: xmlElement) } } /// for objective-c type checking extension ContentDirectory1Object { public func isContentDirectory1VideoItem() -> Bool { return self is ContentDirectory1VideoItem } } /// overrides ExtendedPrintable protocol implementation extension ContentDirectory1VideoItem { override public var className: String { return "\(type(of: self))" } override open var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) properties.add("bitrate", property: "\(bitrate)") properties.add("duration", property: "\(duration)") properties.add("audioChannelCount", property: "\(audioChannelCount)") properties.add("protocolInfo", property: protocolInfo) properties.add("resolution", property: "\(resolution?.width)x\(resolution?.height)") properties.add("sampleFrequency", property: "\(sampleFrequency)") properties.add("size", property: "\(size)") return properties.description } }
apache-2.0
mklbtz/finch
Tests/TaskManagementTests/TranscoderTests.swift
1
1290
import XCTest import TaskManagement class TranscoderTests: XCTestCase { func testStringToData() throws { let subject = Transcoder<String, Data>.stringToData let original = "test" let encoded = original.data(using: .utf8)! XCTAssertEqual(try subject.encode(original), encoded) XCTAssertEqual(try subject.decode(encoded), original) } func testJsonToData() throws { let subject = Transcoder<[[String:Any]], Data>.jsonToData let original = [["key":"value"]] let encoded = try JSONSerialization.data(withJSONObject: original) XCTAssertEqual(try subject.encode(original), encoded) if let value = try subject.decode(encoded).first?["key"] as? String { XCTAssertEqual(value, original.first?["key"]) } else { XCTFail("json was not decoded correctly") } } func testTaskToJson() throws { let subject = Transcoder<[Task], [[String:Any]]>.taskToJson let original = [buildTask()] let encoded = original.map { $0.jsonObject() } XCTAssertEqual(try subject.decode(encoded), original) if let jsonObject = try subject.encode(original).first, let task = Task(from: jsonObject) { XCTAssertEqual(task, original.first) } else { XCTFail("json was not encoded correctly") } } }
mit
groupme/LibGroupMe
LibGroupMeTests/UserTest.swift
1
1811
import LibGroupMe import Quick import Nimble class UserTestHelper: NSObject { func dmIndex() -> NSDictionary { let path = NSBundle(forClass: NSClassFromString(self.className)!).pathForResource("dms-index", ofType: "json") let data = NSData(contentsOfFile: path!) var error: NSError? var dataDict = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.allZeros, error: &error) as! NSDictionary expect(error).to(beNil()) expect(dataDict).toNot(beNil()) return dataDict } } class UserTest: QuickSpec { override func spec() { describe("a list of dm-s") { it("should generate a list of serializable objects") { var dict = UserTestHelper().dmIndex() var dms: Array<User> = Array<User>() if let dmInfos = dict["response"] as? NSArray { expect(dmInfos.count).to(equal(1)) for info in dmInfos { dms.append(User(info: info as! NSDictionary)) } } else { fail() } expect(dms.count).to(equal(1)) for d in dms { expect(d.createdAt).toNot(beNil()) expect(d.updatedAt).toNot(beNil()) expect(d.otherUser).toNot(beNil()) expect(d.otherUser.name).toNot(beNil()) expect(d.otherUser.userID).toNot(beNil()) expect(d.lastMessage).toNot(beNil()) expect(d.lastMessage.text).toNot(beNil()) expect(d.lastMessage.messageID).toNot(beNil()) } } } } }
mit
MadArkitekt/Swift_Tutorials_And_Demos
AdaptiveWeather/AdaptiveWeatherTests/AdaptiveWeatherTests.swift
1
928
// // AdaptiveWeatherTests.swift // AdaptiveWeatherTests // // Created by Edward Salter on 9/25/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import UIKit import XCTest class AdaptiveWeatherTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
gpl-2.0
cclovett/iRemeber
iRemeber/Pods/Bits/Sources/Bits/Data+BytesConvertible.swift
2
287
import Foundation extension Data: BytesConvertible { public func makeBytes() -> Bytes { var array = Bytes(repeating: 0, count: count) let buffer = UnsafeMutableBufferPointer(start: &array, count: count) _ = copyBytes(to: buffer) return array } }
mit