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
dcutting/Syft
Package.swift
1
406
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "Syft", products: [ .library(name: "Syft", targets: ["Syft"]) ], targets: [ .target( name: "Sample", dependencies: ["Syft"]), .target( name: "Syft"), .testTarget( name: "SyftTests", dependencies: ["Syft"]) ] )
mit
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/DataStructures/Bag.swift
12
7470
// // Bag.swift // Rx // // Created by Krunoslav Zaher on 2/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import Swift let arrayDictionaryMaxSize = 30 /** Class that enables using memory allocations as a means to uniquely identify objects. */ class Identity { // weird things have known to happen with Swift var _forceAllocation: Int32 = 0 } func hash(_ _x: Int) -> Int { var x = _x x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) return x; } /** Unique identifier for object added to `Bag`. */ public struct BagKey : Hashable { let uniqueIdentity: Identity? let key: Int public var hashValue: Int { if let uniqueIdentity = uniqueIdentity { return hash(key) ^ (ObjectIdentifier(uniqueIdentity).hashValue) } else { return hash(key) } } } /** Compares two `BagKey`s. */ public func == (lhs: BagKey, rhs: BagKey) -> Bool { return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity } /** Data structure that represents a bag of elements typed `T`. Single element can be stored multiple times. Time and space complexity of insertion an deletion is O(n). It is suitable for storing small number of elements. */ public struct Bag<T> : CustomDebugStringConvertible { /** Type of identifier for inserted elements. */ public typealias KeyType = BagKey fileprivate typealias ScopeUniqueTokenType = Int typealias Entry = (key: BagKey, value: T) fileprivate var _uniqueIdentity: Identity? fileprivate var _nextKey: ScopeUniqueTokenType = 0 // data // first fill inline variables fileprivate var _key0: BagKey? = nil fileprivate var _value0: T? = nil fileprivate var _key1: BagKey? = nil fileprivate var _value1: T? = nil // then fill "array dictionary" fileprivate var _pairs = ContiguousArray<Entry>() // last is sparse dictionary fileprivate var _dictionary: [BagKey : T]? = nil fileprivate var _onlyFastPath = true /** Creates new empty `Bag`. */ public init() { } /** Inserts `value` into bag. - parameter element: Element to insert. - returns: Key that can be used to remove element from bag. */ public mutating func insert(_ element: T) -> BagKey { _nextKey = _nextKey &+ 1 #if DEBUG _nextKey = _nextKey % 20 #endif if _nextKey == 0 { _uniqueIdentity = Identity() } let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey) if _key0 == nil { _key0 = key _value0 = element return key } _onlyFastPath = false if _key1 == nil { _key1 = key _value1 = element return key } if _dictionary != nil { _dictionary![key] = element return key } if _pairs.count < arrayDictionaryMaxSize { _pairs.append(key: key, value: element) return key } if _dictionary == nil { _dictionary = [:] } _dictionary![key] = element return key } /** - returns: Number of elements in bag. */ public var count: Int { let dictionaryCount: Int = _dictionary?.count ?? 0 return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount } /** Removes all elements from bag and clears capacity. */ public mutating func removeAll() { _key0 = nil _value0 = nil _key1 = nil _value1 = nil _pairs.removeAll(keepingCapacity: false) _dictionary?.removeAll(keepingCapacity: false) } /** Removes element with a specific `key` from bag. - parameter key: Key that identifies element to remove from bag. - returns: Element that bag contained, or nil in case element was already removed. */ public mutating func removeKey(_ key: BagKey) -> T? { if _key0 == key { _key0 = nil let value = _value0! _value0 = nil return value } if _key1 == key { _key1 = nil let value = _value1! _value1 = nil return value } if let existingObject = _dictionary?.removeValue(forKey: key) { return existingObject } for i in 0 ..< _pairs.count { if _pairs[i].key == key { let value = _pairs[i].value _pairs.remove(at: i) return value } } return nil } } extension Bag { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription : String { return "\(self.count) elements in Bag" } } // MARK: forEach extension Bag { /** Enumerates elements inside the bag. - parameter action: Enumeration closure. */ public func forEach(_ action: (T) -> Void) { if _onlyFastPath { if let value0 = _value0 { action(value0) } return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { action(value0) } if let value1 = value1 { action(value1) } for i in 0 ..< pairs.count { action(pairs[i].value) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { action(element) } } } } extension Bag where T: ObserverType { /** Dispatches `event` to app observers contained inside bag. - parameter action: Enumeration closure. */ public func on(_ event: Event<T.E>) { if _onlyFastPath { _value0?.on(event) return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { value0.on(event) } if let value1 = value1 { value1.on(event) } for i in 0 ..< pairs.count { pairs[i].value.on(event) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.on(event) } } } } /** Dispatches `dispose` to all disposables contained inside bag. */ @available(*, deprecated, renamed: "disposeAll(in:)") public func disposeAllIn(_ bag: Bag<Disposable>) { disposeAll(in: bag) } /** Dispatches `dispose` to all disposables contained inside bag. */ public func disposeAll(in bag: Bag<Disposable>) { if bag._onlyFastPath { bag._value0?.dispose() return } let pairs = bag._pairs let value0 = bag._value0 let value1 = bag._value1 let dictionary = bag._dictionary if let value0 = value0 { value0.dispose() } if let value1 = value1 { value1.dispose() } for i in 0 ..< pairs.count { pairs[i].value.dispose() } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.dispose() } } }
mit
Q42/NoticeWindow
Pod/Classes/NoticeView.swift
1
2780
// // NoticeView.swift // Pods // // Created by Tim van Steenis on 09/12/15. // // import Foundation import UIKit class NoticeView: UIView { @IBOutlet weak var horizontalStackView: UIStackView! @IBOutlet weak var leftImage: UIImageView! @IBOutlet weak var rightImage: UIImageView! @IBOutlet weak var leftImageWidth: NSLayoutConstraint! @IBOutlet weak var rightImageWidth: NSLayoutConstraint! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! var style: NoticeViewStyle = NoticeViewStyle() { didSet { backgroundColor = style.backgroundColor titleLabel.textColor = style.textColor messageLabel.textColor = style.textColor titleLabel.numberOfLines = style.titleNumberOfLines messageLabel.numberOfLines = style.messageNumberOfLines horizontalStackView.spacing = style.imageSpacing layoutMargins = style.insets if let image = style.leftImage { leftImage.isHidden = false leftImageWidth.constant = image.width leftImage.image = image.image leftImage.tintColor = image.tintColor leftImage.contentMode = image.contentMode } else { leftImage.isHidden = true } if let image = style.rightImage { rightImage.isHidden = false rightImageWidth.constant = image.width rightImage.image = image.image rightImage.tintColor = image.tintColor rightImage.contentMode = image.contentMode } else { rightImage.isHidden = true } } } public override init(frame: CGRect) { super.init(frame: frame) NotificationCenter.default .addObserver(self, selector: #selector(adjustForStatusBarFrameChanges), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default .addObserver(self, selector: #selector(adjustForStatusBarFrameChanges), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) } @objc fileprivate func adjustForStatusBarFrameChanges() { guard style.position == .top else { return } // For some reason, statusBarFrame hasn't been updated yet when rotating, but it is in next event loop DispatchQueue.main.async { self.updateLayoutMarginsWithStatusBarHeight() } } override func didMoveToWindow() { super.didMoveToWindow() updateLayoutMarginsWithStatusBarHeight() } private func updateLayoutMarginsWithStatusBarHeight() { guard style.position == .top else { return } let additionalHeight = (window as? NoticeWindow)?.additionalStatusBarHeight() ?? 0 layoutMargins.top = style.insets.top + additionalHeight } }
mit
Brightify/ReactantUI
Sources/Tokenizer/Properties/AssignableProperty.swift
1
3261
// // AssignablePropertyDescription.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif /** * Standard typed property obtained from an XML attribute. */ public struct AssignableProperty<T: AttributeSupportedPropertyType>: TypedProperty { public var namespace: [PropertyContainer.Namespace] public var name: String public var description: AssignablePropertyDescription<T> public var value: T public var attributeName: String { return namespace.resolvedAttributeName(name: name) } /** * - parameter context: property context to use * - returns: Swift `String` representation of the property application on the target */ public func application(context: PropertyContext) -> String { return value.generate(context: context.child(for: value)) } /** * - parameter target: UI element to be targetted with the property * - parameter context: property context to use * - returns: Swift `String` representation of the property application on the target */ public func application(on target: String, context: PropertyContext) -> String { let namespacedTarget = namespace.resolvedSwiftName(target: target) return "\(namespacedTarget).\(description.swiftName) = \(application(context: context))" } #if SanAndreas public func dematerialize(context: PropertyContext) -> XMLSerializableAttribute { return XMLSerializableAttribute(name: attributeName, value: value.dematerialize(context: context.child(for: value))) } #endif #if canImport(UIKit) /** * Try to apply the property on an object using the passed property context. * - parameter object: UI element to apply the property to * - parameter context: property context to use */ public func apply(on object: AnyObject, context: PropertyContext) throws { let key = description.key let selector = Selector("set\(key.capitalizingFirstLetter()):") let target = try resolveTarget(for: object) guard target.responds(to: selector) else { throw LiveUIError(message: "!! Object `\(target)` doesn't respond to selector `\(key)` to set value `\(value)`") } guard let resolvedValue = value.runtimeValue(context: context.child(for: value)) else { throw LiveUIError(message: "!! Value `\(value)` couldn't be resolved in runtime for key `\(key)`") } do { try catchException { _ = target.setValue(resolvedValue, forKey: key) } } catch { _ = target.perform(selector, with: resolvedValue) } } private func resolveTarget(for object: AnyObject) throws -> AnyObject { if namespace.isEmpty { return object } else { let keyPath = namespace.resolvedKeyPath guard let target = object.value(forKeyPath: keyPath) else { throw LiveUIError(message: "!! Object \(object) doesn't have keyPath \(keyPath) to resolve real target") } return target as AnyObject } } #endif }
mit
Zewo/TrieRouteMatcher
Package.swift
1
299
import PackageDescription let package = Package( name: "TrieRouteMatcher", dependencies: [ .Package(url: "https://github.com/Zewo/HTTP.git", majorVersion: 0, minor: 7), .Package(url: "https://github.com/Zewo/PathParameterMiddleware.git", majorVersion: 0, minor: 7), ] )
mit
brentsimmons/Frontier
BeforeTheRename/Frontier/DB/DBViewController.swift
1
250
// // DBViewController.swift // // // Created by Brent Simmons on 4/19/17. // // import Cocoa class DBViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
gpl-2.0
mownier/pyrobase
Pyrobase/Pyrobase.swift
1
2029
// // Pyrobase.swift // Pyrobase // // Created by Mounir Ybanez on 01/05/2017. // Copyright © 2017 Ner. All rights reserved. // public class Pyrobase { internal var path: RequestPathProtocol internal var request: RequestProtocol public var baseURL: String { return path.baseURL } public init(request: RequestProtocol, path: RequestPathProtocol) { self.request = request self.path = path } public func get(path relativePath: String, query: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.read(path: path.build(relativePath), query: query) { result in completion(result) } } public func put(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .put, data: value) { result in completion(result) } } public func post(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .post, data: value) { result in completion(result) } } public func patch(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .patch, data: value) { result in completion(result) } } public func delete(path relativePath: String, completion: @escaping (RequestResult) -> Void) { request.delete(path: path.build(relativePath), completion: completion) } } extension Pyrobase { public class func create(baseURL: String, accessToken: String) -> Pyrobase { let path = RequestPath(baseURL: baseURL, accessToken: accessToken) let request = Request.create() let pyrobase = Pyrobase(request: request, path: path) return pyrobase } }
mit
Quick/Spry
Source/Spry/Core/Helpers.swift
1
327
// // Helpers.swift // Spry // // Created by Shahpour Benkau on 22/02/2017. // // import Foundation extension Sequence { func all(_ fn: (Iterator.Element) -> Bool) -> Bool { for item in self { if !fn(item) { return false } } return true } }
apache-2.0
Diego5529/tcc-swift3
tcc-swift3/src/controllers/view/form/Commons/Login.swift
2
272
// // Login.swift // Former-Demo // // Created by Ryo Aoyama on 11/8/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit final class Login { static let sharedInstance = Login() var username: String? var password: String? }
mit
lukejmann/FBLA2017
Pods/Instructions/Sources/Helpers/CoachMarkLayoutHelper.swift
1
9860
// CoachMarkLayoutHelper.swift // // Copyright (c) 2016 Frédéric Maquin <fred@ephread.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 // swiftlint:disable line_length class CoachMarkLayoutHelper { var layoutDirection: UIUserInterfaceLayoutDirection = .leftToRight // TODO: Improve the layout system. Make it smarter. func constraints(for coachMarkView: CoachMarkView, coachMark: CoachMark, parentView: UIView, layoutDirection: UIUserInterfaceLayoutDirection? = nil) -> [NSLayoutConstraint] { if coachMarkView.superview != parentView { print("coachMarkView was not added to parentView, returned constraints will be empty") return [] } if layoutDirection == nil { if #available(iOS 9, *) { self.layoutDirection = UIView.userInterfaceLayoutDirection( for: parentView.semanticContentAttribute) } } else { self.layoutDirection = layoutDirection! } let computedProperties = computeProperties(for: coachMark, inParentView: parentView) let offset = arrowOffset(for: coachMark, withProperties: computedProperties, inParentView: parentView) switch computedProperties.segmentIndex { case 1: coachMarkView.changeArrowPosition(to: .leading, offset: offset) return leadingConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) case 2: coachMarkView.changeArrowPosition(to: .center, offset: offset) return middleConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) case 3: coachMarkView.changeArrowPosition(to: .trailing, offset: offset) return trailingConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) default: return [NSLayoutConstraint]() } } private func leadingConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth))]-(>=\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) } private func middleConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth)@1000)]-(>=\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) constraints.append(NSLayoutConstraint( item: coachMarkView, attribute: .centerX, relatedBy: .equal, toItem: parentView, attribute: .centerX, multiplier: 1, constant: 0 )) return constraints } private func trailingConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth))]-(==\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) } /// Returns the arrow offset, based on the layout and the /// segment in which the coach mark will be. /// /// - Parameter coachMark: coachmark data. /// - Parameter properties: precomputed properties. /// - Parameter parentView: view showing the coachmarks. private func arrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { var arrowOffset: CGFloat switch properties.segmentIndex { case 1: arrowOffset = leadingArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) case 2: arrowOffset = middleArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) case 3: arrowOffset = trailingArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) default: arrowOffset = 0 break } return arrowOffset } private func leadingArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return pointOfInterest.x - coachMark.horizontalMargin } else { return parentView.bounds.size.width - pointOfInterest.x - coachMark.horizontalMargin } } private func middleArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return parentView.center.x - pointOfInterest.x } else { return pointOfInterest.x - parentView.center.x } } private func trailingArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return parentView.bounds.size.width - pointOfInterest.x - coachMark.horizontalMargin } else { return pointOfInterest.x - coachMark.horizontalMargin } } /// Compute the segment index (for now the screen is separated /// in three horizontal areas and depending in which one the coach /// mark stand, it will be layed out in a different way. /// /// - Parameter coachMark: coachmark data. /// - Parameter layoutDirection: the layout direction (LTR or RTL) /// - Parameter frame: frame of the parent view /// /// - Returns: the segment index (either 1, 2 or 3) private func computeSegmentIndex( of coachMark: CoachMark, forLayoutDirection layoutDirection: UIUserInterfaceLayoutDirection, inFrame frame: CGRect ) -> Int { if let pointOfInterest = coachMark.pointOfInterest { var segmentIndex = 3 * pointOfInterest.x / frame.size.width if layoutDirection == .rightToLeft { segmentIndex = 3 - segmentIndex } return Int(ceil(segmentIndex)) } else { print("The point of interest was found nil. Fallbacking to middle segment.") return 1 } } private func computeProperties(for coachMark: CoachMark, inParentView parentView: UIView) -> CoachMarkComputedProperties { let segmentIndex = computeSegmentIndex(of: coachMark, forLayoutDirection: layoutDirection, inFrame: parentView.frame) return CoachMarkComputedProperties( layoutDirection: layoutDirection, segmentIndex: segmentIndex ) } } struct CoachMarkComputedProperties { let layoutDirection: UIUserInterfaceLayoutDirection let segmentIndex: Int }
mit
keyeMyria/edx-app-ios
Source/OEXStyles+Swift.swift
4
3515
// // OEXStyles+Swift.swift // edX // // Created by Ehmad Zubair Chughtai on 25/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit extension OEXStyles { var navigationTitleTextStyle : OEXTextStyle { return OEXTextStyle(weight: .SemiBold, size: .Base, color : navigationItemTintColor()) } var navigationButtonTextStyle : OEXTextStyle { return OEXTextStyle(weight: .SemiBold, size: .XSmall, color: nil) } public func applyGlobalAppearance() { if (OEXConfig.sharedConfig().shouldEnableNewCourseNavigation()) { //Probably want to set the tintColor of UIWindow but it didn't seem necessary right now UINavigationBar.appearance().barTintColor = navigationBarColor() UINavigationBar.appearance().barStyle = UIBarStyle.Black UINavigationBar.appearance().tintColor = navigationItemTintColor() UINavigationBar.appearance().titleTextAttributes = navigationTitleTextStyle.attributes UIBarButtonItem.appearance().setTitleTextAttributes(navigationButtonTextStyle.attributes, forState: .Normal) UIToolbar.appearance().tintColor = navigationBarColor() let styleAttributes = OEXTextStyle(weight: .Normal, size : .Small, color : self.neutralBlack()).attributes UISegmentedControl.appearance().setTitleTextAttributes(styleAttributes, forState: UIControlState.Selected) UISegmentedControl.appearance().setTitleTextAttributes(styleAttributes, forState: UIControlState.Normal) UISegmentedControl.appearance().tintColor = self.neutralLight() } if UIDevice.currentDevice().isOSVersionAtLeast8() { UINavigationBar.appearance().translucent = false } } ///**Warning:** Not from style guide. Do not add more uses public var progressBarTintColor : UIColor { return UIColor(red: CGFloat(126.0/255.0), green: CGFloat(199.0/255.0), blue: CGFloat(143.0/255.0), alpha: CGFloat(1.00)) } ///**Warning:** Not from style guide. Do not add more uses public var progressBarTrackTintColor : UIColor { return UIColor(red: CGFloat(223.0/255.0), green: CGFloat(242.0/255.0), blue: CGFloat(228.0/255.0), alpha: CGFloat(1.00)) } var standardTextViewInsets : UIEdgeInsets { return UIEdgeInsetsMake(8, 8, 8, 8) } var standardFooterHeight : CGFloat { return 50 } // Standard text Styles var textAreaBodyStyle : OEXTextStyle { let style = OEXMutableTextStyle(weight: OEXTextWeight.Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) style.lineBreakMode = .ByWordWrapping return style } // Standard button styles var filledPrimaryButtonStyle : ButtonStyle { let buttonMargins : CGFloat = 8 let borderStyle = BorderStyle() let textStyle = OEXTextStyle(weight: .Normal, size: .Small, color: self.neutralWhite()) return ButtonStyle(textStyle: textStyle, backgroundColor: OEXStyles.sharedStyles().primaryBaseColor(), borderStyle: borderStyle, contentInsets : UIEdgeInsetsMake(buttonMargins, buttonMargins, buttonMargins, buttonMargins)) } // Standard border styles var entryFieldBorderStyle : BorderStyle { return BorderStyle(width: .Size(1), color: OEXStyles.sharedStyles().neutralLight()) } }
apache-2.0
relayr/apple-sdk
Sources/common/services/API/APIUsers.swift
1
7530
import ReactiveSwift import Result import Foundation internal extension API { /// User entity as represented on the relayr API platform. struct User: JSONable { let identifier: String var email: String? var nickname: String? var name: (first: String?, last: String?) var companyName: String? var industryArea: String? } } /// Instances of conforming type can request OAuth codes from the cloud servers. /// /// An OAuth code is the first step on an OAuth login process. Arm with the code, you can request an OAuth token. internal protocol OAuthCodeRetrievable { /// It request an OAuth code to the instance of the conforming type. /// The OAuth process won't start till a `start()` message is send to the `SignalProducer`. static func requestOAuthCode(toURL url: String, withRedirectURI redirectURI: String, willAnimate: Bool, cancellableButton: Bool) -> SignalProducer<String,API.Error> } // HTTP APIs for user related endpoints. internal extension API { /// Requests information about the user currently logged in which owns this API instance. func currentUserInfo() -> SignalProducer<API.User,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/user-info") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.User(fromJSON: json) } } } /// Updates the user with the arguments passed. /// /// If no arguments are given, no HTTP call is performed and an error is returned. /// - parameter firstName: Modify the user's first name. /// - parameter lastName: Modify the user's last name. /// - parameter companyName: Modify the user's company name. /// - parameter industryArea: Modify the user's company area. func setUserInfo(withID userID: String, firstName: String?=nil, lastName: String?=nil, companyName: String?=nil, industryArea: String?=nil) -> SignalProducer<API.User,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)") var body: [String:String] = [:] if let firstName = firstName { body[User.Keys.firstName] = firstName } if let lastName = lastName { body[User.Keys.lastName] = lastName } if let company = companyName { body[User.Keys.companyName] = company } if let industry = industryArea { body[User.Keys.industryArea] = industry } guard !body.isEmpty else { return SignalProducer(error: .insufficientInformation) } return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Patch, token: token, contentType: .JSON, body: body, expectedCodes: [200]).attemptMap { (json: [String:Any]) in Result { guard let data = json["data"] as? [String:Any] else { throw API.Error.invalidResponseBody(body: json) } return try API.User(fromJSON: data) } } } // MARK: Login & Tokens #if os(macOS) || os(iOS) /// It requests the temporal access OAuth code needed to ask for a 100 year OAuth access token. /// - parameter clientID: `String` representing the Oauth client ID. You receive this when creating an app in the relayr developer platform. /// - parameter redirectURI: `String` representing the redirect URI you chosed when creating an app in the relayr developer platform. func oauthCode(withProjectID projectID: String, oauthRedirectURI redirectURI: String, willAnimate: Bool=false, cancellableButton: Bool=true) -> SignalProducer<String,API.Error> { let scope = "access-own-user-info+configure-devices+read-device-history" let relativePath = "oauth2/auth?client_id=\(projectID)&redirect_uri=\(redirectURI)&response_type=code&scope=\(scope)" let url = Addresses.build(withHostURL: urls.root, relativeURL: relativePath) return WebOAuthController.requestOAuthCode(toURL: url, withRedirectURI: redirectURI, willAnimate: willAnimate, cancellableButton: cancellableButton) } #endif /// It request a valid OAuth token from an OAuth code, clientID, clientSecret, and redirectURI. /// - parameter tmpCode: Temporal OAuth code (usually valid for 5 minutes) that it is required to retrieve a token. /// - parameter projectID: String representing the Oauth client ID. You receive this when creating an app in the relayr developer platform. /// - parameter oauthSecret: String representing the Oauth client secret. You receive this when creating an app in the relayr developer platform. /// - parameter redirectURI: String representing the redirect URI you chosed when creating an app in the Relayr developer platform. func oauthToken(withTemporalCode tmpCode: String, projectID: String, oauthSecret: String, redirectURI: String) -> SignalProducer<String,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/token") let body = ["code": tmpCode, "client_id": projectID, "redirect_uri": redirectURI, "scope": "", "client_secret": oauthSecret, "grant_type": "authorization_code"] return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Post, contentType: .Xform, body: body, expectedCodes: [200]).attemptMap { (json : [String:Any]) in let token = json["access_token"] as? String return Result(token, failWith: .invalidResponseBody(body: json)) } } } internal extension API.User { typealias JSONType = [String:Any] init(fromJSON json: JSONType) throws { guard let identifier = json[Keys.identifier] as? String else { throw API.Error.invalidResponseBody(body: json) } self.identifier = identifier self.email = json[Keys.email] as? String self.nickname = json[Keys.name] as? String self.name = (json[Keys.firstName] as? String, json[Keys.lastName] as? String) self.companyName = json[Keys.companyName] as? String self.industryArea = json[Keys.industryArea] as? String } var json: JSONType { var result: JSONType = [Keys.identifier: self.identifier] if let email = self.email { result[Keys.email] = email } if let nickname = self.nickname { result[Keys.name] = nickname } if let firstName = self.name.first { result[Keys.firstName] = firstName } if let lastName = self.name.last { result[Keys.lastName] = lastName } if let company = self.companyName { result[Keys.companyName] = company } if let industry = self.industryArea { result[Keys.industryArea] = industry } return result } fileprivate init(withIdentifier identifier: String, email: String?=nil, nickname: String?=nil, firstName: String?=nil, lastName: String?=nil, company: String?=nil, industry: String?=nil) { self.identifier = identifier self.email = email self.nickname = nickname self.name = (firstName, lastName) self.companyName = company self.industryArea = industry } fileprivate struct Keys { static let identifier = "id" static let email = "email" static let name = "name" fileprivate static let firstName = "firstName" static let lastName = "lastName" static let companyName = "companyName" static let industryArea = "industryArea" } }
mit
tomas789/JustLog
JustLog/Extensions/Data+Representation.swift
1
304
// // Data+Representation.swift // JustLog // // Created by Alberto De Bortoli on 15/12/2016. // Copyright © 2017 Just Eat. All rights reserved. // import Foundation extension Data { func stringRepresentation() -> String { return String(data: self, encoding: .utf8) ?? "" } }
apache-2.0
dnosk/Explore
Example/Explore/ViewController.swift
1
1164
// // ViewController.swift // Explore // // Created by dnosk on 04/26/2017. // Copyright (c) 2017 dnosk. All rights reserved. // import Explore import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var appsDownloaded = [String]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self appsDownloaded = exploreAppsDownloaded() tableView.reloadData() } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appsDownloaded.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let app = appsDownloaded[indexPath.row] cell.textLabel?.text = app return cell } }
mit
bm842/TradingLibrary
Sources/OandaRestV1Instrument.swift
2
9009
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier 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 public final class OandaInstrument: GenericInstrument, Instrument { weak var oandaAccount: OandaRestAccount! { return account as! OandaRestAccount } weak var oanda: OandaRestBroker! init(account: OandaRestAccount, instrumentData: OandaRestV1Instrument) { self.oanda = account.oanda let instrument = instrumentData.instrument let elements = instrument.components(separatedBy: "_") super.init(instrument: instrument, displayName: instrumentData.displayName, pip: instrumentData.pip, minTradeUnits: 1, maxTradeUnits: instrumentData.maxTradeUnits, precision: instrumentData.precision, marginRate: instrumentData.marginRate, base: Currency(rawValue: elements[0]), quote: Currency(rawValue: elements[1])!) self.account = account } public override func stopRateEventsStreaming() { oanda.ratesStreamingConnection.stopStreaming() } public override func startRateEventsStreaming(_ queue: DispatchQueue, handler: @escaping (RatesEvent) -> ()) -> RequestStatus { var query = "prices?" query += "accountId=\(oandaAccount.id)" query += "&instruments=" + instrument return oanda.ratesStreamingConnection.startStreaming(query) { (status, json) in guard let json = json else { queue.async { handler(.status(time: Timestamp.now, status: status)) } return } if let price: OandaRestV1Price = try? json.value(for: "tick") { queue.async { handler(.tickEvent(tick: Tick(fromOanda: price))) } return } if let heartbeat: OandaRestV1Heartbeat = try? json.value(for: "heartbeat") { queue.async { handler(.heartBeat(time: Timestamp(microSeconds: heartbeat.time))) } return } log.error("%f: unexpected json = \(json)") } } public override func submitOrder(_ info: OrderCreation, completion: @escaping (RequestStatus, _ execution: OrderExecution) -> ()) { var params: String = "type=\(info.type.oandaValue)" params += "&side=\(info.side.oandaValue)" params += "&units=\(info.units)" params += "&instrument=\(instrument)" params += "&stopLoss=\(info.stopLoss ?? 0)" params += "&takeProfit=\(info.takeProfit ?? 0)" params += "&price=\(info.entry ?? 0)" params += "&expiry=\(info.expiry?.oandaRestV1Value ?? 0)" /*params += "&lowerBound=\(lowerBound)" params += "&upperBound=\(upperBound)" params += "&trailingStop=\(trailingStop)"*/ oanda.restConnection.fetchJson("accounts/\(oandaAccount.id)/orders", method: "POST", data: params) { (status, json) in var execution: OrderExecution = .none guard let json = json else { log.error("no json, status = \(status) creation=\(info)") return } do { let response = try OandaRestV1CreateOrderResponse(object: json) let time = Timestamp(microSeconds: response.time) if let orderOpened = response.orderOpened { let openedOrder = OrderInfo(orderId: "\(orderOpened.id)", time: time, type: info.type, side: info.side, units: info.units, entry: response.price, stopLoss: nilIfZero(orderOpened.stopLoss), takeProfit: nilIfZero(orderOpened.takeProfit), expiry: Timestamp(microSeconds: orderOpened.expiry)) let order = OandaOrder(instrument: self, info: openedOrder) self.oandaAccount.queue.sync { self.oandaAccount.internalOpenOrders.append(order) } self.notify(tradeEvent: .orderCreated(info: openedOrder)) execution = .orderCreated(orderId: openedOrder.orderId) } if let tradeOpened = response.tradeOpened { let createdTrade = TradeInfo(tradeId: "\(tradeOpened.id)", time: time, side: info.side, units: tradeOpened.units, entry: response.price, stopLoss: nilIfZero(tradeOpened.stopLoss), takeProfit: nilIfZero(tradeOpened.takeProfit)) let trade = OandaTrade(instrument: self, info: createdTrade) self.oandaAccount.queue.sync { self.oandaAccount.internalOpenTrades.append(trade) } self.notify(tradeEvent: .tradeCreated(info: createdTrade)) execution = .orderFilled(tradeId: createdTrade.tradeId) } if let tradesClosed = response.tradesClosed { for tradeClosed in tradesClosed { self.reduceTrade(withId: "\(tradeClosed.id)", atTime: time, units: tradeClosed.units, atPrice: response.price, reason: .reverseOrder) } } if let tradeReduced = response.tradeReduced { self.reduceTrade(withId: "\(tradeReduced.id)", atTime: time, units: tradeReduced.units, atPrice: response.price, reason: .reverseOrder) } completion(status, execution) } catch { completion(OandaStatus.jsonParsingError(error), execution) } } } public override func quote(_ completion: @escaping (RequestStatus, _ tick: Tick?) -> ()) { oanda.restConnection.fetchArray("prices", query: "instruments=" + instrument) { (status, prices: [OandaRestV1Price]?) in if let setPrices = prices { for price in setPrices where price.instrument == self.instrument { completion(status, Tick(fromOanda: price)) break } } else { completion(status, nil) } } } }
mit
pocketworks/Dollar.swift
Cent/Cent/Int.swift
1
2807
// // Int.swift // Cent // // Created by Ankur Patel on 6/30/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation extension Int { /// Invoke a callback n times /// /// :param callback The function to invoke that accepts the index public func times(callback: (Int) -> ()) { (0..<self).eachWithIndex { callback($0) } } /// Invoke a callback n times /// /// :param callback The function to invoke public func times(function: () -> ()) { self.times { (index: Int) -> () in function() } } /// Check if it is even /// /// :return Bool whether int is even public var isEven: Bool { get { return self % 2 == 0 } } /// Check if it is odd /// /// :return Bool whether int is odd public var isOdd: Bool { get { return self % 2 == 1 } } /// Splits the int into array of digits /// /// :return Bool whether int is odd public func digits() -> [Int] { var digits: [Int] = [] var selfCopy = self while selfCopy > 0 { digits << (selfCopy % 10) selfCopy = (selfCopy / 10) } return Array(digits.reverse()) } /// Get the next int /// /// :return next int public func next() -> Int { return self + 1 } /// Get the previous int /// /// :return previous int public func prev() -> Int { return self - 1 } /// Invoke the callback from int up to and including limit /// /// :params limit the max value to iterate upto /// :params callback to invoke public func upTo(limit: Int, callback: () -> ()) { (self...limit).each { callback() } } /// Invoke the callback from int up to and including limit passing the index /// /// :params limit the max value to iterate upto /// :params callback to invoke public func upTo(limit: Int, callback: (Int) -> ()) { (self...limit).eachWithIndex { callback($0) } } /// Invoke the callback from int down to and including limit /// /// :params limit the min value to iterate upto /// :params callback to invoke public func downTo(limit: Int, callback: () -> ()) { var selfCopy = self while selfCopy-- >= limit { callback() } } /// Invoke the callback from int down to and including limit passing the index /// /// :params limit the min value to iterate upto /// :params callback to invoke public func downTo(limit: Int, callback: (Int) -> ()) { var selfCopy = self while selfCopy >= limit { callback(selfCopy--) } } }
mit
natecook1000/swift
test/PlaygroundTransform/high_performance.swift
7
1253
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main2 %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift // RUN: %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test var a = true if (a) { 5 } else { 7 } for i in 0..<3 { i } // CHECK: [{{.*}}] __builtin_log[a='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='5'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [{{.*}}] __builtin_log[='1'] // CHECK-NEXT: [{{.*}}] __builtin_log[='2'] var b = true for i in 0..<3 { i continue } // CHECK-NEXT: [{{.*}}] __builtin_log[b='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [{{.*}}] __builtin_log[='1'] // CHECK-NEXT: [{{.*}}] __builtin_log[='2'] var c = true for i in 0..<3 { i break } // CHECK-NEXT: [{{.*}}] __builtin_log[c='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0']
apache-2.0
danfsd/FolioReaderKit
Example/Example/ViewController.swift
1
1987
// // ViewController.swift // Example // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import FolioReaderKit class ViewController: UIViewController { @IBOutlet var bookOne: UIButton! @IBOutlet var bookTwo: UIButton! let epubSampleFiles = [ "The Silver Chair", // standard eBook // "Medcel", "The Adventures Of Sherlock Holmes - Adventure I", // audio-eBook ] override func viewDidLoad() { super.viewDidLoad() setCover(bookOne, index: 0) setCover(bookTwo, index: 1) } @IBAction func didOpen(sender: AnyObject) { openEpub(sender.tag); } func openEpub(sampleNum: Int) { let config = FolioReaderConfig() config.shouldHideNavigationOnTap = sampleNum == 1 ? true : false config.scrollDirection = sampleNum == 1 ? .horizontal : .vertical // See more at FolioReaderConfig.swift // config.enableTTS = false // config.allowSharing = false // config.tintColor = UIColor.blueColor() // config.toolBarTintColor = UIColor.redColor() // config.toolBarBackgroundColor = UIColor.purpleColor() // config.menuTextColor = UIColor.brownColor() // config.menuBackgroundColor = UIColor.lightGrayColor() let epubName = epubSampleFiles[sampleNum-1]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") FolioReader.presentReader(parentViewController: self, withEpubPath: bookPath!, andConfig: config, shouldRemoveEpub: false) } func setCover(button: UIButton, index: Int) { let epubName = epubSampleFiles[index]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") if let image = FolioReader.getCoverImage(bookPath!) { button.setBackgroundImage(image, forState: .Normal) } } }
bsd-3-clause
coodly/TalkToCloud
Sources/TalkToCloud/APIKeyConsumer.swift
1
683
/* * Copyright 2016 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public protocol APIKeyConsumer { var apiKeyID: String! { get set } }
apache-2.0
codercd/DPlayer
DPlayer/Model.swift
1
1721
// // Model.swift // DPlayer // // Created by LiChendi on 16/4/19. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit class Model: NSObject { } enum LiveBaseURL:String { case rtmp = "rtmp://live.quanmin.tv/live/1456011" case hls = "http://hls.quanmin.tv/live/1456011/playlist.m3u8" case flv = "http://flv.quanmin.tv/live/1456011.flv" } //struct HomepageModel { // var homepageCategories = Array<HomepageCategory>() // // // var list = Array<AnyObject>() { // willSet { //// print("will - list---- \(newValue)") // } // } // var homepageItems = Dictionary<String, AnyObject>() { // willSet { // for categories in newValue { // var homepageCategory = HomepageCategory() // homepageCategory.name = categories.0 // homepageCategory.detail = categories.1 as! Array<AnyObject> // homepageCategories.append(homepageCategory) // } // } // } //} //struct HomepageCategory { // var name = "" { // willSet { // print("name----\(newValue)") // } // } // var detail = Array<AnyObject>() { // willSet { // print("detail----\(newValue)") //// RoomDetail(). // } // } //} struct recommendList { // var } struct RoomDetail { var stateus = 0 var follow = 0 var avatar = "" var view = 0 var intro = "" var slug = "" var category_id = 0 var category_name = "" var category_slug = "" var recommend_image = "" var nick = "" var play_at = "" var announcement = "" var title = "" var uid = "" var thumb = "" }
mit
wunshine/FoodStyle
FoodStyle/FoodStyle/Classes/View/WXTextField.swift
1
845
// // WXTextField.swift // FoodStyle // // Created by Woz Wong on 16/3/5. // Copyright © 2016年 code4Fun. All rights reserved. // import UIKit class WXTextField: UITextField { override func textRectForBounds(bounds: CGRect) -> CGRect { super.textRectForBounds(bounds) return CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width, bounds.size.height) } override func placeholderRectForBounds(bounds: CGRect) -> CGRect { super.placeholderRectForBounds(bounds) return CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width, bounds.size.height) } override func editingRectForBounds(bounds: CGRect) -> CGRect { super.editingRectForBounds(bounds) return CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width, bounds.size.height) } }
mit
ociata/OCIKeyboardAdjuster
OCIKeyboardAdjuster.swift
1
7643
// // KeyboardAdjuster.swift // // // Created by Hristo Todorov - Oci on 6/5/15. // Copyright (c) 2015 // import UIKit class OCIKeyboardAdjuster: NSObject { static let sharedKeyboardAdjuster = OCIKeyboardAdjuster() weak var focusedControl: UIView? private override init() { //this way users will always use singleton instance } private(set) weak var scrollView: UIScrollView? private(set) weak var view: UIView! private var originalScrollOffset: CGPoint? private var originalScrollSize: CGSize? func startObserving(scrollableView: UIScrollView, holderView: UIView) { scrollView = scrollableView view = holderView //remove old observers stopObserving() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func stopObserving() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: scrollview ajust when keyboard present @objc private func keyboardWillShow(notification: NSNotification) { if nil == self.view || self.view.window == nil { return } if let scrollView = scrollView, let userInfo = notification.userInfo, let keyboardFrameInWindow = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let keyboardFrameInWindowBegin = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue, let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let animationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { // the keyboard frame is specified in window-level coordinates. this calculates the frame as if it were a subview of our view, making it a sibling of the scroll view let keyboardFrameInView = self.view.convertRect(keyboardFrameInWindow.CGRectValue(), fromView: nil) let scrollViewKeyboardIntersection = CGRectIntersection(scrollView.frame, keyboardFrameInView) UIView.animateWithDuration(animationDuration.doubleValue, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve.unsignedLongValue)), animations: { [weak self] in if let strongSelf = self, let scrollView = strongSelf.scrollView { if let focusedControl = strongSelf.focusedControl { // if the control is a deep in the hierarchy below the scroll view, this will calculate the frame as if it were a direct subview var controlFrameInScrollView = scrollView.convertRect(focusedControl.bounds, fromView: focusedControl) controlFrameInScrollView = CGRectInset(controlFrameInScrollView, 0, -10) let controlVisualOffsetToTopOfScrollview = controlFrameInScrollView.origin.y - scrollView.contentOffset.y let controlVisualBottom = controlVisualOffsetToTopOfScrollview + controlFrameInScrollView.size.height // this is the visible part of the scroll view that is not hidden by the keyboard let scrollViewVisibleHeight = scrollView.frame.size.height - scrollViewKeyboardIntersection.size.height var newContentOffset = scrollView.contentOffset //store it to better update latter strongSelf.originalScrollOffset = newContentOffset if controlVisualBottom > scrollViewVisibleHeight // check if the keyboard will hide the control in question { newContentOffset.y += (controlVisualBottom - scrollViewVisibleHeight) //check for impossible offset newContentOffset.y = min(newContentOffset.y, scrollView.contentSize.height - scrollViewVisibleHeight) } else if controlFrameInScrollView.origin.y < scrollView.contentOffset.y // if the control is not fully visible, make it so (useful if the user taps on a partially visible input field { newContentOffset.y = controlFrameInScrollView.origin.y } //no animation as we had own animation already going scrollView.setContentOffset(newContentOffset, animated: false) } var scrollSize = scrollView.contentSize if let _ = strongSelf.originalScrollSize { //subtract old keyboard value scrollSize.height -= strongSelf.view.convertRect(keyboardFrameInWindowBegin.CGRectValue(), fromView: nil).size.height } strongSelf.originalScrollSize = scrollSize scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, scrollSize.height + keyboardFrameInView.height) } }, completion: nil) } } @objc private func keyboardWillHide(notification: NSNotification) { if self.view == nil || self.view.window == nil { return } if let _ = scrollView, let userInfo = notification.userInfo, let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let animationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { UIView.animateWithDuration(animationDuration.doubleValue, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve.unsignedLongValue)), animations: { if let scrollView = self.scrollView { if let originalContentSize = self.originalScrollSize { scrollView.contentSize = originalContentSize } if let originalScrollOffset = self.originalScrollOffset { scrollView.setContentOffset( originalScrollOffset, animated: false) } } }, completion: { success in self.originalScrollOffset = nil self.originalScrollSize = nil }) } } }
mit
RCacheaux/BitbucketKit
Carthage/Checkouts/Swinject/Sources/SwinjectStoryboard/Container+SwinjectStoryboard.swift
1
2302
// // Container+SwinjectStoryboard.swift // Swinject // // Created by Yoichi Tagaya on 11/28/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // #if os(iOS) || os(OSX) || os(tvOS) extension Container { /// Adds a registration of the specified view or window controller that is configured in a storyboard. /// /// - Note: Do NOT explicitly resolve the controller registered by this method. /// The controller is intended to be resolved by `SwinjectStoryboard` implicitly. /// /// - Parameters: /// - controllerType: The controller type to register as a service type. /// The type is `UIViewController` in iOS, `NSViewController` or `NSWindowController` in OS X. /// - name: A registration name, which is used to differenciate from other registrations /// that have the same view or window controller type. /// - initCompleted: A closure to specifiy how the dependencies of the view or window controller are injected. /// It is invoked by the `Container` when the view or window controller is instantiated by `SwinjectStoryboard`. public func registerForStoryboard<C: Controller>(controllerType: C.Type, name: String? = nil, initCompleted: (ResolverType, C) -> ()) { // Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7. // The actual controller type is distinguished by the dynamic type name in `nameWithActualType`. let nameWithActualType = String(reflecting: controllerType) + ":" + (name ?? "") let wrappingClosure: (ResolverType, Controller) -> () = { r, c in initCompleted(r, c as! C) } self.register(Controller.self, name: nameWithActualType) { (_: ResolverType, controller: Controller) in controller } .initCompleted(wrappingClosure) } } #endif extension Container { #if os(iOS) || os(tvOS) /// The typealias to UIViewController. public typealias Controller = UIViewController #elseif os(OSX) /// The typealias to AnyObject, which should be actually NSViewController or NSWindowController. /// See the reference of NSStoryboard.instantiateInitialController method. public typealias Controller = AnyObject #endif }
apache-2.0
adamnemecek/SortedArray.swift
Cmdline/main.swift
1
931
// // main.swift // Cmdline // // Created by Adam Nemecek on 5/6/17. // // import Foundation import SortedArray let s = SortedSet([5,2,1,2,3,6,7,8]) let a = [1,2,3,4,5,6] let b = [1, 2, 2, 3, 3, 5, 6] print(b) //var u = UnionIterator(a: a, b: b) { $0 < $1 } //print(s.contains(1)) //while let n = u.next() { // print(n) //} // //struct UniqueSequence<Element : Equatable> : IteratorProtocol { // private var i: AnyIterator<Element> //// // private var last : Element? // // init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element { // self.i = AnyIterator(sequence.makeIterator()) // last = i.next() // } // // func next() -> Element? { // return nil //// while let n = i.next() { //// //// } // } //} let c = SortedSet(b) //let ii = s.intersection(c) //print(s.intersection(c)) for e in s.symmetricDifference(c) { print(e) }
mit
KBryan/SwiftFoundation
Darwin Support/NSUUID.swift
1
1268
// // NSUUID.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/4/15. // Copyright © 2015 PureSwift. All rights reserved. // import Foundation public extension NSUUID { convenience init(byteValue: uuid_t) { var value = byteValue let buffer = withUnsafeMutablePointer(&value, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> UnsafeMutablePointer<UInt8> in let bufferType = UnsafeMutablePointer<UInt8>.self return unsafeBitCast(valuePointer, bufferType) }) self.init(UUIDBytes: buffer) } var byteValue: uuid_t { var uuid = uuid_t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) withUnsafeMutablePointer(&uuid, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> Void in let bufferType = UnsafeMutablePointer<UInt8>.self let buffer = unsafeBitCast(valuePointer, bufferType) self.getUUIDBytes(buffer) }) return uuid } var rawValue: String { return UUIDString } convenience init?(rawValue: String) { self.init(UUIDString: rawValue) } }
mit
chizcake/ReplayKitExample
ReplayKitExampleStarter/Carthage/Checkouts/CleanroomLogger/Tests/CleanroomLoggerTests/LogSeverityTests.swift
2
974
// // LogSeverityTests.swift // Cleanroom Project // // Created by Claudio Romandini on 5/19/15. // Copyright © 2015 Gilt Groupe. All rights reserved. // import XCTest import CleanroomLogger class LogSeverityTests: XCTestCase { func testLogSeverityEquality() { XCTAssertTrue(LogSeverity.debug == LogSeverity.debug, "Debug should be equal to itself.") XCTAssertTrue(LogSeverity.info != LogSeverity.warning, "Info should be not equal to Warning.") } func testLogSeverityComparableImplementation() { XCTAssertTrue(LogSeverity.verbose < LogSeverity.debug, "Verbose should be less than Debug.") XCTAssertTrue(LogSeverity.info >= LogSeverity.debug, "Info should be greater than or equal to Debug.") XCTAssertTrue(LogSeverity.warning > LogSeverity.info, "Warning should be greater than Info.") XCTAssertTrue(LogSeverity.warning <= LogSeverity.error, "Warning should be less than or equal to Error.") } }
mit
EstebanVallejo/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/MercadoPago.swift
1
17199
// // MercadoPago.swift // MercadoPagoSDK // // Created by Matias Gualino on 28/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class MercadoPago : NSObject { public class var PUBLIC_KEY : String { return "public_key" } public class var PRIVATE_KEY : String { return "private_key" } public class var ERROR_KEY_CODE : Int { return -1 } public class var ERROR_API_CODE : Int { return -2 } public class var ERROR_UNKNOWN_CODE : Int { return -3 } public class var ERROR_NOT_INSTALLMENTS_FOUND : Int { return -4 } public class var ERROR_PAYMENT : Int { return -4 } let BIN_LENGTH : Int = 6 let MP_API_BASE_URL : String = "https://api.mercadopago.com" public var privateKey : String? public var publicKey : String? public var paymentMethodId : String? public var paymentTypeId : String? public init (publicKey: String) { self.publicKey = publicKey } public init (keyType: String?, key: String?) { if keyType != nil && key != nil { if keyType != MercadoPago.PUBLIC_KEY && keyType != MercadoPago.PRIVATE_KEY { fatalError("keyType must be 'public_key' or 'private_key'.") } else { if keyType == MercadoPago.PUBLIC_KEY { self.publicKey = key } else if keyType == MercadoPago.PUBLIC_KEY { self.privateKey = key } } } else { fatalError("keyType and key cannot be nil.") } } public class func startCustomerCardsViewController(cards: [Card], callback: (selectedCard: Card?) -> Void) -> CustomerCardsViewController { return CustomerCardsViewController(cards: cards, callback: callback) } public class func startNewCardViewController(keyType: String, key: String, paymentMethod: PaymentMethod, requireSecurityCode: Bool, callback: (cardToken: CardToken) -> Void) -> NewCardViewController { return NewCardViewController(keyType: keyType, key: key, paymentMethod: paymentMethod, requireSecurityCode: requireSecurityCode, callback: callback) } public class func startPaymentMethodsViewController(merchantPublicKey: String, supportedPaymentTypes: [String], callback:(paymentMethod: PaymentMethod) -> Void) -> PaymentMethodsViewController { return PaymentMethodsViewController(merchantPublicKey: merchantPublicKey, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public class func startIssuersViewController(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (issuer: Issuer) -> Void) -> IssuersViewController { return IssuersViewController(merchantPublicKey: merchantPublicKey, paymentMethod: paymentMethod, callback: callback) } public class func startInstallmentsViewController(payerCosts: [PayerCost], amount: Double, callback: (payerCost: PayerCost?) -> Void) -> InstallmentsViewController { return InstallmentsViewController(payerCosts: payerCosts, amount: amount, callback: callback) } public class func startCongratsViewController(payment: Payment, paymentMethod: PaymentMethod) -> CongratsViewController { return CongratsViewController(payment: payment, paymentMethod: paymentMethod) } public class func startPromosViewController(merchantPublicKey: String) -> PromoViewController { return PromoViewController(publicKey: merchantPublicKey) } public class func startVaultViewController(merchantPublicKey: String, merchantBaseUrl: String?, merchantGetCustomerUri: String?, merchantAccessToken: String?, amount: Double, supportedPaymentTypes: [String], callback: (paymentMethod: PaymentMethod, tokenId: String?, issuerId: Int64?, installments: Int) -> Void) -> VaultViewController { return VaultViewController(merchantPublicKey: merchantPublicKey, merchantBaseUrl: merchantBaseUrl, merchantGetCustomerUri: merchantGetCustomerUri, merchantAccessToken: merchantAccessToken, amount: amount, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public func createNewCardToken(cardToken : CardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { cardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, cardToken: cardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func createToken(savedCardToken : SavedCardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { savedCardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, savedCardToken: savedCardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPaymentMethods(success: (paymentMethods: [PaymentMethod]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getPaymentMethods(public_key: self.publicKey!, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var paymentMethods = jsonResult as? NSArray var pms : [PaymentMethod] = [PaymentMethod]() if paymentMethods != nil { for i in 0..<paymentMethods!.count { if let pmDic = paymentMethods![i] as? NSDictionary { pms.append(PaymentMethod.fromJSON(pmDic)) } } } success(paymentMethods: pms) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIdentificationTypes(success: (identificationTypes: [IdentificationType]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : IdentificationService = IdentificationService(baseURL: MP_API_BASE_URL) service.getIdentificationTypes(public_key: self.publicKey, privateKey: self.privateKey, success: {(jsonResult: AnyObject?) -> Void in if let error = jsonResult as? NSDictionary { if (error["status"]! as? Int) == 404 { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_API_CODE, userInfo: error as [NSObject : AnyObject])) } } } else { var identificationTypesResult = jsonResult as? NSArray? var identificationTypes : [IdentificationType] = [IdentificationType]() if identificationTypesResult != nil { for var i = 0; i < identificationTypesResult!!.count; i++ { if let identificationTypeDic = identificationTypesResult!![i] as? NSDictionary { identificationTypes.append(IdentificationType.fromJSON(identificationTypeDic)) } } } success(identificationTypes: identificationTypes) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getInstallments(bin: String, amount: Double, issuerId: Int64?, paymentTypeId: String, success: (installments: [Installment]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getInstallments(public_key: self.publicKey!, bin: bin, amount: amount, issuer_id: issuerId, payment_type_id: paymentTypeId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var paymentMethods = jsonResult as? NSArray var installments : [Installment] = [Installment]() if paymentMethods != nil && paymentMethods?.count > 0 { if let dic = paymentMethods![0] as? NSDictionary { installments.append(Installment.fromJSON(dic)) } success(installments: installments) } else { var error : NSError = NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_NOT_INSTALLMENTS_FOUND, userInfo: ["message": "NOT_INSTALLMENTS_FOUND".localized + "\(amount)"]) failure?(error: error) } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIssuers(paymentMethodId : String, success: (issuers: [Issuer]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getIssuers(public_key: self.publicKey!, payment_method_id: paymentMethodId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var issuersArray = jsonResult as? NSArray var issuers : [Issuer] = [Issuer]() if issuersArray != nil { for i in 0..<issuersArray!.count { if let issuerDic = issuersArray![i] as? NSDictionary { issuers.append(Issuer.fromJSON(issuerDic)) } } } success(issuers: issuers) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPromos(success: (promos: [Promo]?) -> Void, failure: ((error: NSError) -> Void)?) { // TODO: Está hecho para MLA fijo porque va a cambiar la URL para que dependa de una API y una public key let service : PromosService = PromosService(baseURL: MP_API_BASE_URL) service.getPromos(public_key: self.publicKey!, success: { (jsonResult) -> Void in var promosArray = jsonResult as? NSArray? var promos : [Promo] = [Promo]() if promosArray != nil { for var i = 0; i < promosArray!!.count; i++ { if let promoDic = promosArray!![i] as? NSDictionary { promos.append(Promo.fromJSON(promoDic)) } } } success(promos: promos) }, failure: failure) } public class func isCardPaymentType(paymentTypeId: String) -> Bool { if paymentTypeId == "credit_card" || paymentTypeId == "debit_card" || paymentTypeId == "prepaid_card" { return true } return false } public class func getBundle() -> NSBundle? { var bundle : NSBundle? = nil var privatePath = NSBundle.mainBundle().privateFrameworksPath if privatePath != nil { var path = privatePath!.stringByAppendingPathComponent("MercadoPagoSDK.framework") return NSBundle(path: path) } return nil } public class func getImage(name: String) -> UIImage? { var bundle = getBundle() if (UIDevice.currentDevice().systemVersion as NSString).compare("8.0", options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending { var nameArr = split(name) {$0 == "."} var imageExtension : String = nameArr[1] var imageName : String = nameArr[0] var filePath = bundle?.pathForResource(name, ofType: imageExtension) if filePath != nil { return UIImage(contentsOfFile: filePath!) } else { return nil } } return UIImage(named:name, inBundle: bundle, compatibleWithTraitCollection:nil) } public class func screenBoundsFixedToPortraitOrientation() -> CGRect { var screenSize : CGRect = UIScreen.mainScreen().bounds if NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1 && UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) { return CGRectMake(0.0, 0.0, screenSize.height, screenSize.width) } return screenSize } public class func showAlertViewWithError(error: NSError?, nav: UINavigationController?) { let msgDefault = "An error occurred while processing your request. Please try again." var msg : String? = msgDefault if error != nil { msg = error!.userInfo!["message"] as? String } let alert = UIAlertController() alert.title = "MercadoPago Error" alert.message = "Error = \(msg != nil ? msg! : msgDefault)" alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in switch action.style{ case .Default: nav!.popViewControllerAnimated(true) case .Cancel: println("cancel") case .Destructive: println("destructive") } })) nav!.presentViewController(alert, animated: true, completion: nil) } }
mit
xmartlabs/XLSlidingContainer
Example/Example/ScrollViewController.swift
1
1800
// // ScrollViewController.swift // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import SlidingContainer class ScrollViewController: UIViewController, ContainedViewController { private var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(image: UIImage(named: "stonehenge")!) let scrollView = UIScrollView() scrollView.addSubview(imageView) scrollView.contentSize = imageView.bounds.size view = scrollView } func didMinimizeControllerWith(diff: CGFloat) { view.alpha = 0.3 } func didMaximizeControllerWith(diff: CGFloat) { view.alpha = 1.0 } }
mit
abdullahselek/SwiftyNotifications
Sample/Sample/ViewController.swift
1
2983
// // ViewController.swift // Sample // // Created by Abdullah Selek on 03/04/2017. // Copyright © 2017 Abdullah Selek. All rights reserved. // import UIKit import SwiftyNotifications class ViewController: UIViewController, SwiftyNotificationsDelegate { private var notification: SwiftyNotifications! private var customNotification: SwiftyNotifications! override func viewDidLoad() { super.viewDidLoad() notification = SwiftyNotifications.withStyle(style: .info, title: "Swifty Notifications", subtitle: "Highly configurable iOS UIView for presenting notifications that doesn't block the UI", direction: .bottom) notification.delegate = self notification.addTouchHandler { } notification.addSwipeGestureRecognizer(direction: .down) view.addSubview(notification) customNotification = SwiftyNotifications.withStyle(style: .custom, title: "Custom", subtitle: "Custom notification with custom image and colors", direction: .top) customNotification.leftAccessoryView.image = UIImage(named: "apple_logo")! customNotification.setCustomColors(backgroundColor: UIColor.cyan, textColor: UIColor.white) view.addSubview(customNotification) } @IBAction func show(_ sender: Any) { notification.show() } @IBAction func dismiss(_ sender: Any) { if customNotification != nil { customNotification.dismiss() } notification.dismiss() } @IBAction func changeStyle(_ sender: Any) { let style = (sender as! UIButton).tag switch style { case 0: notification.customize(style: .normal) break case 1: notification.customize(style: .error) break case 2: notification.customize(style: .success) break case 3: notification.customize(style: .info) break case 4: notification.customize(style: .warning) break case 5: notification.dismiss() customNotification.show() break default: break } } // MARK: SwiftyNotifications Delegates func willShowNotification(notification: UIView) { } func didShowNotification(notification: UIView) { } func willDismissNotification(notification: UIView) { } func didDismissNotification(notification: UIView) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
tarun-talentica/TalNet
Source/Request/NetworkService.swift
2
1023
// // NetworkService.swift // GSignIn // // Created by Tarun Sharma on 07/05/16. // Copyright © 2016 Appcoda. All rights reserved. // import Foundation public protocol NetworkService { var host: String { get } var port: Int? {get} var scheme: String { get } var serviceType: NSURLRequestNetworkServiceType { get } func refreshAccessToken(request request: NSMutableURLRequest,completionHandler:(NSMutableURLRequest,Bool)->Void) func authorizeRequest(request: NSMutableURLRequest) -> NSMutableURLRequest } public extension NetworkService { var port: Int? { return nil } /// Network service has network service type as default var serviceType: NSURLRequestNetworkServiceType { return .NetworkServiceTypeDefault } func refreshAccessToken(request request: NSMutableURLRequest,completionHandler:(NSMutableURLRequest,Bool)->Void){ completionHandler(request,true) } func authorizeRequest(request: NSMutableURLRequest) -> NSMutableURLRequest { return request } }
mit
agrippa1994/iOS-PLC
PLC/CoreData/Entities/StaticData+CoreDataProperties.swift
1
374
// // StaticData+CoreDataProperties.swift // PLC // // Created by Manuel Stampfl on 08.09.15. // Copyright © 2015 mani1337. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension StaticData { }
mit
kallahir/MarvelFinder
MarvelFinder/CharacterDetailCollectionCell.swift
1
359
// // CharacterDetailCollectionCell.swift // MarvelFinder // // Created by Itallo Rossi Lucas on 10/01/17. // Copyright © 2017 Kallahir Labs. All rights reserved. // import UIKit class CharacterDetailCollectionCell: UICollectionViewCell { @IBOutlet weak var collectionImage: UIImageView! @IBOutlet weak var collectionName: UILabel! }
mit
wireapp/wire-ios
Wire-iOS Tests/DeviceManagement/CoreDataFixture+MockUserClient.swift
1
1530
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire extension CoreDataFixture { func mockUserClient(fingerprintString: String = "102030405060708090102030405060708090102030405060708090") -> UserClient! { let client = UserClient.insertNewObject(in: uiMOC) client.remoteIdentifier = "102030405060708090" client.user = ZMUser.insertNewObject(in: uiMOC) client.deviceClass = .tablet client.model = "Simulator" client.label = "Bill's MacBook Pro" let fingerprint: Data? = fingerprintString.data(using: .utf8) client.fingerprint = fingerprint let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm" let activationDate = formatter.date(from: "2016/05/01 14:31") client.activationDate = activationDate return client } }
gpl-3.0
wireapp/wire-ios
Wire-iOS Tests/ConversationCell/ConversationCellBurstTimestampViewSnapshotTests.swift
1
1759
// // Wire // Copyright (C) 2021 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire final class ConversationCellBurstTimestampViewSnapshotTests: XCTestCase { var sut: ConversationCellBurstTimestampView! override func setUp() { super.setUp() sut = ConversationCellBurstTimestampView() sut.frame = CGRect(origin: .zero, size: CGSize(width: 320, height: 40)) sut.unreadDot.backgroundColor = .red sut.backgroundColor = .lightGray } override func tearDown() { sut = nil super.tearDown() } func testForInitState() { verify(matching: sut) } func testForIncludeDayOfWeekAndDot() { // GIVEN & WHEN sut.configure(with: Date(timeIntervalSinceReferenceDate: 0), includeDayOfWeek: true, showUnreadDot: true) // THEN verify(matching: sut) } func testForNotIncludeDayOfWeekAndDot() { // GIVEN & WHEN sut.configure(with: Date(timeIntervalSinceReferenceDate: 0), includeDayOfWeek: false, showUnreadDot: false) // THEN verify(matching: sut) } }
gpl-3.0
derrh/CanvasKit
CanvasKitTests/Model Tests/CKIActivityStreamCollaborationItemTests.swift
3
1036
// // CKIActivityStreamCollaborationItemTests.swift // CanvasKit // // Created by Nathan Lambson on 7/17/14. // Copyright (c) 2014 Instructure. All rights reserved. // import UIKit import XCTest class CKIActivityStreamCollaborationItemTests: 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 testJSONModelConversion() { let activityStreamCollaborationItemDictionary = Helpers.loadJSONFixture("activity_stream_collaboration_item") as NSDictionary let streamItem = CKIActivityStreamCollaborationItem(fromJSONDictionary: activityStreamCollaborationItemDictionary) XCTAssertEqual(streamItem.collaborationID!, "1234", "Stream Collaboration Item id was not parsed correctly") } }
mit
terhechte/SourceKittenDaemon
Tests/SourceKittenDaemonTests/Fixtures/Sources/CompleteMethodFromFrameworkFixture.swift
2
70
import Foundation import AVFoundation let devices = AVCaptureDevice.
mit
novi/i2c-swift-example
Sources/I2CDeviceModule/SHT21.swift
1
1397
// // SHT21.swift // I2CDeviceModule // // Created by Yusuke Ito on 3/1/17. // Copyright © 2017 Yusuke Ito. All rights reserved. // import Foundation import I2C public final class SHT21 { public let address: UInt8 public let device: I2CDevice public init(device: I2CDevice, address: UInt8 = 0x40) { self.device = device self.address = address } } fileprivate extension SHT21 { enum Command: UInt8 { case mesureHoldT = 0xe3 case mesureHoldRH = 0xe5 case reset = 0xfe } func sendAndRead(command: Command, readByte: UInt32) throws -> [UInt8] { return try device.write(toAddress: address, data: [command.rawValue], readBytes: readByte) } func send(command: Command) throws -> UInt16 { let data = try sendAndRead(command: command, readByte: 3) let value: UInt16 = (UInt16(data[0]) << 8) | UInt16(data[1] & 0xfc) return value } } public extension SHT21 { func reset() throws { _ = try sendAndRead(command: .reset, readByte: 0) } func mesureTemperature() throws -> Double { let val = Double(try send(command: .mesureHoldT)) return -46.85 + (175.72 * val / 65536) } func mesureRH() throws -> Double { let val = Double(try send(command: .mesureHoldRH)) return -6 + (125 * val / 65536) } }
mit
HasanEdain/NPCColorPicker
NPCColorPicker/NPCPaleteUtility.swift
1
4578
// // NPCPaleteUtility.swift // NPCColorPicker // // Created by Hasan D Edain and Andrew Bush on 12/6/15. // Copyright © 2015-2017 NPC Unlimited. All rights reserved. // import UIKit open class NPCPaleteUtility { open static func twelveColorWheel()->[UIColor] { let colorArray = [NPCColorUtility.colorWithHex("fe7923"), NPCColorUtility.colorWithHex("fd0d1b"), NPCColorUtility.colorWithHex("bf1698"), NPCColorUtility.colorWithHex("941abe"), NPCColorUtility.colorWithHex("6819bd"), NPCColorUtility.colorWithHex("1024fc"), NPCColorUtility.colorWithHex("1ec0a8"), NPCColorUtility.colorWithHex("1dbb20"), NPCColorUtility.colorWithHex("c7f131"), NPCColorUtility.colorWithHex("e8ea34"), NPCColorUtility.colorWithHex("fad931"), NPCColorUtility.colorWithHex("feb92b")] return colorArray } open static func colorArrayWithRGBAStringArray(_ hexStringArray: [String]) -> [UIColor] { var colorArray = [UIColor]() for hexString in hexStringArray { let color = NPCColorUtility.colorWithRGBA(hexString) colorArray.append(color) } return colorArray } open static func colorArrayWithHexStringArray(_ hexStringArray: [String]) -> [UIColor] { var colorArray = [UIColor]() for hexString in hexStringArray { let color = NPCColorUtility.colorWithHex(hexString) colorArray.append(color) } return colorArray } // These colors are specified in #ffffffff Hexidecimal form open static func colorArrayWithGradient(_ startColor: String, endColor: String, steps: Int) -> [UIColor] { var colorArray = [UIColor]() let startRed = NPCColorUtility.redPercentForHexString(startColor as NSString) let startGreen = NPCColorUtility.greenPercentForHexString(startColor as NSString) let startBlue = NPCColorUtility.bluePercentForHexString(startColor as NSString) let startAlpha = NPCColorUtility.alphaPercentForHexString(startColor as NSString) let endRed = NPCColorUtility.redPercentForHexString(endColor as NSString) let endGreen = NPCColorUtility.greenPercentForHexString(endColor as NSString) let endBlue = NPCColorUtility.bluePercentForHexString(endColor as NSString) let endAlpha = NPCColorUtility.alphaPercentForHexString(endColor as NSString) let redDelta = -1 * (startRed - endRed) let greenDelta = -1 * (startGreen - endGreen) let blueDelta = -1 * (startBlue - endBlue) let alphaDelta = -1 * (startAlpha - endAlpha) var redIncrement:CGFloat = 0.0 if steps > 0 && redDelta != 0 { redIncrement = redDelta / CGFloat(steps) } var greenIncrement: CGFloat = 0.0 if steps > 0 && greenDelta != 0 { greenIncrement = greenDelta / CGFloat(steps) } var blueIncrement: CGFloat = 0.0 if steps > 0 && blueDelta != 0 { blueIncrement = blueDelta / CGFloat(steps) } var alphaIncrement: CGFloat = 0.0 if steps > 0 && alphaDelta != 0 { alphaIncrement = alphaDelta / CGFloat(steps) } for step in 1...steps { let red = startRed + (redIncrement * CGFloat(step)) let green = startGreen + (greenIncrement * CGFloat(step)) let blue = startBlue + (blueIncrement * CGFloat(step)) let alpha = startAlpha + (alphaIncrement * CGFloat(step)) let color = UIColor(red: red, green: green, blue: blue, alpha: alpha) colorArray.append(color) } return colorArray } open static func colorArrayWithColorStringArray(_ colorStrings: [String], steps: Int)->[UIColor] { if colorStrings.count <= 0 { return [UIColor.white] } else if colorStrings.count == 1 { return NPCPaleteUtility.colorArrayWithGradient(colorStrings[0], endColor: "ffffff", steps: steps) } else { var gradients = [UIColor]() for index in 1...(colorStrings.count - 1){ let start = colorStrings[index - 1] let end = colorStrings[index] var gradient = NPCPaleteUtility.colorArrayWithGradient(start, endColor: end, steps: steps) if index > 1 { gradient.removeFirst() } gradients.append(contentsOf: gradient) } return gradients } } }
mit
ByteriX/BxInputController
BxInputController/Sources/Rows/Boolean/View/BxInputCheckRowBinder.swift
1
1126
/** * @file BxInputCheckRowBinder.swift * @namespace BxInputController * * @details Binder for check box row subclasses * @date 17.03.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Binder for check box Row subclasses open class BxInputCheckRowBinder<Row : BxInputCheckRow, Cell>: BxInputStandartTextRowBinder<Row, Cell> where Cell : UITableViewCell, Cell : BxInputFieldCell { /// call when user selected this cell override open func didSelected() { super.didSelected() owner?.dissmissAllRows() row.value = !row.value didChangeValue() update() } /// call after common update for text attributes updating override open func updateCell() { cell?.valueTextField.isEnabled = false cell?.valueTextField.text = "" cell?.accessoryType = row.value ? .checkmark : .none cell?.selectionStyle = .default } }
mit
LunaGao/cnblogs-Mac-Swift
CNBlogsForMac/WebApi/BaseWebApi.swift
1
1904
// // BaseWebApi.swift // CNBlogsForMac // // Created by Luna Gao on 15/11/16. // Copyright © 2015年 gao.luna.com. All rights reserved. // import Foundation class BaseWebApi : NSObject { func basicRequest(callback:(String?)->Void){ let basicAuth = "Basic 这个值是根据ClientId和ClientSercret计算得来,这里隐藏" let urlstr = "https://api.cnblogs.com/token" let url = NSURL(string: urlstr) let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.addValue(basicAuth, forHTTPHeaderField: "Authorization") let op:NSOperationQueue = NSOperationQueue.mainQueue() request.HTTPBody = "grant_type=client_credentials".dataUsingEncoding(NSUTF8StringEncoding) //通过NSURLConnection发送请求 NSURLConnection.sendAsynchronousRequest(request, queue: op) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in //异步处理 dispatch_async(dispatch_get_main_queue(), { () -> Void in do { let jsonValue: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) if let statusesArray = jsonValue as? NSDictionary{ // NSLog("%@",statusesArray) if let aStatus = statusesArray["access_token"] as? String{ callback(aStatus) } else { callback(nil) } } } catch { callback(nil) } // NSLog("%@", String.init(data: data!, encoding: NSUTF8StringEncoding)!) }) } } } //同步处理 // dispatch_sync(dispatch_get_main_queue(), { () -> Void in // // })
mit
therealglazou/quaxe-for-swift
quaxe/protocols/core/DOMString.swift
1
226
/** * Quaxe for Swift * * Copyright 2016-2017 Disruptive Innovations * * Original author: * Daniel Glazman <daniel.glazman@disruptive-innovations.com> * * Contributors: * */ public typealias DOMString = String
mpl-2.0
noppoMan/SwiftJNChatApp
Package.swift
1
655
import PackageDescription let package = Package( name: "SwiftJNChatApp", targets: [ Target(name: "Config"), Target(name: "Migration", dependencies: ["Config"]), Target(name: "SwiftJNChatApp", dependencies: ["Config"]) ], dependencies: [ .Package(url: "https://github.com/noppoMan/WebAppKit.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/noppoMan/SwiftKnex.git", majorVersion: 0, minor: 2), .Package(url: "https://github.com/apple/swift-protobuf.git", Version(0,9,27)), .Package(url: "https://github.com/noppoMan/JSONWebToken.swift.git", Version(2,1,1)) ] )
mit
q231950/appwatch
AppWatch/ViewControllers/TimeTableViewController.swift
1
1268
// // TimeTableViewController.swift // AppWatch // // Created by Martin Kim Dung-Pham on 25.08.15. // Copyright © 2015 Martin Kim Dung-Pham. All rights reserved. // import AppKit class TimeTableViewController: NSViewController { @IBOutlet weak var collectionView: NSCollectionView! override func viewDidLoad() { super.viewDidLoad() // collectionView.content = ["hu", "lu"] // collectionView.itemPrototype = storyboard!.instantiateControllerWithIdentifier("collectionViewItem") as? NSCollectionViewItem } // func numberOfSectionsInCollectionView(collectionView: NSCollectionView) -> Int { // return 1 // } // // func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { // return 4 // } // // func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem { // // let item: NSCollectionViewItem // if let i = collectionView.itemAtIndexPath(indexPath) { // item = i // } else { // item = collectionView.newItemForRepresentedObject("hulu") // } // // return item // } // // }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/18378-swift-lexer-leximpl.swift
11
308
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let d { deinit { protocol e { let b = { case { func c { if true { class a { class case , let { { { [ { { [ [ { { { { { { { { { { { { c " "
mit
praca-japao/156
PMC156Inteligente/MyProfileTableViewController.swift
1
3269
// // MyProfileTableViewController.swift // PMC156Inteligente // // Created by Giovanni Pietrangelo on 11/29/15. // Copyright © 2015 Sigma Apps. All rights reserved. // import UIKit class MyProfileTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // 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 numberOfSectionsInTableView(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, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
albertinopadin/SwiftBreakout
Breakout/AppDelegate.swift
1
2153
// // AppDelegate.swift // Breakout // // Created by Albertino Padin on 10/26/14. // Copyright (c) 2014 Albertino Padin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-2.0
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
1
5571
// // ImageDataProvider.swift // Kingfisher // // Created by onevcat on 2018/11/13. // // 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 Foundation /// Represents a data provider to provide image data to Kingfisher when setting with /// `Source.provider` source. Compared to `Source.network` member, it gives a chance /// to load some image data in your own way, as long as you can provide the data /// representation for the image. public protocol ImageDataProvider { /// The key used in cache. var cacheKey: String { get } /// Provides the data which represents image. Kingfisher uses the data you pass in the /// handler to process images and caches it for later use. /// /// - Parameter handler: The handler you should call when you prepared your data. /// If the data is loaded successfully, call the handler with /// a `.success` with the data associated. Otherwise, call it /// with a `.failure` and pass the error. /// /// - Note: /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError` /// from the framework. func data(handler: @escaping (Result<Data, Error>) -> Void) } /// Represents an image data provider for loading from a local file URL on disk. /// Uses this type for adding a disk image to Kingfisher. Compared to loading it /// directly, you can get benefit of using Kingfisher's extension methods, as well /// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher. public struct LocalFileImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The file URL from which the image be loaded. public let fileURL: URL // MARK: Initializers /// Creates an image data provider by supplying the target local file URL. /// /// - Parameters: /// - fileURL: The file URL from which the image be loaded. /// - cacheKey: The key is used for caching the image data. By default, /// the `absoluteString` of `fileURL` is used. public init(fileURL: URL, cacheKey: String? = nil) { self.fileURL = fileURL self.cacheKey = cacheKey ?? fileURL.absoluteString } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: (Result<Data, Error>) -> Void) { handler( Result { try Data(contentsOf: fileURL) } ) } } /// Represents an image data provider for loading image from a given Base64 encoded string. public struct Base64ImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The encoded Base64 string for the image. public let base64String: String // MARK: Initializers /// Creates an image data provider by supplying the Base64 encoded string. /// /// - Parameters: /// - base64String: The Base64 encoded string for an image. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. public init(base64String: String, cacheKey: String) { self.base64String = base64String self.cacheKey = cacheKey } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: (Result<Data, Error>) -> Void) { let data = Data(base64Encoded: base64String)! handler(.success(data)) } } /// Represents an image data provider for a raw data object. public struct RawImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The raw data object to provide to Kingfisher image loader. public let data: Data // MARK: Initializers /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache. /// /// - Parameters: /// - data: The raw data reprensents an image. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. public init(data: Data, cacheKey: String) { self.data = data self.cacheKey = cacheKey } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: @escaping (Result<Data, Error>) -> Void) { handler(.success(data)) } }
mit
therealbnut/swift
stdlib/public/SDK/Foundation/NSString.swift
9
4420
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(_ string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
apache-2.0
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Dealer Detail/Presenter Tests/WhenBindingAboutTheArtistComponent_DealerDetailPresenterShould.swift
1
1348
@testable import Eurofurence import EurofurenceModel import XCTest class WhenBindingAboutTheArtistComponent_DealerDetailPresenterShould: XCTestCase { func testBindTheArtistDescriptionOntoTheComponent() { let aboutTheArtistViewModel = DealerDetailAboutTheArtistViewModel.random let viewModel = FakeDealerDetailAboutTheArtistViewModel(aboutTheArtist: aboutTheArtistViewModel) let interactor = FakeDealerDetailInteractor(viewModel: viewModel) let context = DealerDetailPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.bindComponent(at: 0) XCTAssertEqual(aboutTheArtistViewModel.artistDescription, context.boundAboutTheArtistComponent?.capturedArtistDescription) } func testBindTheTitleOntoTheComponent() { let aboutTheArtistViewModel = DealerDetailAboutTheArtistViewModel.random let viewModel = FakeDealerDetailAboutTheArtistViewModel(aboutTheArtist: aboutTheArtistViewModel) let interactor = FakeDealerDetailInteractor(viewModel: viewModel) let context = DealerDetailPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.bindComponent(at: 0) XCTAssertEqual(aboutTheArtistViewModel.title, context.boundAboutTheArtistComponent?.capturedTitle) } }
mit
grandiere/box
box/Metal/Texture/MetalTexture.swift
1
1392
import UIKit import MetalKit class MetalTexture { let totalFrames:Int var currentFrame:Int private var frameTick:Int private let frames:[MTLTexture] private let ticksPerFrame:Int init( ticksPerFrame:Int, images:[UIImage], textureLoader:MTKTextureLoader) { self.ticksPerFrame = ticksPerFrame currentFrame = 0 frameTick = 0 var frames:[MTLTexture] = [] for image:UIImage in images { guard let texture:MTLTexture = textureLoader.loadImage(image:image) else { continue } frames.append(texture) } self.frames = frames totalFrames = frames.count } //MARK: public func changeFrame() { } //MARK final final func current() -> MTLTexture? { if totalFrames < 1 { return nil } frameTick += 1 if frameTick >= ticksPerFrame { frameTick = 0 changeFrame() } let texture:MTLTexture = frames[currentFrame] return texture } final func restart() { currentFrame = 0 frameTick = 0 } }
mit
serieuxchat/SwiftySRP
SwiftySRP/SRPData+BigIntType.swift
1
9367
// // SRPData+BigIntType.swift // SwiftySRP // // Created by Sergey A. Novitsky on 20/03/2017. // Copyright © 2017 Flock of Files. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// Internal extension to short-circuit conversions between Data and BigIntType extension SRPData { // Client specific data /// Password hash 'x' (see SRP spec. in SRPProtocol.swift) func bigInt_x<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._x } return BigIntType(passwordHash) } /// Client private value 'a' (see SRP spec. in SRPProtocol.swift) func bigInt_a<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._a } return BigIntType(clientPrivateValue) } /// Client public value 'A' (see SRP spec. in SRPProtocol.swift) func bigInt_A<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._A } return BigIntType(clientPublicValue) } /// Client evidence message, computed as: M = H( pA | pB | pS), where pA, pB, and pS - padded values of A, B, and S (see SRP spec. in SRPProtocol.swift) func bigInt_clientM<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._clientM } return BigIntType(clientEvidenceMessage) } mutating func setBigInt_clientM<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._clientM = newValue self = impl as! Self } else { clientEvidenceMessage = newValue.serialize() } } /// Server evidence message, computed as: M = H( pA | pMc | pS), where pA is the padded A value; pMc is the padded client evidence message, and pS is the padded shared secret. (see SRP spec. in SRPProtocol.swift) func bigInt_serverM<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._serverM } return BigIntType(serverEvidenceMessage) } mutating func setBigInt_serverM<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._serverM = newValue self = impl as! Self } else { serverEvidenceMessage = newValue.serialize() } } // Common data: /// SRP Verifier 'v' (see SRP spec. in SRPProtocol.swift) func bigInt_v<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._v } return BigIntType(verifier) } mutating func setBigInt_v<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._v = newValue self = impl as! Self } else { self.verifier = newValue.serialize() } } // Scrambler parameter 'u'. u = H(A, B) (see SRP spec. in SRPProtocol.swift) func bigInt_u<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._u } return BigIntType(scrambler) } mutating func setBigInt_u<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._u = newValue self = impl as! Self } else { self.scrambler = newValue.serialize() } } /// Shared secret 'S' . Computed on the client as: S = (B - kg^x) ^ (a + ux) (see SRP spec. in SRPProtocol.swift) func bigInt_clientS<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._clientS } return BigIntType(clientSecret) } mutating func setBigInt_clientS<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._clientS = newValue self = impl as! Self } else { self.clientSecret = newValue.serialize() } } /// Shared secret 'S'. Computed on the server as: S = (Av^u) ^ b (see SRP spec. in SRPProtocol.swift) func bigInt_serverS<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._serverS } return BigIntType(serverSecret) } mutating func setBigInt_serverS<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._serverS = newValue self = impl as! Self } else { self.serverSecret = newValue.serialize() } } // Server specific data /// Multiplier parameter 'k'. Computed as: k = H(N, g) (see SRP spec. in SRPProtocol.swift) func bigInt_k<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._k } return BigIntType(multiplier) } mutating func setBigInt_k<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._k = newValue self = impl as! Self } else { self.multiplier = newValue.serialize() } } /// Server private value 'b' (see SRP spec. in SRPProtocol.swift) func bigInt_b<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._b } return BigIntType(serverPrivateValue) } /// Server public value 'B' (see SRP spec. in SRPProtocol.swift) func bigInt_B<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._B } return BigIntType(serverPublicValue) } }
mit
jatiwn/geocore-tutorial-1
Carthage/Checkouts/PromiseKit/Categories/Foundation/NSNotificationCenter+Promise.swift
1
986
import Foundation.NSNotification import PromiseKit /** To import the `NSNotificationCenter` category: use_frameworks! pod "PromiseKit/Foundation" Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: use_frameworks! pod "PromiseKit" And then in your sources: import PromiseKit */ extension NSNotificationCenter { public class func once(name: String) -> Promise<[NSObject: AnyObject]> { return once(name).then(on: zalgo) { (note: NSNotification) -> [NSObject: AnyObject] in return note.userInfo ?? [:] } } public class func once(name: String) -> Promise<NSNotification> { return Promise { fulfill, _ in var id: AnyObject? id = NSNotificationCenter.defaultCenter().addObserverForName(name, object: nil, queue: nil){ note in fulfill(note) NSNotificationCenter.defaultCenter().removeObserver(id!) } } } }
apache-2.0
tokyovigilante/CesiumKit
CesiumKit/Core/EllipsoidGeodesic.swift
1
14805
// // EllipsoidGeodesic.swift // CesiumKit // // Created by Ryan Walklin on 2/11/2015. // Copyright © 2015 Test Toast. All rights reserved. // import Foundation /** * Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points. * * @alias EllipsoidGeodesic * @constructor * * @param {Cartographic} [start] The initial planetodetic point on the path. * @param {Cartographic} [end] The final planetodetic point on the path. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies. */ class EllipsoidGeodesic { /** * Gets the ellipsoid. * @memberof EllipsoidGeodesic.prototype * @type {Ellipsoid} * @readonly */ let ellipsoid: Ellipsoid /** * Gets the initial planetodetic point on the path. * @memberof EllipsoidGeodesic.prototype * @type {Cartographic?} * @readonly */ fileprivate (set) var start: Cartographic? = nil /** * Gets the final planetodetic point on the path. * @memberof EllipsoidGeodesic.prototype * @type {Cartographic?} * @readonly */ fileprivate (set) var end: Cartographic? = nil /** * Gets the heading at the initial point. * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var startHeading: Double { assert(_distance != nil, "set end positions before getting startHeading") return _startHeading! } fileprivate var _startHeading: Double? = nil /** * Gets the heading at the final point. * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var endHeading: Double { assert(_distance != nil, "set end positions before getting endHeading") return _endHeading! } fileprivate var _endHeading: Double? = nil /** * Gets the surface distance between the start and end point * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var surfaceDistance: Double { assert(_distance != nil, "set end positions before getting surfaceDistance") return _distance! } fileprivate var _distance: Double? = nil fileprivate var _uSquared: Double? = nil fileprivate var _constants = EllipsoidGeodesicConstants() init (start: Cartographic? = nil, end: Cartographic? = nil, ellipsoid: Ellipsoid = Ellipsoid.wgs84) { self.ellipsoid = ellipsoid if start != nil && end != nil { computeProperties(start: start!, end: end!) } } /** * Sets the start and end points of the geodesic * * @param {Cartographic} start The initial planetodetic point on the path. * @param {Cartographic} end The final planetodetic point on the path. */ func setEndPoints (start: Cartographic, end: Cartographic) { computeProperties(start: start, end: end) } fileprivate func computeProperties(start: Cartographic, end: Cartographic) { let firstCartesian = ellipsoid.cartographicToCartesian(start).normalize() let lastCartesian = ellipsoid.cartographicToCartesian(end).normalize() assert(abs(abs(firstCartesian.angle(between: lastCartesian)) - .pi) >= 0.0125, "geodesic position is not unique") vincentyInverseFormula(major: ellipsoid.maximumRadius, minor: ellipsoid.minimumRadius, firstLongitude: start.longitude, firstLatitude: start.latitude, secondLongitude: end.longitude, secondLatitude: end.latitude) var surfaceStart = start var surfaceEnd = end surfaceStart.height = 0 surfaceEnd.height = 0 self.start = surfaceStart self.end = surfaceEnd setConstants() } fileprivate func vincentyInverseFormula(major: Double, minor: Double, firstLongitude: Double, firstLatitude: Double, secondLongitude: Double, secondLatitude: Double) { let eff = (major - minor) / major let l = secondLongitude - firstLongitude let u1 = atan((1 - eff) * tan(firstLatitude)) let u2 = atan((1 - eff) * tan(secondLatitude)) let cosineU1 = cos(u1) let sineU1 = sin(u1) let cosineU2 = cos(u2) let sineU2 = sin(u2) let cc = cosineU1 * cosineU2 let cs = cosineU1 * sineU2 let ss = sineU1 * sineU2 let sc = sineU1 * cosineU2 var lambda = l var lambdaDot = M_2_PI var cosineLambda = cos(lambda) var sineLambda = sin(lambda) var sigma: Double var cosineSigma: Double var sineSigma: Double var cosineSquaredAlpha: Double var cosineTwiceSigmaMidpoint: Double repeat { cosineLambda = cos(lambda) sineLambda = sin(lambda) let temp = cs - sc * cosineLambda sineSigma = sqrt(cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp) cosineSigma = ss + cc * cosineLambda sigma = atan2(sineSigma, cosineSigma) let sineAlpha: Double if sineSigma == 0.0 { sineAlpha = 0.0 cosineSquaredAlpha = 1.0 } else { sineAlpha = cc * sineLambda / sineSigma cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha } lambdaDot = lambda cosineTwiceSigmaMidpoint = cosineSigma - 2.0 * ss / cosineSquaredAlpha; if cosineTwiceSigmaMidpoint.isNaN { cosineTwiceSigmaMidpoint = 0.0 } lambda = l + computeDeltaLambda(eff, sineAlpha: sineAlpha, cosineSquaredAlpha: cosineSquaredAlpha, sigma: sigma, sineSigma: sineSigma, cosineSigma: cosineSigma, cosineTwiceSigmaMidpoint: cosineTwiceSigmaMidpoint) } while (abs(lambda - lambdaDot) > Math.Epsilon12) let uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor) let A = 1.0 + uSquared * (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0)) / 16384.0 let B = uSquared * (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0)) / 1024.0 let cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint; let deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma * (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - B * cosineTwiceSigmaMidpoint * (4.0 * sineSigma * sineSigma - 3.0) * (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0) / 6.0) / 4.0); _distance = minor * A * (sigma - deltaSigma) _startHeading = atan2(cosineU2 * sineLambda, cs - sc * cosineLambda) _endHeading = atan2(cosineU1 * sineLambda, cs * cosineLambda - sc) _uSquared = uSquared } fileprivate func setConstants() { let a = ellipsoid.maximumRadius let b = ellipsoid.minimumRadius let f = (a - b) / a let cosineHeading = cos(startHeading) let sineHeading = sin(startHeading) let tanU = (1 - f) * tan(start!.latitude) let cosineU = 1.0 / sqrt(1.0 + tanU * tanU) let sineU = cosineU * tanU let sigma = atan2(tanU, cosineHeading) let sineAlpha = cosineU * sineHeading let sineSquaredAlpha = sineAlpha * sineAlpha let cosineSquaredAlpha = 1.0 - sineSquaredAlpha let cosineAlpha = sqrt(cosineSquaredAlpha) let u2Over4 = _uSquared! / 4.0 let u4Over16 = u2Over4 * u2Over4 let u6Over64 = u4Over16 * u2Over4 let u8Over256 = u4Over16 * u4Over16 let a0: Double = (1.0 + u2Over4 - 3.0 * u4Over16 / 4.0 + 5.0 * u6Over64 / 4.0 - 175.0 * u8Over256 / 64.0) let a1: Double = (1.0 - u2Over4 + 15.0 * u4Over16 / 8.0 - 35.0 * u6Over64 / 8.0) let a2: Double = (1.0 - 3.0 * u2Over4 + 35.0 * u4Over16 / 4.0) let a3: Double = (1.0 - 5.0 * u2Over4) // FIXME: Compiler //let distanceRatio0 = a0 * sigma - a1 * sin(2.0 * sigma) * u2Over4 / 2.0 - a2 * sin(4.0 * sigma) * u4Over16 / 16.0 - a3 * sin(6.0 * sigma) * u6Over64 / 48.0 - sin(8.0 * sigma) * 5.0 * u8Over256 / 512 let dr0 = a0 * sigma let dr1 = a1 * sin(2.0 * sigma) * u2Over4 / 2.0 let dr2 = a2 * sin(4.0 * sigma) * u4Over16 / 16.0 let dr3 = a3 * sin(6.0 * sigma) * u6Over64 / 48.0 let dr4 = sin(8.0 * sigma) * 5.0 * u8Over256 / 512 let distanceRatio = dr0 - dr1 - dr2 - dr3 - dr4 _constants.a = a _constants.b = b _constants.f = f _constants.cosineHeading = cosineHeading _constants.sineHeading = sineHeading _constants.tanU = tanU _constants.cosineU = cosineU _constants.sineU = sineU _constants.sigma = sigma _constants.sineAlpha = sineAlpha _constants.sineSquaredAlpha = sineSquaredAlpha _constants.cosineSquaredAlpha = cosineSquaredAlpha _constants.cosineAlpha = cosineAlpha _constants.u2Over4 = u2Over4 _constants.u4Over16 = u4Over16 _constants.u6Over64 = u6Over64 _constants.u8Over256 = u8Over256 _constants.a0 = a0 _constants.a1 = a1 _constants.a2 = a2 _constants.a3 = a3 _constants.distanceRatio = distanceRatio } fileprivate func computeDeltaLambda(_ f: Double, sineAlpha: Double, cosineSquaredAlpha: Double, sigma: Double, sineSigma: Double, cosineSigma: Double, cosineTwiceSigmaMidpoint: Double) -> Double { let C = computeC(f, cosineSquaredAlpha: cosineSquaredAlpha) return (1.0 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint + C * cosineSigma * (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0))) } fileprivate func computeC(_ f: Double, cosineSquaredAlpha: Double) -> Double { return f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha)) / 16.0 } /** * Provides the location of a point at the indicated portion along the geodesic. * * @param {Number} fraction The portion of the distance between the initial and final points. * @returns {Cartographic} The location of the point along the geodesic. */ func interpolate (fraction: Double) -> Cartographic { assert(fraction >= 0.0 && fraction <= 1.0, "fraction out of bounds") assert(_distance != nil, "start and end must be set before calling funciton interpolateUsingSurfaceDistance") return interpolate(surfaceDistance: _distance! * fraction) } /** * Provides the location of a point at the indicated distance along the geodesic. * * @param {Number} distance The distance from the inital point to the point of interest along the geodesic * @returns {Cartographic} The location of the point along the geodesic. * * @exception {DeveloperError} start and end must be set before calling funciton interpolateUsingSurfaceDistance */ func interpolate (surfaceDistance distance: Double) -> Cartographic { assert(_distance != nil, "start and end must be set before calling funciton interpolateUsingSurfaceDistance") let constants = _constants let s = constants.distanceRatio + distance / constants.b let cosine2S = cos(2.0 * s) let cosine4S = cos(4.0 * s) let cosine6S = cos(6.0 * s) let sine2S = sin(2.0 * s) let sine4S = sin(4.0 * s) let sine6S = sin(6.0 * s) let sine8S = sin(8.0 * s) let s2 = s * s; let s3 = s * s2; let u8Over256 = constants.u8Over256 let u2Over4 = constants.u2Over4 let u6Over64 = constants.u6Over64 let u4Over16 = constants.u4Over16 var sigma = 2.0 * s3 * u8Over256 * cosine2S / 3.0 + s * (1.0 - u2Over4 + 7.0 * u4Over16 / 4.0 - 15.0 * u6Over64 / 4.0 + 579.0 * u8Over256 / 64.0 - (u4Over16 - 15.0 * u6Over64 / 4.0 + 187.0 * u8Over256 / 16.0) * cosine2S - (5.0 * u6Over64 / 4.0 - 115.0 * u8Over256 / 16.0) * cosine4S - 29.0 * u8Over256 * cosine6S / 16.0) + (u2Over4 / 2.0 - u4Over16 + 71.0 * u6Over64 / 32.0 - 85.0 * u8Over256 / 16.0) * sine2S + (5.0 * u4Over16 / 16.0 - 5.0 * u6Over64 / 4.0 + 383.0 * u8Over256 / 96.0) * sine4S - s2 * ((u6Over64 - 11.0 * u8Over256 / 2.0) * sine2S + 5.0 * u8Over256 * sine4S / 2.0) + (29.0 * u6Over64 / 96.0 - 29.0 * u8Over256 / 16.0) * sine6S + 539.0 * u8Over256 * sine8S / 1536.0; let theta = asin(sin(sigma) * constants.cosineAlpha) let latitude = atan(constants.a / constants.b * tan(theta)) // Redefine in terms of relative argument of latitude. sigma = sigma - constants.sigma let cosineTwiceSigmaMidpoint = cos(2.0 * constants.sigma + sigma) let sineSigma = sin(sigma) let cosineSigma = cos(sigma) let cc = constants.cosineU * cosineSigma; let ss = constants.sineU * sineSigma; let lambda = atan2(sineSigma * constants.sineHeading, cc - ss * constants.cosineHeading) let l = lambda - computeDeltaLambda(constants.f, sineAlpha: constants.sineAlpha, cosineSquaredAlpha: constants.cosineSquaredAlpha, sigma: sigma, sineSigma: sineSigma, cosineSigma: cosineSigma, cosineTwiceSigmaMidpoint: cosineTwiceSigmaMidpoint) return Cartographic(longitude: start!.longitude + l, latitude: latitude, height: 0.0) } fileprivate struct EllipsoidGeodesicConstants { var a = Double.nan var b = Double.nan var f = Double.nan var cosineHeading = Double.nan var sineHeading = Double.nan var tanU = Double.nan var cosineU = Double.nan var sineU = Double.nan var sigma = Double.nan var sineAlpha = Double.nan var sineSquaredAlpha = Double.nan var cosineSquaredAlpha = Double.nan var cosineAlpha = Double.nan var u2Over4 = Double.nan var u4Over16 = Double.nan var u6Over64 = Double.nan var u8Over256 = Double.nan var a0 = Double.nan var a1 = Double.nan var a2 = Double.nan var a3 = Double.nan var distanceRatio = Double.nan } }
apache-2.0
sarahspins/Loop
Loop/Extensions/NSBundle.swift
1
683
// // NSBundle.swift // Loop // // Created by Nate Racklyeft on 7/28/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation extension NSBundle { var shortVersionString: String { return objectForInfoDictionaryKey("CFBundleShortVersionString") as! String } var bundleDisplayName: String { return objectForInfoDictionaryKey("CFBundleDisplayName") as! String } var localizedNameAndVersion: String { return String(format: NSLocalizedString("%1$@ v%2$@", comment: "The format string for the app name and version number. (1: bundle name)(2: bundle version)"), bundleDisplayName, shortVersionString) } }
apache-2.0
3drobotics/SwiftIO
Sources/UDPChannel.swift
1
9242
// // UDPMavlinkReceiver.swift // SwiftIO // // Created by Jonathan Wight on 4/22/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Darwin import Dispatch import SwiftUtilities /** * A GCD based UDP listener. */ public class UDPChannel { public enum PreconditionError: ErrorType { case QueueSuspended case QueueNotExist } public let label: String? public let address: Address public var readHandler: (Datagram -> Void)? = loggingReadHandler public var errorHandler: (ErrorType -> Void)? = loggingErrorHandler private var resumed: Bool = false private let receiveQueue: dispatch_queue_t! private let sendQueue: dispatch_queue_t! private var source: dispatch_source_t! public private(set) var socket: Socket! public var configureSocket: (Socket -> Void)? // MARK: - Initialization public init(label: String? = nil, address: Address, qos: dispatch_qos_class_t = QOS_CLASS_DEFAULT, readHandler: (Datagram -> Void)? = nil) { self.label = label self.address = address assert(address.port != nil) if let readHandler = readHandler { self.readHandler = readHandler } let queueAttribute = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos, 0) receiveQueue = dispatch_queue_create("io.schwa.SwiftIO.UDP.receiveQueue", queueAttribute) guard receiveQueue != nil else { fatalError("dispatch_queue_create() failed") } sendQueue = dispatch_queue_create("io.schwa.SwiftIO.UDP.sendQueue", queueAttribute) guard sendQueue != nil else { fatalError("dispatch_queue_create() failed") } } // MARK: - Actions public func resume() throws { do { socket = try Socket(domain: address.family.rawValue, type: SOCK_DGRAM, protocol: IPPROTO_UDP) } catch let error { cleanup() errorHandler?(error) } configureSocket?(socket) source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, UInt(socket.descriptor), 0, receiveQueue) guard source != nil else { cleanup() throw Error.Generic("dispatch_source_create() failed") } dispatch_source_set_cancel_handler(source) { [weak self] in guard let strong_self = self else { return } strong_self.cleanup() strong_self.resumed = false } dispatch_source_set_event_handler(source) { [weak self] in guard let strong_self = self else { return } do { try strong_self.read() } catch let error { strong_self.errorHandler?(error) } } dispatch_source_set_registration_handler(source) { [weak self] in guard let strong_self = self else { return } do { try strong_self.socket.bind(strong_self.address) strong_self.resumed = true } catch let error { strong_self.errorHandler?(error) tryElseFatalError() { try strong_self.cancel() } return } } dispatch_resume(source) } public func cancel() throws { if resumed == true { assert(source != nil, "Cancel called with source = nil.") dispatch_source_cancel(source) } } public func send(data: DispatchData <Void>, address: Address? = nil, callback: Result <Void> -> Void) { guard sendQueue != nil else { callback(.Failure(PreconditionError.QueueNotExist)) return } guard resumed else { callback(.Failure(PreconditionError.QueueSuspended)) return } dispatch_async(sendQueue) { [weak self] in guard let strong_self = self else { return } do { // use default address if address parameter is not set let address = address ?? strong_self.address if address.family != strong_self.address.family { throw Error.Generic("Cannot send UDP data down a IPV6 socket with a IPV4 address or vice versa.") } try strong_self.socket.sendto(data, address: address) } catch let error { strong_self.errorHandler?(error) callback(.Failure(error)) return } callback(.Success()) } } public static func send(data: DispatchData <Void>, address: Address, queue: dispatch_queue_t, writeHandler: Result <Void> -> Void) { let socket = try! Socket(domain: address.family.rawValue, type: SOCK_DGRAM, protocol: IPPROTO_UDP) dispatch_async(queue) { do { try socket.sendto(data, address: address) } catch let error { writeHandler(.Failure(error)) return } writeHandler(.Success()) } } } // MARK: - extension UDPChannel: CustomStringConvertible { public var description: String { return "\(self.dynamicType)(\"\(label ?? "")\")" } } // MARK: - private extension UDPChannel { func read() throws { let data: NSMutableData! = NSMutableData(length: 4096) var addressData = Array <Int8> (count: Int(SOCK_MAXADDRLEN), repeatedValue: 0) let (result, address) = addressData.withUnsafeMutableBufferPointer() { (inout ptr: UnsafeMutableBufferPointer <Int8>) -> (Int, Address?) in var addrlen: socklen_t = socklen_t(SOCK_MAXADDRLEN) let result = Darwin.recvfrom(socket.descriptor, data.mutableBytes, data.length, 0, UnsafeMutablePointer<sockaddr> (ptr.baseAddress), &addrlen) guard result >= 0 else { return (result, nil) } let addr = UnsafeMutablePointer <sockaddr_storage> (ptr.baseAddress) let address = Address(sockaddr: addr.memory) return (result, address) } guard result >= 0 else { let error = Error.Generic("recvfrom() failed") errorHandler?(error) throw error } data.length = result let datagram = Datagram(from: address!, timestamp: Timestamp(), data: DispatchData <Void> (buffer: data.toUnsafeBufferPointer())) readHandler?(datagram) } func cleanup() { defer { socket = nil source = nil } do { try socket.close() } catch let error { errorHandler?(error) } } } // MARK: - public extension UDPChannel { public func send(data: NSData, address: Address? = nil, callback: Result <Void> -> Void) { let data = DispatchData <Void> (start: data.bytes, count: data.length) send(data, address: address ?? self.address, callback: callback) } } // Private for now - make public soon? private extension Socket { func sendto(data: DispatchData <Void>, address: Address) throws { var addr = sockaddr_storage(address: address) let result = withUnsafePointer(&addr) { ptr in return data.createMap() { (_, buffer) in return Darwin.sendto(descriptor, buffer.baseAddress, buffer.count, 0, UnsafePointer <sockaddr> (ptr), socklen_t(addr.ss_len)) } } // TODO: what about "partial" sends. if result < data.length { throw Errno(rawValue: errno) ?? Error.Unknown } } }
mit
jisudong/study
MyPlayground.playground/Pages/可选链式调用.xcplaygroundpage/Contents.swift
1
1812
//: [Previous](@previous) import Foundation class Person { var residence: Residence? } class Residence { var rooms = [Room]() var address: Address? var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room{ get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } } class Room { var name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName != nil { return buildingName } else if buildingNumber != nil && street != nil { return "\(String(describing: buildingNumber))\(String(describing: street))" } else { return nil } } } let john = Person() if let roomCount = john.residence?.numberOfRooms { print("John's residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" john.residence?.address = someAddress // residence 为nil if john.residence?.printNumberOfRooms() != nil { print("It was possible to print the number of rooms.") } else { print("It was not possible to print the number of rooms.") } if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { print("Unable to retrieve the first room name.") } var dict = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]] dict["Dave"]?[0] = 91 dict["Bev"]?[0] += 1 dict["Brian"]?[0] = 72
mit
STShenZhaoliang/Swift2Guide
Swift2Guide/Swift100Tips/Swift100Tips/ErrorController.swift
1
3869
// // ErrorController.swift // Swift100Tips // // Created by 沈兆良 on 16/5/30. // Copyright © 2016年 ST. All rights reserved. // import UIKit class ErrorController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("", ofType: "")! let file = NSFileManager.defaultManager().contentsAtPath(path)! do { try file.writeToFile("Hello", options: []) } catch let error as NSError { print ("Error: \(error.domain)") } do { try login("onevcat", password: "123") } catch LoginError.UserNotFound { print("UserNotFound") } catch LoginError.UserPasswordNotMatch { print("UserPasswordNotMatch") } catch { } let result = doSomethingParam(path) switch result { case let .Success(ok): let serverResponse = ok case let .Error(error): let serverResponse = error.description } do { try methodRethrows(1, f: methodThrows) } catch _ { } // 输出: // Int } enum LoginError: ErrorType { case UserNotFound, UserPasswordNotMatch } var users:[String: String]! func login(user: String, password: String) throws { //users 是 [String: String],存储[用户名:密码] if !users.keys.contains(user) { throw LoginError.UserNotFound } if users[user] != password { throw LoginError.UserPasswordNotMatch } print("Login successfully.") } enum Result { case Success(String) case Error(NSError) } func doSomethingParam(param:AnyObject) -> Result { //...做某些操作,成功结果放在 success 中 let success = true if success { return Result.Success("成功完成") } else { let error = NSError(domain: "errorDomain", code: 1, userInfo: nil) return Result.Error(error) } } func methodThrows(num: Int) throws { if num < 0 { print("Throwing!") // throw Error.Negative } print("Executed!") } func methodRethrows(num: Int, f: Int throws -> ()) rethrows { try f(num) } } //在 Swift 2.0 中,我们甚至可以在 enum 中指定泛型,这样就使结果统一化了。 enum Result<T> { case Success(T) case Failure(NSError) } //在 Swift 2 时代中的错误处理,现在一般的最佳实践是对于同步 API 使用异常机制,对于异步 API 使用泛型枚举。 //首先,try 可以接 ! 表示强制执行,这代表你确定知道这次调用不会抛出异常。如果在调用中出现了异常的话,你的程序将会崩溃,这和我们在对 Optional 值用 ! 进行强制解包时的行为是一致的。另外,我们也可以在 try 后面加上 ? 来进行尝试性的运行。try? 会返回一个 Optional 值:如果运行成功,没有抛出错误的话,它会包含这条语句的返回值,否则将为 nil。和其他返回 Optional 的方法类似,一个典型的 try? 的应用场景是和 if let 这样的语句搭配使用,不过如果你用了 try? 的话,就意味着你无视了错误的具体类型 /* 简单理解的话你可以将 rethrows 看做是 throws 的“子类”,rethrows 的方法可以用来重载那些被标为 throws 的方法或者参数,或者用来满足被标为 throws 的接口,但是反过来不行。如果你拿不准要怎么使用的话,就先记住你在要 throws 另一个 throws 时,应该将前者改为 rethrows。这样在不失灵活性的同时保证了代码的可读性和准确性。 */
mit
AaronMT/firefox-ios
Client/Frontend/AuthenticationManager/PagingPasscodeViewController.swift
9
3110
/* 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 private let PaneSwipeDuration: TimeInterval = 0.3 /// Base class for implementing a Passcode configuration screen with multiple 'panes'. class PagingPasscodeViewController: BasePasscodeViewController { fileprivate lazy var pager: UIScrollView = { let scrollView = UIScrollView() scrollView.isPagingEnabled = true scrollView.isUserInteractionEnabled = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false return scrollView }() var panes = [PasscodePane]() var currentPaneIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() view.addSubview(pager) panes.forEach { pager.addSubview($0) } pager.snp.makeConstraints { make in make.bottom.left.right.equalTo(self.view) make.top.equalTo(self.view.safeArea.top) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() panes.enumerated().forEach { index, pane in pane.frame = CGRect(origin: CGPoint(x: CGFloat(index) * pager.frame.width, y: 0), size: pager.frame.size) } pager.contentSize = CGSize(width: CGFloat(panes.count) * pager.frame.width, height: pager.frame.height) scrollToPaneAtIndex(currentPaneIndex) if self.authenticationInfo?.isLocked() ?? false { return } panes[currentPaneIndex].codeInputView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.view.endEditing(true) } } extension PagingPasscodeViewController { @discardableResult func scrollToNextAndSelect() -> PasscodePane { scrollToNextPane() panes[currentPaneIndex].codeInputView.becomeFirstResponder() return panes[currentPaneIndex] } @discardableResult func scrollToPreviousAndSelect() -> PasscodePane { scrollToPreviousPane() panes[currentPaneIndex].codeInputView.becomeFirstResponder() return panes[currentPaneIndex] } func resetAllInputFields() { panes.forEach { $0.codeInputView.resetCode() } } func scrollToNextPane() { guard (currentPaneIndex + 1) < panes.count else { return } currentPaneIndex += 1 scrollToPaneAtIndex(currentPaneIndex) } func scrollToPreviousPane() { guard (currentPaneIndex - 1) >= 0 else { return } currentPaneIndex -= 1 scrollToPaneAtIndex(currentPaneIndex) } func scrollToPaneAtIndex(_ index: Int) { UIView.animate(withDuration: PaneSwipeDuration, delay: 0, options: [], animations: { self.pager.contentOffset = CGPoint(x: CGFloat(self.currentPaneIndex) * self.pager.frame.width, y: 0) }, completion: nil) } }
mpl-2.0
heitorgcosta/Quiver
Quiver/Validating/Extensions/Validator+Misc.swift
1
696
// // Validator+Misc.swift // Quiver // // Created by Heitor Costa on 20/10/17. // Copyright © 2017 Heitor Costa. All rights reserved. // import Foundation // Misc Validators public extension Validator { static func required(message: String? = nil) -> Validator { return RequiredValidator().with(message: message) } static func not(_ validator: Validator, message: String? = nil) -> Validator { return NegateValidator(validator: validator).with(message: message) } static func when(_ condition: @escaping () -> Bool, use validator: Validator) -> Validator { return ConditionalValidator(conditionClosure: condition, validator: validator) } }
mit
rnystrom/GitHawk
Classes/Repository/RepositoryIssueSummaryModel+Filterable.swift
1
699
// // RepositoryIssueSummaryModel+Filterable.swift // Freetime // // Created by Ryan Nystrom on 10/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation extension RepositoryIssueSummaryModel: Filterable { func match(query: String) -> Bool { if query.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil { let ticketNumber = String(number) return ticketNumber.contains(query) } let lowerQuery = query.lowercased() if title.string.allText.lowercased().contains(lowerQuery) { return true } if author.lowercased().contains(lowerQuery) { return true } return false } }
mit
djq993452611/YiYuDaoJia_Swift
YiYuDaoJia/YiYuDaoJia/Classes/Main/Controller/BaseViewController.swift
1
2249
// // BaseViewController.swift // YiYuDaoJia // // Created by 蓝海天网Djq on 2017/4/25. // Copyright © 2017年 蓝海天网Djq. All rights reserved. // import UIKit class BaseViewController: UIViewController { // MARK: 定义属性 var contentView : UIView? var baseVM : BaseViewModel! // MARK: 懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: #imageLiteral(resourceName: "daipingjia")) imageView.center = self.view.center imageView.animationImages = [#imageLiteral(resourceName: "daipingjia"),#imageLiteral(resourceName: "daishouhuo")] imageView.animationDuration = 2 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // extension BaseViewController { func setupUI() { // 1.隐藏内容的View contentView?.isHidden = true // 2.添加执行动画的UIImageView view.addSubview(animImageView) // 3.给animImageView执行动画 animImageView.startAnimating() // 4.设置view的背景颜色 view.backgroundColor = UIColor.ColorHexString(hexStr: "#f0f0f0") //5.设置返回按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(backImage: #imageLiteral(resourceName: "back"), title: nil, parentVc: self, action: #selector(self.popAction)) navigationController?.navigationBar.tintColor = UIColor.gray } func loadDataFinished() { // 1.停止动画 animImageView.stopAnimating() // 2.隐藏animImageView animImageView.isHidden = true // 3.显示内容的View contentView?.isHidden = false } func popAction(){ navigationController?.popViewController(animated: true) } } // MARK:- 请求数据 extension BaseViewController { func loadData() { } }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/25512-swift-genericsignature-get.swift
13
240
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let c{{let c{class case,
apache-2.0
frootloops/swift
validation-test/Sema/type_checker_perf/slow/rdar35213699.swift
1
359
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts func test() { let x: UInt = 1 * 2 + 3 * 4 + 5 * 6 + 7 * 8 + 9 * 10 + 11 * 12 + 13 * 14 // expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}} }
apache-2.0
piv199/LocalisysChat
LocalisysChat/Sources/Modules/Common/Chat/Views/Inputs/AutoTextView.swift
1
5792
// // ALTextView.swift // ALTextInputBar // // Created by Alex Littlejohn on 2015/04/24. // Copyright (c) 2015 zero. All rights reserved. // import UIKit public protocol AutoTextViewDelegate: UITextViewDelegate { /** Notifies the receiver of a change to the contentSize of the textView The receiver is responsible for layout - parameter textView: The text view that triggered the size change - parameter newHeight: The ideal height for the new text view */ func textViewHeightChanged(textView: AutoTextView, newHeight: CGFloat) } public class AutoTextView: UITextView { // MARK: - Core properties fileprivate var textObserver: NSObjectProtocol? // MARK: - UI fileprivate lazy var placeholderLabel: UILabel = { var _placeholderLabel = UILabel() _placeholderLabel.clipsToBounds = false _placeholderLabel.autoresizesSubviews = false _placeholderLabel.numberOfLines = 1 _placeholderLabel.font = self.font _placeholderLabel.backgroundColor = UIColor.clear _placeholderLabel.textColor = self.tintColor _placeholderLabel.isHidden = true self.addSubview(_placeholderLabel) return _placeholderLabel }() // MARK: - Public properties override public var font: UIFont? { didSet { placeholderLabel.font = font } } override public var contentSize: CGSize { didSet { updateSize() } } public weak var textViewDelegate: AutoTextViewDelegate? { didSet { delegate = textViewDelegate } } public var placeholder: String = "" { didSet { placeholderLabel.text = placeholder } } /// The color of the placeholder text public var placeholderColor: UIColor! { get { return placeholderLabel.textColor } set { placeholderLabel.textColor = newValue } } public override var textAlignment: NSTextAlignment { get { return super.textAlignment } set { super.textAlignment = newValue placeholderLabel.textAlignment = newValue } } /// The maximum number of lines that will be shown before the text view will scroll. 0 = no limit public var maxNumberOfLines: CGFloat = 0 public fileprivate(set) var expectedHeight: CGFloat = 0 { didSet { guard oldValue != expectedHeight else { return } textViewDelegate?.textViewHeightChanged(textView: self, newHeight: expectedHeight) } } public var minimumHeight: CGFloat { get { return ceil(font?.lineHeight ?? 0.0) + textContainerInset.top + textContainerInset.bottom } } // MARK: - Lifecycle override public init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { isScrollEnabled = false configureObservers() updateSize() } fileprivate func configureObservers() { textObserver = NotificationCenter.default .addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: self, queue: nil) { [unowned self] (notification) in guard (notification.object as? AutoTextView) == self else { return } self.textViewDidChange() } } // MARK: - Layout override public func layoutSubviews() { super.layoutSubviews() placeholderLabel.isHidden = shouldHidePlaceholder() if !placeholderLabel.isHidden { placeholderLabel.frame = placeholderRectThatFits(rect: bounds) sendSubview(toBack: placeholderLabel) } } //MARK: - Sizing and scrolling private func updateSize() { let maxHeight = maxNumberOfLines > 0 ? (ceil(font!.lineHeight) * maxNumberOfLines) + textContainerInset.top + textContainerInset.bottom : CGFloat.greatestFiniteMagnitude let roundedHeight = roundHeight() if roundedHeight >= maxHeight { expectedHeight = maxHeight isScrollEnabled = true } else { isScrollEnabled = false expectedHeight = roundedHeight } ensureCaretDisplaysCorrectly() } /** Calculates the correct height for the text currently in the textview as we cannot rely on contentsize to do the right thing */ private func roundHeight() -> CGFloat { let boundingSize = CGSize(width: bounds.width, height: .greatestFiniteMagnitude) let size = sizeThatFits(boundingSize) return max(ceil(size.height), minimumHeight) } /** Ensure that when the text view is resized that the caret displays correctly withing the visible space */ private func ensureCaretDisplaysCorrectly() { guard let range = selectedTextRange else { return } DispatchQueue.main.async { let rect = self.caretRect(for: range.end) UIView.performWithoutAnimation { self.scrollRectToVisible(rect, animated: false) } } } //MARK: - Placeholder Layout - /** Determines if the placeholder should be hidden dependant on whether it was set and if there is text in the text view - returns: true if it should not be visible */ private func shouldHidePlaceholder() -> Bool { return placeholder.characters.count == 0 || text.characters.count > 0 } /** Layout the placeholder label to fit in the rect specified - parameter rect: The constrained size in which to fit the label - returns: The placeholder label frame */ private func placeholderRectThatFits(rect: CGRect) -> CGRect { let padding = textContainer.lineFragmentPadding var placeHolderRect = UIEdgeInsetsInsetRect(rect, textContainerInset) placeHolderRect.origin.x += padding placeHolderRect.size.width -= padding * 2 return placeHolderRect } //MARK: - Notifications - internal func textViewDidChange() { placeholderLabel.isHidden = shouldHidePlaceholder() updateSize() } }
unlicense
olejnjak/KartingCoach
KartingCoach/Extensions/UICollectionViewExtensions.swift
1
435
// // UICollectionViewExtensions.swift // KartingCoach // // Created by Lukáš Hromadník on 14.09.17. // import UIKit extension UICollectionView { func dequeueCell<Cell: UICollectionViewCell>(for indexPath: IndexPath) -> Cell { register(Cell.self, forCellWithReuseIdentifier: Cell.reuseIdentifier) return dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier, for: indexPath) as! Cell } }
gpl-3.0
keygx/Swift-Helpers
Helpers/HelpersTests/PhotosHelperTests.swift
1
4106
// // PhotosHelperTests.swift // HelpersTests // // Created by keygx on 2015/08/05. // Copyright (c) 2015年 keygx. All rights reserved. // import UIKit import XCTest import Photos class PhotosHelperTests: 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 test_A_SaveImageToPhotosLibraryFromUIImage() { let view = UIView(frame: CGRectMake(0, 0, 300, 300)) view.backgroundColor = UIColor.redColor() let image = view.toImage()! let expectation = expectationWithDescription("Save Image from UIImage") PhotosHelper().saveImageToPhotosLibrary(image) { (success, error) in PAssert(success, ==, true) expectation.fulfill() } waitForExpectationsWithTimeout(5.0, handler: nil) } func test_B_SaveImageToPhotosLibraryFromURL() { let path = NSBundle(forClass: self.dynamicType).pathForResource("nadeusagi", ofType: "png") let url = NSURL(fileURLWithPath: path!) let metadata: NSDictionary = PhotosHelper().metadata(url!) PAssert(metadata["ColorModel"] as! String, ==, "RGB") PAssert(metadata["PixelHeight"] as! NSNumber, ==, NSNumber(integer: 640)) PAssert(metadata["PixelWidth"] as! NSNumber, ==, NSNumber(integer: 960)) let expectation = expectationWithDescription("Save Image from URL") PhotosHelper().saveImageToPhotosLibrary(url!) { (success, error) in PAssert(success, ==, true) expectation.fulfill() } waitForExpectationsWithTimeout(5.0, handler: nil) } func test_C_SaveVideoToPhotosLibrary() { let path = NSBundle(forClass: self.dynamicType).pathForResource("nadeusagi", ofType: "mov") let url = NSURL(fileURLWithPath: path!) let expectation = expectationWithDescription("Save Video from URL") PhotosHelper().saveVideoToPhotosLibrary(url!) { (success, error) in PAssert(success, ==, true) expectation.fulfill() } waitForExpectationsWithTimeout(5.0, handler: nil) } func test_D_AssetsAndMetadata() { let allIDs = PhotosHelper().allAssetIDs() let assetList = PhotosHelper().assets(allIDs) // All Asset List PAssert(assetList.count, ==, allIDs.count) let expectation = expectationWithDescription("metadata") assetList[assetList.count-1].requestContentEditingInputWithOptions(nil) { (contentEditingInput, info) -> Void in let metadata: NSDictionary = PhotosHelper().metadata(contentEditingInput.fullSizeImageURL) //println(meta) // Metadata PAssert(metadata["ColorModel"] as! String, ==, "RGB") PAssert(metadata["PixelHeight"] as! NSNumber, ==, NSNumber(integer: 600)) PAssert(metadata["PixelWidth"] as! NSNumber, ==, NSNumber(integer: 600)) expectation.fulfill() } waitForExpectationsWithTimeout(5.0, handler: nil) } func test_E_DeletaAssets() { let allIDs = PhotosHelper().allAssetIDs() let assetList = PhotosHelper().assets(allIDs) let startIndex = assetList.count-2-1 let endIndex = assetList.count-1 var deleteAssets: [PHAsset] = Array(assetList[startIndex...endIndex]) let expectation = expectationWithDescription("delete") PhotosHelper().deletaAssets(deleteAssets) { (success, error) in PAssert(success, ==, true) expectation.fulfill() } waitForExpectationsWithTimeout(10.0, handler: nil) } }
mit
n8armstrong/CalendarView
CalendarView/CalendarViewTests/CalendarViewTests.swift
1
1469
// // CalendarViewTests.swift // CalendarViewTests // // Created by Nate Armstrong on 10/12/15. // Copyright © 2015 Nate Armstrong. All rights reserved. // import XCTest @testable import CalendarView import SwiftMoment class CalendarViewTests: 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 testNovember2015Bug() { let october = moment("10-12-2015")! XCTAssertEqual("October 12, 2015", october.format("MMMM d, yyyy")) let november = october.add(1, .Months) let date = november.startOf(.Months) XCTAssertEqual(1, date.day) let date2 = date.endOf(.Days).add(1, .Days) XCTAssertEqual(2, date2.day) } // See: https://github.com/n8armstrong/CalendarView/issues/7 func testSecondSundayInMarchBug() { let marchFirst = moment("3-1-2016")! let firstVisibleDay = marchFirst.startOf(.Months).endOf(.Days).subtract(marchFirst.weekday - 1, .Days).startOf(.Days) XCTAssertEqual("February 28, 2016", firstVisibleDay.format("MMMM d, yyyy")) let dayInQuestion = firstVisibleDay.add(14, .Days) XCTAssertEqual(13, dayInQuestion.day) } }
mit
khizkhiz/swift
validation-test/compiler_crashers_2_fixed/0007-rdar20750480.swift
24
157
// RUN: not %target-swift-frontend %s -parse protocol X { typealias R } extension Array : X { } let xs = [1,2,3] func z<A: X>(A) { } let ys = z(xs)
apache-2.0
parkboo/ios-charts
Charts/Classes/Data/CubicLineChartData.swift
1
754
// // LineChartData.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation /// Data object that encapsulates all data associated with a LineChart. public class CubicLineChartData: ChartData { public override init() { super.init() } public override init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } }
apache-2.0
te-th/xID3
Tests/xID3Tests/WithFilesTests.swift
1
1814
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 @testable import xID3 /// Verifies loading MP3 Files and extracting ID3 Tag class WithFilesTest: XCTestCase { /// Verifies that reading a MP3 file without ID3 data results in an absent ID3Tag. func testNonTaggedFile() { if let url = Bundle(for: type(of: self)).url(forResource: "without-id3", withExtension: "mp3") { if let inputStream = InputStream(url: url) { TestUtils.expectedAbsentID3Tag(inputStream) } } } /// Verifies that reading a MP3 file with an existing ID3 Tag func testTaggedFile() { if let url = Bundle(for: type(of: self)).url(forResource: "with-some-frames", withExtension: "mp3") { if let inputstream = InputStream(url: url) { let id3Tag = TestUtils.id3Tag(from: inputstream) XCTAssertNotNil(id3Tag) XCTAssertGreaterThan(id3Tag!.rawFrames().count, 0) } else { XCTFail("Could not find file with-some-frames.mp3") } } } }
apache-2.0
duliodenis/HackingWithSwift
project-15/Animation/AnimationTests/AnimationTests.swift
1
906
// // AnimationTests.swift // AnimationTests // // Created by Dulio Denis on 2/27/15. // Copyright (c) 2015 Dulio Denis. All rights reserved. // import UIKit import XCTest class AnimationTests: 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
radex/swift-compiler-crashes
crashes-fuzzing/02635-swift-printingdiagnosticconsumer-handlediagnostic.swift
11
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where f:V{ class C<T where S.e=c struct A{ let:={ class C
mit
naokits/my-programming-marathon
MapDirectionDemo/MapDirectionDemo/ViewController.swift
1
517
// // ViewController.swift // MapDirectionDemo // // Created by Naoki Tsutsui on 2/15/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
MarvinNazari/ICSPullToRefresh.Swift
ICSPullToRefresh/NVActivityIndicatorAnimationBallPulseRise.swift
1
3984
// // NVActivityIndicatorAnimationBallPulseRise.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallPulseRise: NVActivityIndicatorAnimationDelegate { func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - 4 * circleSpacing) / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - circleSize) / 2 let deltaY = size.height / 2 let duration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(controlPoints: 0.15, 0.46, 0.9, 0.6) let oddAnimation = self.oddAnimation(duration: duration, deltaY: deltaY, timingFunction: timingFunction) let evenAnimation = self.evenAnimation(duration: duration, deltaY: deltaY, timingFunction: timingFunction) // Draw circles for var i = 0; i < 5; i++ { let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), y: y, width: circleSize, height: circleSize) circle.frame = frame if i % 2 == 0 { circle.addAnimation(evenAnimation, forKey: "animation") } else { circle.addAnimation(oddAnimation, forKey: "animation") } layer.addSublayer(circle) } } func oddAnimation(duration duration: CFTimeInterval, deltaY: CGFloat, timingFunction: CAMediaTimingFunction) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [0.4, 1.1, 0.75] scaleAnimation.duration = duration // Translate animation let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") translateAnimation.keyTimes = [0, 0.25, 0.75, 1] translateAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction] translateAnimation.values = [0, deltaY, -deltaY, 0] translateAnimation.duration = duration let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false return animation } func evenAnimation(duration duration: CFTimeInterval, deltaY: CGFloat, timingFunction: CAMediaTimingFunction) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1.1, 0.4, 1] scaleAnimation.duration = duration // Translate animation let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") translateAnimation.keyTimes = [0, 0.25, 0.75, 1] translateAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction] translateAnimation.values = [0, -deltaY, deltaY, 0] translateAnimation.duration = duration let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false return animation } }
mit
neotron/SwiftBot-Discord
DiscordAPI/Source/API/Utility/URLEndpoints.swift
1
727
// // Created by David Hedbor on 2/12/16. // Copyright (c) 2016 NeoTron. All rights reserved. // import Foundation import Alamofire enum URLEndpoint: String { case Login = "auth/login", Logout = "auth/logout", Gateway = "gateway", Channel = "channels", User = "users" } class Endpoints { class func Simple(_ endpoint: URLEndpoint) -> String { return "https://discordapp.com/api/\(endpoint.rawValue)" } class func Channel(_ channel: String) -> String { return "\(Simple(.Channel))/\(channel)/messages" } class func User(_ userId: String, endpoint: URLEndpoint) -> String { return "\(Simple(.User))/\(userId)/\(endpoint.rawValue)" } }
gpl-3.0
vokal/Xcode-Template
Vokal-Swift.xctemplate/TokenStorageHelperTests.swift
2
1934
// // ___FILENAME___ // ___PACKAGENAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation import XCTest import SwiftKeychainWrapper @testable import ___PACKAGENAME___ class TokenStorageHelperTests: XCTestCase { let testEmail = "iamatest@example.com" let testToken = "SomeSuperLongGibberishFromTheServer" // MARK: - Test Lifecycle override func tearDown() { TokenStorageHelper.nukeAuthorizationToken() super.tearDown() } private func storeAuthorizationTokenForTestUser() { //GIVEN: There is nothing in the keychain //WHEN: I store the test token for the test email TokenStorageHelper.store(authorizationToken: testToken, forEmail: testEmail) //THEN: The test token is returned when I get the authorization token. let retrieved = TokenStorageHelper.getAuthorizationToken() XCTAssertEqual(retrieved, testToken) } func testStoringAuthorizationTokenWorks() { storeAuthorizationTokenForTestUser() } func testStoringAuthorizationTokenForSecondUserNukesFirst() { //GIVEN: The test user's token is already stored storeAuthorizationTokenForTestUser() //WHEN: I add a new user's auth token let user = "someoneelse@example.com" let token = "MoarToken" TokenStorageHelper.store(authorizationToken: token, forEmail: user) //THEN: The new user's token is returned when I get the auth token let retrieved = TokenStorageHelper.getAuthorizationToken() XCTAssertEqual(retrieved, token) //THEN: If I access the keychain directly, there is no value for the test user. if let _ = KeychainWrapper.standard.string(forKey: testEmail) { XCTFail("There should not be a token for the test email after setting a new one!") } } }
mit
vandadnp/chorizo
Chorizo/Playground.playground/section-1.swift
1
84
// Playground - noun: a place where people can play import UIKit import Foundation
mit
syoutsey/swift-corelibs-foundation
Foundation/NSScanner.swift
2
23943
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public class NSScanner : NSObject, NSCopying { internal var _scanString: String internal var _skipSet: NSCharacterSet? internal var _invertedSkipSet: NSCharacterSet? internal var _scanLocation: Int public func copyWithZone(zone: NSZone) -> AnyObject { return NSScanner(string: string) } public var string: String { return _scanString } public var scanLocation: Int { get { return _scanLocation } set { if newValue > string.length { fatalError("Index \(newValue) beyond bounds; string length \(string.length)") } _scanLocation = newValue } } /*@NSCopying*/ public var charactersToBeSkipped: NSCharacterSet? { get { return _skipSet } set { _skipSet = newValue?.copy() as? NSCharacterSet _invertedSkipSet = nil } } internal var invertedSkipSet: NSCharacterSet? { get { if let inverted = _invertedSkipSet { return inverted } else { if let set = charactersToBeSkipped { _invertedSkipSet = set.invertedSet return _invertedSkipSet } return nil } } } public var caseSensitive: Bool = false public var locale: NSLocale? internal static let defaultSkipSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() public init(string: String) { _scanString = string _skipSet = NSScanner.defaultSkipSet _scanLocation = 0 } } private struct _NSStringBuffer { var bufferLen: Int var bufferLoc: Int var string: NSString var stringLen: Int var stringLoc: Int var buffer = Array<unichar>(count: 32, repeatedValue: 0) var curChar: unichar static let EndCharacter = unichar(0xffff) init(string: String, start: Int, end: Int) { self.string = string._bridgeToObjectiveC() stringLoc = start stringLen = end if stringLoc < stringLen { bufferLen = min(32, stringLen - stringLoc); let range = NSMakeRange(stringLoc, bufferLen) bufferLoc = 1 curChar = buffer[0] buffer.withUnsafeMutableBufferPointer({ (inout ptr: UnsafeMutableBufferPointer<unichar>) -> Void in self.string.getCharacters(ptr.baseAddress, range: range) }) } else { bufferLen = 0 bufferLoc = 1 curChar = _NSStringBuffer.EndCharacter } } var currentCharacter: unichar { return curChar } var isAtEnd: Bool { return curChar == _NSStringBuffer.EndCharacter } mutating func fill() { bufferLen = min(32, stringLen - stringLoc); let range = NSMakeRange(stringLoc, bufferLen) buffer.withUnsafeMutableBufferPointer({ (inout ptr: UnsafeMutableBufferPointer<unichar>) -> Void in string.getCharacters(ptr.baseAddress, range: range) }) bufferLoc = 1 curChar = buffer[0] } mutating func advance() { if bufferLoc < bufferLen { /*buffer is OK*/ curChar = buffer[bufferLoc++] } else if (stringLoc + bufferLen < stringLen) { /* Buffer is empty but can be filled */ stringLoc += bufferLen fill() } else { /* Buffer is empty and we're at the end */ bufferLoc = bufferLen + 1 curChar = _NSStringBuffer.EndCharacter } } mutating func skip(skipSet: NSCharacterSet?) { if let set = skipSet { while set.characterIsMember(currentCharacter) && !isAtEnd { advance() } } } } private func isADigit(ch: unichar) -> Bool { struct Local { static let set = NSCharacterSet.decimalDigitCharacterSet() } return Local.set.characterIsMember(ch) } // This is just here to allow just enough generic math to handle what is needed for scanning an abstract integer from a string, perhaps these should be on IntegerType? internal protocol _BitShiftable { func >>(lhs: Self, rhs: Self) -> Self func <<(lhs: Self, rhs: Self) -> Self } internal protocol _IntegerLike : IntegerType, _BitShiftable { init(_ value: Int) static var max: Self { get } static var min: Self { get } } internal protocol _FloatArithmeticType { func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self } internal protocol _FloatLike : FloatingPointType, _FloatArithmeticType { init(_ value: Int) init(_ value: Double) static var max: Self { get } static var min: Self { get } } extension Int : _IntegerLike { } extension Int32 : _IntegerLike { } extension Int64 : _IntegerLike { } extension UInt32 : _IntegerLike { } extension UInt64 : _IntegerLike { } // these might be good to have in the stdlib extension Float : _FloatLike { static var max: Float { return FLT_MAX } static var min: Float { return FLT_MIN } } extension Double : _FloatLike { static var max: Double { return DBL_MAX } static var min: Double { return DBL_MIN } } private func numericValue(ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else { return __CFCharDigitValue(UniChar(ch)) } } private func numericOrHexValue(ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else if (ch >= unichar(unicodeScalarLiteral: "A") && ch <= unichar(unicodeScalarLiteral: "F")) { return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "A")) } else if (ch >= unichar(unicodeScalarLiteral: "a") && ch <= unichar(unicodeScalarLiteral: "f")) { return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "a")) } else { return -1; } } private func decimalSep(locale: NSLocale?) -> String { if let loc = locale { if let sep = loc.objectForKey(NSLocaleDecimalSeparator) as? NSString { return sep._swiftObject } return "." } else { return decimalSep(NSLocale.currentLocale()) } } extension String { internal func scan<T: _IntegerLike>(skipSet: NSCharacterSet?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var neg = false var localResult: T = 0 if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(skipSet) } if (!isADigit(buf.currentCharacter)) { return false } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } if (localResult >= T.max / 10) && ((localResult > T.max / 10) || T(numeral - (neg ? 1 : 0)) >= T.max - localResult * 10) { // apply the clamps and advance past the ending of the buffer where there are still digits localResult = neg ? T.min : T.max neg = false repeat { buf.advance() } while (isADigit(buf.currentCharacter)) break } else { // normal case for scanning localResult = localResult * 10 + T(numeral) } buf.advance() } while (isADigit(buf.currentCharacter)) to(neg ? -1 * localResult : localResult) locationToScanFrom = buf.stringLoc return true } internal func scanHex<T: _IntegerLike>(skipSet: NSCharacterSet?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var localResult: T = 0 var curDigit: Int if buf.currentCharacter == unichar(unicodeScalarLiteral: "0") { buf.advance() let locRewindTo = buf.stringLoc curDigit = numericOrHexValue(buf.currentCharacter) if curDigit == -1 { if buf.currentCharacter == unichar(unicodeScalarLiteral: "x") || buf.currentCharacter == unichar(unicodeScalarLiteral: "X") { buf.advance() curDigit = numericOrHexValue(buf.currentCharacter) } } if curDigit == -1 { locationToScanFrom = locRewindTo to(T(0)) return true } } else { curDigit = numericOrHexValue(buf.currentCharacter) if curDigit == -1 { return false } } repeat { if localResult > T.max >> T(4) { localResult = T.max } else { localResult = (localResult << T(4)) + T(curDigit) } buf.advance() curDigit = numericOrHexValue(buf.currentCharacter) } while (curDigit != -1) to(localResult) locationToScanFrom = buf.stringLoc return true } internal func scan<T: _FloatLike>(skipSet: NSCharacterSet?, locale: NSLocale?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { let ds_chars = decimalSep(locale).utf16 let ds = ds_chars[ds_chars.startIndex] var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var neg = false var localResult: T = T(0) if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(skipSet) } if (!isADigit(buf.currentCharacter)) { return false } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } // if (localResult >= T.max / T(10)) && ((localResult > T.max / T(10)) || T(numericValue(buf.currentCharacter) - (neg ? 1 : 0)) >= T.max - localResult * T(10)) is evidently too complex; so break it down to more "edible chunks" let limit1 = localResult >= T.max / T(10) let limit2 = localResult > T.max / T(10) let limit3 = T(numeral - (neg ? 1 : 0)) >= T.max - localResult * T(10) if (limit1) && (limit2 || limit3) { // apply the clamps and advance past the ending of the buffer where there are still digits localResult = neg ? T.min : T.max neg = false repeat { buf.advance() } while (isADigit(buf.currentCharacter)) break } else { localResult = localResult * T(10) + T(numeral) } buf.advance() } while (isADigit(buf.currentCharacter)) if buf.currentCharacter == ds { var factor = T(0.1) buf.advance() repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } localResult = localResult + T(numeral) * factor factor = factor * T(0.1) buf.advance() } while (isADigit(buf.currentCharacter)) } to(neg ? T(-1) * localResult : localResult) locationToScanFrom = buf.stringLoc return true } internal func scanHex<T: _FloatLike>(skipSet: NSCharacterSet?, locale: NSLocale?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { NSUnimplemented() } } extension NSScanner { // On overflow, the below methods will return success and clamp public func scanInt(result: UnsafeMutablePointer<Int32>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int32) -> Void in result.memory = value } } public func scanInteger(result: UnsafeMutablePointer<Int>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int) -> Void in result.memory = value } } public func scanLongLong(result: UnsafeMutablePointer<Int64>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int64) -> Void in result.memory = value } } public func scanUnsignedLongLong(result: UnsafeMutablePointer<UInt64>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt64) -> Void in result.memory = value } } public func scanFloat(result: UnsafeMutablePointer<Float>) -> Bool { return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Float) -> Void in result.memory = value } } public func scanDouble(result: UnsafeMutablePointer<Double>) -> Bool { return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Double) -> Void in result.memory = value } } public func scanHexInt(result: UnsafeMutablePointer<UInt32>) -> Bool { return _scanString.scanHex(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt32) -> Void in result.memory = value } } public func scanHexLongLong(result: UnsafeMutablePointer<UInt64>) -> Bool { return _scanString.scanHex(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt64) -> Void in result.memory = value } } public func scanHexFloat(result: UnsafeMutablePointer<Float>) -> Bool { return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Float) -> Void in result.memory = value } } public func scanHexDouble(result: UnsafeMutablePointer<Double>) -> Bool { return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Double) -> Void in result.memory = value } } public var atEnd: Bool { var stringLoc = scanLocation let stringLen = string.length if let invSet = invertedSkipSet { let range = string._nsObject.rangeOfCharacterFromSet(invSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } return stringLoc == stringLen } public class func localizedScannerWithString(string: String) -> AnyObject { NSUnimplemented() } } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer and better Optional usage. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future extension NSScanner { public func scanInt() -> Int32? { var value: Int32 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int32>) -> Int32? in if scanInt(ptr) { return ptr.memory } else { return nil } } } public func scanInteger() -> Int? { var value: Int = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int>) -> Int? in if scanInteger(ptr) { return ptr.memory } else { return nil } } } public func scanLongLong() -> Int64? { var value: Int64 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int64>) -> Int64? in if scanLongLong(ptr) { return ptr.memory } else { return nil } } } public func scanUnsignedLongLong() -> UInt64? { var value: UInt64 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in if scanUnsignedLongLong(ptr) { return ptr.memory } else { return nil } } } public func scanFloat() -> Float? { var value: Float = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in if scanFloat(ptr) { return ptr.memory } else { return nil } } } public func scanDouble() -> Double? { var value: Double = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in if scanDouble(ptr) { return ptr.memory } else { return nil } } } public func scanHexInt() -> UInt32? { var value: UInt32 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt32>) -> UInt32? in if scanHexInt(ptr) { return ptr.memory } else { return nil } } } public func scanHexLongLong() -> UInt64? { var value: UInt64 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in if scanHexLongLong(ptr) { return ptr.memory } else { return nil } } } public func scanHexFloat() -> Float? { var value: Float = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in if scanHexFloat(ptr) { return ptr.memory } else { return nil } } } public func scanHexDouble() -> Double? { var value: Double = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in if scanHexDouble(ptr) { return ptr.memory } else { return nil } } } // These methods avoid calling the private API for _invertedSkipSet and manually re-construct them so that it is only usage of public API usage // Future implementations on Darwin of these methods will likely be more optimized to take advantage of the cached values. public func scanString(string searchString: String) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = [caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch, NSStringCompareOptions.AnchoredSearch] if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } let range = str.rangeOfString(searchString, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length > 0 { /* ??? Is the range below simply range? 99.9% of the time, and perhaps even 100% of the time... Hmm... */ let res = str.substringWithRange(NSMakeRange(stringLoc, range.location + range.length - stringLoc)) scanLocation = range.location + range.length return res } return nil } public func scanCharactersFromSet(set: NSCharacterSet) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfCharacterFromSet(set.invertedSet, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } public func scanUpToString(string: String) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfString(string, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } public func scanUpToCharactersFromSet(set: NSCharacterSet) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfCharacterFromSet(set, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } }
apache-2.0
chrisamanse/CryptoKit
Tests/CryptoKitTests/MD5Tests.swift
1
1824
// // MD5Tests.swift // MD5Tests // // Created by Chris Amanse on 29/08/2016. // // import Foundation import XCTest @testable import CryptoKit class MD5Tests: 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 testMD5() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Verification strings from RFC 1321 XCTAssertEqual("".md5().hexString, "d41d8cd98f00b204e9800998ecf8427e") XCTAssertEqual("a".md5().hexString, "0cc175b9c0f1b6a831c399e269772661") XCTAssertEqual("abc".md5().hexString, "900150983cd24fb0d6963f7d28e17f72") XCTAssertEqual("message digest".md5().hexString, "f96b697d7cb7938d525a2f31aaf161d0") XCTAssertEqual("abcdefghijklmnopqrstuvwxyz".md5().hexString , "c3fcd3d76192e4007dfb496cca67e13b") XCTAssertEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".md5().hexString, "d174ab98d277d9f5a5611c2c9f419d9f") XCTAssertEqual("12345678901234567890123456789012345678901234567890123456789012345678901234567890".md5().hexString, "57edf4a22be3c955ac49da2e2107b67a") } static var allTests : [(String, (MD5Tests) -> () throws -> Void)] { return [ ("testMD5", testMD5), ] } } extension String { func md5() -> Data { return (self.data(using: .utf8) ?? Data()).digest(using: .md5) } }
mit
MadAppGang/SmartLog
iOS/Pods/Dip/Sources/Register_swift2.swift
3
2586
// // Dip // // Copyright (c) 2015 Olivier Halligon <olivier@halligon.net> // // 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. // #if !swift(>=3.0) extension DependencyContainer { /** Registers definition for passed type. If instance created by factory of definition, passed as a first parameter, does not implement type passed in a `type` parameter, container will throw `DipError.DefinitionNotFound` error when trying to resolve that type. - parameters: - definition: Definition to register - type: Type to register definition for - tag: Optional tag to associate definition with. Default is `nil`. - returns: New definition registered for passed type. */ public func register<T, U, F>(definition: Definition<T, U>, type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition<F, U> { return _register(definition: definition, type: type, tag: tag) } /** Register definiton in the container and associate it with an optional tag. Will override already registered definition for the same type and factory, associated with the same tag. - parameters: - tag: The arbitrary tag to associate this definition with. Pass `nil` to associate with any tag. Default value is `nil`. - definition: The definition to register in the container. */ public func register<T, U>(definition: Definition<T, U>, tag: DependencyTagConvertible? = nil) { _register(definition: definition, tag: tag) } } #endif
mit
ResearchSuite/ResearchSuiteExtensions-iOS
Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/RSTBServiceLoader.swift
1
510
// // RSTBServiceLoader.swift // Pods // // Created by James Kizer on 1/9/17. // // import UIKit class RSTBServiceLoader<Proto> { private var serviceProviders: [Proto]! = [] public func addService<T>(service: T) { if let protoService = service as? Proto { self.serviceProviders = self.serviceProviders + [protoService] } } public func iterator() -> IndexingIterator<Array<Proto>> { return self.serviceProviders.makeIterator() } }
apache-2.0
MrAlek/PagedArray
Sources/PagedArray.swift
1
6848
// // PagedArray.swift // // Created by Alek Åström on 2015-02-14. // Copyright (c) 2015 Alek Åström. (https://github.com/MrAlek) // // 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. /// /// A paging collection type for arbitrary elements. Great for implementing paging /// mechanisms to scrolling UI elements such as `UICollectionView` and `UITableView`. /// public struct PagedArray<T> { public typealias PageIndex = Int /// The datastorage public fileprivate(set) var elements = [PageIndex: [T]]() // MARK: Public properties /// The size of each page public let pageSize: Int /// The total count of supposed elements, including nil values public var count: Int /// The starting page index public let startPage: PageIndex /// When set to true, no size or upper index checking /// is done when setting pages, making the paged array /// adjust its size dynamically. /// /// Useful for infinite lists and when data count cannot /// be guaranteed not to change while loading new pages. public var updatesCountWhenSettingPages: Bool = false /// The last valid page index public var lastPage: PageIndex { if count == 0 { return 0 } else if count%pageSize == 0 { return count/pageSize+startPage-1 } else { return count/pageSize+startPage } } /// All elements currently set, in order public var loadedElements: [T] { return self.compactMap { $0 } } // MARK: Initializers /// Creates an empty `PagedArray` public init(count: Int, pageSize: Int, startPage: PageIndex = 0) { self.count = count self.pageSize = pageSize self.startPage = startPage } // MARK: Public functions /// Returns the page index for an element index public func page(for index: Index) -> PageIndex { assert(index >= startIndex && index < endIndex, "Index out of bounds") return index/pageSize+startPage } /// Returns a `Range` corresponding to the indexes for a page public func indexes(for page: PageIndex) -> CountableRange<Index> { assert(page >= startPage && page <= lastPage, "Page index out of bounds") let start: Index = (page-startPage)*pageSize let end: Index if page == lastPage { end = count } else { end = start+pageSize } return (start..<end) } // MARK: Public mutating functions /// Sets a page of elements for a page index public mutating func set(_ elements: [T], forPage page: PageIndex) { assert(page >= startPage, "Page index out of bounds") assert(count == 0 || elements.count > 0, "Can't set empty elements page on non-empty array") let pageIndexForExpectedSize = (page > lastPage) ? lastPage : page let expectedSize = size(for: pageIndexForExpectedSize) if !updatesCountWhenSettingPages { assert(page <= lastPage, "Page index out of bounds") assert(elements.count == expectedSize, "Incorrect page size") } else { // High Chaparall mode, array can change in size count += elements.count-expectedSize if page > lastPage { count += (page-lastPage)*pageSize } } self.elements[page] = elements } /// Removes the elements corresponding to the page, replacing them with `nil` values public mutating func remove(_ page: PageIndex) { elements[page] = nil } /// Removes all loaded elements, replacing them with `nil` values public mutating func removeAllPages() { elements.removeAll(keepingCapacity: true) } } // MARK: SequenceType extension PagedArray : Sequence { public func makeIterator() -> IndexingIterator<PagedArray> { return IndexingIterator(_elements: self) } } // MARK: CollectionType extension PagedArray : BidirectionalCollection { public typealias Index = Int public var startIndex: Index { return 0 } public var endIndex: Index { return count } public func index(after i: Index) -> Index { return i+1 } public func index(before i: Index) -> Index { return i-1 } /// Accesses and sets elements for a given flat index position. /// Currently, setter can only be used to replace non-optional values. public subscript (position: Index) -> T? { get { let pageIndex = page(for: position) if let page = elements[pageIndex] { return page[position%pageSize] } else { // Return nil for all pages that haven't been set yet return nil } } set(newValue) { guard let newValue = newValue else { return } let pageIndex = page(for: position) var elementPage = elements[pageIndex] elementPage?[position % pageSize] = newValue elements[pageIndex] = elementPage } } } // MARK: Printable extension PagedArray : CustomStringConvertible { public var description: String { return "PagedArray(\(Array(self)))" } } // MARK: DebugPrintable extension PagedArray : CustomDebugStringConvertible { public var debugDescription: String { return "PagedArray(Pages: \(elements), Array representation: \(Array(self)))" } } // MARK: Private functions private extension PagedArray { func size(for page: PageIndex) -> Int { let indexes = self.indexes(for: page) return indexes.endIndex-indexes.startIndex } }
mit
SimonLYU/Swift-Transitioning
highGo2/LYUMainNAV.swift
1
270
// // LYUMainNAV.swift // highGo2 // // Created by 吕旭明 on 16/8/4. // Copyright © 2016年 lyu. All rights reserved. // import UIKit class LYUMainNAV: UINavigationController { override func viewDidLoad() { super.viewDidLoad() } }
mit
danielsaidi/Vandelay
VandelayDemo/ViewController.swift
1
2514
// // ViewController.swift // VandelayExample // // Created by Daniel Saidi on 2018-09-12. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit import Vandelay class ViewController: UITableViewController { // MARK: - View lifecycle override func viewWillAppear(_ animated: Bool) { reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let id = segue.identifier else { return } switch id { case "PhotoSegue": let vc = segue.destination as? PhotoViewController vc?.repository = photoRepository case "TodoSegue": let vc = segue.destination as? TodoItemViewController vc?.repository = todoItemRepository default: break } } // MARK: - Dependencies let todoItemRepository = TodoItemRepository() let photoRepository = PhotoRepository() // MARK: - Properties let photoFile = "photoAlbum.vdl" var photoUrl: URL { FileExporter(fileName: photoFile).getFileUrl()! } let todoFile = "todoList.vdl" var todoUrl: URL { FileExporter(fileName: todoFile).getFileUrl()! } // MARK: - Outlets @IBOutlet weak var exportPhotoAlbumCell: UITableViewCell! @IBOutlet weak var exportTodoItemsCell: UITableViewCell! @IBOutlet weak var importPhotoAlbumCell: UITableViewCell! @IBOutlet weak var importTodoItemsCell: UITableViewCell! @IBOutlet weak var photoAlbumCell: UITableViewCell! @IBOutlet weak var todoItemCell: UITableViewCell! } // MARK: - Public Functions extension ViewController { func reloadData() { let items = todoItemRepository.getItems() let photos = photoRepository.getPhotos() todoItemCell.detailTextLabel?.text = "\(items.count) items" photoAlbumCell.detailTextLabel?.text = "\(photos.count) photos" } } // MARK: - UITableViewDelegate extension ViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) else { return } switch cell { case exportPhotoAlbumCell: exportPhotoAlbum() case exportTodoItemsCell: exportTodoList() case importTodoItemsCell: importTodoList() case importPhotoAlbumCell: importPhotoAlbum() default: break } } }
mit
xuzhuoyi/EmbControl
embcontrol/yudpsocket.swift
1
6170
/* Copyright (c) <2014>, skysent 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by skysent. 4. Neither the name of the skysent 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 skysent ''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 skysent BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation @asmname("yudpsocket_server") func c_yudpsocket_server(host:UnsafePointer<Int8>,port:Int32) -> Int32 @asmname("yudpsocket_recive") func c_yudpsocket_recive(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32 @asmname("yudpsocket_close") func c_yudpsocket_close(fd:Int32) -> Int32 @asmname("yudpsocket_client") func c_yudpsocket_client() -> Int32 @asmname("yudpsocket_get_server_ip") func c_yudpsocket_get_server_ip(host:UnsafePointer<Int8>,ip:UnsafePointer<Int8>) -> Int32 @asmname("yudpsocket_sentto") func c_yudpsocket_sentto(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,ip:UnsafePointer<Int8>,port:Int32) -> Int32 public class UDPClient: YSocket { public override init(addr a:String,port p:Int){ super.init() var remoteipbuff:[Int8] = [Int8](count:16,repeatedValue:0x0) var ret=c_yudpsocket_get_server_ip(a, ip: remoteipbuff) if ret==0{ if let ip=String(CString: remoteipbuff, encoding: NSUTF8StringEncoding){ self.addr=ip self.port=p var fd:Int32=c_yudpsocket_client() if fd>0{ self.fd=fd } } } } /* * send data * return success or fail with message */ public func send(data d:[UInt8])->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_yudpsocket_sentto(fd, buff: d, len: Int32(d.count), ip: self.addr,port: Int32(self.port)) if Int(sendsize)==d.count{ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * send string * return success or fail with message */ public func send(str s:String)->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_yudpsocket_sentto(fd, buff: s, len: Int32(strlen(s)), ip: self.addr,port: Int32(self.port)) if sendsize==Int32(strlen(s)){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * * send nsdata */ public func send(data d:NSData)->(Bool,String){ if let fd:Int32=self.fd{ var buff:[UInt8] = [UInt8](count:d.length,repeatedValue:0x0) d.getBytes(&buff, length: d.length) var sendsize:Int32=c_yudpsocket_sentto(fd, buff: buff, len: Int32(d.length), ip: self.addr,port: Int32(self.port)) if sendsize==Int32(d.length){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } public func close()->(Bool,String){ if let fd:Int32=self.fd{ c_yudpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } //TODO add multycast and boardcast } public class UDPServer:YSocket{ public override init(addr a:String,port p:Int){ super.init(addr: a, port: p) var fd:Int32 = c_yudpsocket_server(self.addr, port: Int32(self.port)) if fd>0{ self.fd=fd } } //TODO add multycast and boardcast public func recv(expectlen:Int)->([UInt8]?,String,Int){ if let fd:Int32 = self.fd{ var buff:[UInt8] = [UInt8](count:expectlen,repeatedValue:0x0) var remoteipbuff:[Int8] = [Int8](count:16,repeatedValue:0x0) var remoteport:Int32=0 var readLen:Int32=c_yudpsocket_recive(fd, buff: buff, len: Int32(expectlen), ip: &remoteipbuff, port: &remoteport) var port:Int=Int(remoteport) var addr:String="" if let ip=String(CString: remoteipbuff, encoding: NSUTF8StringEncoding){ addr=ip } if readLen<=0{ return (nil,addr,port) } var rs=buff[0...Int(readLen-1)] var data:[UInt8] = Array(rs) return (data,addr,port) } return (nil,"no ip",0) } public func close()->(Bool,String){ if let fd:Int32=self.fd{ c_yudpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } }
gpl-3.0
haldun/MapleBacon
MapleBaconExample/MapleBaconExample/ImageManagerExample.swift
2
2419
// // Copyright (c) 2015 Zalando SE. All rights reserved. // import UIKit import MapleBacon class ImageCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView? override func prepareForReuse() { self.imageView?.image = nil } } class ImageExampleViewController: UICollectionViewController { var imageURLs = ["http://media.giphy.com/media/lI6nHr5hWXlu0/giphy.gif"] override func viewDidLoad() { if let file = NSBundle.mainBundle().pathForResource("imageURLs", ofType: "plist"), let paths = NSArray(contentsOfFile: file) { for url in paths { imageURLs.append(url as! String) } } collectionView?.reloadData() super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let gradient = CAGradientLayer() gradient.frame = view.frame gradient.colors = [UIColor(red: 127 / 255, green: 187 / 255, blue: 154 / 255, alpha: 1).CGColor, UIColor(red: 14 / 255, green: 43 / 255, blue: 57 / 255, alpha: 1).CGColor] view.layer.insertSublayer(gradient, atIndex: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() MapleBaconStorage.sharedStorage.clearMemoryStorage() } @IBAction func clearCache(sender: AnyObject) { MapleBaconStorage.sharedStorage.clearStorage() } } extension ImageExampleViewController { // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageURLs.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! ImageCell let url = imageURLs[indexPath.row] if let imageURL = NSURL(string: imageURLs[indexPath.row]) { cell.imageView?.setImageWithURL(imageURL) { (_, error) in if error == nil { let transition = CATransition() cell.imageView?.layer.addAnimation(transition, forKey: "fade") } } } return cell } }
mit
soffes/RateLimit
RateLimit/SyncLimiter.swift
2
403
// // SyncLimiter.swift // RateLimit // // Created by Sam Soffes on 10/20/16. // Copyright © 2016 Sam Soffes. All rights reserved. // public protocol SyncLimiter { @discardableResult func execute(_ block: () -> Void) -> Bool func reset() } extension SyncLimiter { public func execute<T>(_ block: () -> T) -> T? { var value: T? = nil execute { value = block() } return value } }
mit
anthonyqz/CQZContactManger
project/CQZContactMangerTests/CQZContactMangerTests.swift
1
1004
// // CQZContactMangerTests.swift // CQZContactMangerTests // // Created by Christian Quicano on 3/18/17. // Copyright © 2017 ca9z. All rights reserved. // import XCTest @testable import CQZContactManger class CQZContactMangerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
spitzgoby/Tunits
Pod/Classes/TimeUnit+DateTraversal.swift
1
22034
// // TimeUnit+DateTraversal.swift // Pods // // Created by Tom on 12/27/15. // // 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. // // Large portions of this code were influenced by Matt Thompson (http://mattt.me). // The original code can be found at https://github.com/mattt/CupertinoYankee // import Foundation extension TimeUnit { // MARK: - Previous and Next Time Units // MARK: minutes /************** *** PLURAL *** **************/ /** Creates a new date by subtracting the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ public func minutesBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.minutesAfter(date, delta: -delta) } /** Creates a new date by subtracting the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ static public func minutesBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.minutesBefore(date, delta: delta) } /** Creates a new date by adding the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ static public func minutesAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.minutesAfter(date, delta: delta) } /** Creates a new date by adding the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ public func minutesAfter(date:NSDate, delta:Int = 1) -> NSDate { let minute = self.calendar.dateByAddingUnit(.Minute, value: delta, toDate: date, options: [])! return self.beginningOfMinute(minute) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the minute prior to the given date. - parameter date: The date for which to find the previous minute. - returns: The newly created date. */ public func minuteBefore(date:NSDate) -> NSDate { return self.minutesBefore(date) } /** Creates a new date at the first second of the minute prior to the given date. - parameter date: The date for which to find the previous minute. - returns: The newly created date. */ static public func minuteBefore(date:NSDate) -> NSDate { return sharedInstance.minuteBefore(date) } /** Creates a new date at the first second of the minute following the given date. - parameter date: The date for which to calculate the next minute. - returns: The newly created date. */ public func minuteAfter(date:NSDate) -> NSDate { return self.minutesAfter(date) } /** Creates a new date at the first second of the minute following the given date. - parameter date: The date for which to calculate the next minute. - returns: The newly created date. */ static public func minuteAfter(date:NSDate) -> NSDate { return sharedInstance.minuteAfter(date) } // MARK: hours /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of hours to the given date and truncating to the first second of the date's hour. - parameter date: The date to which to add hours. - parameter delta: The number of hours to be added - returns: The newly created date. */ public func hoursAfter(date:NSDate, delta: Int = 1) -> NSDate { let hour = self.calendar.dateByAddingUnit(.Hour, value: delta, toDate: date, options: [])! return self.beginningOfHour(hour) } /** Creates a new date by adding the given number of hours to the given date and truncating to the first second of the date's hour. - parameter date: The date to which to add hours. - parameter delta: The number of hours to be added - returns: The newly created date. */ static public func hoursAfter(date:NSDate, delta: Int = 1) -> NSDate { return sharedInstance.hoursAfter(date, delta: delta) } /** Creates a new date by subtracting the given number of hours from the given date and truncating to the first second of the date's hour. - parameter date: The date from which to subtract hours. - parameter delta: The number of hours to be subtracted - returns: The newly created date. */ public func hoursBefore(date:NSDate, delta: Int = 1) -> NSDate { return self.hoursAfter(date, delta: -delta) } /** Creates a new date by subtracting the given number of hours from the given date and truncating to the first second of the date's hour. - parameter date: The date from which to subtract hours. - parameter delta: The number of hours to be subtracted - returns: The newly created date. */ static public func hoursBefore(date:NSDate, delta: Int = 1) -> NSDate { return sharedInstance.hoursBefore(date, delta: delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the hour prior to the given date. - parameter date: The date for which to find the previous hour - returns: The newly created date. */ public func hourBefore(date:NSDate) -> NSDate { return self.hoursBefore(date) } /** Creates a new date at the first second of the hour prior to the given date. - parameter date: The date for which to find the previous hour - returns: The newly created date. */ static public func hourBefore(date:NSDate) -> NSDate { return sharedInstance.hourBefore(date) } /** Creates a new date at the first second of the hour following the given date. - parameter date: The date for which to find the next hour - returns: The newly created date. */ public func hourAfter(date:NSDate) -> NSDate { return self.hoursAfter(date) } /** Creates a new date at the first second of the hour following the given date. - parameter date: The date for which to find the next hour - returns: The newly created date. */ static public func hourAfter(date:NSDate) -> NSDate { return sharedInstance.hourAfter(date) } // MARK: days /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of days to the given date and truncating to the first second of the date's day. - parameter date: The date to which to add days. - parameter delta: The number of days to be added - returns: The newly created date. */ public func daysAfter(date:NSDate, delta:Int = 1) -> NSDate { let day = self.calendar.dateByAddingUnit(.Day, value: delta, toDate: date, options: [])! return self.beginningOfDay(day) } /** Creates a new date by adding the given number of days to the given date and truncating to the first second of the date's day. - parameter date: The date to which to add days. - parameter delta: The number of days to be added - returns: The newly created date. */ static public func daysAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.daysAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of days from the given date and truncating to the first second of the date's day. - parameter date: The date from which to subtract days. - parameter delta: The number of days to be subtracted - returns: The newly created date. */ public func daysBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.daysAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of days from the given date and truncating to the first second of the date's day. - parameter date: The date from which to subtract days. - parameter delta: The number of days to be subtracted - returns: The newly created date. */ static public func daysBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.daysBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the day prior to the given date. - parameter date: The date for which to find the previous day. - returns: The newly created date. */ public func dayBefore(date:NSDate) -> NSDate { return self.daysBefore(date) } /** Creates a new date at the first second of the day prior to the given date. - parameter date: The date for which to find the previous day. - returns: The newly created date. */ static public func dayBefore(date:NSDate) -> NSDate { return sharedInstance.dayBefore(date) } /** Creates a new date at the first second of the day following the given date. - parameter date: The date for which to find the next day. - returns: The newly created date. */ public func dayAfter(date:NSDate) -> NSDate { return self.daysAfter(date) } /** Creates a new date at the first second of the day following the given date. - parameter date: The date for which to find the next day. - returns: The newly created date. */ static public func dayAfter(date:NSDate) -> NSDate { return sharedInstance.dayAfter(date) } // MARK: weeks /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of weeks to the given date and truncating to the first second of the date's week. - parameter date: The date to which to add weeks. - parameter delta: The number of weeks to be added - returns: The newly created date. */ public func weeksAfter(date:NSDate, delta:Int = 1) -> NSDate { let week = self.calendar.dateByAddingUnit(.WeekOfYear, value: delta, toDate: date, options: [])! return self.beginningOfWeek(week) } /** Creates a new date by adding the given number of weeks to the given date and truncating to the first second of the date's week. - parameter date: The date to which to add weeks. - parameter delta: The number of weeks to be added - returns: The newly created date. */ static public func weeksAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.weeksAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of weeks from the given date and truncating to the first second of the date's week. - parameter date: The date from which to subtract weeks. - parameter delta: The number of weeks to be subtracted - returns: The newly created date. */ public func weeksBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.weeksAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of weeks from the given date and truncating to the first second of the date's week. - parameter date: The date from which to subtract weeks. - parameter delta: The number of weeks to be subtracted - returns: The newly created date. */ static public func weeksBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.weeksBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the week prior to the given date. - parameter date: The date for which to find the previous week - returns: The newly created date. */ public func weekBefore(date:NSDate) -> NSDate { return self.weeksBefore(date) } /** Creates a new date at the first second of the week prior to the given date. - parameter date: The date for which to find the previous week - returns: The newly created date. */ static public func weekBefore(date:NSDate) -> NSDate { return sharedInstance.weekBefore(date) } /** Creates a new date at the first second of the week following the given date. - parameter date: The date for which to find the next week - returns: The newly created date. */ public func weekAfter(date:NSDate) -> NSDate { return self.weeksAfter(date) } /** Creates a new date at the first second of the week following the given date. - parameter date: The date for which to find the next week - returns: The newly created date. */ static public func weekAfter(date:NSDate) -> NSDate { return sharedInstance.weekAfter(date) } // MARK: months /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of months to the given date and truncating to the first second of the date's month. - parameter date: The date to which to add months. - parameter delta: The number of months to be added - returns: The newly created date. */ public func monthsAfter(date:NSDate, delta:Int = 1) -> NSDate { let month = self.calendar.dateByAddingUnit(.Month, value: delta, toDate: date, options: [])! return self.beginningOfMonth(month) } /** Creates a new date by adding the given number of months to the given date and truncating to the first second of the date's month. - parameter date: The date to which to add months. - parameter delta: The number of months to be added - returns: The newly created date. */ static public func monthsAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.monthsAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of months from the given date and truncating to the first second of the date's months. - parameter date: The date from which to subtract months. - parameter delta: The number of months to be subtracted - returns: The newly created date. */ public func monthsBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.monthsAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of months from the given date and truncating to the first second of the date's month. - parameter date: The date from which to add months. - parameter delta: The number of months to be subtracted. - returns: The newly created date. */ static public func monthsBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.monthsBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the month prior to the given date. - parameter date: The date for which to find the previous month. - returns: The newly created date. */ public func monthBefore(date:NSDate) -> NSDate { let previousMonth = self.calendar.dateByAddingUnit(.Month, value: -1, toDate: date, options: [])! return self.beginningOfMonth(previousMonth) } /** Creates a new date at the first second of the month prior to the given date. - parameter date: The date for which to find the previous month. - returns: The newly created date. */ static public func monthBefore(date:NSDate) -> NSDate { return sharedInstance.monthBefore(date) } /** Creates a new date at the first second of the month following the given date. - parameter date: The date for which to find the next month. - returns: The newly created date. */ public func monthAfter(date:NSDate) -> NSDate { let nextMonth = self.calendar.dateByAddingUnit(.Month, value: 1, toDate: date, options: [])! return self.beginningOfMonth(nextMonth) } /** Creates a new date at the first second of the month following the given date. - parameter date: The date for which to find the next month. - returns: The newly created date. */ static public func monthAfter(date:NSDate) -> NSDate { return sharedInstance.monthAfter(date) } // MARK: years /************** *** SINGLE *** **************/ /** Creates a new date by adding the given number of years to the given date and truncating to the first second of the date's year. - parameter date: The date to which to add years. - parameter delta: The number of years to be added. - returns: The newly created date. */ public func yearsAfter(date:NSDate, delta:Int = 1) -> NSDate { let year = self.calendar.dateByAddingUnit(.Year, value: delta, toDate: date, options: [])! return self.beginningOfYear(year) } /** Creates a new date by adding the given number of years to the given date and truncating to the first second of the date's year. - parameter date: The date to which to add year. - parameter delta: The number of years to be added. - returns: The newly created date. */ static public func yearsAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.yearsAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of years from the given date and truncating to the first second of the date's year. - parameter date: The date from which to add years. - parameter delta: The number of years to be subtracted. - returns: The newly created date. */ public func yearsBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.yearsAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of years from the given date and truncating to the first second of the date's year. - parameter date: The date from which to add year. - parameter delta: The number of years to be subtracted. - returns: The newly created date. */ static public func yearsBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.yearsBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the year prior to the given date. - parameter date: The date for which to find the previous year. - returns: The newly created date. */ public func yearBefore(date:NSDate) -> NSDate { return self.yearsBefore(date) } /** Creates a new date at the first second of the year prior to the given date. - parameter date: The date for which to find the previous year. - returns: The newly created date. */ static public func yearBefore(date:NSDate) -> NSDate { return sharedInstance.yearBefore(date) } /** Creates a new date at the first second of the year following the given date. - parameter date: The date for which to find the next year. - returns: The newly created date. */ public func yearAfter(date:NSDate) -> NSDate { return self.yearsAfter(date) } /** Creates a new date at the first second of the year following the given date. - parameter date: The date for which to find the next year. - returns: The newly created date. */ static public func yearAfter(date:NSDate) -> NSDate { return sharedInstance.yearAfter(date) } }
mit
stephentyrone/swift
test/Driver/PrivateDependencies/Inputs/one-way-external-fine/other.swift
29
1898
# Fine-grained v0 --- allNodes: - key: kind: sourceFileProvide aspect: interface context: '' name: other.swiftdeps fingerprint: 72e95f4a11b98227c1f6ad6ea7f6cdba sequenceNumber: 0 defsIDependUpon: [ 6, 7, 2, 5, 4 ] isProvides: true - key: kind: sourceFileProvide aspect: implementation context: '' name: other.swiftdeps fingerprint: 72e95f4a11b98227c1f6ad6ea7f6cdba sequenceNumber: 1 defsIDependUpon: [ ] isProvides: true - key: kind: topLevel aspect: interface context: '' name: a sequenceNumber: 2 defsIDependUpon: [ 0 ] isProvides: true - key: kind: topLevel aspect: implementation context: '' name: a sequenceNumber: 3 defsIDependUpon: [ ] isProvides: true - key: kind: topLevel aspect: interface context: '' name: IntegerLiteralType sequenceNumber: 4 defsIDependUpon: [ ] isProvides: false - key: kind: topLevel aspect: interface context: '' name: FloatLiteralType sequenceNumber: 5 defsIDependUpon: [ ] isProvides: false - key: kind: externalDepend aspect: interface context: '' name: './other1-external' sequenceNumber: 6 defsIDependUpon: [ ] isProvides: false - key: kind: externalDepend aspect: interface context: '' name: './other2-external' sequenceNumber: 7 defsIDependUpon: [ ] isProvides: false ...
apache-2.0
Chaosspeeder/YourGoals
YourGoalsTests/Business/TaskProgressCalculatorTests.swift
1
3652
// // TaskProgressCalculatorTests.swift // YourGoalsTests // // Created by André Claaßen on 27.09.18. // Copyright © 2018 André Claaßen. All rights reserved. // import XCTest import CoreData @testable import YourGoals class TaskProgressCalculatorTests: StorageTestCase { func testCalculateProgressOnGoal() { let referenceDateStart = Date.dateTimeWithYear(2018, month: 09, day: 27, hour: 12, minute: 00, second: 00) let referenceDateCurrent = referenceDateStart.addMinutesToDate(20) // setup 3 tasks with 100 Minutes total size let goal = self.testDataCreator.createGoalWithTasks(infos: [ (name: "Task 1", prio: 1, size: 40.0, nil ,commitmentDate: nil, beginTime: nil, state: nil), // 40 minutes (name: "Task 2", prio: 2, size: 20.0, nil ,commitmentDate: nil, beginTime: nil, state: nil), // 20 minutes (name: "Task 3", prio: 3, size: 40.0, nil ,commitmentDate: nil, beginTime: nil, state: nil) // 40 minutes ] ) // fetch the first task in progress and work on it 20 Minutes eg. 30% on the task let taskInProgress = goal.allTasks().filter({$0.name == "Task 1" }).first! let progress = self.testDataCreator.createProgress(forTask: taskInProgress, start: referenceDateStart, end: referenceDateCurrent) // act let percentage = TaskProgressCalculator(manager: self.manager, backburnedGoals: false).calculateProgressOnGoal(taskProgress: progress, forDate: referenceDateCurrent) // test XCTAssertEqual(0.2, percentage, "the percentage should be 20% which corresponds with 20 out 100 Minutes") } func testCalculateProgressOnTodayGoal() { let referenceDateStart = Date.dateTimeWithYear(2018, month: 09, day: 27, hour: 12, minute: 00, second: 00) let referenceDateCurrent = referenceDateStart.addMinutesToDate(20) let today = referenceDateStart.day() let yesterday = today.addDaysToDate(-1) // setup 3 tasks with 100 Minutes total size let strategyManager = StrategyManager(manager: self.manager) let strategy = try! strategyManager.assertValidActiveStrategy() let todayGoal = try! strategyManager.assertTodayGoal(strategy: strategy) self.testDataCreator.createTasks(forGoal: todayGoal, infos: [ (name: "Task 1", prio: 1, size: 20.0, nil ,commitmentDate: today, beginTime: nil, state: nil) // 40 minutes ] ) let _ = self.testDataCreator.createGoalWithTasks(infos: [ (name: "Task 2", prio: 2, size: 20.0, nil ,commitmentDate: yesterday, beginTime: nil, state: nil), // 20 minutes and yet in the abstract today task (name: "Task 3", prio: 3, size: 40.0, nil ,commitmentDate: nil, beginTime: nil, state: nil) // 40 minutes ]) // fetch the first task in progress and work on it 20 Minutes eg. 30% on the task let taskInProgress = todayGoal.allTasks().filter({$0.name == "Task 1" }).first! let progress = self.testDataCreator.createProgress(forTask: taskInProgress, start: referenceDateStart, end: referenceDateCurrent) // act let percentage = TaskProgressCalculator(manager: self.manager, backburnedGoals: false).calculateProgressOnGoal(taskProgress: progress, forDate: referenceDateCurrent) // test XCTAssertEqual(0.5, percentage, "the percentage should be 50% which corresponds to 20.0 minutes from Task 1 and 20.0 minutes from Task 2 against 40.0 minutes from Task3") } }
lgpl-3.0
iosdevelopershq/code-challenges
CodeChallenge/Challenges/LetterCombinationsOfPhoneNumber/LetterCombinationsOfPhoneNumberChallenge.swift
1
1597
// // LetterCombinationsOfPhoneNumberChallenge.swift // CodeChallenge // // Created by Ryan Arana on 11/1/15. // Copyright © 2015 iosdevelopers. All rights reserved. // import Foundation /** https://leetcode.com/problems/letter-combinations-of-a-phone-number/ Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. ![keypad](http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png) Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. */ struct LetterCombinationsOfPhoneNumberChallenge: CodeChallengeType { typealias InputType = String typealias OutputType = [String] let title = "Letter Combinations of Phone Number" let entries: [CodeChallengeEntry<LetterCombinationsOfPhoneNumberChallenge>] = [ bugKrushaLetterCombinationOfPhoneNumberEntry, LoganWrightLetterCombinationOfPhoneNumberEntry, juliand665LetterCombinationOfPhoneNumberEntry ] func generateDataset() -> [InputType] { return ["23"] } func verifyOutput(_ output: OutputType, forInput input: InputType) -> Bool { guard let expected = verificationDictionary[input] else { return false } return output.sorted(by: <) == expected.sorted(by: <) } fileprivate let verificationDictionary = [ "23": ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] ] }
mit
caynan/Horus
Sources/Helpers/StringHelper.swift
2
507
// // StringHelper.swift // Horus // // Created by Caynan Sousa on 6/29/17. // Copyright © 2017 Caynan. All rights reserved. // import Foundation extension String { /// Check the if string is a valid hexadecimal. /// /// - Returns: `true` if string is a valid hexadecimal; false otherwise. func isHexadecimal() -> Bool { let hexaRegex = "[0-9A-F]+" let hexaTest = NSPredicate(format: "SELF MATCHES %@", hexaRegex) return hexaTest.evaluate(with: self) } }
mit
WhiskerzAB/PlaygroundTDD
PlaygroundTDD.playground/Sources/Core/Loggable.swift
1
987
// // Loggable.swift // TDD Example // // Created by Gabriel Peart 08/11/16. // Copyright (c) 2016 Whiskerz AB. All rights reserved. // public protocol Loggable { var verbosity: Verbosity { get set } func log(message: String) } public struct Logger: Loggable { public var verbosity: Verbosity public init(verbosity: Verbosity) { self.verbosity = verbosity } public func log(message: String) { switch verbosity { case .debug: print("Debug: \(message)") case .info: print("Info: \(message)") case .notice: print("Notice: \(message)") case .warning: print("Warning: \(message)") case .error: print("Error: \(message)") case .critical: print("Critical: \(message)") case .alert: print("Alert: \(message)") case .emergency: print("Emergency: \(message)") } } }
mit
milseman/swift
stdlib/public/core/Reverse.swift
10
19479
//===--- Reverse.swift - Sequence and collection reversal -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension MutableCollection where Self : BidirectionalCollection { /// Reverses the elements of the collection in place. /// /// The following example reverses the elements of an array of characters: /// /// var characters: [Character] = ["C", "a", "f", "é"] /// characters.reverse() /// print(characters) /// // Prints "["é", "f", "a", "C"] /// /// - Complexity: O(*n*), where *n* is the number of elements in the /// collection. public mutating func reverse() { if isEmpty { return } var f = startIndex var l = index(before: endIndex) while f < l { swapAt(f, l) formIndex(after: &f) formIndex(before: &l) } } } /// An iterator that can be much faster than the iterator of a reversed slice. // TODO: See about using this in more places @_fixed_layout public struct _ReverseIndexingIterator< Elements : BidirectionalCollection > : IteratorProtocol, Sequence { @_inlineable @inline(__always) /// Creates an iterator over the given collection. public /// @testable init(_elements: Elements, _position: Elements.Index) { self._elements = _elements self._position = _position } @_inlineable @inline(__always) public mutating func next() -> Elements.Element? { guard _fastPath(_position != _elements.startIndex) else { return nil } _position = _elements.index(before: _position) return _elements[_position] } @_versioned internal let _elements: Elements @_versioned internal var _position: Elements.Index } // FIXME(ABI)#59 (Conditional Conformance): we should have just one type, // `ReversedCollection`, that has conditional conformances to // `RandomAccessCollection`, and possibly `MutableCollection` and // `RangeReplaceableCollection`. // rdar://problem/17144340 // FIXME: swift-3-indexing-model - should gyb ReversedXxx & ReversedRandomAccessXxx /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. @_fixed_layout public struct ReversedIndex<Base : Collection> : Comparable { /// Creates a new index into a reversed collection for the position before /// the specified index. /// /// When you create an index into a reversed collection using `base`, an /// index from the underlying collection, the resulting index is the /// position of the element *before* the element referenced by `base`. The /// following example creates a new `ReversedIndex` from the index of the /// `"a"` character in a string's character view. /// /// let name = "Horatio" /// let aIndex = name.index(of: "a")! /// // name[aIndex] == "a" /// /// let reversedName = name.reversed() /// let i = ReversedIndex<String>(aIndex) /// // reversedName[i] == "r" /// /// The element at the position created using `ReversedIndex<...>(aIndex)` is /// `"r"`, the character before `"a"` in the `name` string. /// /// - Parameter base: The position after the element to create an index for. @_inlineable public init(_ base: Base.Index) { self.base = base } /// The position after this position in the underlying collection. /// /// To find the position that corresponds with this index in the original, /// underlying collection, use that collection's `index(before:)` method /// with the `base` property. /// /// The following example declares a function that returns the index of the /// last even number in the passed array, if one is found. First, the /// function finds the position of the last even number as a `ReversedIndex` /// in a reversed view of the array of numbers. Next, the function calls the /// array's `index(before:)` method to return the correct position in the /// passed array. /// /// func indexOfLastEven(_ numbers: [Int]) -> Int? { /// let reversedNumbers = numbers.reversed() /// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 }) /// else { return nil } /// /// return numbers.index(before: i.base) /// } /// /// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51] /// if let lastEven = indexOfLastEven(numbers) { /// print("Last even number: \(numbers[lastEven])") /// } /// // Prints "Last even number: 40" public let base: Base.Index @_inlineable public static func == ( lhs: ReversedIndex<Base>, rhs: ReversedIndex<Base> ) -> Bool { return lhs.base == rhs.base } @_inlineable public static func < ( lhs: ReversedIndex<Base>, rhs: ReversedIndex<Base> ) -> Bool { // Note ReversedIndex has inverted logic compared to base Base.Index return lhs.base > rhs.base } } /// A collection that presents the elements of its base collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having bidirectional indices. /// /// The `reversed()` method is always lazy when applied to a collection /// with bidirectional indices, but does not implicitly confer /// laziness on algorithms applied to its result. In other words, for /// ordinary collections `c` having bidirectional indices: /// /// * `c.reversed()` does not create new storage /// * `c.reversed().map(f)` maps eagerly and returns a new array /// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - See also: `ReversedRandomAccessCollection` @_fixed_layout public struct ReversedCollection< Base : BidirectionalCollection > : BidirectionalCollection { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) @_versioned @_inlineable internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReversedIndex<Base> public typealias IndexDistance = Base.IndexDistance @_fixed_layout public struct Iterator : IteratorProtocol, Sequence { @_inlineable @inline(__always) public /// @testable init(elements: Base, endPosition: Base.Index) { self._elements = elements self._position = endPosition } @_inlineable @inline(__always) public mutating func next() -> Base.Iterator.Element? { guard _fastPath(_position != _elements.startIndex) else { return nil } _position = _elements.index(before: _position) return _elements[_position] } @_versioned internal let _elements: Base @_versioned internal var _position: Base.Index } @_inlineable @inline(__always) public func makeIterator() -> Iterator { return Iterator(elements: _base, endPosition: _base.endIndex) } @_inlineable public var startIndex: Index { return ReversedIndex(_base.endIndex) } @_inlineable public var endIndex: Index { return ReversedIndex(_base.startIndex) } @_inlineable public func index(after i: Index) -> Index { return ReversedIndex(_base.index(before: i.base)) } @_inlineable public func index(before i: Index) -> Index { return ReversedIndex(_base.index(after: i.base)) } @_inlineable public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. return ReversedIndex(_base.index(i.base, offsetBy: -n)) } @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { ReversedIndex($0) } } @_inlineable public func distance(from start: Index, to end: Index) -> IndexDistance { return _base.distance(from: end.base, to: start.base) } @_inlineable public subscript(position: Index) -> Base.Element { return _base[_base.index(before: position.base)] } @_inlineable public subscript(bounds: Range<Index>) -> BidirectionalSlice<ReversedCollection> { return BidirectionalSlice(base: self, bounds: bounds) } public let _base: Base } /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. @_fixed_layout public struct ReversedRandomAccessIndex< Base : RandomAccessCollection > : Comparable { /// Creates a new index into a reversed collection for the position before /// the specified index. /// /// When you create an index into a reversed collection using the index /// passed as `base`, an index from the underlying collection, the resulting /// index is the position of the element *before* the element referenced by /// `base`. The following example creates a new `ReversedIndex` from the /// index of the `"a"` character in a string's character view. /// /// let name = "Horatio" /// let aIndex = name.index(of: "a")! /// // name[aIndex] == "a" /// /// let reversedName = name.reversed() /// let i = ReversedIndex<String>(aIndex) /// // reversedName[i] == "r" /// /// The element at the position created using `ReversedIndex<...>(aIndex)` is /// `"r"`, the character before `"a"` in the `name` string. Viewed from the /// perspective of the `reversedCharacters` collection, of course, `"r"` is /// the element *after* `"a"`. /// /// - Parameter base: The position after the element to create an index for. @_inlineable public init(_ base: Base.Index) { self.base = base } /// The position after this position in the underlying collection. /// /// To find the position that corresponds with this index in the original, /// underlying collection, use that collection's `index(before:)` method /// with this index's `base` property. /// /// The following example declares a function that returns the index of the /// last even number in the passed array, if one is found. First, the /// function finds the position of the last even number as a `ReversedIndex` /// in a reversed view of the array of numbers. Next, the function calls the /// array's `index(before:)` method to return the correct position in the /// passed array. /// /// func indexOfLastEven(_ numbers: [Int]) -> Int? { /// let reversedNumbers = numbers.reversed() /// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 }) /// else { return nil } /// /// return numbers.index(before: i.base) /// } /// /// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51] /// if let lastEven = indexOfLastEven(numbers) { /// print("Last even number: \(numbers[lastEven])") /// } /// // Prints "Last even number: 40" public let base: Base.Index @_inlineable public static func == ( lhs: ReversedRandomAccessIndex<Base>, rhs: ReversedRandomAccessIndex<Base> ) -> Bool { return lhs.base == rhs.base } @_inlineable public static func < ( lhs: ReversedRandomAccessIndex<Base>, rhs: ReversedRandomAccessIndex<Base> ) -> Bool { // Note ReversedRandomAccessIndex has inverted logic compared to base Base.Index return lhs.base > rhs.base } } /// A collection that presents the elements of its base collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having random access indices. /// - See also: `ReversedCollection` @_fixed_layout public struct ReversedRandomAccessCollection< Base : RandomAccessCollection > : RandomAccessCollection { // FIXME: swift-3-indexing-model: tests for ReversedRandomAccessIndex and // ReversedRandomAccessCollection. /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) @_versioned @_inlineable internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReversedRandomAccessIndex<Base> public typealias IndexDistance = Base.IndexDistance /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator< ReversedRandomAccessCollection > @_inlineable public var startIndex: Index { return ReversedRandomAccessIndex(_base.endIndex) } @_inlineable public var endIndex: Index { return ReversedRandomAccessIndex(_base.startIndex) } @_inlineable public func index(after i: Index) -> Index { return ReversedRandomAccessIndex(_base.index(before: i.base)) } @_inlineable public func index(before i: Index) -> Index { return ReversedRandomAccessIndex(_base.index(after: i.base)) } @_inlineable public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. // FIXME: swift-3-indexing-model: tests. return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n)) } @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. // FIXME: swift-3-indexing-model: tests. return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { Index($0) } } @_inlineable public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: tests. return _base.distance(from: end.base, to: start.base) } @_inlineable public subscript(position: Index) -> Base.Element { return _base[_base.index(before: position.base)] } // FIXME: swift-3-indexing-model: the rest of methods. public let _base: Base } extension BidirectionalCollection { /// Returns a view presenting the elements of the collection in reverse /// order. /// /// You can reverse a collection without allocating new space for its /// elements by calling this `reversed()` method. A `ReversedCollection` /// instance wraps an underlying collection and provides access to its /// elements in reverse order. This example prints the characters of a /// string in reverse order: /// /// let word = "Backwards" /// for char in word.reversed() { /// print(char, terminator: "") /// } /// // Prints "sdrawkcaB" /// /// If you need a reversed collection of the same type, you may be able to /// use the collection's sequence-based or collection-based initializer. For /// example, to get the reversed version of a string, reverse its /// characters and initialize a new `String` instance from the result. /// /// let reversedWord = String(word.reversed()) /// print(reversedWord) /// // Prints "sdrawkcaB" /// /// - Complexity: O(1) @_inlineable public func reversed() -> ReversedCollection<Self> { return ReversedCollection(_base: self) } } extension RandomAccessCollection { /// Returns a view presenting the elements of the collection in reverse /// order. /// /// You can reverse a collection without allocating new space for its /// elements by calling this `reversed()` method. A /// `ReversedRandomAccessCollection` instance wraps an underlying collection /// and provides access to its elements in reverse order. This example /// prints the elements of an array in reverse order: /// /// let numbers = [3, 5, 7] /// for number in numbers.reversed() { /// print(number) /// } /// // Prints "7" /// // Prints "5" /// // Prints "3" /// /// If you need a reversed collection of the same type, you may be able to /// use the collection's sequence-based or collection-based initializer. For /// example, to get the reversed version of an array, initialize a new /// `Array` instance from the result of this `reversed()` method. /// /// let reversedNumbers = Array(numbers.reversed()) /// print(reversedNumbers) /// // Prints "[7, 5, 3]" /// /// - Complexity: O(1) @_inlineable public func reversed() -> ReversedRandomAccessCollection<Self> { return ReversedRandomAccessCollection(_base: self) } } extension LazyCollectionProtocol where Self : BidirectionalCollection, Elements : BidirectionalCollection { /// Returns the elements of the collection in reverse order. /// /// - Complexity: O(1) @_inlineable public func reversed() -> LazyBidirectionalCollection< ReversedCollection<Elements> > { return ReversedCollection(_base: elements).lazy } } extension LazyCollectionProtocol where Self : RandomAccessCollection, Elements : RandomAccessCollection { /// Returns the elements of the collection in reverse order. /// /// - Complexity: O(1) @_inlineable public func reversed() -> LazyRandomAccessCollection< ReversedRandomAccessCollection<Elements> > { return ReversedRandomAccessCollection(_base: elements).lazy } } @available(*, unavailable, renamed: "ReversedCollection") public typealias ReverseCollection<Base : BidirectionalCollection> = ReversedCollection<Base> @available(*, unavailable, renamed: "ReversedRandomAccessCollection") public typealias ReverseRandomAccessCollection<Base : RandomAccessCollection> = ReversedRandomAccessCollection<Base> extension ReversedCollection { @available(*, unavailable, renamed: "BidirectionalCollection.reversed(self:)") public init(_ base: Base) { Builtin.unreachable() } } extension ReversedRandomAccessCollection { @available(*, unavailable, renamed: "RandomAccessCollection.reversed(self:)") public init(_ base: Base) { Builtin.unreachable() } } extension BidirectionalCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> ReversedCollection<Self> { Builtin.unreachable() } } extension RandomAccessCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> ReversedRandomAccessCollection<Self> { Builtin.unreachable() } } extension LazyCollectionProtocol where Self : BidirectionalCollection, Elements : BidirectionalCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> LazyCollection< ReversedCollection<Elements> > { Builtin.unreachable() } } extension LazyCollectionProtocol where Self : RandomAccessCollection, Elements : RandomAccessCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> LazyCollection< ReversedRandomAccessCollection<Elements> > { Builtin.unreachable() } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
apache-2.0
psartzetakis/JRKeyboardManagerKit
Example/Sources/AppDelegate.swift
1
2211
// // AppDelegate.swift // KeyboardManagerExample // // Created by Panagiotis Sartzetakis on 22/11/2016. // Copyright © 2016 Panagiotis Sartzetakis. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
skedgo/tripkit-ios
Sources/TripKit/model/API/LocationAPIModel.swift
1
12686
// // TKHelperTypes.swift // TripKit // // Created by Adrian Schoenig on 28/10/16. // Copyright © 2016 SkedGo. All rights reserved. // import Foundation import CoreLocation protocol RealTimeUpdatable { var hasRealTime: Bool { get } } extension TKAPI { public struct BikePodInfo: Codable, Hashable, RealTimeUpdatable { // static information public let identifier: String public let operatorInfo: TKAPI.CompanyInfo public let source: TKAPI.DataAttribution? public let deepLink: URL? // availability information (usually real-time) public let inService: Bool public let availableBikes: Int? public let totalSpaces: Int? public let lastUpdate: Date? private enum CodingKeys: String, CodingKey { case identifier case operatorInfo = "operator" case source case deepLink case inService case availableBikes case totalSpaces case lastUpdate } public var availableSpaces: Int? { guard let total = totalSpaces, let bikes = availableBikes else { return nil } // available bikes can exceed number of spaces! return max(0, total - bikes) } public var hasRealTime: Bool { return inService && availableBikes != nil } } public struct CarPodInfo: Codable, Hashable, RealTimeUpdatable { // static information public let identifier: String public let operatorInfo: TKAPI.CompanyInfo public let deepLink: URL? // real-time availability information public let availabilityMode: TKAPI.AvailabilityMode? public let availabilities: [TKAPI.CarAvailability]? public let inService: Bool? public let availableVehicles: Int? public let availableChargingSpaces: Int? public let totalSpaces: Int? public let lastUpdate: Date? private enum CodingKeys: String, CodingKey { case identifier case operatorInfo = "operator" case deepLink case availabilityMode case availabilities case inService case availableVehicles case availableChargingSpaces case totalSpaces case lastUpdate } public var availableSpaces: Int? { guard let total = totalSpaces, let vehicles = availableVehicles else { return nil } // available vehicles can exceed number of spaces! return max(0, total - vehicles) } public var hasRealTime: Bool { return inService != false && availableVehicles != nil } } public struct CarParkInfo: Codable, Hashable, RealTimeUpdatable { public enum EntranceType: String, Codable { case entranceAndExit = "ENTRANCE_EXIT" case entranceOnly = "ENTRANCE_ONLY" case exitOnly = "EXIT_ONLY" case pedestrian = "PEDESTRIAN" case disabledPedestrian = "DISABLED_PEDESTRIAN" case permit = "PERMIT" } public struct Entrance: Codable, Hashable { public let type: EntranceType public let lat: CLLocationDegrees public let lng: CLLocationDegrees public let address: String? } public let identifier: String public let name: String public let operatorInfo: TKAPI.CompanyInfo? public let source: TKAPI.DataAttribution? public let deepLink: URL? /// Additional information text from the provider. Can be long and over multiple lines. public let info: String? /// The polygon defining the parking area as an encoded polyline. /// /// See `CLLocationCoordinate2D.decodePolyline` public let encodedParkingArea: String? public let entrances: [Entrance]? public let openingHours: TKAPI.OpeningHours? public let pricingTables: [TKAPI.PricingTable]? public let availableSpaces: Int? public let totalSpaces: Int? public let lastUpdate: Date? private enum CodingKeys: String, CodingKey { case identifier case name case operatorInfo = "operator" case source case deepLink case encodedParkingArea case info case entrances case openingHours case pricingTables case availableSpaces case totalSpaces case lastUpdate } public var hasRealTime: Bool { return availableSpaces != nil } } public struct CarRentalInfo: Codable, Hashable, RealTimeUpdatable { public let identifier: String public let company: TKAPI.CompanyInfo public let openingHours: TKAPI.OpeningHours? public let source: TKAPI.DataAttribution? public var hasRealTime: Bool { false } } @available(*, unavailable, renamed: "SharedVehicleInfo") public typealias FreeFloatingVehicleInfo = SharedVehicleInfo public enum VehicleFormFactor: String, Codable { case bicycle = "BICYCLE" case car = "CAR" case scooter = "SCOOTER" case moped = "MOPED" case other = "OTHER" } public enum VehiclePropulsionType: String, Codable { case human = "HUMAN" case electric = "ELECTRIC" case electricAssist = "ELECTRIC_ASSIST" case combustion = "COMBUSTION" } public struct VehicleTypeInfo: Codable, Hashable { public let name: String? public let formFactor: VehicleFormFactor public let propulsionType: VehiclePropulsionType? public let maxRangeMeters: Int? } public struct SharedVehicleInfo: Codable, Hashable, RealTimeUpdatable { public let identifier: String public let name: String? public let details: String? public let operatorInfo: TKAPI.CompanyInfo public let vehicleType: VehicleTypeInfo public let source: TKAPI.DataAttribution? public let deepLink: URL? public let imageURL: URL? public let licensePlate: String? public let isDisabled: Bool public let isReserved: Bool? public let batteryLevel: Int? // percentage, i.e., 0-100 public let currentRange: CLLocationDistance? // metres public let lastReported: Date? private enum CodingKeys: String, CodingKey { case identifier case name case batteryLevel case operatorInfo = "operator" case licensePlate case vehicleType = "vehicleTypeInfo" case isDisabled = "disabled" case isReserved = "reserved" case lastReported case currentRange = "currentRangeMeters" case imageURL // NOT DOCUMENTED case details = "description" case source case deepLink = "deepLinks" // NOT DOCUMENTED } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) identifier = try container.decode(String.self, forKey: .identifier) operatorInfo = try container.decode(TKAPI.CompanyInfo.self, forKey: .operatorInfo) vehicleType = try container.decode(VehicleTypeInfo.self, forKey: .vehicleType) isDisabled = try container.decode(Bool.self, forKey: .isDisabled) source = try? container.decode(TKAPI.DataAttribution.self, forKey: .source) if let deepLinkDict = try? container.decode([String: String].self, forKey: .deepLink), let link = deepLinkDict["ios"], let linkURL = URL(string: link) { deepLink = linkURL } else { deepLink = nil } name = try? container.decode(String.self, forKey: .name) details = try? container.decode(String.self, forKey: .details) imageURL = try? container.decode(URL.self, forKey: .imageURL) licensePlate = try? container.decode(String.self, forKey: .licensePlate) isReserved = try? container.decode(Bool.self, forKey: .isReserved) batteryLevel = try? container.decode(Int.self, forKey: .batteryLevel) currentRange = try? container.decode(CLLocationDistance.self, forKey: .currentRange) lastReported = try? container.decode(Date.self, forKey: .lastReported) } public var hasRealTime: Bool { true } public var isAvailable: Bool { !isDisabled && (isReserved != true) } } public struct OnStreetParkingInfo: Codable, Hashable, RealTimeUpdatable { public enum PaymentType: String, Codable { case meter = "METER" case creditCard = "CREDIT_CARD" case phone = "PHONE" case coins = "COINS" case app = "APP" } public enum AvailableContent: String, Codable, CaseIterable { public init(from decoder: Decoder) throws { // We do this manually rather than using the default Codable // implementation, to flag unknown content as `.unknown`. let single = try decoder.singleValueContainer() let string = try single.decode(String.self) let match = AvailableContent.allCases.first { $0.rawValue == string } if let known = match { self = known } else { self = .unknown } } public func encode(to encoder: Encoder) throws { var single = encoder.singleValueContainer() try single.encode(rawValue) } case restrictions case paymentTypes case totalSpaces case availableSpaces case actualRate case unknown } public enum Vacancy: String, Codable { case unknown = "UNKNOWN" case full = "NO_VACANCY" case limited = "LIMITED_VACANCY" case plenty = "PLENTY_VACANCY" } public struct Restriction: Codable, Hashable { public let color: String public let maximumParkingMinutes: Int public let parkingSymbol: String public let daysAndTimes: OpeningHours public let type: String } public let actualRate: String? public let identifier: String public let description: String public let availableContent: [AvailableContent]? public let source: TKAPI.DataAttribution? public let paymentTypes: [PaymentType]? public let restrictions: [Restriction]? public let availableSpaces: Int? public let totalSpaces: Int? public let occupiedSpaces: Int? public let parkingVacancy: Vacancy? public let lastUpdate: Date? /// The polyline defining the parking area along the street as an encoded polyline. /// /// This is optional as some on-street parking isn't defined by a line, /// but by an area. See `encodedPolygon` /// /// See `CLLocationCoordinate2D.decodePolyline` public let encodedPolyline: String? /// The polygon defining the parking area as an encoded polyline. /// /// This is optional as most on-street parking isn't defined by an area, /// but by a line. See `encodedPolyline` /// /// See `CLLocationCoordinate2D.decodePolyline` public let encodedPolygon: String? public var hasRealTime: Bool { return availableSpaces != nil } } public struct LocationInfo : Codable, Hashable, RealTimeUpdatable { public struct Details: Codable, Hashable { public let w3w: String? public let w3wInfoURL: URL? } public let details: Details? public let alerts: [Alert]? public let stop: TKStopCoordinate? public let bikePod: TKAPI.BikePodInfo? public let carPod: TKAPI.CarPodInfo? public let carPark: TKAPI.CarParkInfo? public let carRental: TKAPI.CarRentalInfo? public let freeFloating: TKAPI.SharedVehicleInfo? // TODO: Also add to API specs public let onStreetParking: TKAPI.OnStreetParkingInfo? public var hasRealTime: Bool { let sources: [RealTimeUpdatable?] = [bikePod, carPod, carPod, carRental, freeFloating, onStreetParking] return sources.contains { $0?.hasRealTime == true } } } public struct LocationsResponse: Codable, Hashable { public static let empty: LocationsResponse = LocationsResponse(groups: []) public let groups: [Group] public struct Group: Codable, Hashable { public let key: String public let hashCode: Int public let stops: [TKStopCoordinate]? public let bikePods: [TKBikePodLocation]? public let carPods: [TKCarPodLocation]? public let carParks: [TKCarParkLocation]? public let carRentals: [TKCarRentalLocation]? public let freeFloating: [TKFreeFloatingVehicleLocation]? public let onStreetParking: [TKOnStreetParkingLocation]? public var all: [TKModeCoordinate] { return (stops ?? []) as [TKModeCoordinate] + (bikePods ?? []) as [TKModeCoordinate] + (carPods ?? []) as [TKModeCoordinate] + (carParks ?? []) as [TKModeCoordinate] + (carRentals ?? []) as [TKModeCoordinate] + (freeFloating ?? []) as [TKModeCoordinate] + (onStreetParking ?? []) as [TKModeCoordinate] } } } }
apache-2.0
brightify/Bond
BondTests/PerformanceTests.swift
1
1299
// // PerformanceTests.swift // Bond // // Created by Ivan Moskalev on 19.06.15. // Copyright (c) 2015 Bond. All rights reserved. // import XCTest import Bond class BondPerformanceTests: XCTestCase { func testBindPerformance() { let dynamicInt = Dynamic<Int>(0) let intBond = Bond<Int>({ value in }) self.measureBlock { dynamicInt.bindTo(intBond) } } func testUnbindAllPerformance() { self.measureMetrics(self.dynamicType.defaultPerformanceMetrics(), automaticallyStartMeasuring: false) { () -> Void in // Setup let dynamics = Array(count: 100, repeatedValue: Dynamic<Int>(0)) let intBond = Bond<Int>({ value in }) for dynamic in dynamics { dynamic ->| intBond } // Test self.startMeasuring() intBond.unbind() self.stopMeasuring() } } } class DynamicPerformanceTests: XCTestCase { func testDispatchPerformance() { self.measureMetrics(self.dynamicType.defaultPerformanceMetrics(), automaticallyStartMeasuring: false) { () -> Void in // Setup let dynamicInt = Dynamic<Int>(0) let intBond = Bond<Int>({ value in }) dynamicInt.bindTo(intBond) // Test self.startMeasuring() dynamicInt.value = 1 self.stopMeasuring() } } }
mit
fluidsonic/JetPack
Sources/UI/DispatchQueue+UI.swift
1
113
import Dispatch public func assert(queue: DispatchQueue) { dispatchPrecondition(condition: .onQueue(queue)) }
mit
franklinsch/usagi
iOS/usagi-iOS/usagi-iOS/AddTaskTableViewController.swift
1
4095
// // AddTaskTableViewController.swift // usagi-iOS // // Created by Franklin Schrans on 31/01/2016. // Copyright © 2016 Franklin Schrans. All rights reserved. // import UIKit class AddTaskTableViewController: UITableViewController { var projectName: String? var tasks = [Project]() override func viewDidLoad() { super.viewDidLoad() // 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 numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return tasks.count } @IBAction func addNewTask(sender: UIStoryboardSegue) { guard let sourceViewController = sender.sourceViewController as? NewTaskTableViewController else { fatalError() } let newTask = Project(name: sourceViewController.taskNameField.text!, description: sourceViewController.descriptionField.text!, participants: [], subtasks: [], progress: 0, timeLeft: "1h00", dependsOnTasks: sourceViewController.dependencies) tasks.append(newTask) tableView.reloadData() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("taskCell", forIndexPath: indexPath) let task = tasks[indexPath.row] cell.textLabel!.text = task.name return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "newTaskSegue" { guard let destinationViewController = segue.destinationViewController as? NewTaskTableViewController else { fatalError() } destinationViewController.projectName = projectName destinationViewController.tasks = tasks } } }
mit