repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pkl728/ZombieInjection | Pods/Dip/Sources/Definition.swift | 1 | 10615 | //
// Dip
//
// Copyright (c) 2015 Olivier Halligon <[email protected]>
//
// 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 key used to store definitons in a container.
public struct DefinitionKey: Hashable, CustomStringConvertible {
public let type: Any.Type
public let typeOfArguments: Any.Type
public private(set) var tag: DependencyContainer.Tag?
init(type: Any.Type, typeOfArguments: Any.Type, tag: DependencyContainer.Tag? = nil) {
self.type = type
self.typeOfArguments = typeOfArguments
self.tag = tag
}
public var hashValue: Int {
return "\(type)-\(typeOfArguments)-\(tag.desc)".hashValue
}
public var description: String {
return "type: \(type), arguments: \(typeOfArguments), tag: \(tag.desc)"
}
func tagged(with tag: DependencyContainer.Tag?) -> DefinitionKey {
var tagged = self
tagged.tag = tag
return tagged
}
/// Check two definition keys on equality by comparing their `type`, `factoryType` and `tag` properties.
public static func ==(lhs: DefinitionKey, rhs: DefinitionKey) -> Bool {
return
lhs.type == rhs.type &&
lhs.typeOfArguments == rhs.typeOfArguments &&
lhs.tag == rhs.tag
}
}
///Dummy protocol to store definitions for different types in collection
public protocol DefinitionType: class { }
/**
`Definition<T, U>` describes how instances of type `T` should be created when this type is resolved by the `DependencyContainer`.
- `T` is the type of the instance to resolve
- `U` is the type of runtime arguments accepted by factory that will create an instance of T.
For example `Definition<Service, String>` is the type of definition that will create an instance of type `Service` using factory that accepts `String` argument.
*/
public final class Definition<T, U>: DefinitionType {
public typealias F = (U) throws -> T
//MARK: - _Definition
weak var container: DependencyContainer?
let factory: F
let scope: ComponentScope
var weakFactory: ((Any) throws -> Any)!
var resolveProperties: ((DependencyContainer, Any) throws -> ())?
init(scope: ComponentScope, factory: @escaping F) {
self.factory = factory
self.scope = scope
}
/**
Set the block that will be used to resolve dependencies of the instance.
This block will be called before `resolve(tag:)` returns.
- parameter block: The block to resolve property dependencies of the instance.
- returns: modified definition
- note: To resolve circular dependencies at least one of them should use this block
to resolve its dependencies. Otherwise the application will enter an infinite loop and crash.
- note: You can call this method several times on the same definition.
Container will call all provided blocks in the same order.
**Example**
```swift
container.register { ClientImp(service: try container.resolve() as Service) as Client }
container.register { ServiceImp() as Service }
.resolvingProperties { container, service in
service.client = try container.resolve() as Client
}
```
*/
@discardableResult public func resolvingProperties(_ block: @escaping (DependencyContainer, T) throws -> ()) -> Definition {
if let oldBlock = self.resolveProperties {
self.resolveProperties = {
try oldBlock($0, $1 as! T)
try block($0, $1 as! T)
}
}
else {
self.resolveProperties = { try block($0, $1 as! T) }
}
return self
}
/// Calls `resolveDependencies` block if it was set.
func resolveProperties(of instance: Any, container: DependencyContainer) throws {
guard let resolvedInstance = instance as? T else { return }
if let forwardsTo = forwardsTo {
try forwardsTo.resolveProperties(of: resolvedInstance, container: container)
}
if let resolveProperties = self.resolveProperties {
try resolveProperties(container, resolvedInstance)
}
}
//MARK: - AutoWiringDefinition
var autoWiringFactory: ((DependencyContainer, DependencyContainer.Tag?) throws -> Any)?
var numberOfArguments: Int = 0
//MARK: - TypeForwardingDefinition
/// Types that can be resolved using this definition.
private(set) var implementingTypes: [Any.Type] = [(T?).self, (T!).self]
/// Return `true` if type can be resolved using this definition
func doesImplements(type aType: Any.Type) -> Bool {
return implementingTypes.contains(where: { $0 == aType })
}
//MARK: - _TypeForwardingDefinition
/// Adds type as being able to be resolved using this definition
func _implements(type aType: Any.Type) {
_implements(types: [aType])
}
/// Adds types as being able to be resolved using this definition
func _implements(types aTypes: [Any.Type]) {
implementingTypes.append(contentsOf: aTypes.filter({ !doesImplements(type: $0) }))
}
/// Definition to which resolution will be forwarded to
weak var forwardsTo: _TypeForwardingDefinition? {
didSet {
//both definitions (self and forwardsTo) can resolve
//each other types and each other implementing types
//this relationship can be used to reuse previously resolved instances
if let forwardsTo = forwardsTo {
_implements(type: forwardsTo.type)
_implements(types: forwardsTo.implementingTypes)
//definitions for types that can be resolved by `forwardsTo` definition
//can also be used to resolve self type and it's implementing types
//this way container properly reuses previosly resolved instances
//when there are several forwarded definitions
//see testThatItReusesInstanceResolvedByTypeForwarding)
for definition in forwardsTo.forwardsFrom {
definition._implements(type: type)
definition._implements(types: implementingTypes)
}
//forwardsTo can be used to resolve self type and it's implementing types
forwardsTo._implements(type: type)
forwardsTo._implements(types: implementingTypes)
forwardsTo.forwardsFrom.append(self)
}
}
}
/// Definitions that will forward resolution to this definition
var forwardsFrom: [_TypeForwardingDefinition] = []
}
//MARK: - _Definition
protocol _Definition: AutoWiringDefinition, TypeForwardingDefinition {
var type: Any.Type { get }
var scope: ComponentScope { get }
var weakFactory: ((Any) throws -> Any)! { get }
func resolveProperties(of instance: Any, container: DependencyContainer) throws
var container: DependencyContainer? { get set }
}
//MARK: - Type Forwarding
protocol _TypeForwardingDefinition: _Definition {
weak var forwardsTo: _TypeForwardingDefinition? { get }
var forwardsFrom: [_TypeForwardingDefinition] { get set }
func _implements(type aType: Any.Type)
func _implements(types aTypes: [Any.Type])
}
extension Definition: _TypeForwardingDefinition {
var type: Any.Type {
return T.self
}
}
extension Definition: CustomStringConvertible {
public var description: String {
return "type: \(T.self), factory: \(F.self), scope: \(scope)"
}
}
//MARK: - Definition Builder
/// Internal class used to build definition
class DefinitionBuilder<T, U> {
typealias F = (U) throws -> T
var scope: ComponentScope!
var factory: F!
var numberOfArguments: Int = 0
var autoWiringFactory: ((DependencyContainer, DependencyContainer.Tag?) throws -> T)?
var forwardsTo: _Definition?
init(configure: (DefinitionBuilder) -> ()) {
configure(self)
}
func build() -> Definition<T, U> {
let factory = self.factory!
let definition = Definition<T, U>(scope: scope, factory: factory)
definition.numberOfArguments = numberOfArguments
definition.autoWiringFactory = autoWiringFactory
definition.weakFactory = { try factory($0 as! U) }
definition.forwardsTo = forwardsTo as? _TypeForwardingDefinition
return definition
}
}
//MARK: - KeyDefinitionPair
typealias KeyDefinitionPair = (key: DefinitionKey, definition: _Definition)
/// Definitions are matched if they are registered for the same tag and thier factories accept the same number of runtime arguments.
private func ~=(lhs: KeyDefinitionPair, rhs: KeyDefinitionPair) -> Bool {
guard lhs.key.type == rhs.key.type else { return false }
guard lhs.key.tag == rhs.key.tag else { return false }
guard lhs.definition.numberOfArguments == rhs.definition.numberOfArguments else { return false }
return true
}
/// Returns key-defintion pairs with definitions able to resolve that type (directly or via type forwarding)
/// and which tag matches provided key's tag or is nil if strictByTag is false.
/// In the end filters defintions by type of runtime arguments.
func filter(definitions _definitions: [KeyDefinitionPair], byKey key: DefinitionKey, strictByTag: Bool = false, byTypeOfArguments: Bool = false) -> [KeyDefinitionPair] {
let definitions = _definitions
.filter({ $0.key.type == key.type || $0.definition.doesImplements(type: key.type) })
.filter({ $0.key.tag == key.tag || (!strictByTag && $0.key.tag == nil) })
if byTypeOfArguments {
return definitions.filter({ $0.key.typeOfArguments == key.typeOfArguments })
}
else {
return definitions
}
}
/// Orders key-definition pairs putting first definitions registered for provided tag.
func order(definitions _definitions: [KeyDefinitionPair], byTag tag: DependencyContainer.Tag?) -> [KeyDefinitionPair] {
return
_definitions.filter({ $0.key.tag == tag }) +
_definitions.filter({ $0.key.tag != tag })
}
| mit | 0a62d2478184a21fb94e7ffa82f464f8 | 35.477663 | 169 | 0.70683 | 4.346847 | false | false | false | false |
chrismanahan/ExtRxSwift | Source/RxButtonExtensions.swift | 1 | 2246 | //
// RxButtonExtensions.swift
// EmojiSearch
//
// Created by Chris M on 1/23/16.
// Copyright © 2016 Chris Manahan. All rights reserved.
//
import RxCocoa
import RxSwift
extension UIButton {
public func rx_hold(interval: Double = 0.2) -> ControlEvent<Void> {
let source: Observable<Void> = Observable.create { [weak self] observer in
MainScheduler.ensureExecutingOnScheduler()
guard self != nil else {
observer.on(.Completed)
return NopDisposable.instance
}
var isHeld = false
let down = self!.rx_controlEvent(.TouchDown)
.subscribeNext { isHeld = true }
let upInside = self!.rx_controlEvent(.TouchUpInside)
.subscribeNext { isHeld = false }
let upOutside = self!.rx_controlEvent(.TouchUpOutside)
.subscribeNext { isHeld = false }
let target = HoldTarget(button: self!, interval: interval) { button in
if isHeld {
observer.on(.Next())
}
}
return AnonymousDisposable {
target.dispose()
down.dispose()
upInside.dispose()
upOutside.dispose()
}
}.takeUntil(rx_deallocated)
return ControlEvent(events: source)
}
}
class HoldTarget: Disposable {
typealias Callback = (UIButton) -> Void
let selector: Selector = "timerHandler"
weak var button: UIButton?
var callback: Callback?
var timer: NSTimer?
init(button: UIButton, interval: Double = 0.2, callback: Callback) {
self.button = button
self.callback = callback
self.timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
@objc func timerHandler() {
if let callback = self.callback, button = self.button {
callback(button)
}
}
func dispose() {
self.timer?.invalidate()
self.timer = nil
self.callback = nil
}
}
| mit | 87ed998bf935f5dcd273cce803a66f24 | 27.782051 | 133 | 0.542984 | 5.044944 | false | false | false | false |
alblue/swift | stdlib/public/SDK/Foundation/NSStringAPI.swift | 1 | 77330 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Important Note
// ==============
//
// This file is shared between two projects:
//
// 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation
// 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation
//
// If you change this file, you must update it in both places.
#if !DEPLOYMENT_RUNTIME_SWIFT
@_exported import Foundation // Clang module
#endif
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
#endif
/// From a non-`nil` `UnsafePointer` to a null-terminated string
/// with possibly-transient lifetime, create a null-terminated array of 'C' char.
/// Returns `nil` if passed a null pointer.
internal func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? {
guard let cString = p else {
return nil
}
let len = UTF8._nullCodeUnitOffset(in: cString)
var result = [CChar](repeating: 0, count: len + 1)
for i in 0..<len {
result[i] = cString[i]
}
return result
}
extension String {
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// An array of the encodings that strings support in the application's
/// environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// The C-string encoding assumed for any method accepting a C string as an
/// argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of the specified encoding.
///
/// - Parameter encoding: A string encoding. For possible values, see
/// `String.Encoding`.
/// - Returns: A human-readable string giving the name of `encoding` in the
/// current locale.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Creates a string by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
}
extension String {
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Creates a new string equivalent to the given bytes interpreted in the
/// specified encoding.
///
/// - Parameters:
/// - bytes: A sequence of bytes to interpret using `encoding`.
/// - encoding: The ecoding to use to interpret `bytes`.
public init? <S: Sequence>(bytes: __shared S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of bytes from the
/// given buffer, interpreted in the specified encoding, and optionally
/// frees the buffer.
///
/// - Warning: This initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Creates a new string that contains the specified number of characters
/// from the given C array of Unicode characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count))
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of characters
/// from the given C array of UTF-16 code units.
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag))
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: __shared String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: __shared String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOfFile path: __shared String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: __shared URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: __shared URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOf url: __shared URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: __shared Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = String._unconditionallyBridgeFromObjectiveC(s)
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: __shared String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: __shared String, arguments: __shared [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: __shared String, locale: __shared Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: __shared String, locale: __shared Locale?, arguments: __shared [CVarArg]) {
#if DEPLOYMENT_RUNTIME_SWIFT
self = withVaList(arguments) {
String._unconditionallyBridgeFromObjectiveC(
NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0)
)
}
#else
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
#endif
}
}
extension StringProtocol where Index == String.Index {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
// FIXME(strings): There is probably a better way to bridge Self to NSString
var _ns: NSString {
return self._ephemeralString._bridgeToObjectiveC()
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _toIndex(_ utf16Index: Int) -> Index {
return self._toUTF16Index(utf16Index)
}
/// Return the UTF-16 code unit offset corresponding to an Index
func _toOffset(_ idx: String.Index) -> Int {
return self._toUTF16Offset(idx)
}
@inlinable
internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(self._toUTF16Offsets(r))
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _toRange(_ r: NSRange) -> Range<Index> {
return self._toUTF16Indices(Range(r)!)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _toRange(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = _toIndex(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._toRange(nsRange)
return result
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the string can be
/// converted to the specified encoding without loss of information.
///
/// - Parameter encoding: A string encoding.
/// - Returns: `true` if the string can be encoded in `encoding` without loss
/// of information; otherwise, `false`.
public func canBeConverted(to encoding: String.Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// A copy of the string with each word changed to its corresponding
/// capitalized spelling.
///
/// This property performs the canonical (non-localized) mapping. It is
/// suitable for programming operations that require stable results not
/// depending on the current locale.
///
/// A capitalized string is a string with the first character in each word
/// changed to its corresponding uppercase value, and all remaining
/// characters set to their corresponding lowercase values. A "word" is any
/// sequence of characters delimited by spaces, tabs, or line terminators.
/// Some common word delimiting punctuation isn't considered, so this
/// property may not generally produce the desired results for multiword
/// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for
/// additional information.
///
/// Case transformations aren’t guaranteed to be symmetrical or to produce
/// strings of the same lengths as the originals.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the string that is produced
/// using the current locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the string
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString._ephemeralString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters this string and the
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix<
T : StringProtocol
>(with aString: T, options: String.CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString._ephemeralString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare<T : StringProtocol>(
_ aString: T,
options mask: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
let aString = aString._ephemeralString
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(
range ?? startIndex..<endIndex
),
locale: locale?._bridgeToObjectiveC()
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the string as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the string.
///
/// - Returns: The actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
#if DEPLOYMENT_RUNTIME_SWIFT
var outputNamePlaceholder: String?
var outputArrayPlaceholder = [String]()
let res = self._ns.completePath(
into: &outputNamePlaceholder,
caseSensitive: caseSensitive,
matchesInto: &outputArrayPlaceholder,
filterTypes: filterTypes
)
if let n = outputNamePlaceholder {
outputName?.pointee = n
} else {
outputName?.pointee = ""
}
outputArray?.pointee = outputArrayPlaceholder
return res
#else // DEPLOYMENT_RUNTIME_SWIFT
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
#endif // DEPLOYMENT_RUNTIME_SWIFT
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the string
/// that have been divided by characters in the given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the string that have been
/// divided by the given separator.
///
/// The substrings in the resulting array appear in the same order as the
/// original string. Adjacent occurrences of the separator string produce
/// empty strings in the result. Similarly, if the string begins or ends
/// with the separator, the first or last substring, respectively, is empty.
/// The following example shows this behavior:
///
/// let list1 = "Karin, Carrie, David"
/// let items1 = list1.components(separatedBy: ", ")
/// // ["Karin", "Carrie", "David"]
///
/// // Beginning with the separator:
/// let list2 = ", Norman, Stanley, Fletcher"
/// let items2 = list2.components(separatedBy: ", ")
/// // ["", "Norman", "Stanley", "Fletcher"
///
/// If the list has no separators, the array contains only the original
/// string itself.
///
/// let name = "Karin"
/// let list = name.components(separatedBy: ", ")
/// // ["Karin"]
///
/// - Parameter separator: The separator string.
/// - Returns: An array containing substrings that have been divided from the
/// string using `separator`.
// FIXME(strings): now when String conforms to Collection, this can be
// replaced by split(separator:maxSplits:omittingEmptySubsequences:)
public func components<
T : StringProtocol
>(separatedBy separator: T) -> [String] {
return _ns.components(separatedBy: separator._ephemeralString)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// The fastest encoding to which the string can be converted without loss
/// of information.
public var fastestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.fastestEncoding)
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding
) -> Bool {
return _ns.getCString(&buffer,
maxLength: Swift.min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and the given string using a case-insensitive,
/// localized, comparison.
public
func localizedCaseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and the given string using a localized comparison.
public func localizedCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCompare(aString._ephemeralString)
}
/// Compares the string and the given string as sorted by the Finder.
public func localizedStandardCompare<
T : StringProtocol
>(_ string: T) -> ComparisonResult {
return _ns.localizedStandardCompare(string._ephemeralString)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
#endif
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns a Boolean value indicating whether the string contains the given
/// string, taking the current locale into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(macOS 10.11, iOS 9.0, *)
public func localizedStandardContains<
T : StringProtocol
>(_ string: T) -> Bool {
return _ns.localizedStandardContains(string._ephemeralString)
}
// @property NSStringEncoding smallestEncoding;
/// The smallest encoding to which the string can be converted without
/// loss of information.
public var smallestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.smallestEncoding)
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string created by replacing all characters in the string
/// not in the specified set with percent encoded characters.
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: CharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string created by appending a string constructed from a given
/// format string and the following arguments.
public func appendingFormat<
T : StringProtocol
>(
_ format: T, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format._ephemeralString, arguments: arguments))
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string created by appending the given string.
// FIXME(strings): shouldn't it be deprecated in favor of `+`?
public func appending<
T : StringProtocol
>(_ aString: T) -> String {
return _ns.appending(aString._ephemeralString)
}
/// Returns a string with the given character folding options
/// applied.
public func folding(
options: String.CompareOptions = [], locale: Locale?
) -> String {
return _ns.folding(options: options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
public func padding<
T : StringProtocol
>(
toLength newLength: Int,
withPad padString: T,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength,
withPad: padString._ephemeralString,
startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// A new string made from the string by replacing all percent encoded
/// sequences with the matching UTF-8 characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
public func replacingCharacters<
T : StringProtocol, R : RangeExpression
>(in range: R, with replacement: T) -> String where R.Bound == Index {
return _ns.replacingCharacters(
in: _toRelativeNSRange(range.relative(to: self)),
with: replacement._ephemeralString)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(StringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the string are replaced by
/// another given string.
public func replacingOccurrences<
Target : StringProtocol,
Replacement : StringProtocol
>(
of target: Target,
with replacement: Replacement,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
let target = target._ephemeralString
let replacement = replacement._ephemeralString
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.replacingPercentEscapes(using: encoding.rawValue)
}
#endif
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
public func trimmingCharacters(in set: CharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
public func uppercased(with locale: Locale?) -> String {
return _ns.uppercased(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write<
T : StringProtocol
>(
toFile path: T, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
toFile: path._ephemeralString,
atomically: useAuxiliaryFile,
encoding: enc.rawValue)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
#if !DEPLOYMENT_RUNTIME_SWIFT
/// Perform string transliteration.
@available(macOS 10.11, iOS 9.0, *)
public func applyingTransform(
_ transform: StringTransform, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
invoking body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) where R.Bound == Index {
let range = range.relative(to: self)
_ns.enumerateLinguisticTags(
in: _toRelativeNSRange(range),
scheme: NSLinguisticTagScheme(rawValue: tagScheme._ephemeralString),
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0!.rawValue, self._toRange($1), self._toRange($2), &stop_)
if stop_ {
$3.pointee = true
}
}
}
#endif
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the specified range of
/// the string.
///
/// Mutation of a string value while enumerating its substrings is not
/// supported. If you need to mutate a string from within `body`, convert
/// your string to an `NSMutableString` instance and then call the
/// `enumerateSubstrings(in:options:using:)` method.
///
/// - Parameters:
/// - range: The range within the string to enumerate substrings.
/// - opts: Options specifying types of substrings and enumeration styles.
/// If `opts` is omitted or empty, `body` is called a single time with
/// the range of the string specified by `range`.
/// - body: The closure executed for each substring in the enumeration. The
/// closure takes four arguments:
/// - The enumerated substring. If `substringNotRequired` is included in
/// `opts`, this parameter is `nil` for every execution of the
/// closure.
/// - The range of the enumerated substring in the string that
/// `enumerate(in:options:_:)` was called on.
/// - The range that includes the substring as well as any separator or
/// filler characters that follow. For instance, for lines,
/// `enclosingRange` contains the line terminators. The enclosing
/// range for the first string enumerated also contains any characters
/// that occur before the string. Consecutive enclosing ranges are
/// guaranteed not to overlap, and every single character in the
/// enumerated range is included in one and only one enclosing range.
/// - An `inout` Boolean value that the closure can use to stop the
/// enumeration by setting `stop = true`.
public func enumerateSubstrings<
R : RangeExpression
>(
in range: R,
options opts: String.EnumerationOptions = [],
_ body: @escaping (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) where R.Bound == Index {
_ns.enumerateSubstrings(
in: _toRelativeNSRange(range.relative(to: self)), options: opts) {
var stop_ = false
body($0,
self._toRange($1),
self._toRange($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes<
R : RangeExpression
>(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: R,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool where R.Bound == Index {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: Swift.min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toRelativeNSRange(range.relative(to: self)),
remaining: $0)
}
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _toRange(_ns.lineRange(
for: _toRelativeNSRange(aRange.relative(to: self))))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
public func linguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil?
) -> [String] where R.Bound == Index {
var nsTokenRanges: NSArray?
let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
self._ns.linguisticTags(
in: _toRelativeNSRange(range.relative(to: self)),
scheme: NSLinguisticTagScheme(rawValue: tagScheme._ephemeralString),
options: opts,
orthography: orthography,
tokenRanges: $0) as NSArray
}
if let nsTokenRanges = nsTokenRanges {
tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map {
self._toRange($0.rangeValue)
}
}
return result as! [String]
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _toRange(
_ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self))))
}
#endif
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
public func rangeOfCharacter(
from aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet,
options: mask,
range: _toRelativeNSRange(
aRange ?? startIndex..<endIndex
)
)
)
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _toRange(
_ns.rangeOfComposedCharacterSequence(at: _toOffset(anIndex)))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
public func rangeOfComposedCharacterSequences<
R : RangeExpression
>(
for range: R
) -> Range<Index> where R.Bound == Index {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _toRange(
_ns.rangeOfComposedCharacterSequences(
for: _toRelativeNSRange(range.relative(to: self))))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(Locale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
public func range<
T : StringProtocol
>(
of aString: T,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
let aString = aString._ephemeralString
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toRelativeNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(macOS 10.11, iOS 9.0, *)
public func localizedStandardRange<
T : StringProtocol
>(of string: T) -> Range<Index>? {
return _optionalRange(
_ns.localizedStandardRange(of: string._ephemeralString))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.addingPercentEscapes(using: encoding.rawValue)
}
#endif
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
public func contains<T : StringProtocol>(_ other: T) -> Bool {
let r = self.range(of: other) != nil
if #available(macOS 10.10, iOS 8.0, *) {
assert(r == _ns.contains(other._ephemeralString))
}
return r
}
/// Returns a Boolean value indicating whether the given string is non-empty
/// and contained within this string by case-insensitive, non-literal
/// search, taking into account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs, can be
/// achieved by calling `range(of:options:range:locale:)`.
///
/// Equivalent to:
///
/// range(of: other, options: .caseInsensitiveSearch,
/// locale: Locale.current) != nil
public func localizedCaseInsensitiveContains<
T : StringProtocol
>(_ other: T) -> Bool {
let r = self.range(
of: other, options: .caseInsensitive, locale: Locale.current
) != nil
if #available(macOS 10.10, iOS 8.0, *) {
assert(r ==
_ns.localizedCaseInsensitiveContains(other._ephemeralString))
}
return r
}
}
// Deprecated slicing
extension StringProtocol where Index == String.Index {
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range from' operator.")
public func substring(from index: Index) -> String {
return _ns.substring(from: _toOffset(index))
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range upto' operator.")
public func substring(to index: Index) -> String {
return _ns.substring(to: _toOffset(index))
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript.")
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toRelativeNSRange(aRange))
}
}
extension StringProtocol {
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
fatalError("unavailable function can't be called")
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
fatalError("unavailable function can't be called")
}
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
fatalError("unavailable function can't be called")
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
fatalError("unavailable function can't be called")
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
fatalError("unavailable function can't be called")
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message: "Use appendingPathComponent on URL instead.")
public func appendingPathComponent(_ aString: String) -> String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message: "Use appendingPathExtension on URL instead.")
public func appendingPathExtension(_ ext: String) -> String? {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.")
public var deletingLastPathComponent: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message: "Use deletingPathExtension on URL instead.")
public var deletingPathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)
// stringByFoldingWithOptions:(StringCompareOptions)options
// locale:(Locale *)locale
@available(*, unavailable, renamed: "folding(options:locale:)")
public func folding(
_ options: String.CompareOptions = [], locale: Locale?
) -> String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.")
public var resolvingSymlinksInPath: String {
fatalError("unavailable property")
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message: "Use standardizingPath on URL instead.")
public var standardizingPath: String {
fatalError("unavailable function can't be called")
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message: "Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed: "localizedName(of:)")
public static func localizedNameOfStringEncoding(
_ encoding: String.Encoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func pathWithComponents(_ components: [String]) -> String {
fatalError("unavailable function can't be called")
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func path(withComponents components: [String]) -> String {
fatalError("unavailable function can't be called")
}
}
extension StringProtocol {
@available(*, unavailable, renamed: "canBeConverted(to:)")
public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "capitalizedString(with:)")
public func capitalizedStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "commonPrefix(with:options:)")
public func commonPrefixWith(
_ aString: String, options: String.CompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
_ outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedByCharactersIn(
_ separator: CharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedBy(_ separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "cString(usingEncoding:)")
public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
_ encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
_ range: Range<Index>,
options opts: String.EnumerationOptions = [],
_ body: (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lengthOfBytes(using:)")
public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lineRange(for:)")
public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "lowercased(with:)")
public func lowercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "maximumLengthOfBytes(using:)")
public
func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "paragraphRange(for:)")
public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
_ aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
_ range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "range(of:options:range:locale:)")
public func rangeOf(
_ aString: String,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "localizedStandardRange(of:)")
public func localizedStandardRangeOf(_ string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)")
public func addingPercentEncodingWithAllowedCharacters(
_ allowedCharacters: CharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEscapes(using:)")
public func addingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "appendingFormat")
public func stringByAppendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "padding(toLength:with:startingAt:)")
public func byPaddingToLength(
_ newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingCharacters(in:with:)")
public func replacingCharactersIn(
_ range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
_ target: String,
withString replacement: String,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "trimmingCharacters(in:)")
public func byTrimmingCharactersIn(_ set: CharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "strings(byAppendingPaths:)")
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(from:)")
public func substringFrom(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(to:)")
public func substringTo(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(with:)")
public func substringWith(_ aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased(with:)")
public func uppercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(toFile:atomically:encoding:)")
public func writeToFile(
_ path: String, atomically useAuxiliaryFile:Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(to:atomically:encoding:)")
public func writeToURL(
_ url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
} | apache-2.0 | f63517c66afa142112648304201d637b | 34.488297 | 279 | 0.676948 | 4.772155 | false | false | false | false |
crazytonyli/GeoNet-iOS | Recent Quakes/TodayViewController.swift | 1 | 3300 | //
// TodayViewController.swift
// Recent Quakes
//
// Created by Tony Li on 10/12/16.
// Copyright © 2016 Tony Li. All rights reserved.
//
import UIKit
import NotificationCenter
import GeoNetAPI
import FormatterKit
@objc(TodayViewController)
class TodayViewController: UITableViewController, NCWidgetProviding {
fileprivate var quakes = [Quake]() {
didSet {
tableView?.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.rowHeight = 50
refresh(completionHandler: nil)
}
func refresh(completionHandler: ((NCUpdateResult) -> Void)?) {
let intensity = UserDefaults.app.selectedIntensity ?? .weak
guard let mmi = QuakeMMI(rawValue: intensity.MMIRange.lowerBound) else {
return
}
URLSession.API.quakes(with: mmi) { [weak self] in
guard let `self` = self else { return }
switch $0 {
case .failure:
completionHandler?(.failed)
case .success(let quakes):
let newQuakes = quakes.count > 2 ? Array(quakes[0...1]) : quakes
let result: NCUpdateResult = self.quakes == newQuakes ? .noData : .newData
self.quakes = newQuakes
completionHandler?(result)
}
}
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
refresh(completionHandler: completionHandler)
}
}
extension TodayViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return quakes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
let quake = quakes[indexPath.row]
cell.textLabel?.text = quake.locality
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.detailTextLabel?.text = TTTTimeIntervalFormatter().stringForTimeInterval(from: Date(), to: quake.time)
cell.detailTextLabel?.textColor = .darkGray
if cell.accessoryView == nil {
let magnitudeLabel = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 44, height: 28)))
magnitudeLabel.font = .systemFont(ofSize: 15)
magnitudeLabel.textColor = .white
magnitudeLabel.textAlignment = .center
magnitudeLabel.layer.masksToBounds = true
magnitudeLabel.layer.cornerRadius = 4
cell.accessoryView = magnitudeLabel
}
if let magnitudeLabel = (cell.accessoryView as? UILabel) {
magnitudeLabel.text = String(format: "%.1f", quake.magnitude)
magnitudeLabel.backgroundColor = quake.mmi.intensity.color
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let url = URL(string: "geonet://quake/\(quakes[indexPath.row].identifier)") {
extensionContext?.open(url, completionHandler: nil)
}
}
}
| mit | 9ed54b7c0fec8e22960b47e91e676ec1 | 33.726316 | 134 | 0.642619 | 4.938623 | false | false | false | false |
raphaelhanneken/apple-juice | AppleJuice/StatusNotification.swift | 1 | 3864 | //
// StatusNotification.swift
// Apple Juice
// https://github.com/raphaelhanneken/apple-juice
//
import Foundation
/// Posts user notifications about the current charging status.
struct StatusNotification {
// MARK: Lifecycle
/// Initializes a new StatusNotification.
///
/// - parameter key: The notification key which to display a user notification for.
/// - returns: An optional StatusNotification; Return nil when the notificationKey
/// is invalid or nil.
init?(forState state: BatteryState?) {
guard let state = state, state != .charging(percentage: Percentage(numeric: 0)) else {
return nil
}
guard let key = NotificationKey(rawValue: state.percentage.numeric ?? 0), key != .invalid else {
return nil
}
self.notificationKey = key
}
// MARK: Internal
/// Present a notification for the current battery status to the user
func postNotification() {
if self.shouldPresentNotification() {
NSUserNotificationCenter.default.deliver(self.createUserNotification())
UserPreferences.lastNotified = self.notificationKey
}
}
// MARK: Private
/// The current notification's key.
private let notificationKey: NotificationKey
/// Check whether to present a notification to the user or not. Depending on the
/// users preferences and whether the user already got notified about the current
/// percentage.
///
/// - returns: Whether to present a notification for the current battery percentage
private func shouldPresentNotification() -> Bool {
(self.notificationKey != UserPreferences.lastNotified
&& UserPreferences.notifications.contains(self.notificationKey))
}
/// Create a user notification for the current battery status
///
/// - returns: The user notification to display
private func createUserNotification() -> NSUserNotification {
let notification = NSUserNotification()
notification.title = self.getNotificationTitle()
notification.informativeText = self.getNotificationText()
return notification
}
/// Get the corresponding notification title for the current battery state
///
/// - returns: The notification title
private func getNotificationTitle() -> String {
if self.notificationKey == .hundredPercent {
return NSLocalizedString("Charged Notification Title", comment: "")
}
return String.localizedStringWithFormat(NSLocalizedString("Low Battery Notification Title", comment: ""),
self.formattedPercentage())
}
/// Get the corresponding notification text for the current battery state
///
/// - returns: The notification text
private func getNotificationText() -> String {
if self.notificationKey == .hundredPercent {
return NSLocalizedString("Charged Notification Message", comment: "")
}
return NSLocalizedString("Low Battery Notification Message", comment: "")
}
/// The current percentage, formatted according to the selected client locale, e.g.
/// en_US: 42% fr_FR: 42 %
///
/// - returns: The localised percentage
private func formattedPercentage() -> String {
let percentageFormatter = NumberFormatter()
percentageFormatter.numberStyle = .percent
percentageFormatter.generatesDecimalNumbers = false
percentageFormatter.localizesFormat = true
percentageFormatter.multiplier = 1.0
percentageFormatter.minimumFractionDigits = 0
percentageFormatter.maximumFractionDigits = 0
return percentageFormatter.string(from: self.notificationKey.rawValue as NSNumber)
?? "\(self.notificationKey.rawValue) %"
}
}
| mit | e5b509a62d56fbbeda8caa248185008d | 37.257426 | 113 | 0.671066 | 5.512126 | false | false | false | false |
XeresRazor/FFXIVServer | Sources/FFXIVServer/AppearanceDatabase.swift | 1 | 1518 | //
// AppearanceDatabase.swift
// FFXIVServer
//
// Created by David Green on 2/24/16.
// Copyright © 2016 David Green. All rights reserved.
//
import Foundation
import SMGOLFramework
struct AppearanceDefinition {
typealias AttributeMap = [String: UInt32]
var attributes = AttributeMap()
}
class AppearanceDatabase {
typealias AppearanceMap = [UInt32: AppearanceDefinition]
var appearances = AppearanceMap()
static func createFromXML(stream: Stream) -> AppearanceDatabase? {
let result = AppearanceDatabase()
guard let documentNode = ParseDocument(stream) else { return nil }
let appearanceNodes = documentNode.selectNodes("Appearances/Appearance")
for appearanceNode in appearanceNodes {
var appearance = AppearanceDefinition()
guard let itemID = GetAttributeIntValue(appearanceNode, name:"ItemId") else { return nil }
for appearanceAttribute in appearanceNode.attributes {
guard appearanceAttribute.0 == "ItemId" else { continue }
guard let attributeValue = UInt32(appearanceAttribute.1) else { return nil }
appearance.attributes[appearanceAttribute.0] = attributeValue
}
result.appearances[UInt32(itemID)] = appearance
}
return result
}
func getAppearanceForItemID(itemID: UInt32) -> AppearanceDefinition? {
guard let appearance = appearances[itemID] else { return nil }
return appearance
}
}
| mit | ba351b5bd2f7ce9cbda5024109fe4bf7 | 35.119048 | 102 | 0.678312 | 4.83121 | false | false | false | false |
NicolasMahe/NMDataUserDefault | NMDataUserDefault/NMDataUserDefaultEnum.swift | 1 | 2925 | //
// NMDataUserDefaultEnum.swift
// NMDataUserDefaultEnum
//
// Created by Nicolas Mahé on 06/03/2017.
//
//
import UIKit
public class NMDataUserDefaultEnum<T: RawRepresentable>: NSObject { //, NMDataUserDefaultProtocol {
public typealias ValueType = T
//----------------------------------------------------------------------------
// MARK: - Properties
//----------------------------------------------------------------------------
var identifier: String
var store: UserDefaults
var defaultValue: ValueType
public var enableInMemory: Bool
var onChange: (() -> Void)?
var _value: ValueType?
//----------------------------------------------------------------------------
// MARK: - Life cycle
//----------------------------------------------------------------------------
required public init(
identifier: String,
store: UserDefaults = UserDefaults.standard,
defaultValue: ValueType,
enableInMemory: Bool,
onChange: (() -> Void)?
) {
self.identifier = identifier
self.store = store
self.defaultValue = defaultValue
self.enableInMemory = enableInMemory
self.onChange = onChange
super.init()
}
//----------------------------------------------------------------------------
// MARK: - Archive / unarchive
//----------------------------------------------------------------------------
func archive(_ value: ValueType) -> Any? {
return value.rawValue
}
func unarchive() -> ValueType? {
if let data = self.store.object(forKey: self.identifier),
let dataRaw = data as? T.RawValue {
return T(rawValue: dataRaw)
}
return nil
}
//----------------------------------------------------------------------------
// MARK: - Notification
//----------------------------------------------------------------------------
public var notification: Notification.Name {
return Notification.Name(rawValue: self.identifier)
}
//----------------------------------------------------------------------------
// MARK: - Value
//----------------------------------------------------------------------------
public var value: ValueType {
get {
//get from memory
if self.enableInMemory == true,
let value = self._value {
return value
}
if let value = self.unarchive() {
self._value = value
return value
}
//get default asset
return self.defaultValue
}
set(value) {
//Set in memory
self._value = value
if let data = self.archive(value) {
self.store.set(data, forKey: self.identifier)
}
else {
self.store.removeObject(forKey: self.identifier)
}
//send notif
NotificationCenter.default.post(
name: self.notification,
object: nil
)
self.onChange?()
}
}
}
| mit | a0a4bb26f5e8e71412cab9e74dfa93ed | 25.342342 | 99 | 0.43844 | 5.813121 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/CoreDataHelper.swift | 1 | 14801 | import Foundation
import CocoaLumberjack
import CoreData
// MARK: - NSManagedObject Default entityName Helper
//
extension NSManagedObject {
/// Returns the Entity Name, if available, as specified in the NSEntityDescription. Otherwise, will return
/// the subclass name.
///
/// Note: entity().name returns nil as per iOS 10, in Unit Testing Targets. Awesome.
///
@objc class func entityName() -> String {
return entity().name ?? classNameWithoutNamespaces()
}
/// Returns a NSFetchRequest instance with it's *Entity Name* always set.
///
/// Note: entity().name returns nil as per iOS 10, in Unit Testing Targets. Awesome.
///
@objc class func safeFetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
guard entity().name == nil else {
return fetchRequest()
}
return NSFetchRequest(entityName: entityName())
}
}
// MARK: - NSManagedObjectContext Helpers!
//
extension NSManagedObjectContext {
/// Returns all of the entities that match with a given predicate.
///
/// - Parameter predicate: Defines the conditions that any given object should meet. Optional.
///
func allObjects<T: NSManagedObject>(ofType type: T.Type, matching predicate: NSPredicate? = nil, sortedBy descriptors: [NSSortDescriptor]? = nil) -> [T] {
let request = T.safeFetchRequest()
request.predicate = predicate
request.sortDescriptors = descriptors
return loadObjects(ofType: type, with: request)
}
/// Returns the number of entities found that match with a given predicate.
///
/// - Parameter predicate: Defines the conditions that any given object should meet. Optional.
///
func countObjects<T: NSManagedObject>(ofType type: T.Type, matching predicate: NSPredicate? = nil) -> Int {
let request = T.safeFetchRequest()
request.includesSubentities = false
request.predicate = predicate
request.resultType = .countResultType
var result = 0
do {
result = try count(for: request)
} catch {
DDLogError("Error counting objects [\(String(describing: T.entityName))]: \(error)")
assertionFailure()
}
return result
}
/// Deletes the specified Object Instance
///
func deleteObject<T: NSManagedObject>(_ object: T) {
delete(object)
}
/// Deletes all of the NSMO instances associated to the current kind
///
func deleteAllObjects<T: NSManagedObject>(ofType type: T.Type) {
let request = T.safeFetchRequest()
request.includesPropertyValues = false
request.includesSubentities = false
for object in loadObjects(ofType: type, with: request) {
delete(object)
}
}
/// Retrieves the first entity that matches with a given predicate
///
/// - Parameter predicate: Defines the conditions that any given object should meet.
///
func firstObject<T: NSManagedObject>(ofType type: T.Type, matching predicate: NSPredicate) -> T? {
let request = T.safeFetchRequest()
request.predicate = predicate
request.fetchLimit = 1
return loadObjects(ofType: type, with: request).first
}
/// Inserts a new Entity. For performance reasons, this helper *DOES NOT* persists the context.
///
func insertNewObject<T: NSManagedObject>(ofType type: T.Type) -> T {
return NSEntityDescription.insertNewObject(forEntityName: T.entityName(), into: self) as! T
}
/// Loads a single NSManagedObject instance, given its ObjectID, if available.
///
/// - Parameter objectID: Unique Identifier of the entity to retrieve, if available.
///
func loadObject<T: NSManagedObject>(ofType type: T.Type, with objectID: NSManagedObjectID) -> T? {
var result: T?
do {
result = try existingObject(with: objectID) as? T
} catch {
DDLogError("Error loading Object [\(String(describing: T.entityName))]")
}
return result
}
/// Returns an entity already stored or it creates a new one of a specific type
///
/// - Parameters:
/// - type: Type of the Entity
/// - predicate: A predicate used to fetch a stored Entity
/// - Returns: A valid Entity
func entity<Entity: NSManagedObject>(of type: Entity.Type, with predicate: NSPredicate) -> Entity {
guard let entity = firstObject(ofType: type, matching: predicate) else {
return insertNewObject(ofType: type)
}
return entity
}
/// Loads the collection of entities that match with a given Fetch Request
///
private func loadObjects<T: NSManagedObject>(ofType type: T.Type, with request: NSFetchRequest<NSFetchRequestResult>) -> [T] {
var objects: [T]?
do {
objects = try fetch(request) as? [T]
} catch {
DDLogError("Error loading Objects [\(String(describing: T.entityName))")
assertionFailure()
}
return objects ?? []
}
}
extension NSPersistentStoreCoordinator {
/// Retrieves an NSManagedObjectID in a safe way, so even if the URL is not in a valid CoreData format no exceptions will be throw.
///
/// - Parameter uri: the core-data object uri representation
/// - Returns: a NSManagedObjectID if the uri is valid or nil if not.
///
public func safeManagedObjectID(forURIRepresentation uri: URL) -> NSManagedObjectID? {
guard let scheme = uri.scheme, scheme == "x-coredata" else {
return nil
}
var result: NSManagedObjectID? = nil
do {
try WPException.objcTry {
result = self.managedObjectID(forURIRepresentation: uri)
}
} catch {
return nil
}
return result
}
}
// MARK: - ContextManager Helpers
extension ContextManager {
static var overrideInstance: CoreDataStack?
@objc class func sharedInstance() -> CoreDataStack {
if let overrideInstance = overrideInstance {
return overrideInstance
}
return ContextManager.internalSharedInstance()
}
static var shared: CoreDataStack {
return sharedInstance()
}
/// Tests purpose only
@objc public class func overrideSharedInstance(_ instance: CoreDataStack?) {
ContextManager.overrideInstance = instance
}
enum ContextManagerError: Error {
case missingCoordinatorOrStore
case missingDatabase
}
}
extension CoreDataStack {
func performAndSave<T>(_ block: @escaping (NSManagedObjectContext) throws -> T, completion: ((Result<T, Error>) -> Void)?) {
let context = newDerivedContext()
context.perform {
let result = Result(catching: { try block(context) })
if case .success = result {
self.saveContextAndWait(context)
}
completion?(result)
}
}
func performAndSave<T>(_ block: @escaping (NSManagedObjectContext) throws -> T) async throws -> T {
try await withCheckedThrowingContinuation { continuation in
performAndSave(block) {
continuation.resume(with: $0)
}
}
}
/// Creates a copy of the current open store and saves it to the specified destination
/// - Parameter backupLocation: Location to save the store copy to
func createStoreCopy(to backupLocation: URL) throws {
let (backupLocation, shmLocation, walLocation) = databaseFiles(for: backupLocation)
try? FileManager.default.removeItem(at: backupLocation)
try? FileManager.default.removeItem(at: shmLocation)
try? FileManager.default.removeItem(at: walLocation)
guard let storeCoordinator = mainContext.persistentStoreCoordinator,
let store = storeCoordinator.persistentStores.first else {
throw ContextManager.ContextManagerError.missingCoordinatorOrStore
}
let model = storeCoordinator.managedObjectModel
let storeCoordinatorCopy = NSPersistentStoreCoordinator(managedObjectModel: model)
var storeOptions = store.options
storeOptions?[NSReadOnlyPersistentStoreOption] = true
let storeCopy = try storeCoordinatorCopy.addPersistentStore(ofType: store.type,
configurationName: store.configurationName,
at: store.url,
options: storeOptions)
try storeCoordinatorCopy.migratePersistentStore(storeCopy,
to: backupLocation,
withType: storeCopy.type)
}
/// Replaces the current active store with the database at the specified location.
///
/// The following steps are performed:
/// - Remove the current store from the store coordinator.
/// - Create a backup of the current database.
/// - Copy the source database over the current database. If this fails, restore the backup files.
/// - Attempt to re-add the store with the new database or original database if the copy failed. If adding the new store fails, restore the backup and try to re-add the old store.
/// - Finally, remove all the backup files and source database if everything was successful.
///
/// **Warning: This is destructive towards the active database. It will be overwritten on success.**
/// - Parameter databaseLocation: Database to overwrite the current one with
func restoreStoreCopy(from databaseLocation: URL) throws {
guard let storeCoordinator = mainContext.persistentStoreCoordinator,
let store = storeCoordinator.persistentStores.first else {
throw ContextManager.ContextManagerError.missingCoordinatorOrStore
}
let (databaseLocation, shmLocation, walLocation) = databaseFiles(for: databaseLocation)
guard let currentDatabaseLocation = store.url,
FileManager.default.fileExists(atPath: databaseLocation.path),
FileManager.default.fileExists(atPath: shmLocation.path),
FileManager.default.fileExists(atPath: walLocation.path) else {
throw ContextManager.ContextManagerError.missingDatabase
}
mainContext.reset()
try storeCoordinator.remove(store)
let databaseReplaced = replaceDatabase(from: databaseLocation, to: currentDatabaseLocation)
do {
try storeCoordinator.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil,
at: currentDatabaseLocation)
if databaseReplaced {
// The database was replaced successfully and the store added with no errors so we
// can remove the source database & backup files
let (databaseBackup, shmBackup, walBackup) = backupFiles(for: currentDatabaseLocation)
try? FileManager.default.removeItem(at: databaseLocation)
try? FileManager.default.removeItem(at: shmLocation)
try? FileManager.default.removeItem(at: walLocation)
try? FileManager.default.removeItem(at: databaseBackup)
try? FileManager.default.removeItem(at: shmBackup)
try? FileManager.default.removeItem(at: walBackup)
}
} catch {
// Re-adding the store failed for some reason, attempt to restore the backup
// and use that store instead. We re-throw the error so that the caller can
// attempt to handle the error
restoreDatabaseBackup(at: currentDatabaseLocation)
_ = try? storeCoordinator.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil,
at: currentDatabaseLocation)
throw error
}
}
private func databaseFiles(for database: URL) -> (database: URL, shm: URL, wal: URL) {
let shmFile = URL(string: database.absoluteString.appending("-shm"))!
let walFile = URL(string: database.absoluteString.appending("-wal"))!
return (database, shmFile, walFile)
}
private func backupFiles(for database: URL) -> (database: URL, shm: URL, wal: URL) {
let (database, shmFile, walFile) = databaseFiles(for: database)
let databaseBackup = database.appendingPathExtension("backup")
let shmBackup = shmFile.appendingPathExtension("backup")
let walBackup = walFile.appendingPathExtension("backup")
return (databaseBackup, shmBackup, walBackup)
}
private func replaceDatabase(from source: URL, to destination: URL) -> Bool {
let (source, sourceShm, sourceWal) = databaseFiles(for: source)
let (destination, destinationShm, destinationWal) = databaseFiles(for: destination)
let (databaseBackup, shmBackup, walBackup) = backupFiles(for: destination)
do {
try FileManager.default.copyItem(at: destination, to: databaseBackup)
try FileManager.default.copyItem(at: destinationShm, to: shmBackup)
try FileManager.default.copyItem(at: destinationWal, to: walBackup)
try FileManager.default.removeItem(at: destination)
try FileManager.default.removeItem(at: destinationShm)
try FileManager.default.removeItem(at: destinationWal)
try FileManager.default.copyItem(at: source, to: destination)
try FileManager.default.copyItem(at: sourceShm, to: destinationShm)
try FileManager.default.copyItem(at: sourceWal, to: destinationWal)
return true
} catch {
// Attempt to restore backup files. Some might not exist depending on where the process failed
DDLogError("Error when replacing database: \(error)")
restoreDatabaseBackup(at: destination)
return false
}
}
private func restoreDatabaseBackup(at location: URL) {
let (location, locationShm, locationWal) = databaseFiles(for: location)
let (databaseBackup, shmBackup, walBackup) = backupFiles(for: location)
_ = try? FileManager.default.replaceItemAt(location, withItemAt: databaseBackup)
_ = try? FileManager.default.replaceItemAt(locationShm, withItemAt: shmBackup)
_ = try? FileManager.default.replaceItemAt(locationWal, withItemAt: walBackup)
}
}
| gpl-2.0 | a30c7860bffacda2c8b96c53d754fd5c | 41.168091 | 185 | 0.639551 | 5.191512 | false | false | false | false |
ioscreator/ioscreator | IOSPrototypeCellsTutorial/IOSPrototypeCellsTutorial/TableViewController.swift | 1 | 3209 | //
// TableViewController.swift
// IOSPrototypeCellsTutorial
//
// Created by Arthur Knopper on 08/02/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
let transportItems =
["Bus","Helicopter","Truck","Boat","Bicycle","Motorcycle","Plane","Train","Car","Scooter","Caravan"]
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
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return the number of rows
return transportItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "transportCell", for: indexPath)
cell.textLabel?.text = transportItems[indexPath.row]
let imageName = UIImage(named: transportItems[indexPath.row])
cell.imageView?.image = imageName
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 58dd7c3e40aaaaaf96bb52018060ffbd | 32.416667 | 136 | 0.667394 | 5.182553 | false | false | false | false |
slavapestov/swift | validation-test/stdlib/GameplayKit.swift | 2 | 2793 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
import GameplayKit
// GameplayKit is only available on iOS 9.0 and above, OS X 10.11 and above, and
// tvOS 9.0 and above.
var GamePlayKitTests = TestSuite("GameplayKit")
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *) {
class TestComponent : GKComponent {}
class OtherTestComponent : GKComponent {}
class TestState1 : GKState {}
class TestState2 : GKState {}
GamePlayKitTests.test("GKEntity.componentForClass()") {
let entity = GKEntity()
entity.addComponent(TestComponent())
do {
var componentForTestComponent =
entity.componentForClass(TestComponent.self)
var componentForOtherTestComponent_nil =
entity.componentForClass(OtherTestComponent.self)
expectNotEmpty(componentForTestComponent)
expectType(Optional<TestComponent>.self, &componentForTestComponent)
expectEmpty(componentForOtherTestComponent_nil)
}
entity.removeComponentForClass(TestComponent.self)
entity.addComponent(OtherTestComponent())
do {
var componentForOtherTestComponent =
entity.componentForClass(OtherTestComponent.self)
var componentForTestComponent_nil =
entity.componentForClass(TestComponent.self)
expectNotEmpty(componentForOtherTestComponent)
expectType(Optional<OtherTestComponent>.self, &componentForOtherTestComponent)
expectEmpty(componentForTestComponent_nil)
}
}
GamePlayKitTests.test("GKStateMachine.stateForClass()") {
do {
// Construct a state machine with a custom subclass as the only state.
let stateMachine = GKStateMachine(
states: [TestState1()])
var stateForTestState1 =
stateMachine.stateForClass(TestState1.self)
var stateForTestState2_nil =
stateMachine.stateForClass(TestState2.self)
expectNotEmpty(stateForTestState1)
expectType(Optional<TestState1>.self, &stateForTestState1)
expectEmpty(stateForTestState2_nil)
}
do {
// Construct a state machine with a custom subclass as the only state.
let stateMachine = GKStateMachine(
states: [TestState2()])
var stateForTestState2 =
stateMachine.stateForClass(TestState2.self)
var stateForTestState1_nil =
stateMachine.stateForClass(TestState1.self)
expectNotEmpty(stateForTestState2)
expectType(Optional<TestState2>.self, &stateForTestState2)
expectEmpty(stateForTestState1_nil)
}
}
} // if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *)
runAllTests()
| apache-2.0 | ce087e558c4dad828285b4dafab05e4f | 26.653465 | 82 | 0.75546 | 4.119469 | false | true | false | false |
farshadtx/Fleet | FleetTests/CoreExtensions/UINavigationController+FleetSpec.swift | 1 | 10229 | import XCTest
import Fleet
import Nimble
class UINavigationController_FleetSpec: XCTestCase {
fileprivate class TestViewController: UIViewController {
var testViewDidLoadCallCount: UInt = 0
var capturedNavigationController: UINavigationController?
fileprivate override func viewDidLoad() {
super.viewDidLoad()
testViewDidLoadCallCount += 1
capturedNavigationController = navigationController
}
}
func test_pushViewController_immediatelySetsTheViewControllerAsTheTopController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerToPush = UIViewController()
navigationController.pushViewController(controllerToPush, animated: true)
expect(navigationController.topViewController).to(beIdenticalTo(controllerToPush))
}
func test_pushViewController_immediatelyLoadsThePushedViewController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerToPush = TestViewController()
navigationController.pushViewController(controllerToPush, animated: true)
expect(controllerToPush.testViewDidLoadCallCount).to(equal(1))
}
func test_pushViewController_doesNotCausePushedViewControllerToLoadMultipleTimes() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerToPush = TestViewController()
navigationController.pushViewController(controllerToPush, animated: true)
expect(controllerToPush.testViewDidLoadCallCount).toEventuallyNot(beGreaterThan(1))
}
func test_pushViewController_doesNotLoadThePushedViewControllerUntilItWouldHaveANavigationController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerToPush = TestViewController()
navigationController.pushViewController(controllerToPush, animated: true)
expect(controllerToPush.capturedNavigationController).toEventuallyNot(beNil())
}
func test_popViewController_returnsPoppedViewController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerToPushThenPop = UIViewController()
navigationController.pushViewController(controllerToPushThenPop, animated: true)
let poppedViewController = navigationController.popViewController(animated: true)
expect(poppedViewController).to(beIdenticalTo(controllerToPushThenPop))
}
func test_popViewController_immediatelySetsTheNextViewControllerInStackAsTopViewController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerToPushThenPop = UIViewController()
navigationController.pushViewController(controllerToPushThenPop, animated: true)
navigationController.popViewController(animated: true)
expect(navigationController.topViewController).to(beIdenticalTo(root))
}
func test_popToViewController_immediatelySetsTheGivenViewControllerAsTopViewController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerOne = UIViewController()
let controllerTwo = UIViewController()
let controllerThree = UIViewController()
navigationController.pushViewController(controllerOne, animated: false)
navigationController.pushViewController(controllerTwo, animated: false)
navigationController.pushViewController(controllerThree, animated: false)
navigationController.popToViewController(controllerOne, animated: true)
expect(navigationController.topViewController).to(beIdenticalTo(controllerOne))
}
func test_popToViewController_whenTheNavigationControllerIsInVisibleWindow_returnsThePoppedViewControllers() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerOne = UIViewController()
let controllerTwo = UIViewController()
let controllerThree = UIViewController()
navigationController.pushViewController(controllerOne, animated: false)
navigationController.pushViewController(controllerTwo, animated: false)
navigationController.pushViewController(controllerThree, animated: false)
let poppedControllers = navigationController.popToViewController(controllerOne, animated: true)
if poppedControllers != nil {
expect(poppedControllers!.count).to(equal(2))
expect(poppedControllers![0]).to(beIdenticalTo(controllerTwo))
expect(poppedControllers![1]).to(beIdenticalTo(controllerThree))
} else {
fail("Expected popToViewController(_:animated:) to return popped view controllers")
}
}
func test_popToViewController_whenTheNavigationControllerNotInVisibleWindow_returnsNil() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
let controllerOne = UIViewController()
let controllerTwo = UIViewController()
let controllerThree = UIViewController()
navigationController.pushViewController(controllerOne, animated: false)
navigationController.pushViewController(controllerTwo, animated: false)
navigationController.pushViewController(controllerThree, animated: false)
let poppedControllers = navigationController.popToViewController(controllerOne, animated: true)
expect(poppedControllers).to(beNil())
}
func test_popToRootViewController_immediatelySetsTheRootViewControllerAsTheTopViewController() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerOne = UIViewController()
let controllerTwo = UIViewController()
navigationController.pushViewController(controllerOne, animated: true)
navigationController.pushViewController(controllerTwo, animated: true)
navigationController.popToRootViewController(animated: false)
expect(navigationController.topViewController).to(beIdenticalTo(root))
}
func test_popToRootViewController_whenTheNavigationControllerIsInVisibleWindow_returnsThePoppedViewControllers() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
let controllerOne = UIViewController()
let controllerTwo = UIViewController()
navigationController.pushViewController(controllerOne, animated: false)
navigationController.pushViewController(controllerTwo, animated: false)
let poppedControllers = navigationController.popToRootViewController(animated: true)
if poppedControllers != nil {
expect(poppedControllers!.count).to(equal(2))
expect(poppedControllers![0]).to(beIdenticalTo(controllerOne))
expect(poppedControllers![1]).to(beIdenticalTo(controllerTwo))
} else {
fail("Expected popToRootViewControllerAnimated(_:) to return popped view controllers")
}
}
func test_popToRootViewController_whenTheNavigationControllerIsNotInVisibleWindow_returnsNil() {
let root = UIViewController()
let navigationController = UINavigationController(rootViewController: root)
let window = UIWindow()
window.rootViewController = navigationController
let controllerOne = UIViewController()
let controllerTwo = UIViewController()
navigationController.pushViewController(controllerOne, animated: false)
navigationController.pushViewController(controllerTwo, animated: false)
let poppedControllers = navigationController.popToRootViewController(animated: true)
expect(poppedControllers).to(beNil())
}
func test_navigationControllerWithSegueInViewDidLoad_segueHappensAndResultIsImmediatelyVisible() {
let storyboard = UIStoryboard(name: "KittensStoryboard", bundle: nil)
let viewController = UIViewController()
try! storyboard.bind(viewController: viewController, toIdentifier: "KittenImage")
let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
let window = UIWindow()
window.rootViewController = navigationController
window.makeKeyAndVisible()
expect(navigationController?.visibleViewController).to(beIdenticalTo(viewController))
}
}
| apache-2.0 | f3b0fe83452aeee9fa075ae75e77c331 | 41.978992 | 118 | 0.742595 | 6.573907 | false | true | false | false |
brentsimmons/Evergreen | Shared/SmartFeeds/UnreadFeed.swift | 1 | 1923 | //
// UnreadFeed.swift
// NetNewsWire
//
// Created by Brent Simmons on 11/19/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
#if os(macOS)
import AppKit
#else
import Foundation
#endif
import RSCore
import Account
import Articles
import ArticlesDatabase
// This just shows the global unread count, which appDelegate already has. Easy.
final class UnreadFeed: PseudoFeed {
var account: Account? = nil
public var defaultReadFilterType: ReadFilterType {
return .alwaysRead
}
var feedID: FeedIdentifier? {
return FeedIdentifier.smartFeed(String(describing: UnreadFeed.self))
}
let nameForDisplay = NSLocalizedString("All Unread", comment: "All Unread pseudo-feed title")
let fetchType = FetchType.unread(nil)
var unreadCount = 0 {
didSet {
if unreadCount != oldValue {
postUnreadCountDidChangeNotification()
}
}
}
var smallIcon: IconImage? {
return AppAssets.unreadFeedImage
}
#if os(macOS)
var pasteboardWriter: NSPasteboardWriting {
return SmartFeedPasteboardWriter(smartFeed: self)
}
#endif
init() {
self.unreadCount = appDelegate.unreadCount
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: appDelegate)
}
@objc func unreadCountDidChange(_ note: Notification) {
assert(note.object is AppDelegate)
unreadCount = appDelegate.unreadCount
}
}
extension UnreadFeed: ArticleFetcher {
func fetchArticles() throws -> Set<Article> {
return try fetchUnreadArticles()
}
func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
fetchUnreadArticlesAsync(completion)
}
func fetchUnreadArticles() throws -> Set<Article> {
return try AccountManager.shared.fetchArticles(fetchType)
}
func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) {
AccountManager.shared.fetchArticlesAsync(fetchType, completion)
}
}
| mit | f8949b4ca2cf17b964c9b4fe9617d086 | 21.880952 | 143 | 0.759105 | 3.890688 | false | false | false | false |
SEEK-Jobs/seek-stackable | Sources/VStack.swift | 1 | 2782 | // Copyright © 2016 SEEK. All rights reserved.
//
import UIKit
open class VStack: Stack {
public let thingsToStack: [Stackable]
public let spacing: CGFloat
public let layoutMargins: UIEdgeInsets
public let width: CGFloat?
public init(spacing: CGFloat = 0.0, layoutMargins: UIEdgeInsets = UIEdgeInsets.zero, thingsToStack: [Stackable], width: CGFloat? = nil) {
self.spacing = spacing
self.layoutMargins = layoutMargins
self.thingsToStack = thingsToStack
self.width = width
}
public convenience init(spacing: CGFloat = 0.0, layoutMargins: UIEdgeInsets = UIEdgeInsets.zero, width: CGFloat? = nil, thingsToStack: () -> [Stackable]) {
self.init(
spacing: spacing,
layoutMargins: layoutMargins,
thingsToStack: thingsToStack(),
width: width
)
}
open func framesForLayout(_ width: CGFloat, origin: CGPoint) -> [CGRect] {
var origin = origin
var width = width
if layoutMargins != UIEdgeInsets.zero {
origin.x += layoutMargins.left
origin.y += layoutMargins.top
width -= (layoutMargins.left + layoutMargins.right)
}
var frames: [CGRect] = []
var y: CGFloat = origin.y
self.visibleThingsToStack()
.forEach { stackable in
if let stack = stackable as? Stack {
let innerFrames = stack.framesForLayout(width, origin: CGPoint(x: origin.x, y: y))
frames.append(contentsOf: innerFrames)
y = frames.maxY
} else if let item = stackable as? StackableItem {
let itemHeight = item.heightForWidth(width)
let itemWidth = min(width, item.intrinsicContentSize.width)
let frame = CGRect(x: origin.x, y: y, width: itemWidth, height: itemHeight)
frames.append(frame)
y += itemHeight
}
y += self.spacing
}
return frames
}
public var intrinsicContentSize: CGSize {
let items = visibleThingsToStack()
guard !items.isEmpty else { return .zero }
// width
let intrinsicWidth = items.reduce(0, { max($0, $1.intrinsicContentSize.width) }) + layoutMargins.horizontalInsets
// height
let totalHeightOfItems = items.reduce(0, { $0 + $1.intrinsicContentSize.height })
let totalVerticalSpacing = max(CGFloat(items.count) - 1, 0) * spacing
let intrinsicHeight = totalHeightOfItems + totalVerticalSpacing + layoutMargins.verticalInsets
return CGSize(width: intrinsicWidth, height: intrinsicHeight)
}
}
| mit | 48a5d1d32b91cfa9b052cd67346c8513 | 38.169014 | 159 | 0.591514 | 4.930851 | false | false | false | false |
nolili/BluetoothExampleTV | BluetoothExampleTV/BluetoothAccess.swift | 1 | 4472 | //
// BluetoothAccess.swift
// BluetoothExampleTV
//
// Created by Noritaka Kamiya on 2015/10/30.
// Copyright © 2015年 Noritaka Kamiya. All rights reserved.
//
import Foundation
import CoreBluetooth
typealias HeartRateRawData = NSData
enum HeartRateRawDataError: ErrorType {
case Unknown
}
extension HeartRateRawData {
func heartRateValue() throws -> Int {
var buffer = [UInt8](count: self.length, repeatedValue: 0x00)
self.getBytes(&buffer, length: buffer.count)
var bpm:UInt16
if buffer.count >= 2 {
if buffer[0] & 0x01 == 0 {
bpm = UInt16(buffer[1])
} else {
bpm = UInt16(buffer[1]) << 8
bpm = bpm | UInt16(buffer[2])
}
} else {
throw HeartRateRawDataError.Unknown
}
return Int(bpm)
}
}
struct HeartRateService {
static let UUID = CBUUID(string: "180D")
}
struct HeartRateMesurement {
static var UUID : CBUUID = CBUUID(string: "2A37")
}
struct BodySensorLocation {
static var UUID : CBUUID = CBUUID(string: "2A38")
}
struct HeartRateControlUnit {
static var UUID: CBUUID = CBUUID(string: "2A39")
}
typealias HeartRateUpdateHandler = (Int) -> (Void)
class BluetoothManager :NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager:CBCentralManager!
var connectingPeripheral:CBPeripheral?
var heartRateUpdateHandler: HeartRateUpdateHandler?
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: dispatch_get_main_queue())
}
func centralManagerDidUpdateState(central: CBCentralManager) {
switch central.state {
case .PoweredOn:
startScan()
default:
break
}
}
func startScan() -> Void {
centralManager.scanForPeripheralsWithServices([HeartRateService.UUID], options: nil)
}
// swiftlint:disable variable_name
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
connectingPeripheral = peripheral
centralManager.connectPeripheral(peripheral, options: nil)
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([HeartRateService.UUID])
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
self.connectingPeripheral?.delegate = nil
self.connectingPeripheral = nil
self.startScan()
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
self.connectingPeripheral?.delegate = nil
self.connectingPeripheral = nil
self.startScan()
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
peripheral.services?.forEach { service in
if service.UUID == HeartRateService.UUID {
peripheral.discoverCharacteristics([HeartRateMesurement.UUID, BodySensorLocation.UUID, HeartRateControlUnit.UUID], forService: service)
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
service.characteristics?.forEach { characteristic in
switch characteristic.UUID {
case HeartRateMesurement.UUID:
peripheral.setNotifyValue(true, forCharacteristic: characteristic)
case BodySensorLocation.UUID:
peripheral.readValueForCharacteristic(characteristic)
default:
break
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
switch characteristic.UUID {
case HeartRateMesurement.UUID:
guard let value = characteristic.value else {
break
}
guard let bpm = try? value.heartRateValue() else {
break
}
self.heartRateUpdateHandler?(bpm)
default:
break
}
}
}
| mit | 51ed8738741dcbfb886263c0a6bcbffc | 30.251748 | 157 | 0.641083 | 5.276269 | false | false | false | false |
animalsBeef/CF-TestDYZ | DYZB/DYZB/Classes/Main/Model/AnchorGroup.swift | 1 | 1187 | //
// AnchorGroup.swift
// DYZB
//
// Created by 陈峰 on 16/10/14.
// Copyright © 2016年 陈峰. All rights reserved.
//
import UIKit
class AnchorGroup: NSObject {
var room_list : [[String : NSObject]]? {
didSet {
guard let room_list = room_list else { return }
for dict in room_list {
anchors.append(AnchorModel( dict : dict))
}
}
}
var tag_name : String = ""
var icon_name : String = "home_header_normal"
var icon_url : String = ""
var anchors : [AnchorModel] = [AnchorModel]()
override init() {
}
init(dict : [String : NSObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
/*
override func setValue(value: AnyObject?, forKey key: String) {
if key == "romm_list" {
if let dataArray = value as? [[String : NSObject]]{
for dict in dataArray{
anchors.append(AnchorModel(dict:dict))
}
}
}
}
*/
}
| mit | b75c91340998c6f6296fa2a65559c9c0 | 21.188679 | 76 | 0.510204 | 4.323529 | false | false | false | false |
huonw/swift | test/Interpreter/protocol_initializers.swift | 3 | 14966 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -swift-version 5 %s -o %t/a.out
//
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
import StdlibUnittest
var ProtocolInitTestSuite = TestSuite("ProtocolInit")
func mustThrow<T>(_ f: () throws -> T) {
do {
_ = try f()
preconditionFailure("Didn't throw")
} catch {}
}
func mustFail<T>(f: () -> T?) {
if f() != nil {
preconditionFailure("Didn't fail")
}
}
enum E : Error { case X }
protocol TriviallyConstructible {
init(x: LifetimeTracked)
init(x: LifetimeTracked, throwsDuring: Bool) throws
init?(x: LifetimeTracked, failsDuring: Bool)
}
extension TriviallyConstructible {
init(x: LifetimeTracked, throwsBefore: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: x)
}
init(x: LifetimeTracked, throwsAfter: Bool) throws {
self.init(x: x)
if throwsAfter {
throw E.X
}
}
init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: x, throwsDuring: throwsDuring)
}
init(x: LifetimeTracked, throwsBefore: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: x)
if throwsAfter {
throw E.X
}
}
init(x: LifetimeTracked, throwsDuring: Bool, throwsAfter: Bool) throws {
try self.init(x: x, throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: x, throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
init?(x: LifetimeTracked, failsBefore: Bool) {
if failsBefore {
return nil
}
self.init(x: x)
}
init?(x: LifetimeTracked, failsAfter: Bool) {
self.init(x: x)
if failsAfter {
return nil
}
}
init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool) {
if failsBefore {
return nil
}
self.init(x: x, failsDuring: failsDuring)
}
init?(x: LifetimeTracked, failsBefore: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: x)
if failsAfter {
return nil
}
}
init?(x: LifetimeTracked, failsDuring: Bool, failsAfter: Bool) {
self.init(x: x, failsDuring: failsDuring)
if failsAfter {
return nil
}
}
init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: x, failsDuring: failsDuring)
if failsAfter {
return nil
}
}
}
class TrivialClass : TriviallyConstructible {
let tracker: LifetimeTracked
// Protocol requirements
required init(x: LifetimeTracked) {
self.tracker = x
}
required convenience init(x: LifetimeTracked, throwsDuring: Bool) throws {
self.init(x: x)
if throwsDuring {
throw E.X
}
}
required convenience init?(x: LifetimeTracked, failsDuring: Bool) {
self.init(x: x)
if failsDuring {
return nil
}
}
// Class initializers delegating to protocol initializers
convenience init(throwsBefore: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: LifetimeTracked(0))
}
convenience init(throwsAfter: Bool) throws {
self.init(x: LifetimeTracked(0))
if throwsAfter {
throw E.X
}
}
convenience init(throwsBefore: Bool, throwsDuring: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring)
}
convenience init(throwsBefore: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: LifetimeTracked(0))
if throwsAfter {
throw E.X
}
}
convenience init(throwsDuring: Bool, throwsAfter: Bool) throws {
try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
convenience init(throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
convenience init?(failsBefore: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0))
}
convenience init?(failsAfter: Bool) {
self.init(x: LifetimeTracked(0))
if failsAfter {
return nil
}
}
convenience init?(failsBefore: Bool, failsDuring: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0), failsDuring: failsDuring)
}
convenience init?(failsBefore: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0))
if failsAfter {
return nil
}
}
convenience init?(failsDuring: Bool, failsAfter: Bool) {
self.init(x: LifetimeTracked(0), failsDuring: failsDuring)
if failsAfter {
return nil
}
}
convenience init?(failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0), failsDuring: failsDuring)
if failsAfter {
return nil
}
}
}
ProtocolInitTestSuite.test("ExtensionInit_Success") {
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsAfter: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: false)
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsAfter: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: false)!
}
ProtocolInitTestSuite.test("ClassInit_Success") {
_ = try! TrivialClass(throwsBefore: false)
_ = try! TrivialClass(throwsAfter: false)
_ = try! TrivialClass(throwsBefore: false, throwsDuring: false)
_ = try! TrivialClass(throwsDuring: false, throwsAfter: false)
_ = try! TrivialClass(throwsBefore: false, throwsAfter: false)
_ = try! TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: false)
_ = TrivialClass(failsBefore: false)!
_ = TrivialClass(failsAfter: false)!
_ = TrivialClass(failsBefore: false, failsDuring: false)!
_ = TrivialClass(failsDuring: false, failsAfter: false)!
_ = TrivialClass(failsBefore: false, failsAfter: false)!
_ = TrivialClass(failsBefore: false, failsDuring: false, failsAfter: false)!
}
ProtocolInitTestSuite.test("ExtensionInit_Failure") {
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsAfter: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: true) }
}
ProtocolInitTestSuite.test("ClassInit_Failure") {
mustThrow { try TrivialClass(throwsBefore: true) }
mustThrow { try TrivialClass(throwsAfter: true) }
mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true) }
mustThrow { try TrivialClass(throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(throwsDuring: false, throwsAfter: true) }
mustThrow { try TrivialClass(throwsBefore: true, throwsAfter: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsAfter: true) }
mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false, throwsAfter: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: true) }
mustFail { TrivialClass(failsBefore: true) }
mustFail { TrivialClass(failsAfter: true) }
mustFail { TrivialClass(failsBefore: true, failsDuring: false) }
mustFail { TrivialClass(failsBefore: false, failsDuring: true) }
mustFail { TrivialClass(failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(failsDuring: false, failsAfter: true) }
mustFail { TrivialClass(failsBefore: true, failsAfter: false) }
mustFail { TrivialClass(failsBefore: false, failsAfter: true) }
mustFail { TrivialClass(failsBefore: true, failsDuring: false, failsAfter: false) }
mustFail { TrivialClass(failsBefore: false, failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(failsBefore: false, failsDuring: false, failsAfter: true) }
}
struct TrivialStruct : TriviallyConstructible {
let x: LifetimeTracked
init(x: LifetimeTracked) {
self.x = x
}
init(x: LifetimeTracked, throwsDuring: Bool) throws {
self.init(x: x)
if throwsDuring {
throw E.X
}
}
init?(x: LifetimeTracked, failsDuring: Bool) {
self.init(x: x)
if failsDuring {
return nil
}
}
}
struct AddrOnlyStruct : TriviallyConstructible {
let x: LifetimeTracked
let y: Any
init(x: LifetimeTracked) {
self.x = x
self.y = "Hello world"
}
init(x: LifetimeTracked, throwsDuring: Bool) throws {
self.init(x: x)
if throwsDuring {
throw E.X
}
}
init?(x: LifetimeTracked, failsDuring: Bool) {
self.init(x: x)
if failsDuring {
return nil
}
}
}
extension TriviallyConstructible {
init(throwsFirst: Bool, throwsSecond: Bool, initThenInit: ()) throws {
try self.init(x: LifetimeTracked(0), throwsDuring: throwsFirst)
try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond)
}
init(throwsFirst: Bool, throwsSecond: Bool, initThenAssign: ()) throws {
try self.init(x: LifetimeTracked(0), throwsDuring: throwsFirst)
self = try Self(x: LifetimeTracked(0), throwsDuring: throwsSecond)
}
init(throwsFirst: Bool, throwsSecond: Bool, assignThenInit: ()) throws {
self = try Self(x: LifetimeTracked(0), throwsDuring: throwsFirst)
try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond)
}
init(throwsFirst: Bool, throwsSecond: Bool, assignThenAssign: ()) throws {
self = try Self(x: LifetimeTracked(0), throwsDuring: throwsFirst)
try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond)
}
}
ProtocolInitTestSuite.test("Struct_Success") {
_ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, initThenInit: ())
_ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, initThenAssign: ())
_ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, assignThenInit: ())
_ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, assignThenAssign: ())
}
ProtocolInitTestSuite.test("Struct_Failure") {
mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, initThenInit: ()) }
mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, initThenInit: ()) }
mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, initThenAssign: ()) }
mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, initThenAssign: ()) }
mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, assignThenInit: ()) }
mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, assignThenInit: ()) }
mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, assignThenAssign: ()) }
mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, assignThenAssign: ()) }
}
ProtocolInitTestSuite.test("AddrOnlyStruct_Success") {
_ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, initThenInit: ())
_ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, initThenAssign: ())
_ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, assignThenInit: ())
_ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, assignThenAssign: ())
}
ProtocolInitTestSuite.test("AddrOnlyStruct_Failure") {
mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, initThenInit: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, initThenInit: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, initThenAssign: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, initThenAssign: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, assignThenInit: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, assignThenInit: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, assignThenAssign: ()) }
mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, assignThenAssign: ()) }
}
runAllTests()
| apache-2.0 | 824a7f38099098f50bbec7897e6b3a95 | 33.16895 | 116 | 0.701791 | 4.144558 | false | false | false | false |
barteljan/VISPER | VISPER-Redux/Classes/AnyAsyncActionReducer.swift | 1 | 2398 | //
// AnyAsyncActionReducer.swift
// Pods-VISPER-Entity-Example
//
// Created by bartel on 15.06.18.
//
import Foundation
import VISPER_Core
/// A substitution wrapper for an instance of ActionReducerType
public struct AnyAsyncActionReducer {
private let _isResponsible : (_ action: Action, _ state: Any) -> Bool
private let _reduce: (_ provider: ReducerProvider,_ action: Action, _ completion: @escaping (Any) -> Void) -> Void
/// Create an AnyActionReducer with an instance of type ActionReducerType
public init<R : AsyncActionReducerType>(_ reducer : R){
let actionReducer = AsyncActionReducer(reducer)
self.init(actionReducer)
}
/// Create an AnyActionReducer with an instance of an ActionReducer
public init<StateType, ActionType>(_ reducer : AsyncActionReducer<StateType,ActionType>) {
self._isResponsible = reducer.isResponsible(action:state:)
self._reduce = { container, action, completion in
guard let action = action as? ActionType else {
return
}
reducer.reduce(provider: container,action: action, completion: completion)
}
}
/// Check if this reducer is responsible for a given action and state
/// - Note: The default implementation simply checks if the given action and state conform to the reducers action and state types
/// - Parameters:
/// - action: a given action
/// - state: a given state
/// - Returns: returns if the reducer is responsible for this action/state pair
public func isResponsible(action: Action, state: Any) -> Bool {
return self._isResponsible(action,state)
}
/// Take a given action, modify a given state and return a new state
///
/// - Parameters:
/// - action: a given action
/// - state: a given state
/// - Returns: the new state
public func reduce<StateType>(provider: ReducerProvider,
action: Action,
completion: @escaping (_ newState: StateType) -> Void) {
let wrappedCompletion = { (newState: Any) -> Void in
guard let newState = newState as? StateType else {
return
}
completion(newState)
}
self._reduce(provider,action,wrappedCompletion)
}
}
| mit | 0968eb3af51b85cdb69a828f4a8f9f4c | 34.791045 | 133 | 0.622602 | 4.776892 | false | false | false | false |
austinzheng/swift | test/IRGen/type_layout_reference_storage.swift | 2 | 9971 | // RUN: %target-swift-frontend -emit-ir %s -enable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-objc-%target-ptrsize
// RUN: %target-swift-frontend -emit-ir %s -disable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-native-%target-ptrsize
class C {}
protocol P: class {}
protocol Q: class {}
// CHECK: @"$s29type_layout_reference_storage26ReferenceStorageTypeLayoutVMn" = hidden constant {{.*}} @"$s29type_layout_reference_storage26ReferenceStorageTypeLayoutVMP"
// CHECK: define internal %swift.type* @"$s29type_layout_reference_storage26ReferenceStorageTypeLayoutVMi"
struct ReferenceStorageTypeLayout<T, Native : C, Unknown : AnyObject> {
var z: T
// -- Known-Swift-refcounted type
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI:[0-9a-f][0-9a-f][0-9a-f]+]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI:[0-9a-f][0-9a-f][0-9a-f]+]]_pod to i8**)
unowned(unsafe) var cu: C
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_1_bt to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_1_bt to i8**)
unowned(safe) var cs: C
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var cwo: C?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var cwi: C!
// -- Known-Swift-refcounted archetype
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_pod to i8**)
unowned(unsafe) var nu: Native
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_1_bt to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_1_bt to i8**)
unowned(safe) var nc: Native
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var nwo: Native?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var nwi: Native!
// -- Open-code layout for protocol types with witness tables. Note:
// 1) The layouts for unowned(safe) references are only bitwise takable
// when ObjC interop is disabled.
// 2) 0x7fffffff is the max extra inhabitant count, but not all types in
// all scenarios.
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_16_8_[[REF_XI]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_4_[[REF_XI]]_pod to i8**)
unowned(unsafe) var pu: P
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_16_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_16_8_7fffffff to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_4_7fffffff to i8**)
unowned(safe) var ps: P
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_16_8_7fffffff to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_4_7fffffff to i8**)
weak var pwo: P?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_16_8_7fffffff to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_4_7fffffff to i8**)
weak var pwi: P!
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_7fffffff to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_7fffffff to i8**)
unowned(safe) var pqs: P & Q
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_[[REF_XI]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_[[REF_XI]]_pod to i8**)
unowned(unsafe) var pqu: P & Q
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_7fffffff to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_7fffffff to i8**)
weak var pqwo: (P & Q)?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_7fffffff to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_7fffffff to i8**)
weak var pqwi: (P & Q)!
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_7fffffff_bt to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_7fffffff_bt to i8**)
unowned(safe) var pqcs: P & Q & C
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_[[REF_XI]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_[[REF_XI]]_pod to i8**)
unowned(unsafe) var pqcu: P & Q & C
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_7fffffff to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_7fffffff to i8**)
weak var pqcwo: (P & Q & C)?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_24_8_7fffffff to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_12_4_7fffffff to i8**)
weak var pqcwi: (P & Q & C)!
// -- Unknown-refcounted existential without witness tables.
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_pod to i8**)
unowned(unsafe) var aou: AnyObject
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_1 to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_1 to i8**)
unowned(safe) var aos: AnyObject
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var aowo: AnyObject?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var aowi: AnyObject!
// -- Unknown-refcounted archetype
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_pod to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_pod to i8**)
unowned(unsafe) var uu: Unknown
// CHECK-native-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_[[REF_XI]]_bt to i8**)
// CHECK-objc-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_1 to i8**)
// CHECK-native-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_[[REF_XI]]_bt to i8**)
// CHECK-objc-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_1 to i8**)
unowned(safe) var us: Unknown
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var uwo: Unknown?
// CHECK-64: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_8_8_0 to i8**)
// CHECK-32: store i8** bitcast ({ [[INT]], [[INT]], i32, i32 }* @type_layout_4_4_0 to i8**)
weak var uwi: Unknown!
}
public class Base {
var a: UInt32 = 0
}
// CHECK-LABEL: %swift.metadata_response @{{.*}}7DerivedCMr"(
// CHECK: call void @swift_initClassMetadata
// CHECK: ret
public class Derived<T> : Base {
var type : P.Type
var k = C()
init(_ t: P.Type) {
type = t
}
}
| apache-2.0 | 29cd600b554c3c1c1400c12c1b5b7a25 | 69.716312 | 205 | 0.56564 | 2.714675 | false | false | false | false |
gaplo917/RxAlamofire | RxAlamofire/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift | 1 | 12196 | //
// DelegateProxyType.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
#if !RX_NO_MODULE
import RxSwift
#endif
/**
`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with
views that can have only one delegate/datasource registered.
`Proxies` store information about observers, subscriptions and delegates
for specific views.
Type implementing `DelegateProxyType` should never be initialized directly.
To fetch initialized instance of type implementing `DelegateProxyType`, `proxyForObject` method
should be used.
This is more or less how it works.
+-------------------------------------------+
| |
| UIView subclass (UIScrollView) |
| |
+-----------+-------------------------------+
|
| Delegate
|
|
+-----------v-------------------------------+
| |
| Delegate proxy : DelegateProxyType +-----+----> Observable<T1>
| , UIScrollViewDelegate | |
+-----------+-------------------------------+ +----> Observable<T2>
| |
| +----> Observable<T3>
| |
| forwards events |
| to custom delegate |
| v
+-----------v-------------------------------+
| |
| Custom delegate (UIScrollViewDelegate) |
| |
+-------------------------------------------+
Since RxCocoa needs to automagically create those Proxys
..and because views that have delegates can be hierarchical
UITableView : UIScrollView : UIView
.. and corresponding delegates are also hierarchical
UITableViewDelegate : UIScrollViewDelegate : NSObject
.. and sometimes there can be only one proxy/delegate registered,
every view has a corresponding delegate virtual factory method.
In case of UITableView / UIScrollView, there is
class RxScrollViewDelegateProxy: DelegateProxy {
static var factory = DelegateProxyFactory { (parentObject: UIScrollView) in
RxScrollViewDelegateProxy(parentObject: parentObject)
}
}
....
and extend it
RxScrollViewDelegateProxy.extendProxy { (parentObject: UITableView) in
RxTableViewDelegateProxy(parentObject: parentObject)
}
*/
public protocol DelegateProxyType : AnyObject {
/// DelegateProxy factory
static var factory: DelegateProxyFactory { get }
/// Returns assigned proxy for object.
///
/// - parameter object: Object that can have assigned delegate proxy.
/// - returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned.
static func assignedProxyFor(_ object: AnyObject) -> AnyObject?
/// Assigns proxy to object.
///
/// - parameter object: Object that can have assigned delegate proxy.
/// - parameter proxy: Delegate proxy object to assign to `object`.
static func assignProxy(_ proxy: AnyObject, toObject object: AnyObject)
/// Returns designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// - parameter object: Object that has delegate property.
/// - returns: Value of delegate property.
static func currentDelegateFor(_ object: AnyObject) -> AnyObject?
/// Sets designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// - parameter toObject: Object that has delegate property.
/// - parameter delegate: Delegate value.
static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject)
/// Returns reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - returns: Value of reference if set or nil.
func forwardToDelegate() -> AnyObject?
/// Sets reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
/// - parameter retainDelegate: Should `self` retain `forwardToDelegate`.
func setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool)
}
extension DelegateProxyType {
/// Returns existing proxy for object or installs new instance of delegate proxy.
///
/// - parameter object: Target object on which to install delegate proxy.
/// - returns: Installed instance of delegate proxy.
///
///
/// extension Reactive where Base: UISearchBar {
///
/// public var delegate: DelegateProxy {
/// return RxSearchBarDelegateProxy.proxyForObject(base)
/// }
///
/// public var text: ControlProperty<String> {
/// let source: Observable<String> = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:)))
/// ...
/// }
/// }
public static func proxyForObject(_ object: AnyObject) -> Self {
MainScheduler.ensureExecutingOnScheduler()
let maybeProxy = Self.assignedProxyFor(object) as? Self
let proxy: Self
if let existingProxy = maybeProxy {
proxy = existingProxy
}
else {
proxy = Self.createProxy(for: object) as! Self
Self.assignProxy(proxy, toObject: object)
assert(Self.assignedProxyFor(object) === proxy)
}
let currentDelegate: AnyObject? = Self.currentDelegateFor(object)
if currentDelegate !== proxy {
proxy.setForwardToDelegate(currentDelegate, retainDelegate: false)
assert(proxy.forwardToDelegate() === currentDelegate)
Self.setCurrentDelegate(proxy, toObject: object)
assert(Self.currentDelegateFor(object) === proxy)
assert(proxy.forwardToDelegate() === currentDelegate)
}
return proxy
}
/// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate.
/// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations.
///
/// - parameter forwardDelegate: Delegate object to set.
/// - parameter retainDelegate: Retain `forwardDelegate` while it's being set.
/// - parameter onProxyForObject: Object that has `delegate` property.
/// - returns: Disposable object that can be used to clear forward delegate.
public static func installForwardDelegate(_ forwardDelegate: AnyObject, retainDelegate: Bool, onProxyForObject object: AnyObject) -> Disposable {
weak var weakForwardDelegate: AnyObject? = forwardDelegate
let proxy = Self.proxyForObject(object)
assert(proxy.forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" +
"If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" +
" This is the source object value: \(object)\n" +
" This this the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" +
"Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n")
proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate)
return Disposables.create {
MainScheduler.ensureExecutingOnScheduler()
let delegate: AnyObject? = weakForwardDelegate
assert(delegate == nil || proxy.forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)")
proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate)
}
}
/// Extend DelegateProxy for specific subclass
/// See 'DelegateProxyFactory.extendedProxy'
public static func extendProxy<Object: AnyObject>(with creation: @escaping ((Object) -> AnyObject)) {
_ = factory.extended(factory: creation)
}
/// Creates new proxy for target object.
public static func createProxy(for object: AnyObject) -> AnyObject {
return factory.createProxy(for: object)
}
}
#if os(iOS) || os(tvOS)
import UIKit
extension ObservableType {
func subscribeProxyDataSource<P: DelegateProxyType>(ofObject object: UIView, dataSource: AnyObject, retainDataSource: Bool, binding: @escaping (P, Event<E>) -> Void)
-> Disposable {
let proxy = P.proxyForObject(object)
let unregisterDelegate = P.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object)
// this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75)
object.layoutIfNeeded()
let subscription = self.asObservable()
.observeOn(MainScheduler())
.catchError { error in
bindingErrorToInterface(error)
return Observable.empty()
}
// source can never end, otherwise it would release the subscriber, and deallocate the data source
.concat(Observable.never())
.takeUntil(object.rx.deallocated)
.subscribe { [weak object] (event: Event<E>) in
if let object = object {
assert(proxy === P.currentDelegateFor(object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: P.currentDelegateFor(object)))")
}
binding(proxy, event)
switch event {
case .error(let error):
bindingErrorToInterface(error)
unregisterDelegate.dispose()
case .completed:
unregisterDelegate.dispose()
default:
break
}
}
return Disposables.create { [weak object] in
subscription.dispose()
object?.layoutIfNeeded()
unregisterDelegate.dispose()
}
}
}
#endif
#endif
| mit | 5083cc6abef17b838724d3c90447499d | 43.184783 | 358 | 0.562198 | 6.121988 | false | false | false | false |
tardieu/swift | test/SILGen/objc_protocols.swift | 1 | 12582 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
import objc_protocols_Bas
@objc protocol NSRuncing {
func runce() -> NSObject
func copyRuncing() -> NSObject
func foo()
static func mince() -> NSObject
}
@objc protocol NSFunging {
func funge()
func foo()
}
protocol Ansible {
func anse()
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F
func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) {
return (x.runce(), x.copyRuncing())
// -- Result of runce is autoreleased according to default objc conv
// CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.runce!1.foreign
// CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[THIS1:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject
// -- Result of copyRuncing is received copy_valued according to -copy family
// CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.copyRuncing!1.foreign
// CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[THIS2:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject
// -- Arguments are not consumed by objc calls
// CHECK: destroy_value [[THIS2]]
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () {
func objc_generic_partial_apply<T : NSRuncing>(_ x: T) {
// CHECK: bb0([[ARG:%.*]] : $T):
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO]] :
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]])
// CHECK: destroy_value [[METHOD]]
_ = x.runce
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] :
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<T>()
// CHECK: destroy_value [[METHOD]]
_ = T.runce
// CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTcTO]]
// CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]])
// CHECK: destroy_value [[METHOD:%.*]]
_ = T.mince
// CHECK: destroy_value [[ARG]]
}
// CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF'
// CHECK: sil shared [thunk] @[[THUNK1]] :
// CHECK: bb0([[SELF:%.*]] : $Self):
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTO]] :
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>([[SELF]])
// CHECK: return [[METHOD]]
// CHECK: } // end sil function '[[THUNK1]]'
// CHECK: sil shared [thunk] @[[THUNK1_THUNK]]
// CHECK: bb0([[SELF:%.*]] : $Self):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.runce!1.foreign
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK1_THUNK]]'
// CHECK: sil shared [thunk] @[[THUNK2]] :
// CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTO]]
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0)
// CHECK: return [[METHOD]]
// CHECK: } // end sil function '[[THUNK2]]'
// CHECK: sil shared [thunk] @[[THUNK2_THUNK]] :
// CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.mince!1.foreign
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0)
// CHECK-NEXT: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK2_THUNK]]'
// CHECK-LABEL: sil hidden @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F
func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) {
return (x.runce(), x.copyRuncing())
// -- Result of runce is autoreleased according to default objc conv
// CHECK: [[THIS1:%.*]] = open_existential_ref [[THIS1_ORIG:%.*]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign
// CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]])
// -- Result of copyRuncing is received copy_valued according to -copy family
// CHECK: [[THIS2:%.*]] = open_existential_ref [[THIS2_ORIG:%.*]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign
// CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]])
// -- Arguments are not consumed by objc calls
// CHECK: destroy_value [[THIS2_ORIG]]
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () {
func objc_protocol_partial_apply(_ x: NSRuncing) {
// CHECK: bb0([[ARG:%.*]] : $NSRuncing):
// CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]]
// CHECK: [[FN:%.*]] = function_ref @_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]])
// CHECK: destroy_value [[RESULT]]
// CHECK: destroy_value [[ARG]]
_ = x.runce
// FIXME: rdar://21289579
// _ = NSRuncing.runce
}
// CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF'
// CHECK-LABEL: sil hidden @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F
func objc_protocol_composition(_ x: NSRuncing & NSFunging) {
// CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign
// CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]])
x.runce()
// CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSFunging.funge!1.foreign
// CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]])
x.funge()
}
// -- ObjC thunks get emitted for ObjC protocol conformances
class Foo : NSRuncing, NSFunging, Ansible {
// -- NSRuncing
@objc func runce() -> NSObject { return NSObject() }
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc static func mince() -> NSObject { return NSObject() }
// -- NSFunging
@objc func funge() {}
// -- Both NSRuncing and NSFunging
@objc func foo() {}
// -- Ansible
func anse() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo
// CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}}
class Bar { }
extension Bar : NSRuncing {
@objc func runce() -> NSObject { return NSObject() }
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc func foo() {}
@objc static func mince() -> NSObject { return NSObject() }
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo
// class Bas from objc_protocols_Bas module
extension Bas : NSRuncing {
// runce() implementation from the original definition of Bas
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc func foo() {}
@objc static func mince() -> NSObject { return NSObject() }
}
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo
// -- Inherited objc protocols
protocol Fungible : NSFunging { }
class Zim : Fungible {
@objc func funge() {}
@objc func foo() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo
// class Zang from objc_protocols_Bas module
extension Zang : Fungible {
// funge() implementation from the original definition of Zim
@objc func foo() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo
// -- objc protocols with property requirements in extensions
// <rdar://problem/16284574>
@objc protocol NSCounting {
var count: Int {get}
}
class StoredPropertyCount {
@objc let count = 0
}
extension StoredPropertyCount: NSCounting {}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols19StoredPropertyCountC5countSifgTo
class ComputedPropertyCount {
@objc var count: Int { return 0 }
}
extension ComputedPropertyCount: NSCounting {}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols21ComputedPropertyCountC5countSifgTo
// -- adding @objc protocol conformances to native ObjC classes should not
// emit thunks since the methods are already available to ObjC.
// Gizmo declared in Inputs/usr/include/Gizmo.h
extension Gizmo : NSFunging { }
// CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}}
@objc class InformallyFunging {
@objc func funge() {}
@objc func foo() {}
}
extension InformallyFunging: NSFunging { }
@objc protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable {
func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable {
// CHECK: bb0([[META:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int):
// CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable }
// CHECK: [[PB:%.*]] = project_box [[I2_BOX]]
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type
// CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method [volatile] $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0
// CHECK: [[I2_COPY:%.*]] = copy_value [[I2_ALLOC]]
// CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_COPY]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0
// CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable
// CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable
// CHECK: [[I2:%[0-9]+]] = load [copy] [[PB]] : $*Initializable
// CHECK: destroy_value [[I2_BOX]] : ${ var Initializable }
// CHECK: return [[I2]] : $Initializable
var i2 = im.init(int: i)
return i2
}
// CHECK: } // end sil function '_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF'
class InitializableConformer: Initializable {
@objc required init(int: Int) {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo
final class InitializableConformerByExtension {
init() {}
}
extension InitializableConformerByExtension: Initializable {
@objc convenience init(int: Int) {
self.init()
}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo
// Make sure we're crashing from trying to use materializeForSet here.
@objc protocol SelectionItem {
var time: Double { get set }
}
func incrementTime(contents: SelectionItem) {
contents.time += 1.0
}
| apache-2.0 | 3aae8e17d9d6fa73b187292f439de75a | 42.189003 | 274 | 0.645528 | 3.405962 | false | false | false | false |
h0lyalg0rithm/Appz | Appz/Appz/Apps/Mail.swift | 1 | 1166 | //
// Mail.swift
// Appz
//
// Created by Suraj Shirvankar on 12/5/15.
// Copyright © 2015 kitz. All rights reserved.
//
import Foundation
public extension AvailableApplications {
public struct Mail: ExternalApplication {
public let scheme = "mailto:"
public let fallbackURL: String? = ""
}
public func mail(action: Mail.Action) -> Bool {
return appCaller.launch(Mail(), action: action)
}
}
public struct Email {
var to: String
var subject: String
var body: String
init(to: String = "", subject: String = "", body: String = "") {
self.to = to
self.subject = subject
self.body = body
}
}
// MARK: - Actions
public extension AvailableApplications.Mail {
public enum Action {
case Compose(email: Email)
}
}
extension AvailableApplications.Mail.Action: ExternalApplicationAction {
public var path: String {
switch self {
case .Compose(let email):
return escape(String(format: "%@?subject=%@&body=%@",
email.to, email.subject, email.body))
}
}
} | mit | 833c64d1e6a4edd59a14b02a2d0c0a11 | 18.762712 | 72 | 0.581116 | 4.283088 | false | false | false | false |
src256/libswift | libswift/Classes/TextFieldCell.swift | 1 | 1038 | //
// TextFieldCell.swift
// Pods
//
// Created by sora on 2016/11/16.
//
//
import UIKit
// UITextFieldを内蔵したテーブルセル。
public class TextFieldCell: UITableViewCell {
//アウトレットの宛先をCellにしないとクラッシュする
@IBOutlet weak var valueField: UITextField!
override public func awakeFromNib() {
super.awakeFromNib()
}
override public func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
public func setTitle(_ title: String) {
valueField.placeholder = title
}
public func setValue(_ value: String) {
valueField.text = value
}
public func setSecureTextEntry(_ enabled: Bool) {
valueField.isSecureTextEntry = enabled
}
public func setValueFieldTag(_ tag: Int) {
valueField.tag = tag
}
public func setValueFieldDelegate(_ delegate: UITextFieldDelegate) {
valueField.delegate = delegate
}
}
| mit | 5ca9f42743dc2cd13082e0d766594909 | 21.045455 | 72 | 0.646392 | 4.330357 | false | false | false | false |
zhugejunwei/LeetCode | 200. Number of Islands.swift | 1 | 3528 | func numIslands(grid: [[Character]]) -> Int {
var grid = grid
if grid.isEmpty {
return 0
}
var count = 0
let row = grid.count, col = grid[0].count
for i in 0..<row {
for j in 0..<col {
if grid[i][j] == "1" {
// BFS
BFS(&grid, i, j)
// DFS
// DFS(&grid, i, j)
count += 1
}
}
}
return count
}
// MARK: BFS Solution, 244 ms
func BFS(inout grid: [[Character]], _ x: Int, _ y: Int)
{
var q = [[Int]]()
q.append([x,y])
grid[x][y] = "0"
while !q.isEmpty {
let i = q.first![0], j = q.first![1]
q.removeAtIndex(0)
if i-1 >= 0 && grid[i-1][j] == "1" {
grid[i-1][j] = "0"
q.append([i-1, j])
}
if i+1 < grid.count && grid[i+1][j] == "1" {
grid[i+1][j] = "0"
q.append([i+1, j])
}
if j-1 >= 0 && grid[i][j-1] == "1" {
grid[i][j-1] = "0"
q.append([i, j-1])
}
if j+1 < grid[0].count && grid[i][j+1] == "1" {
grid[i][j+1] = "0"
q.append([i, j+1])
}
}
}
// MARK: DFS Solution, 196 ms
func DFS(inout grid: [[Character]], _ x: Int, _ y: Int)
{
if grid[x][y] == "1" {
grid[x][y] = "0"
if x - 1 >= 0 && grid[x-1][y] == "1" {
DFS(&grid, x-1, y)
}
if y - 1 >= 0 && grid[x][y-1] == "1" {
DFS(&grid, x, y-1)
}
if x + 1 < grid.count && grid[x+1][y] == "1" {
DFS(&grid, x+1, y)
}
if y + 1 < grid[0].count && grid[x][y+1] == "1" {
DFS(&grid, x, y+1)
}
}
}
var a:[[Character]] = [["1","0"],["1","0"]]
BFS(&a, 0, 0)
/* Union Find, Java solution from "discuss", 30 ms
public class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
UF uf = new UF(grid);
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (i > 0) if (uf.connect(i, j, i - 1, j)) uf.union(i, j, i - 1, j);
if (i < grid.length - 1) if (uf.connect(i, j, i + 1, j)) uf.union(i, j, i + 1, j);
if (j > 0) if (uf.connect(i, j, i, j - 1)) uf.union(i, j, i, j - 1);
if (j < grid[0].length - 1) if (uf.connect(i, j, i, j + 1)) uf.union(i, j, i, j + 1);
}
}
return uf.count;
}
class UF {
int[] id, size;
char[][] grid;
int count;
public UF(char[][] grid) {
this.grid = grid;
int x = grid.length, y = grid[0].length;
this.id = new int[x * y];
this.size = new int[x * y];
this.count = 0;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
id[i * y + j] = i * y + j;
if (grid[i][j] == '1') {
this.count++;
this.size[i * y + j] = 1;
}
}
}
}
public boolean connect(int x1, int y1, int x2, int y2) {
return ((Math.abs(x1 - x2) == 1 || Math.abs(y1 - y2) == 1) && !(Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1) && grid[x1][y1] == '1' && grid[x2][y2] == '1');
}
public int find(int x, int y) {
int index = x * grid[0].length + y;
while (index != id[index]) index = id[index];
return index;
}
public void union(int x1, int y1, int x2, int y2) {
int index1 = find(x1, y1), index2 = find(x2, y2);
if (index1 == index2) return;
if (size[index1] > size[index2]) {
size[index1] += size[index2];
id[index2] = index1;
}
else {
size[index2] += size[index1];
id[index1] = index2;
}
count--;
}
}
}
*/
| mit | 0656938c593e1640125a067aae7bacd8 | 23.84507 | 162 | 0.435374 | 2.530846 | false | false | false | false |
pyanfield/ataturk_olympic | swift_programming_advanced_operators.playground/section-1.swift | 1 | 3616 | // Playground - noun: a place where people can play
import UIKit
// 2.24
// 不同于C语言中的数值计算,Swift的数值计算默认是不可溢出的。溢出行为会被捕获并报告为错误。
// 你可以使用Swift为你准备的另一套默认允许溢出的数值运算符,如可溢出的加号为&+。所有允许溢出的运算符都是以&开始的。
// 可定制的运算符并不限于那些预设的运算符,你可以自定义中置,前置,后置及赋值运算符,当然还有优先级和结合性。
// 按位异或运算符 ^ 比较两个数,然后返回一个数,这个数的每个位设为1的条件是两个输入数的同一位不同,如果相同就设为0。
// 你有意在溢出时对有效位进行截断,你可采用溢出运算,而非错误处理。Swfit为整型计算提供了5个&符号开头的溢出运算符。
// 溢出加法 &+
// 溢出减法 &-
// 溢出乘法 &*
// 溢出除法 &/
// 溢出求余 &%
var overFlow = UInt8.max
// overFlow += 1
overFlow = overFlow &+ 1
var x = 1
var y = x &/ 0
// 让已有的运算符也可以对自定义的类和结构进行运算,这称为运算符重载。
struct Vector2D{
var x = 0.0, y = 0.0
}
// 需要定义和实现一个中置运算的时候,不需要添加 infix 关键字
func + (letf: Vector2D, right: Vector2D) -> Vector2D{
return Vector2D(x: letf.x + right.x, y: letf.y + right.y)
}
let vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
// 实现一个前置或后置运算符时,在定义该运算符的时候于关键字func之前标注 prefix 或 postfix 属性。
prefix func - (v: Vector2D) -> Vector2D{
return Vector2D(x: -v.x, y: -v.y)
}
let positive = Vector2D(x: 3.0, y: 4.0)
let negative = -positive
// 组合赋值是其他运算符和赋值运算符一起执行的运算。如+=把加运算和赋值运算组合成一个操作。
// 实现一个组合赋值符号需要把运算符的左参数设置成 inout,因为这个参数会在运算符函数内直接修改它的值。
// 不需要 assignment 关键字
func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
var original = Vector2D(x: 1.0, y: 2.0)
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
original += vectorToAdd
// 默认的赋值符(=)是不可重载的。只有组合赋值符可以重载。三目条件运算符 a?b:c 也是不可重载。
// 自定义运算符
// 标准的运算符不够玩,那你可以声明一些个性的运算符,但个性的运算符只能使用这些字符 / = - + * % < > ! & | ^ . ~
// 新的运算符声明需在全局域使用 operator 关键字声明,然后用 prefix, infix, postfix 来标记。
prefix operator +++ {}
prefix func +++ (inout vector: Vector2D) -> Vector2D {
vector += vector
return vector
}
var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// 自定义中置运算符的优先级和结合性
// 结合性(associativity)的值默认为none,优先级(precedence)默认为100。
// 以下例子定义了一个新的中置符+-,是左结合的left,优先级为140
// 注意这里用 infix
infix operator +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
// 这个运算符把两个向量的x相加,把向量的y相减。
| mit | 0767a4f31aeb0ed8fef9e3618e2201be | 23 | 71 | 0.69184 | 2.179754 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/EditHistory/EditHistoryViewModel.swift | 1 | 8525 | // File created from ScreenTemplate
// $ createScreen.sh Room/EditHistory EditHistory
/*
Copyright 2019 New Vector Ltd
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
final class EditHistoryViewModel: EditHistoryViewModelType {
// MARK: - Constants
private enum Pagination {
static let count: UInt = 30
}
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let aggregations: MXAggregations
private let formatter: MXKEventFormatter
private let roomId: String
private let event: MXEvent
private let messageFormattingQueue: DispatchQueue
private var messages: [EditHistoryMessage] = []
private var operation: MXHTTPOperation?
private var nextBatch: String?
private var viewState: EditHistoryViewState?
// MARK: Public
weak var viewDelegate: EditHistoryViewModelViewDelegate?
weak var coordinatorDelegate: EditHistoryViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession,
formatter: MXKEventFormatter,
event: MXEvent) {
self.session = session
self.aggregations = session.aggregations
self.formatter = formatter
self.event = event
self.roomId = event.roomId
self.messageFormattingQueue = DispatchQueue(label: "\(type(of: self)).messageFormattingQueue")
}
// MARK: - Public
func process(viewAction: EditHistoryViewAction) {
switch viewAction {
case .loadMore:
self.loadMoreHistory()
case .close:
self.coordinatorDelegate?.editHistoryViewModelDidClose(self)
}
}
// MARK: - Private
private func canLoadMoreHistory() -> Bool {
guard let viewState = self.viewState else {
return true
}
let canLoadMoreHistory: Bool
switch viewState {
case .loading:
canLoadMoreHistory = false
case .loaded(sections: _, addedCount: _, allDataLoaded: let allLoaded):
canLoadMoreHistory = !allLoaded
default:
canLoadMoreHistory = true
}
return canLoadMoreHistory
}
private func loadMoreHistory() {
guard self.canLoadMoreHistory() else {
MXLog.debug("[EditHistoryViewModel] loadMoreHistory: pending loading or all data loaded")
return
}
guard self.operation == nil else {
MXLog.debug("[EditHistoryViewModel] loadMoreHistory: operation already pending")
return
}
self.update(viewState: .loading)
self.operation = self.aggregations.replaceEvents(forEvent: self.event.eventId, isEncrypted: self.event.isEncrypted, inRoom: self.roomId, from: self.nextBatch, limit: Int(Pagination.count), success: { [weak self] (response) in
guard let sself = self else {
return
}
sself.nextBatch = response.nextBatch
sself.operation = nil
sself.process(editEvents: response.chunk, originalEvent: response.originalEvent, nextBatch: response.nextBatch)
}, failure: { [weak self] error in
guard let sself = self else {
return
}
sself.operation = nil
sself.update(viewState: .error(error))
})
}
private func process(editEvents: [MXEvent], originalEvent: MXEvent?, nextBatch: String?) {
self.messageFormattingQueue.async {
var newMessages: [EditHistoryMessage] = []
let editsMessages = editEvents.reversed()
.compactMap { (editEvent) -> EditHistoryMessage? in
return self.process(editEvent: editEvent)
}
newMessages.append(contentsOf: editsMessages)
if nextBatch == nil, let originalEvent = originalEvent, let originalEventMessage = self.process(event: originalEvent, ts: originalEvent.originServerTs) {
newMessages.append(originalEventMessage)
}
let addedCount: Int
if newMessages.count > 0 {
self.messages.append(contentsOf: newMessages)
addedCount = newMessages.count
} else {
addedCount = 0
}
let allDataLoaded = nextBatch == nil
let editHistorySections = self.editHistorySections(from: self.messages)
DispatchQueue.main.async {
self.update(viewState: .loaded(sections: editHistorySections, addedCount: addedCount, allDataLoaded: allDataLoaded))
}
}
}
private func process(originalEvent: MXEvent) {
self.messageFormattingQueue.async {
var addedCount = 0
if let newMessage = self.process(event: originalEvent, ts: originalEvent.originServerTs) {
addedCount = 1
self.messages.append(newMessage)
}
let editHistorySections = self.editHistorySections(from: self.messages)
DispatchQueue.main.async {
self.update(viewState: .loaded(sections: editHistorySections, addedCount: addedCount, allDataLoaded: true))
}
}
}
private func editHistorySections(from editHistoryMessages: [EditHistoryMessage]) -> [EditHistorySection] {
// Group edit messages by day
let initial: [Date: [EditHistoryMessage]] = [:]
let dateComponents: Set<Calendar.Component> = [.day, .month, .year]
let calendar = Calendar.current
let messagesGroupedByDay = editHistoryMessages.reduce(into: initial) { messagesByDay, message in
let components = calendar.dateComponents(dateComponents, from: message.date)
if let date = calendar.date(from: components) {
var messages = messagesByDay[date] ?? []
messages.append(message)
messagesByDay[date] = messages
}
}
// Create edit sections
var sections: [EditHistorySection] = []
for (date, messages) in messagesGroupedByDay {
// Sort messages descending (most recent first)
let sortedMessages = messages.sorted { $0.date.compare($1.date) == .orderedDescending }
let section = EditHistorySection(date: date, messages: sortedMessages)
sections.append(section)
}
// Sort sections descending (most recent first)
let sortedSections = sections.sorted { $0.date.compare($1.date) == .orderedDescending }
return sortedSections
}
private func process(editEvent: MXEvent) -> EditHistoryMessage? {
// Create a temporary MXEvent that represents this edition
guard let editedEvent = self.event.editedEvent(fromReplacementEvent: editEvent) else {
MXLog.debug("[EditHistoryViewModel] processEditEvent: Cannot build edited event: \(editEvent.eventId ?? "")")
return nil
}
return self.process(event: editedEvent, ts: editEvent.originServerTs)
}
private func process(event: MXEvent, ts: UInt64) -> EditHistoryMessage? {
let formatterError = UnsafeMutablePointer<MXKEventFormatterError>.allocate(capacity: 1)
guard let message = self.formatter.attributedString(from: event, with: nil, error: formatterError) else {
MXLog.debug("[EditHistoryViewModel] processEditEvent: cannot format(error: \(formatterError)) event: \(event.eventId ?? "")")
return nil
}
let date = Date(timeIntervalSince1970: TimeInterval(ts) / 1000)
return EditHistoryMessage(date: date, message: message)
}
private func update(viewState: EditHistoryViewState) {
self.viewState = viewState
self.viewDelegate?.editHistoryViewModel(self, didUpdateViewState: viewState)
}
}
| apache-2.0 | 3810268579195886ab98e434e7c85ac6 | 34.669456 | 233 | 0.631906 | 5.080453 | false | false | false | false |
oceanfive/swift | swift_two/swift_two/Classes/Tools/Global.swift | 1 | 2705 | //
// Global.swift
// weibo_swift
//
// Created by ocean on 16/6/17.
// Copyright © 2016年 ocean. All rights reserved.
//
import UIKit
//MARK: - 屏幕尺寸
let kScreenW = UIScreen.mainScreen().bounds.size.width
let kScreenH = UIScreen.mainScreen().bounds.size.height
//MARK: - 沙盒保存用户的文件名称
let kUserAccountName = "account.plist"
//MARK: - OAuth授权登录
let oauthURLString = "https://api.weibo.com/oauth2/authorize"
let redirect_uri = "http://weibo.com/u/3216382533/home?wvr=5"
let accessTokenURLString = "https://api.weibo.com/oauth2/access_token"
let client_id = "4017753567"
let client_secret = "528d174ef961f18dfe3acce2be8b1e69"
let grant_type = "authorization_code"
//MARK: - 微博相关接口
//获取当前登录用户及其所关注(授权)用户的最新微博
let kHome_timelineString = "https://api.weibo.com/2/statuses/home_timeline.json"
//MARK: - 微博cell相关属性设置
//原创微博nameLabel
let kHomeCellNameLableFont = UIFont.systemFontOfSize(14.0)
let kHomeCellNameLableColorVip = UIColor.orangeColor()
let kHomeCellNameLableColorNormal = UIColor.blackColor()
//原创微博timeLable
let kHomeCellTimeLableFont = UIFont.systemFontOfSize(11.0)
let kHomeCellTimeLableColor = UIColor.orangeColor()
//原创微博sourceLabel
let kHomeCellSourceLabelFont = UIFont.systemFontOfSize(11.0)
let kHomeCellSourceLabelColor = UIColor.blackColor()
//原创微博text
let kHomeCellTextLabelFont = UIFont.systemFontOfSize(14.0)
let kHomeCellTextLabelColor = UIColor.blackColor()
//转发微博name
let kHomeCellRetweetedNameLabelFont = UIFont.systemFontOfSize(12.0)
let kHomeCellRetweetedNameLabelColor = UIColor.blueColor()
//转发微博text
let kHomeCellRetweetedTextLabelFont = UIFont.systemFontOfSize(12.0)
let kHomeCellRetweetedTextLabelColor = UIColor.blackColor()
//toolbar
let kHomeCellToolBarFont = UIFont.systemFontOfSize(12.0)
let kHomeCellToolBarColor = UIColor.blackColor()
//MARK: - tabBar属性
let kTabBarTtitleFont = UIFont.systemFontOfSize(12.0)
let kTabBarTintColor = UIColor.orangeColor()
//MARK: - navigationBar 和 左右item不同状态下的 的属性
let kNaviBarTitleFont = UIFont.systemFontOfSize(20.0)
let kNaviBarTitleColor = UIColor.blackColor()
let kNaviItemTitleFontOfNormal = UIFont.systemFontOfSize(15.0)
let kNaviItemTitleColorOfNormal = UIColor.orangeColor()
let kNaviItemTitleFontOfHighlighted = UIFont.systemFontOfSize(15.0)
let kNaviItemTitleColorOfHighlighted = UIColor.redColor()
//MARK: - cell的重用标示符
//主页
let kHomeTableCellIdentifier = "homeTableCellIdentifier"
//MARK: - 第三方登录信息
/*
App Key
14084daaa97b6
App Secret
eb42509eea896a142ba669eb0b071929
*/
| mit | cf2f1bf0f30d944d5bce79ed213c99ff | 24.070707 | 80 | 0.794521 | 3.418733 | false | false | false | false |
abunur/quran-ios | Quran/DefaultAyahInfoRetriever.swift | 1 | 3699 | //
// DefaultAyahInfoPersistence.swift
// Quran
//
// Created by Mohamed Afifi on 4/22/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import PromiseKit
struct DefaultAyahInfoRetriever: AyahInfoRetriever {
let persistence: AyahInfoPersistence
func retrieveAyahs(in page: Int) -> Promise<[AyahNumber: [AyahInfo]]> {
return DispatchQueue.default
.promise2 { try self.persistence.getAyahInfoForPage(page) }
.then { self.processAyahInfo($0) }
}
private func processAyahInfo(_ info: [AyahNumber: [AyahInfo]]) -> [AyahNumber: [AyahInfo]] {
// group by line
var groupedLines = info.flatMap { $0.value }.group { $0.line }
let groupedLinesKeys = groupedLines.keys.sorted()
// sort each line from left to right
for i in 0..<groupedLinesKeys.count {
let key = groupedLinesKeys[i]
let value = groupedLines[key]!
groupedLines[key] = value.sorted { (info1, info2) in
guard info1.ayah.sura == info2.ayah.sura else {
return info1.ayah.sura < info2.ayah.sura
}
guard info1.ayah.ayah == info2.ayah.ayah else {
return info1.ayah.ayah < info2.ayah.ayah
}
return info1.position < info2.position
}
}
// align vertically each line
for i in 0..<groupedLinesKeys.count {
let key = groupedLinesKeys[i]
let list = groupedLines[key]!
groupedLines[key] = AyahInfo.alignedVertically(list)
}
// union each line with its neighbors
for i in 0..<groupedLinesKeys.count - 1 {
let keyTop = groupedLinesKeys[i]
let keyBottom = groupedLinesKeys[i + 1]
var listTop = groupedLines[keyTop]!
var listBottom = groupedLines[keyBottom]!
AyahInfo.unionVertically(top: &listTop, bottom: &listBottom)
groupedLines[keyTop] = listTop
groupedLines[keyBottom] = listBottom
}
// union each position with its neighbors
for i in 0..<groupedLinesKeys.count {
let key = groupedLinesKeys[i]
var list = groupedLines[key]!
for j in 0..<list.count - 1 {
var first = list[j]
var second = list[j + 1]
first.unionHorizontally(left: &second)
list[j] = first
list[j + 1] = second
}
groupedLines[key] = list
}
// align the edges
var firstEdge = groupedLines.map { $0.value[0] }
var lastEdge = groupedLines.map { $0.value[$0.value.count - 1] }
AyahInfo.unionLeftEdge(&lastEdge)
AyahInfo.unionRightEdge(&firstEdge)
for i in 0..<groupedLinesKeys.count {
let key = groupedLinesKeys[i]
var list = groupedLines[key]!
list[0] = firstEdge[i]
list[list.count - 1] = lastEdge[i]
groupedLines[key] = list
}
return groupedLines.flatMap { $0.value }.group { $0.ayah }
}
}
| gpl-3.0 | 6b8383ea2291803299a7b08c59fb342f | 35.264706 | 96 | 0.591782 | 4.15618 | false | false | false | false |
gerryisaac/iPhone-CTA-Bus-Tracker-App | Bus Tracker/patternDisplayViewController.swift | 1 | 15435 | //
// patternDisplayViewController.swift
// Bus Tracker
//
// Created by Gerard Isaac on 10/28/14.
// Copyright (c) 2014 Gerard Isaac. All rights reserved.
//
import UIKit
class patternDisplayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "cellIdentifier"
var patternRequestNumber:NSString = "0"
var pID:NSString? = NSString()
var textField:UITextView = UITextView()
let patternTable: UITableView = UITableView(frame: CGRectMake(0, 128, 320, UIScreen.mainScreen().bounds.size.height - 128))
//Header Components
var pLength:NSString = "Loading..."
var rtDir:NSString = "Loading..."
//Header Labels
var pIDDisplay: UILabel = UILabel()
var pLengthDisplay: UILabel = UILabel()
var rtDirDisplay: UILabel = UILabel()
//Pattern Table Data Variables
var patterns: NSArray = []
var patternData: NSMutableArray = []
var patternCount: Int = 0
//var routeValue: NSString = "0"
//var routeNumber: NSString? = "0"
var tagValue:Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//println("Pattern View for \(patternRequestNumber) Controller Loaded")
self.view.backgroundColor = UIColor.redColor()
//Create Background Image
let bgImage = UIImage(named:"bg-MainI5.png")
var bgImageView = UIImageView(frame: CGRectMake(0, 0, screenDimensions.screenWidth, screenDimensions.screenHeight))
bgImageView.image = bgImage
bgImageView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
self.view.addSubview(bgImageView)
//Create Pattern Header
let headerImage = UIImage(named:"header-Pattern.png")
var headerImageView = UIImageView(frame: CGRectMake(0, 64, screenDimensions.screenWidth, 64))
headerImageView.image = headerImage
//Create Header Labels
pIDDisplay.frame = CGRectMake(4, 29, 97, 25)
pIDDisplay.font = UIFont(name: "HelveticaNeue-CondensedBold", size:15)
pIDDisplay.textColor = UIColor.whiteColor()
pIDDisplay.textAlignment = NSTextAlignment.Center
pIDDisplay.text = pID
headerImageView.addSubview(pIDDisplay)
pLengthDisplay.frame = CGRectMake(109, 29, 97, 25)
pLengthDisplay.font = UIFont(name: "HelveticaNeue-CondensedBold", size:15)
pLengthDisplay.textColor = UIColor.whiteColor()
pLengthDisplay.textAlignment = NSTextAlignment.Center
pLengthDisplay.text = pLength.uppercaseString
headerImageView.addSubview(pLengthDisplay)
rtDirDisplay.frame = CGRectMake(213, 29, 103, 25)
rtDirDisplay.font = UIFont(name: "HelveticaNeue-CondensedBold", size:15)
rtDirDisplay.textColor = UIColor.whiteColor()
rtDirDisplay.textAlignment = NSTextAlignment.Center
rtDirDisplay.text = rtDir.uppercaseString
headerImageView.addSubview(rtDirDisplay)
self.view.addSubview(headerImageView)
populatePatterns()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Retrieve Waypoints and Stops for this Route
func populatePatterns(){
//Create Spinner
var spinner:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
spinner.frame = CGRectMake(screenDimensions.screenWidth/2 - 25, screenDimensions.screenHeight/2 - 25, 50, 50);
spinner.transform = CGAffineTransformMakeScale(1.5, 1.5);
//spinner.backgroundColor = [UIColor blackColor];
self.view.addSubview(spinner);
spinner.startAnimating()
//Load Bus Tracker Data
let feedURL:NSString = "http://www.ctabustracker.com/bustime/api/v1/getpatterns?key=\(yourCTAkey.keyValue)&rt=\(patternRequestNumber)"
//println("Feed URL is \(feedURL)")
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer = AFHTTPResponseSerializer()
let contentType:NSSet = NSSet(object: "text/xml")
manager.responseSerializer.acceptableContentTypes = contentType
manager.GET(feedURL,
parameters: nil,
success: {
(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
//println("Success")
var responseData:NSData = responseObject as NSData
//var responseString = NSString(data: responseData, encoding:NSASCIIStringEncoding)
//println(responseString)
var rxml:RXMLElement = RXMLElement.elementFromXMLData(responseData) as RXMLElement
var mainXML:RXMLElement = rxml.child("*")
var checker:NSString = NSString(string: mainXML.tag)
/*Pattern Checker*/
if checker.isEqualToString("error") {
//Show Error
//Create Background Image
let bgImage = UIImage(named:"patternsCellNoticeBgI5.png")
var bgImageView = UIImageView(frame: CGRectMake(0, 0, screenDimensions.screenWidth, screenDimensions.screenHeight))
bgImageView.image = bgImage
self.view.addSubview(bgImageView)
self.textField = UITextView(frame:CGRectMake(0, screenDimensions.screenHeight/2 + 50, screenDimensions.screenWidth, 100))
self.textField.editable = false
self.textField.font = UIFont(name: "Gotham-Bold", size:18)
self.textField.textColor = UIColor.whiteColor()
self.textField.backgroundColor = UIColor.clearColor()
self.textField.scrollEnabled = true;
self.textField.text = NSString(string: mainXML.child("msg").text)
self.view.addSubview(self.textField)
} else {
//println("Start Patterns")
//Search Array and Look for the ID that matches Selection
let searchString:NSString = "//ptr[pid="+self.pID!+"]"
rxml.iterateWithRootXPath(searchString, usingBlock: { appElement -> Void in
//println("Found")
//PTR
var patternID:RXMLElement = appElement.child("pid")
var patternLength:RXMLElement = appElement.child("ln")
var patternDirection:RXMLElement = appElement.child("rtdir")
self.pIDDisplay.text = patternID.text
self.pLengthDisplay.text = patternLength.text
self.rtDirDisplay.text = patternDirection.text.uppercaseString
self.patterns = appElement.children("pt")
self.patternData.addObjectsFromArray(self.patterns)
self.patternCount = self.patternData.count
//Create Pattern Entries
self.patternTable.backgroundColor = UIColor.clearColor()
self.patternTable.dataSource = self
self.patternTable.delegate = self
self.patternTable.separatorInset = UIEdgeInsetsZero
self.patternTable.layoutMargins = UIEdgeInsetsZero
// Register the UITableViewCell class with the tableView
self.patternTable.registerClass(PatternCell.self, forCellReuseIdentifier: self.cellIdentifier)
//self.patternTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
//Add the Table View
self.view.addSubview(self.patternTable)
})
}
spinner.stopAnimating()
},
failure: {
(operation: AFHTTPRequestOperation!, error: NSError!) in
var alertView = UIAlertView(title: "Error Retrieving Data", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
alertView.show()
println(error)
})
}
//Table View Configuration
// Table Delegates and Data Source
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, shouldIndentWhileEditing indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return self.patternCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var appElement:RXMLElement = patternData.objectAtIndex(indexPath.row) as RXMLElement
var stopType:NSString? = appElement.child("typ").text
var dist:NSString?
var stopID:NSString?
var stopName:NSString?
var latValue:NSString? = appElement.child("lat").text
var longValue:NSString? = appElement.child("lon").text
var seq:NSString? = appElement.child("seq").text
var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as PatternCell
var checker:NSString = NSString(string:stopType!)
/*Value Checker*/
if checker.isEqualToString("W") {
cell.cellBgImageViewColor.hidden = true
cell.cellBgImageViewBW.hidden = false
cell.cellstopType = "Waypoint"
cell.cellstopTypeLabel.text = "ROUTE WAYPOINT"
cell.cellstopID = "NONE"
cell.cellstopIDLabel.text = "NONE"
cell.cellstopName = "Bus Waypoint Only"
cell.cellstopNameLabel.text = "Bus Waypoint Only"
cell.iconWaypoint.hidden = false
cell.iconBusStop.hidden = true
cell.cellLatLabel.text = latValue!
cell.cellLongLabel.text = longValue!
cell.cellseqLabel.text = seq!
cell.celldistLabel.text = "NONE"
cell.timeButton.enabled = false
cell.newsButton.enabled = false
} else {
stopID = appElement.child("stpid").text
stopName = appElement.child("stpnm").text
dist = appElement.child("pdist").text
cell.cellBgImageViewColor.hidden = false
cell.cellBgImageViewBW.hidden = true
cell.cellstopType = "BUS STOP"
cell.cellstopTypeLabel.text = "BUS STOP"
cell.cellstopID = stopID!
cell.cellstopIDLabel.text = stopID!
cell.cellstopName = stopName!
cell.cellstopNameLabel.text = stopName!
cell.cellLatLabel.text = latValue!
cell.cellLongLabel.text = longValue!
cell.cellseqLabel.text = seq!
cell.celldistLabel.text = dist!
cell.iconWaypoint.hidden = true
cell.iconBusStop.hidden = false
//Add Time Button Tag
//Extract Integer Value of Stop ID and Assign as Tags to Buttons
self.tagValue = NSString(string: stopID!).integerValue
//println(self.tagValue)
cell.timeButton.tag = self.tagValue!
cell.newsButton.tag = self.tagValue!
cell.timeButton.enabled = true
cell.newsButton.enabled = true
cell.timeButton.addTarget(self, action: "timebuttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
cell.newsButton.addTarget(self, action: "newsbuttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
}
return cell
}
//Remove Table Insets and Margins
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset.left = CGFloat(0.0)
}
if tableView.respondsToSelector("setLayoutMargins:") {
tableView.layoutMargins = UIEdgeInsetsZero
}
if cell.respondsToSelector("setLayoutMargins:") {
cell.layoutMargins.left = CGFloat(0.0)
}
}
func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat {
tableView.separatorColor = UIColor.whiteColor()
return 200
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// UITableViewDelegate methods
//Double check didSelectRowAtIndexPath VS didDeselectRowAtIndexPath
//func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { }
//Time Button Action
func timebuttonAction(sender:UIButton!) {
//println("Time Button tapped")
//Cast Self and Get Tag Number
let button:UIButton = sender
//println(button.tag)
//Display Predictions for Selected Stop in this Route
var displayPredictions:predictionDisplayViewController = predictionDisplayViewController()
displayPredictions.stopNumber = String(button.tag)
displayPredictions.routeNumber = self.patternRequestNumber
displayPredictions.title = NSString(string:"Route: \(self.patternRequestNumber) Stop: \(button.tag)")
self.navigationController?.pushViewController(displayPredictions, animated: true)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
}
//News Button Action
func newsbuttonAction(sender:UIButton!) {
//println("News Button tapped")
//Cast Self and Get Tag Number
let button:UIButton = sender
//println(button.tag)
//Display Bulletins for Selected Stop in this Route
var displayBulletins:bulletinDisplayViewController = bulletinDisplayViewController()
displayBulletins.stopNumber = String(button.tag)
displayBulletins.routeNumber = self.patternRequestNumber
displayBulletins.title = NSString(string:"Route: \(self.patternRequestNumber) Stop: \(button.tag)")
self.navigationController?.pushViewController(displayBulletins, animated: true)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
}
}
| mit | c3dab2ef3b381c34bdc89c3ef014ca27 | 40.716216 | 152 | 0.606284 | 5.548167 | false | false | false | false |
feighter09/Cloud9 | SoundCloud Pro/StreamCell.swift | 1 | 4447 | //
// StreamCell.swift
// SoundCloud Pro
//
// Created by Austin Feight on 7/11/15.
// Copyright © 2015 Lost in Flight. All rights reserved.
//
import UIKit
import Bond
let kStreamCellPlaybackControlsHeight: CGFloat = 32
let kStreamCellPlaybackControlsMargin: CGFloat = 4
let kStreamCellVoteControlsWidth: CGFloat = 40
protocol StreamCellDelegate: NSObjectProtocol {
func streamCell(streamCell: StreamCell, didTapAddToPlaylist track: Track)
}
class StreamCell: UITableViewCell {
var track: Track! {
didSet {
assert(track != nil, "Cannot set Track to nil")
updateLabelsAndButtons()
}
}
var playsOnSelection = true
weak var delegate: StreamCellDelegate?
var listenerId = 0
private var playState: PlayState = .Stopped {
didSet { playingLabel.text = playState != .Stopped ? "[\(playState.rawValue)]" : "" }
}
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var artistLabel: UILabel!
@IBOutlet private weak var playingLabel: UILabel!
@IBOutlet private weak var upVoteButton: UIButton!
@IBOutlet private weak var downVoteButton: UIButton!
@IBOutlet private weak var addToPlaylistButton: UIButton!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
AudioPlayer.sharedPlayer.addListener(self)
}
deinit
{
AudioPlayer.sharedPlayer.removeListener(self)
UserPreferences.listeners.removeListener(self)
}
}
// MARK: - Life Cycle
extension StreamCell {
static var nib: UINib { return UINib(nibName: "StreamCell", bundle: nil) }
override func awakeFromNib()
{
super.awakeFromNib()
setColors()
UserPreferences.listeners.addListener(self)
}
override func prepareForReuse()
{
playState = .Stopped
}
private func setColors()
{
backgroundColor = .backgroundColor
titleLabel.textColor = .primaryColor
artistLabel.textColor = .secondaryColor
playingLabel.textColor = .primaryColor
addToPlaylistButton.tintColor = .secondaryColor
}
}
// MARK: - UI Action
extension StreamCell {
@IBAction func upVoteTapped(sender: AnyObject)
{
UserPreferences.toggleUpvote(track)
}
@IBAction func downVoteTapped(sender: AnyObject)
{
UserPreferences.toggleDownvote(track)
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
if !selected { return }
if !trackIsCurrentlyPlaying && playsOnSelection {
AudioPlayer.sharedPlayer.play(track, clearingPlaylist: true)
}
setSelected(false, animated: animated)
}
@IBAction func addToPlaylist(sender: AnyObject)
{
delegate?.streamCell(self, didTapAddToPlaylist: track)
}
}
// MARK: - Audio Playing Listener
extension StreamCell: AudioPlayerListener {
func audioPlayer(audioPlayer: AudioPlayer, didBeginBufferingTrack track: Track)
{
updatePlayStateWithTrack(track)
}
func audioPlayer(audioPlayer: AudioPlayer, didBeginPlayingTrack track: Track)
{
updatePlayStateWithTrack(track)
}
func audioPlayer(audioPlayer: AudioPlayer, didPauseTrack track: Track)
{
updatePlayStateWithTrack(track)
}
func audioPlayer(audioPlayer: AudioPlayer, didStopTrack track: Track)
{
updatePlayStateWithTrack(track)
}
private func updatePlayStateWithTrack(track: Track)
{
if track == self.track { playState = AudioPlayer.sharedPlayer.playState }
else { playState = .Stopped }
}
}
// MARK: - Music Player Listener
extension StreamCell: Listener, UserPreferencesListener {
func upvoteStatusChangedForTrack(track: Track, upvoted: Bool)
{
if track == self.track { upVoteButton.selected = upvoted }
}
}
// MARK: - Helpers
extension StreamCell {
private var trackIsCurrentlyPlaying: Bool
{
return AudioPlayer.sharedPlayer.currentTrack == track && AudioPlayer.sharedPlayer.isPlaying
}
private func updateLabelsAndButtons()
{
titleLabel.text = track.title
artistLabel.text = track.artist
if let currentTrack = AudioPlayer.sharedPlayer.currentTrack where track == currentTrack {
playState = AudioPlayer.sharedPlayer.playState
} else {
playState = .Stopped
}
upVoteButton.selected = UserPreferences.upvotes.contains(track)
downVoteButton.selected = UserPreferences.downvotes.contains(track)
layoutIfNeeded() // makes sure title and artist labels resize to fit text
}
}
| lgpl-3.0 | 0b84f17d6439529d345f96aca366375d | 23.977528 | 95 | 0.721997 | 4.358824 | false | false | false | false |
mownier/pyrobase | Pyrobase/Request.swift | 1 | 4291 | //
// Request.swift
// Pyrobase
//
// Created by Mounir Ybanez on 02/05/2017.
// Copyright © 2017 Ner. All rights reserved.
//
public protocol RequestProtocol {
func read(path: String, query: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void)
func write(path: String, method: RequestMethod, data: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void)
func delete(path: String, completion: @escaping (RequestResult) -> Void)
}
public class Request: RequestProtocol {
internal var session: URLSession
internal var operation: RequestOperation
internal var response: RequestResponseProtocol
public init(session: URLSession, operation: RequestOperation, response: RequestResponseProtocol) {
self.session = session
self.operation = operation
self.response = response
}
public func read(path: String, query: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) {
request(path, .get, query, completion)
}
public func write(path: String, method: RequestMethod, data: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) {
request(path, method, data, completion)
}
public func delete(path: String, completion: @escaping (RequestResult) -> Void) {
request(path, .delete, [:], completion)
}
internal func request(_ path: String, _ method: RequestMethod, _ data: [AnyHashable: Any], _ completion: @escaping (RequestResult) -> Void) {
guard let url = buildURL(path, method, data) else {
completion(.failed(RequestError.invalidURL))
return
}
let request = operation.build(url: url, method: method, data: data)
let task = session.dataTask(with: request) { data, response, error in
guard error == nil else {
completion(.failed(error!))
return
}
guard response != nil else {
completion(.failed(RequestError.noURLResponse))
return
}
let error = self.response.isErroneous(response as? HTTPURLResponse, data: data)
guard error == nil else {
completion(.failed(error!))
return
}
guard data != nil else {
completion(.succeeded([:]))
return
}
let result = self.operation.parse(data: data!)
switch result {
case .error(let info):
completion(.failed(info))
case .okay(let info):
guard let okayInfo = info as? String, okayInfo.lowercased() == "null", method != .delete else {
completion(.succeeded(info))
return
}
completion(.failed(RequestError.nullJSON))
}
}
task.resume()
}
internal func buildURL(_ path: String, _ method: RequestMethod, _ data: [AnyHashable: Any]) -> URL? {
switch method {
case .get where !data.isEmpty:
guard !path.isEmpty, var components = URLComponents(string: path) else {
return nil
}
var queryItems = [URLQueryItem]()
for (key, value) in data {
let item = URLQueryItem(name: "\(key)", value: "\(value)")
queryItems.insert(item, at: 0)
}
if components.queryItems != nil {
components.queryItems!.append(contentsOf: queryItems)
} else {
components.queryItems = queryItems
}
return components.url
default:
return URL(string: path)
}
}
}
extension Request {
public class func create() -> Request {
let session = URLSession.shared
let operation = JSONRequestOperation.create()
let response = RequestResponse()
let request = Request(session: session, operation: operation, response: response)
return request
}
}
| mit | 9ef16f96297359e2bdf721b9abcfe84a | 33.047619 | 145 | 0.548252 | 5.15006 | false | false | false | false |
eocleo/AlbumCore | AlbumDemo/AlbumDemo/AlbumViews/extension/UIViewController+extension.swift | 1 | 2384 | //
// UIViewController+extension.swift
// AlbumDemo
//
// Created by leo on 2017/8/23.
// Copyright © 2017年 leo. All rights reserved.
//
import UIKit
extension UIViewController {
open func createNavButton(image: UIImage?, title: String?) -> UIButton {
let button = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 44.0))
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.setImage(image, for: .normal)
button.setTitle(title, for: .normal)
button.contentHorizontalAlignment = .left
return button
}
open func addRightNav(button: UIButton) -> Void {
let barButtonItem = UIBarButtonItem.init(customView: button)
self.navigationItem.setRightBarButton(barButtonItem, animated: true)
}
open func addLeftNav(button: UIButton) -> Void {
let barButtonItem = UIBarButtonItem.init(customView: button)
self.navigationItem.setLeftBarButton(barButtonItem, animated: true)
}
open func addLeftNavButton(image: UIImage?, title: String?, sel: Selector) -> Void {
let button = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 44.0))
button.setTitleColor(UIColor.white, for: .normal)
button.setImage(image, for: .normal)
button.setTitle(title, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.contentHorizontalAlignment = .left
button.addTarget(self, action: sel, for: .touchUpInside)
let barItem = UIBarButtonItem.init(customView: button)
self.navigationItem.setLeftBarButton(barItem, animated: true)
}
open func addRightNavButton(image: UIImage?, title: String?, sel: Selector) -> Void {
let button = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 44.0))
button.setTitleColor(UIColor.white, for: .normal)
button.setImage(image, for: .normal)
button.setTitle(title, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.contentHorizontalAlignment = .right
button.addTarget(self, action: sel, for: .touchUpInside)
let barItem = UIBarButtonItem.init(customView: button)
self.navigationItem.setRightBarButton(barItem, animated: true)
}
}
| mit | 427d44b793420e4f0b7e6dc0dad03e8f | 41.517857 | 92 | 0.671987 | 4.214159 | false | false | false | false |
cpoutfitters/cpoutfitters | CPOutfitters/SignupViewController.swift | 1 | 4497 | //
// SignupViewController.swift
// CPOutfitters
//
// Created by Aditya Purandare on 19/04/16.
// Copyright © 2016 SnazzyLLama. All rights reserved.
//
import UIKit
import Parse
class SignupViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var fullnameTextField: UITextField!
@IBOutlet weak var genderControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
genderControl.layer.cornerRadius = 4
}
@IBAction func onSignup(sender: AnyObject) {
let email = emailTextField.text
let password = passwordTextField.text
let fullname = fullnameTextField.text
var genders = ["Male", "Female"]
let userGender = genders[genderControl.selectedSegmentIndex]
let finalEmail = email!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString
// Validate the text fields
if (email!.characters.count < 5) {
let alert = UIAlertController(title: "Email Invalid", message: "Please enter a valid email address", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
} else if (password!.characters.count < 8) {
let alert = UIAlertController(title: "Password too short", message: "Password must be at least 8 characters", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
spinner.startAnimating()
let newUser = PFUser()
newUser.username = finalEmail
newUser.email = finalEmail
newUser.password = password
newUser["gender"] = userGender
if fullname != "" {
newUser["fullname"] = fullname
}
emailTextField.enabled = false
passwordTextField.enabled = false
// Sign up the user asynchronously
newUser.signUpInBackgroundWithBlock({ (succeed, error: NSError?) -> Void in
// Stop the spinner
spinner.stopAnimating()
self.emailTextField.enabled = true
self.passwordTextField.enabled = true
if let error = error {
var message: String
switch error.code {
case 125: message = "Please enter a valid email"
case 202, 203: message = "Email is already registered"
default: message = "Unknown error occurred"
}
let alert = UIAlertController(title: "Signup error", message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
NSNotificationCenter.defaultCenter().postNotificationName(userDidLoginNotification, object: nil)
}
})
}
}
@IBAction func onCancel(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dismissKeyboard() {
view.endEditing(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.
}
*/
}
| apache-2.0 | b62be7d44ce4fd302d195703780683b3 | 39.504505 | 145 | 0.61677 | 5.585093 | false | false | false | false |
FredrikSjoberg/SnapStack | SnapStack/Contexts/SnapStack.swift | 1 | 3954 | //
// SnapStack.swift
// SnapStack
//
// Created by Fredrik Sjöberg on 2015-09-18.
// Copyright © 2015 Fredrik Sjoberg. All rights reserved.
//
import Foundation
import CoreData
public class SnapStack : NSManagedObjectContext {
private var storeOptions: StoreOptions
private var rootSavingsContext: NSManagedObjectContext
private var inMemoryStore: NSPersistentStore?
// LoggingType
public var logger: LogProcessorType?
public required init(storeOptions: StoreOptions) throws {
self.storeOptions = storeOptions
// root context
rootSavingsContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
rootSavingsContext.name = "RootContext"
super.init(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
name = "SnapStackContext"
try configureStore()
}
private func configureStore() throws {
// managed object model
guard
let managedObjectModel = NSManagedObjectModel(contentsOfURL: storeOptions.managedObjectModelURL)
else {
throw SnapStackError.InvalidModel
}
// persistent store coordinator
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
// persistent store
let store = try coordinator.addPersistentStoreWithType(storeOptions.storeType.type, configuration: storeOptions.configuration, URL: storeOptions.storeType.url, options: storeOptions.options)
rootSavingsContext.persistentStoreCoordinator = coordinator
// Keep track of in-memory store
switch storeOptions.storeType {
case .InMemory: inMemoryStore = store
default: break
}
}
private func currentStore() throws -> NSPersistentStore {
guard let coordinator = persistentStoreCoordinator else {
throw SnapStackError.NoPersistentStoreCoordinator
}
switch storeOptions.storeType {
case .SQLite(let url):
guard let store = coordinator.persistentStoreForURL(url) else { throw SnapStackError.NoPersistentStore }
return store
case .InMemory:
guard let store = inMemoryStore else { throw SnapStackError.NoPersistentStore }
return store
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - CommitType
extension SnapStack : CommitType { }
// MARK: - SnapStackType
extension SnapStack : SnapStackType {
public var options: StoreOptions {
return storeOptions
}
public var mainContext: NSManagedObjectContext {
return self
}
public var rootContext: NSManagedObjectContext {
return rootSavingsContext
}
public func migrateTo(storeType: StoreType) throws -> NSPersistentStore {
let newOptions = StoreOptions(oldOptions: storeOptions, newStoreType: storeType)
guard let coordinator = persistentStoreCoordinator else {
throw SnapStackError.NoPersistentStoreCoordinator
}
let oldStore = try currentStore()
var newStore: NSPersistentStore? = nil
switch storeType {
case .SQLite(let value):
newStore = try coordinator.migratePersistentStore(oldStore, toURL: value, options: newOptions.options, withType: storeType.type)
default:
throw SnapStackError.MigrationToInMemoryStoreNotAllowed
}
// Reference no longer needed
switch storeOptions.storeType {
case .InMemory: inMemoryStore = nil
default: break
}
storeOptions = newOptions
return newStore!
}
}
// MARK: - LoggingType
extension SnapStack : LoggingType { } | mit | a4b8134feba1b24bd31ce0a54524794f | 31.401639 | 198 | 0.664221 | 5.760933 | false | false | false | false |
dduan/swift | test/1_stdlib/Runtime.swift | 1 | 43054 | // RUN: rm -rf %t && mkdir %t
//
// RUN: %target-build-swift -parse-stdlib -module-name a %s -o %t.out
// RUN: %target-run %t.out
// REQUIRES: executable_test
import Swift
import StdlibUnittest
import SwiftShims
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
#if _runtime(_ObjC)
import ObjectiveC
#endif
var swiftObjectCanaryCount = 0
class SwiftObjectCanary {
init() {
swiftObjectCanaryCount += 1
}
deinit {
swiftObjectCanaryCount -= 1
}
}
struct SwiftObjectCanaryStruct {
var ref = SwiftObjectCanary()
}
var Runtime = TestSuite("Runtime")
Runtime.test("_canBeClass") {
expectEqual(1, _canBeClass(SwiftObjectCanary.self))
expectEqual(0, _canBeClass(SwiftObjectCanaryStruct.self))
typealias SwiftClosure = () -> ()
expectEqual(0, _canBeClass(SwiftClosure.self))
}
//===----------------------------------------------------------------------===//
// The protocol should be defined in the standard library, otherwise the cast
// does not work.
typealias P1 = Boolean
typealias P2 = CustomStringConvertible
protocol Q1 {}
// A small struct that can be stored inline in an opaque buffer.
struct StructConformsToP1 : Boolean, Q1 {
var boolValue: Bool {
return true
}
}
// A small struct that can be stored inline in an opaque buffer.
struct Struct2ConformsToP1<T : Boolean> : Boolean, Q1 {
init(_ value: T) {
self.value = value
}
var boolValue: Bool {
return value.boolValue
}
var value: T
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct3ConformsToP2 : CustomStringConvertible, Q1 {
var a: UInt64 = 10
var b: UInt64 = 20
var c: UInt64 = 30
var d: UInt64 = 40
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = ""
result += _uint64ToString(a) + " "
result += _uint64ToString(b) + " "
result += _uint64ToString(c) + " "
result += _uint64ToString(d)
return result
}
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct4ConformsToP2<T : CustomStringConvertible> : CustomStringConvertible, Q1 {
var value: T
var e: UInt64 = 50
var f: UInt64 = 60
var g: UInt64 = 70
var h: UInt64 = 80
init(_ value: T) {
self.value = value
}
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = value.description + " "
result += _uint64ToString(e) + " "
result += _uint64ToString(f) + " "
result += _uint64ToString(g) + " "
result += _uint64ToString(h)
return result
}
}
struct StructDoesNotConformToP1 : Q1 {}
class ClassConformsToP1 : Boolean, Q1 {
var boolValue: Bool {
return true
}
}
class Class2ConformsToP1<T : Boolean> : Boolean, Q1 {
init(_ value: T) {
self.value = [ value ]
}
var boolValue: Bool {
return value[0].boolValue
}
// FIXME: should be "var value: T", but we don't support it now.
var value: Array<T>
}
class ClassDoesNotConformToP1 : Q1 {}
Runtime.test("dynamicCasting with as") {
var someP1Value = StructConformsToP1()
var someP1Value2 = Struct2ConformsToP1(true)
var someNotP1Value = StructDoesNotConformToP1()
var someP2Value = Struct3ConformsToP2()
var someP2Value2 = Struct4ConformsToP2(Struct3ConformsToP2())
var someP1Ref = ClassConformsToP1()
var someP1Ref2 = Class2ConformsToP1(true)
var someNotP1Ref = ClassDoesNotConformToP1()
expectTrue(someP1Value is P1)
expectTrue(someP1Value2 is P1)
expectFalse(someNotP1Value is P1)
expectTrue(someP2Value is P2)
expectTrue(someP2Value2 is P2)
expectTrue(someP1Ref is P1)
expectTrue(someP1Ref2 is P1)
expectFalse(someNotP1Ref is P1)
expectTrue(someP1Value as P1 is P1)
expectTrue(someP1Value2 as P1 is P1)
expectTrue(someP2Value as P2 is P2)
expectTrue(someP2Value2 as P2 is P2)
expectTrue(someP1Ref as P1 is P1)
expectTrue(someP1Value as Q1 is P1)
expectTrue(someP1Value2 as Q1 is P1)
expectFalse(someNotP1Value as Q1 is P1)
expectTrue(someP2Value as Q1 is P2)
expectTrue(someP2Value2 as Q1 is P2)
expectTrue(someP1Ref as Q1 is P1)
expectTrue(someP1Ref2 as Q1 is P1)
expectFalse(someNotP1Ref as Q1 is P1)
expectTrue(someP1Value as Any is P1)
expectTrue(someP1Value2 as Any is P1)
expectFalse(someNotP1Value as Any is P1)
expectTrue(someP2Value as Any is P2)
expectTrue(someP2Value2 as Any is P2)
expectTrue(someP1Ref as Any is P1)
expectTrue(someP1Ref2 as Any is P1)
expectFalse(someNotP1Ref as Any is P1)
expectTrue(someP1Ref as AnyObject is P1)
expectTrue(someP1Ref2 as AnyObject is P1)
expectFalse(someNotP1Ref as AnyObject is P1)
expectTrue((someP1Value as P1).boolValue)
expectTrue((someP1Value2 as P1).boolValue)
expectEqual("10 20 30 40", (someP2Value as P2).description)
expectEqual("10 20 30 40 50 60 70 80", (someP2Value2 as P2).description)
expectTrue((someP1Ref as P1).boolValue)
expectTrue((someP1Ref2 as P1).boolValue)
expectTrue(((someP1Value as Q1) as! P1).boolValue)
expectTrue(((someP1Value2 as Q1) as! P1).boolValue)
expectEqual("10 20 30 40", ((someP2Value as Q1) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as! P2).description)
expectTrue(((someP1Ref as Q1) as! P1).boolValue)
expectTrue(((someP1Ref2 as Q1) as! P1).boolValue)
expectTrue(((someP1Value as Any) as! P1).boolValue)
expectTrue(((someP1Value2 as Any) as! P1).boolValue)
expectEqual("10 20 30 40", ((someP2Value as Any) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as! P2).description)
expectTrue(((someP1Ref as Any) as! P1).boolValue)
expectTrue(((someP1Ref2 as Any) as! P1).boolValue)
expectTrue(((someP1Ref as AnyObject) as! P1).boolValue)
expectEmpty((someNotP1Value as? P1))
expectEmpty((someNotP1Ref as? P1))
expectTrue(((someP1Value as Q1) as? P1)!.boolValue)
expectTrue(((someP1Value2 as Q1) as? P1)!.boolValue)
expectEmpty(((someNotP1Value as Q1) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Q1) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as? P2)!.description)
expectTrue(((someP1Ref as Q1) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as Q1) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as Q1) as? P1))
expectTrue(((someP1Value as Any) as? P1)!.boolValue)
expectTrue(((someP1Value2 as Any) as? P1)!.boolValue)
expectEmpty(((someNotP1Value as Any) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Any) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as? P2)!.description)
expectTrue(((someP1Ref as Any) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as Any) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as Any) as? P1))
expectTrue(((someP1Ref as AnyObject) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as AnyObject) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as AnyObject) as? P1))
let doesThrow: Int throws -> Int = { $0 }
let doesNotThrow: String -> String = { $0 }
var any: Any = doesThrow
expectTrue(doesThrow as Any is Int throws -> Int)
expectFalse(doesThrow as Any is String throws -> Int)
expectFalse(doesThrow as Any is String throws -> String)
expectFalse(doesThrow as Any is Int throws -> String)
expectFalse(doesThrow as Any is Int -> Int)
expectFalse(doesThrow as Any is String throws -> String)
expectFalse(doesThrow as Any is String -> String)
expectTrue(doesNotThrow as Any is String throws -> String)
expectTrue(doesNotThrow as Any is String -> String)
expectFalse(doesNotThrow as Any is Int -> String)
expectFalse(doesNotThrow as Any is Int -> Int)
expectFalse(doesNotThrow as Any is String -> Int)
expectFalse(doesNotThrow as Any is Int throws -> Int)
expectFalse(doesNotThrow as Any is Int -> Int)
}
extension Int {
class ExtensionClassConformsToP2 : P2 {
var description: String { return "abc" }
}
private class PrivateExtensionClassConformsToP2 : P2 {
var description: String { return "def" }
}
}
Runtime.test("dynamic cast to existential with cross-module extensions") {
let internalObj = Int.ExtensionClassConformsToP2()
let privateObj = Int.PrivateExtensionClassConformsToP2()
expectTrue(internalObj is P2)
expectTrue(privateObj is P2)
}
class SomeClass {}
struct SomeStruct {}
enum SomeEnum {
case A
init() { self = .A }
}
Runtime.test("typeName") {
expectEqual("a.SomeClass", _typeName(SomeClass.self))
expectEqual("a.SomeStruct", _typeName(SomeStruct.self))
expectEqual("a.SomeEnum", _typeName(SomeEnum.self))
expectEqual("protocol<>.Protocol", _typeName(Any.Protocol.self))
expectEqual("Swift.AnyObject.Protocol", _typeName(AnyObject.Protocol.self))
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(AnyClass.Protocol.self))
expectEqual("Swift.Optional<Swift.AnyObject>.Type", _typeName((AnyObject?).Type.self))
var a: Any = SomeClass()
expectEqual("a.SomeClass", _typeName(a.dynamicType))
a = SomeStruct()
expectEqual("a.SomeStruct", _typeName(a.dynamicType))
a = SomeEnum()
expectEqual("a.SomeEnum", _typeName(a.dynamicType))
a = AnyObject.self
expectEqual("Swift.AnyObject.Protocol", _typeName(a.dynamicType))
a = AnyClass.self
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(a.dynamicType))
a = (AnyObject?).self
expectEqual("Swift.Optional<Swift.AnyObject>.Type",
_typeName(a.dynamicType))
a = Any.self
expectEqual("protocol<>.Protocol", _typeName(a.dynamicType))
}
class SomeSubclass : SomeClass {}
protocol SomeProtocol {}
class SomeConformingClass : SomeProtocol {}
Runtime.test("typeByName") {
expectTrue(_typeByName("a.SomeClass") == SomeClass.self)
expectTrue(_typeByName("a.SomeSubclass") == SomeSubclass.self)
// name lookup will be via protocol conformance table
expectTrue(_typeByName("a.SomeConformingClass") == SomeConformingClass.self)
// FIXME: NonObjectiveCBase is slated to die, but I can't think of another
// nongeneric public class in the stdlib...
expectTrue(_typeByName("Swift.NonObjectiveCBase") == NonObjectiveCBase.self)
}
Runtime.test("demangleName") {
expectEqual("", _stdlib_demangleName(""))
expectEqual("abc", _stdlib_demangleName("abc"))
expectEqual("\0", _stdlib_demangleName("\0"))
expectEqual("Swift.Double", _stdlib_demangleName("_TtSd"))
expectEqual("x.a : x.Foo<x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>, x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>>",
_stdlib_demangleName("_Tv1x1aGCS_3FooGS0_GS0_SiSi_GS0_SiSi__GS0_GS0_SiSi_GS0_SiSi___"))
expectEqual("Foobar", _stdlib_demangleName("_TtC13__lldb_expr_46Foobar"))
}
Runtime.test("_stdlib_atomicCompareExchangeStrongPtr") {
typealias IntPtr = UnsafeMutablePointer<Int>
var origP1 = IntPtr(bitPattern: 0x10101010)
var origP2 = IntPtr(bitPattern: 0x20202020)
var origP3 = IntPtr(bitPattern: 0x30303030)
do {
var object = origP1
var expected = origP1
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, object)
expectEqual(origP1, expected)
}
do {
var object = origP1
var expected = origP2
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, object)
expectEqual(origP1, expected)
}
struct FooStruct {
var i: Int
var object: IntPtr
var expected: IntPtr
init(_ object: IntPtr, _ expected: IntPtr) {
self.i = 0
self.object = object
self.expected = expected
}
}
do {
var foo = FooStruct(origP1, origP1)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, foo.object)
expectEqual(origP1, foo.expected)
}
do {
var foo = FooStruct(origP1, origP2)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, foo.object)
expectEqual(origP1, foo.expected)
}
}
Runtime.test("casting AnyObject to class metatypes") {
do {
var ao: AnyObject = SomeClass()
expectTrue(ao as? Any.Type == nil)
expectTrue(ao as? AnyClass == nil)
}
do {
var a: Any = SomeClass()
expectTrue(a as? Any.Type == nil)
expectTrue(a as? AnyClass == nil)
a = SomeClass.self
expectTrue(a as? Any.Type == SomeClass.self)
expectTrue(a as? AnyClass == SomeClass.self)
expectTrue(a as? SomeClass.Type == SomeClass.self)
}
}
class Malkovich: Malkovichable {
var malkovich: String { return "malkovich" }
}
protocol Malkovichable: class {
var malkovich: String { get }
}
struct GenericStructWithReferenceStorage<T> {
var a: T
unowned(safe) var unownedConcrete: Malkovich
unowned(unsafe) var unmanagedConcrete: Malkovich
weak var weakConcrete: Malkovich?
unowned(safe) var unownedProto: Malkovichable
unowned(unsafe) var unmanagedProto: Malkovichable
weak var weakProto: Malkovichable?
}
func exerciseReferenceStorageInGenericContext<T>(
x: GenericStructWithReferenceStorage<T>,
forceCopy y: GenericStructWithReferenceStorage<T>
) {
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
expectEqual(y.unownedConcrete.malkovich, "malkovich")
expectEqual(y.unmanagedConcrete.malkovich, "malkovich")
expectEqual(y.weakConcrete!.malkovich, "malkovich")
expectEqual(y.unownedProto.malkovich, "malkovich")
expectEqual(y.unmanagedProto.malkovich, "malkovich")
expectEqual(y.weakProto!.malkovich, "malkovich")
}
Runtime.test("Struct layout with reference storage types") {
let malkovich = Malkovich()
let x = GenericStructWithReferenceStorage(a: malkovich,
unownedConcrete: malkovich,
unmanagedConcrete: malkovich,
weakConcrete: malkovich,
unownedProto: malkovich,
unmanagedProto: malkovich,
weakProto: malkovich)
exerciseReferenceStorageInGenericContext(x, forceCopy: x)
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
// Make sure malkovich lives long enough.
print(malkovich)
}
var Reflection = TestSuite("Reflection")
func wrap1 (x: Any) -> Any { return x }
func wrap2<T>(x: T) -> Any { return wrap1(x) }
func wrap3 (x: Any) -> Any { return wrap2(x) }
func wrap4<T>(x: T) -> Any { return wrap3(x) }
func wrap5 (x: Any) -> Any { return wrap4(x) }
class JustNeedAMetatype {}
Reflection.test("nested existential containers") {
let wrapped = wrap5(JustNeedAMetatype.self)
expectEqual("\(wrapped)", "JustNeedAMetatype")
}
Reflection.test("dumpToAStream") {
var output = ""
dump([ 42, 4242 ], to: &output)
expectEqual("▿ 2 elements\n - 42\n - 4242\n", output)
}
struct StructWithDefaultMirror {
let s: String
init (_ s: String) {
self.s = s
}
}
Reflection.test("Struct/NonGeneric/DefaultMirror") {
do {
var output = ""
dump(StructWithDefaultMirror("123"), to: &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: \"123\"\n", output)
}
do {
// Build a String around an interpolation as a way of smoke-testing that
// the internal _Mirror implementation gets memory management right.
var output = ""
dump(StructWithDefaultMirror("\(456)"), to: &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: \"456\"\n", output)
}
expectEqual(
.`struct`,
Mirror(reflecting: StructWithDefaultMirror("")).displayStyle)
}
struct GenericStructWithDefaultMirror<T, U> {
let first: T
let second: U
}
Reflection.test("Struct/Generic/DefaultMirror") {
do {
var value = GenericStructWithDefaultMirror<Int, [Any?]>(
first: 123,
second: [ "abc", 456, 789.25 ])
var output = ""
dump(value, to: &output)
let expected =
"▿ a.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<protocol<>>>>\n" +
" - first: 123\n" +
" ▿ second: 3 elements\n" +
" ▿ Optional(\"abc\")\n" +
" - some: \"abc\"\n" +
" ▿ Optional(456)\n" +
" - some: 456\n" +
" ▿ Optional(789.25)\n" +
" - some: 789.25\n"
expectEqual(expected, output)
}
}
enum NoPayloadEnumWithDefaultMirror {
case A, ß
}
Reflection.test("Enum/NoPayload/DefaultMirror") {
do {
let value: [NoPayloadEnumWithDefaultMirror] =
[.A, .ß]
var output = ""
dump(value, to: &output)
let expected =
"▿ 2 elements\n" +
" - a.NoPayloadEnumWithDefaultMirror.A\n" +
" - a.NoPayloadEnumWithDefaultMirror.ß\n"
expectEqual(expected, output)
}
}
enum SingletonNonGenericEnumWithDefaultMirror {
case OnlyOne(Int)
}
Reflection.test("Enum/SingletonNonGeneric/DefaultMirror") {
do {
let value = SingletonNonGenericEnumWithDefaultMirror.OnlyOne(5)
var output = ""
dump(value, to: &output)
let expected =
"▿ a.SingletonNonGenericEnumWithDefaultMirror.OnlyOne\n" +
" - OnlyOne: 5\n"
expectEqual(expected, output)
}
}
enum SingletonGenericEnumWithDefaultMirror<T> {
case OnlyOne(T)
}
Reflection.test("Enum/SingletonGeneric/DefaultMirror") {
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne("IIfx")
var output = ""
dump(value, to: &output)
let expected =
"▿ a.SingletonGenericEnumWithDefaultMirror<Swift.String>.OnlyOne\n" +
" - OnlyOne: \"IIfx\"\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne(
LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum SinglePayloadNonGenericEnumWithDefaultMirror {
case Cat
case Dog
case Volleyball(String, Int)
}
Reflection.test("Enum/SinglePayloadNonGeneric/DefaultMirror") {
do {
let value: [SinglePayloadNonGenericEnumWithDefaultMirror] =
[.Cat,
.Dog,
.Volleyball("Wilson", 2000)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - a.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" +
" - a.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" +
" ▿ a.SinglePayloadNonGenericEnumWithDefaultMirror.Volleyball\n" +
" ▿ Volleyball: (2 elements)\n" +
" - .0: \"Wilson\"\n" +
" - .1: 2000\n"
expectEqual(expected, output)
}
}
enum SinglePayloadGenericEnumWithDefaultMirror<T, U> {
case Well
case Faucet
case Pipe(T, U)
}
Reflection.test("Enum/SinglePayloadGeneric/DefaultMirror") {
do {
let value: [SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>] =
[.Well,
.Faucet,
.Pipe(408, [415])]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" +
" - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" +
" ▿ a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" +
" ▿ Pipe: (2 elements)\n" +
" - .0: 408\n" +
" ▿ .1: 1 element\n" +
" - 415\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsNonGenericEnumWithDefaultMirror {
case Plus
case SE30
case Classic(mhz: Int)
case Performa(model: Int)
}
Reflection.test("Enum/MultiPayloadTagBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsNonGenericEnumWithDefaultMirror] =
[.Plus,
.SE30,
.Classic(mhz: 16),
.Performa(model: 220)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 4 elements\n" +
" - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" +
" - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" +
" ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" +
" - Classic: 16\n" +
" ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Performa\n" +
" - Performa: 220\n"
expectEqual(expected, output)
}
}
class Floppy {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
class CDROM {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
enum MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Floppy)
case HyperCard(cdrom: CDROM)
}
Reflection.test("Enum/MultiPayloadSpareBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: Floppy(capacity: 800)),
.HyperCard(cdrom: CDROM(capacity: 600))]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: a.Floppy #0\n" +
" - capacity: 800\n" +
" ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: a.CDROM #1\n" +
" - capacity: 600\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Bool)
case HyperCard(cdrom: Bool)
}
Reflection.test("Enum/MultiPayloadTagBitsSmallNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: true),
.HyperCard(cdrom: false)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" - ClarisWorks: true\n" +
" ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.HyperCard\n" +
" - HyperCard: false\n"
expectEqual(expected, output)
}
}
enum MultiPayloadGenericEnumWithDefaultMirror<T, U> {
case IIe
case IIgs
case Centris(ram: T)
case Quadra(hdd: U)
case PowerBook170
case PowerBookDuo220
}
Reflection.test("Enum/MultiPayloadGeneric/DefaultMirror") {
do {
let value: [MultiPayloadGenericEnumWithDefaultMirror<Int, String>] =
[.IIe,
.IIgs,
.Centris(ram: 4096),
.Quadra(hdd: "160MB"),
.PowerBook170,
.PowerBookDuo220]
var output = ""
dump(value, to: &output)
let expected =
"▿ 6 elements\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" +
" ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" +
" - Centris: 4096\n" +
" ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" +
" - Quadra: \"160MB\"\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBookDuo220\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = MultiPayloadGenericEnumWithDefaultMirror<LifetimeTracked,
LifetimeTracked>
.Quadra(hdd: LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum Foo<T> {
indirect case Foo(Int)
case Bar(T)
}
enum List<T> {
case Nil
indirect case Cons(first: T, rest: List<T>)
}
Reflection.test("Enum/IndirectGeneric/DefaultMirror") {
let x = Foo<String>.Foo(22)
let y = Foo<String>.Bar("twenty-two")
expectEqual("\(x)", "Foo(22)")
expectEqual("\(y)", "Bar(\"twenty-two\")")
let list = List.Cons(first: 0, rest: .Cons(first: 1, rest: .Nil))
expectEqual("\(list)",
"Cons(0, a.List<Swift.Int>.Cons(1, a.List<Swift.Int>.Nil))")
}
class Brilliant : CustomReflectable {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
var customMirror: Mirror {
return Mirror(self, children: ["first": first, "second": second, "self": self])
}
}
/// Subclasses inherit their parents' custom mirrors.
class Irradiant : Brilliant {
init() {
super.init(400, "")
}
}
Reflection.test("CustomMirror") {
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" ▿ self: a.Brilliant #0\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxDepth: 0)
expectEqual("▹ a.Brilliant #0\n", output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 3)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" (1 more child)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 2)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" (2 more children)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 1)
let expected =
"▿ a.Brilliant #0\n" +
" (3 children)\n"
expectEqual(expected, output)
}
do {
// Check that object identifiers are unique to class instances.
let a = Brilliant(1, "")
let b = Brilliant(2, "")
let c = Brilliant(3, "")
// Equatable
checkEquatable(true, ObjectIdentifier(a), ObjectIdentifier(a))
checkEquatable(false, ObjectIdentifier(a), ObjectIdentifier(b))
// Comparable
func isComparable<X : Comparable>(x: X) {}
isComparable(ObjectIdentifier(a))
// Check the ObjectIdentifier created is stable
expectTrue(
(ObjectIdentifier(a) < ObjectIdentifier(b))
!= (ObjectIdentifier(a) > ObjectIdentifier(b)))
expectFalse(
ObjectIdentifier(a) >= ObjectIdentifier(b)
&& ObjectIdentifier(a) <= ObjectIdentifier(b))
// Check that ordering is transitive.
expectEqual(
[ ObjectIdentifier(a), ObjectIdentifier(b), ObjectIdentifier(c) ].sorted(),
[ ObjectIdentifier(c), ObjectIdentifier(b), ObjectIdentifier(a) ].sorted())
}
}
Reflection.test("CustomMirrorIsInherited") {
do {
var output = ""
dump(Irradiant(), to: &output)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 400\n" +
" - second: \"\"\n" +
" ▿ self: a.Brilliant #0\n"
expectEqual(expected, output)
}
}
protocol SomeNativeProto {}
extension Int: SomeNativeProto {}
Reflection.test("MetatypeMirror") {
do {
var output = ""
let concreteMetatype = Int.self
dump(concreteMetatype, to: &output)
let expectedInt = "- Swift.Int #0\n"
expectEqual(expectedInt, output)
let anyMetatype: Any.Type = Int.self
output = ""
dump(anyMetatype, to: &output)
expectEqual(expectedInt, output)
let nativeProtocolMetatype: SomeNativeProto.Type = Int.self
output = ""
dump(nativeProtocolMetatype, to: &output)
expectEqual(expectedInt, output)
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- a.SomeClass #0\n"
output = ""
dump(concreteClassMetatype, to: &output)
expectEqual(expectedSomeClass, output)
let nativeProtocolConcreteMetatype = SomeNativeProto.self
let expectedNativeProtocolConcrete = "- a.SomeNativeProto #0\n"
output = ""
dump(nativeProtocolConcreteMetatype, to: &output)
expectEqual(expectedNativeProtocolConcrete, output)
}
}
Reflection.test("TupleMirror") {
do {
var output = ""
let tuple =
(Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" ▿ .0: a.Brilliant #0\n" +
" - first: 384\n" +
" - second: \"seven six eight\"\n" +
" ▿ self: a.Brilliant #0\n" +
" ▿ .1: a.StructWithDefaultMirror\n" +
" - s: \"nine\"\n"
expectEqual(expected, output)
expectEqual(.tuple, Mirror(reflecting: tuple).displayStyle)
}
do {
// A tuple of stdlib types with mirrors.
var output = ""
let tuple = (1, 2.5, false, "three")
dump(tuple, to: &output)
let expected =
"▿ (4 elements)\n" +
" - .0: 1\n" +
" - .1: 2.5\n" +
" - .2: false\n" +
" - .3: \"three\"\n"
expectEqual(expected, output)
}
do {
// A nested tuple.
var output = ""
let tuple = (1, ("Hello", "World"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" - .0: 1\n" +
" ▿ .1: (2 elements)\n" +
" - .0: \"Hello\"\n" +
" - .1: \"World\"\n"
expectEqual(expected, output)
}
}
class DullClass {}
Reflection.test("ClassReflection") {
expectEqual(.`class`, Mirror(reflecting: DullClass()).displayStyle)
}
Reflection.test("String/Mirror") {
do {
var output = ""
dump("", to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}", to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("String.UTF8View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
var output = ""
dump("\u{61}\u{304b}\u{3099}".utf8, to: &output)
let expected =
"▿ UTF8View(\"\u{61}\u{304b}\u{3099}\")\n" +
" - 97\n" +
" - 227\n" +
" - 129\n" +
" - 139\n" +
" - 227\n" +
" - 130\n" +
" - 153\n"
expectEqual(expected, output)
}
Reflection.test("String.UTF16View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".utf16, to: &output)
let expected =
"▿ StringUTF16(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - 97\n" +
" - 12363\n" +
" - 12441\n" +
" - 55357\n" +
" - 56357\n"
expectEqual(expected, output)
}
Reflection.test("String.UnicodeScalarView/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".unicodeScalars, to: &output)
let expected =
"▿ StringUnicodeScalarView(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - \"\u{61}\"\n" +
" - \"\\u{304B}\"\n" +
" - \"\\u{3099}\"\n" +
" - \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
Reflection.test("Character/Mirror") {
do {
// U+0061 LATIN SMALL LETTER A
let input: Character = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: Character = "\u{304b}\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{304b}\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: Character = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("UnicodeScalar") {
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{304B}\"\n"
expectEqual(expected, output)
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("Bool") {
do {
var output = ""
dump(false, to: &output)
let expected =
"- false\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(true, to: &output)
let expected =
"- true\n"
expectEqual(expected, output)
}
}
// FIXME: these tests should cover Float80.
// FIXME: these tests should be automatically generated from the list of
// available floating point types.
Reflection.test("Float") {
do {
var output = ""
dump(Float.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Float.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Float = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
Reflection.test("Double") {
do {
var output = ""
dump(Double.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Double.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Double = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
// A struct type and class type whose NominalTypeDescriptor.FieldNames
// data is exactly eight bytes long. FieldNames data of exactly
// 4 or 8 or 16 bytes was once miscompiled on arm64.
struct EightByteFieldNamesStruct {
let abcdef = 42
}
class EightByteFieldNamesClass {
let abcdef = 42
}
Reflection.test("FieldNamesBug") {
do {
let expected =
"▿ a.EightByteFieldNamesStruct\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesStruct(), to: &output)
expectEqual(expected, output)
}
do {
let expected =
"▿ a.EightByteFieldNamesClass #0\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesClass(), to: &output)
expectEqual(expected, output)
}
}
Reflection.test("MirrorMirror") {
var object = 1
var mirror = Mirror(reflecting: object)
var mirrorMirror = Mirror(reflecting: mirror)
expectEqual(0, mirrorMirror.children.count)
}
Reflection.test("OpaquePointer/null") {
// Don't crash on null pointers. rdar://problem/19708338
var sequence: OpaquePointer = nil
var mirror = Mirror(reflecting: sequence)
var child = mirror.children.first!
expectEqual("(Opaque Value)", "\(child.1)")
}
Reflection.test("StaticString/Mirror") {
do {
var output = ""
dump("" as StaticString, to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}" as StaticString, to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("DictionaryIterator/Mirror") {
let d: [MinimalHashableValue : OpaqueValue<Int>] =
[ MinimalHashableValue(0) : OpaqueValue(0) ]
var output = ""
dump(d.makeIterator(), to: &output)
let expected =
"- Swift.DictionaryIterator<StdlibUnittest.MinimalHashableValue, StdlibUnittest.OpaqueValue<Swift.Int>>\n"
expectEqual(expected, output)
}
Reflection.test("SetIterator/Mirror") {
let s: Set<MinimalHashableValue> = [ MinimalHashableValue(0)]
var output = ""
dump(s.makeIterator(), to: &output)
let expected =
"- Swift.SetIterator<StdlibUnittest.MinimalHashableValue>\n"
expectEqual(expected, output)
}
var BitTwiddlingTestSuite = TestSuite("BitTwiddling")
func computeCountLeadingZeroes(x: Int64) -> Int64 {
var x = x
var r: Int64 = 64
while x != 0 {
x >>= 1
r -= 1
}
return r
}
BitTwiddlingTestSuite.test("_pointerSize") {
#if arch(i386) || arch(arm)
expectEqual(4, sizeof(Optional<AnyObject>.self))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le)
expectEqual(8, sizeof(Optional<AnyObject>.self))
#else
fatalError("implement")
#endif
}
BitTwiddlingTestSuite.test("_countLeadingZeros") {
for i in Int64(0)..<1000 {
expectEqual(computeCountLeadingZeroes(i), _countLeadingZeros(i))
}
expectEqual(0, _countLeadingZeros(Int64.min))
}
BitTwiddlingTestSuite.test("_isPowerOf2/Int") {
func asInt(a: Int) -> Int { return a }
expectFalse(_isPowerOf2(asInt(-1025)))
expectFalse(_isPowerOf2(asInt(-1024)))
expectFalse(_isPowerOf2(asInt(-1023)))
expectFalse(_isPowerOf2(asInt(-4)))
expectFalse(_isPowerOf2(asInt(-3)))
expectFalse(_isPowerOf2(asInt(-2)))
expectFalse(_isPowerOf2(asInt(-1)))
expectFalse(_isPowerOf2(asInt(0)))
expectTrue(_isPowerOf2(asInt(1)))
expectTrue(_isPowerOf2(asInt(2)))
expectFalse(_isPowerOf2(asInt(3)))
expectTrue(_isPowerOf2(asInt(1024)))
#if arch(i386) || arch(arm)
// Not applicable to 32-bit architectures.
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le)
expectTrue(_isPowerOf2(asInt(0x8000_0000)))
#else
fatalError("implement")
#endif
expectFalse(_isPowerOf2(Int.min))
expectFalse(_isPowerOf2(Int.max))
}
BitTwiddlingTestSuite.test("_isPowerOf2/UInt") {
func asUInt(a: UInt) -> UInt { return a }
expectFalse(_isPowerOf2(asUInt(0)))
expectTrue(_isPowerOf2(asUInt(1)))
expectTrue(_isPowerOf2(asUInt(2)))
expectFalse(_isPowerOf2(asUInt(3)))
expectTrue(_isPowerOf2(asUInt(1024)))
expectTrue(_isPowerOf2(asUInt(0x8000_0000)))
expectFalse(_isPowerOf2(UInt.max))
}
BitTwiddlingTestSuite.test("_floorLog2") {
expectEqual(_floorLog2(1), 0)
expectEqual(_floorLog2(8), 3)
expectEqual(_floorLog2(15), 3)
expectEqual(_floorLog2(Int64.max), 62) // 63 minus 1 for sign bit.
}
var AvailabilityVersionsTestSuite = TestSuite("AvailabilityVersions")
AvailabilityVersionsTestSuite.test("lexicographic_compare") {
func version(
major: Int,
_ minor: Int,
_ patch: Int
) -> _SwiftNSOperatingSystemVersion {
return _SwiftNSOperatingSystemVersion(
majorVersion: major,
minorVersion: minor,
patchVersion: patch
)
}
checkComparable(.eq, version(0, 0, 0), version(0, 0, 0))
checkComparable(.lt, version(0, 0, 0), version(0, 0, 1))
checkComparable(.lt, version(0, 0, 0), version(0, 1, 0))
checkComparable(.lt, version(0, 0, 0), version(1, 0, 0))
checkComparable(.lt,version(10, 9, 0), version(10, 10, 0))
checkComparable(.lt,version(10, 9, 11), version(10, 10, 0))
checkComparable(.lt,version(10, 10, 3), version(10, 11, 0))
checkComparable(.lt, version(8, 3, 0), version(9, 0, 0))
checkComparable(.lt, version(0, 11, 0), version(10, 10, 4))
checkComparable(.lt, version(0, 10, 0), version(10, 10, 4))
checkComparable(.lt, version(3, 2, 1), version(4, 3, 2))
checkComparable(.lt, version(1, 2, 3), version(2, 3, 1))
checkComparable(.eq, version(10, 11, 12), version(10, 11, 12))
checkEquatable(true, version(1, 2, 3), version(1, 2, 3))
checkEquatable(false, version(1, 2, 3), version(1, 2, 42))
checkEquatable(false, version(1, 2, 3), version(1, 42, 3))
checkEquatable(false, version(1, 2, 3), version(42, 2, 3))
}
AvailabilityVersionsTestSuite.test("_stdlib_isOSVersionAtLeast") {
func isAtLeastOS(major: Int, _ minor: Int, _ patch: Int) -> Bool {
return _getBool(_stdlib_isOSVersionAtLeast(major._builtinWordValue,
minor._builtinWordValue,
patch._builtinWordValue))
}
// _stdlib_isOSVersionAtLeast is broken for
// watchOS. rdar://problem/20234735
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
// This test assumes that no version component on an OS we test upon
// will ever be greater than 1066 and that every major version will always
// be greater than 1.
expectFalse(isAtLeastOS(1066, 0, 0))
expectTrue(isAtLeastOS(0, 1066, 0))
expectTrue(isAtLeastOS(0, 0, 1066))
#endif
}
runAllTests()
| apache-2.0 | c6b39b0a369dc76fdcbf192359b8de7c | 26.530128 | 158 | 0.65483 | 3.742984 | false | false | false | false |
russbishop/swift | stdlib/public/SDK/Dispatch/Queue.swift | 1 | 16161 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// dispatch/queue.h
public struct DispatchQueueAttributes : OptionSet {
public let rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
public static let serial = DispatchQueueAttributes(rawValue: 0<<0)
public static let concurrent = DispatchQueueAttributes(rawValue: 1<<1)
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static let initiallyInactive = DispatchQueueAttributes(rawValue: 1<<2)
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static let autoreleaseInherit = DispatchQueueAttributes(rawValue: 1<<3)
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static let autoreleaseWorkItem = DispatchQueueAttributes(rawValue: 1<<4)
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static let autoreleaseNever = DispatchQueueAttributes(rawValue: 1<<5)
@available(OSX 10.10, iOS 8.0, *)
public static let qosUserInteractive = DispatchQueueAttributes(rawValue: 1<<6)
@available(OSX 10.10, iOS 8.0, *)
public static let qosUserInitiated = DispatchQueueAttributes(rawValue: 1<<7)
@available(OSX 10.10, iOS 8.0, *)
public static let qosDefault = DispatchQueueAttributes(rawValue: 1<<8)
@available(OSX 10.10, iOS 8.0, *)
public static let qosUtility = DispatchQueueAttributes(rawValue: 1<<9)
@available(OSX 10.10, iOS 8.0, *)
public static let qosBackground = DispatchQueueAttributes(rawValue: 1<<10)
@available(*, deprecated, message: ".noQoS has no effect, it should not be used")
public static let noQoS = DispatchQueueAttributes(rawValue: 1<<11)
private var attr: __OS_dispatch_queue_attr? {
var attr: __OS_dispatch_queue_attr?
if self.contains(.concurrent) {
attr = _swift_dispatch_queue_concurrent()
}
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
if self.contains(.initiallyInactive) {
attr = __dispatch_queue_attr_make_initially_inactive(attr)
}
if self.contains(.autoreleaseWorkItem) {
// DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM
attr = __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(1))
} else if self.contains(.autoreleaseInherit) {
// DISPATCH_AUTORELEASE_FREQUENCY_INHERIT
attr = __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(0))
} else if self.contains(.autoreleaseNever) {
// DISPATCH_AUTORELEASE_FREQUENCY_NEVER
attr = __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(2))
}
}
if #available(OSX 10.10, iOS 8.0, *) {
if self.contains(.qosUserInteractive) {
attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_USER_INTERACTIVE, 0)
} else if self.contains(.qosUserInitiated) {
attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_USER_INITIATED, 0)
} else if self.contains(.qosDefault) {
attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_DEFAULT, 0)
} else if self.contains(.qosUtility) {
attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_UTILITY, 0)
} else if self.contains(.qosBackground) {
attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_BACKGROUND, 0)
}
}
return attr
}
}
public final class DispatchSpecificKey<T> {
public init() {}
}
internal class _DispatchSpecificValue<T> {
internal let value: T
internal init(value: T) { self.value = value }
}
public extension DispatchQueue {
public struct GlobalAttributes : OptionSet {
public let rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
@available(OSX 10.10, iOS 8.0, *)
public static let qosUserInteractive = GlobalAttributes(rawValue: 1<<0)
@available(OSX 10.10, iOS 8.0, *)
public static let qosUserInitiated = GlobalAttributes(rawValue: 1<<1)
@available(OSX 10.10, iOS 8.0, *)
public static let qosDefault = GlobalAttributes(rawValue: 1<<2)
@available(OSX 10.10, iOS 8.0, *)
public static let qosUtility = GlobalAttributes(rawValue: 1<<3)
@available(OSX 10.10, iOS 8.0, *)
public static let qosBackground = GlobalAttributes(rawValue: 1<<4)
// Avoid using our own deprecated constants here by declaring
// non-deprecated constants and then basing the public ones on those.
internal static let _priorityHigh = GlobalAttributes(rawValue: 1<<5)
internal static let _priorityDefault = GlobalAttributes(rawValue: 1<<6)
internal static let _priorityLow = GlobalAttributes(rawValue: 1<<7)
internal static let _priorityBackground = GlobalAttributes(rawValue: 1<<8)
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
public static let priorityHigh = _priorityHigh
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
public static let priorityDefault = _priorityDefault
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
public static let priorityLow = _priorityLow
@available(OSX, deprecated: 10.10, message: "Use qos attributes instead")
@available(*, deprecated: 8.0, message: "Use qos attributes instead")
public static let priorityBackground = _priorityBackground
internal var _translatedValue: Int {
if #available(OSX 10.10, iOS 8.0, *) {
if self.contains(.qosUserInteractive) { return Int(QOS_CLASS_USER_INTERACTIVE.rawValue) }
else if self.contains(.qosUserInitiated) { return Int(QOS_CLASS_USER_INITIATED.rawValue) }
else if self.contains(.qosDefault) { return Int(QOS_CLASS_DEFAULT.rawValue) }
else if self.contains(.qosUtility) { return Int(QOS_CLASS_UTILITY.rawValue) }
else { return Int(QOS_CLASS_BACKGROUND.rawValue) }
}
if self.contains(._priorityHigh) { return 2 } // DISPATCH_QUEUE_PRIORITY_HIGH
else if self.contains(._priorityDefault) { return 0 } // DISPATCH_QUEUE_PRIORITY_DEFAULT
else if self.contains(._priorityLow) { return -2 } // // DISPATCH_QUEUE_PRIORITY_LOW
else if self.contains(._priorityBackground) { return Int(Int16.min) } // // DISPATCH_QUEUE_PRIORITY_BACKGROUND
return 0
}
}
public class func concurrentPerform(iterations: Int, execute work: @noescape (Int) -> Void) {
_swift_dispatch_apply_current(iterations, work)
}
public class var main: DispatchQueue {
return _swift_dispatch_get_main_queue()
}
public class func global(attributes: GlobalAttributes = []) -> DispatchQueue {
return __dispatch_get_global_queue(attributes._translatedValue, 0)
}
public class func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? {
let k = Unmanaged.passUnretained(key).toOpaque()
if let p = __dispatch_get_specific(k) {
let v = Unmanaged<_DispatchSpecificValue<T>>
.fromOpaque(p)
.takeUnretainedValue()
return v.value
}
return nil
}
public convenience init(
label: String,
attributes: DispatchQueueAttributes = .serial,
target: DispatchQueue? = nil)
{
if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
self.init(__label: label, attr: attributes.attr, queue: target)
} else {
self.init(__label: label, attr: attributes.attr)
if let tq = target { self.setTarget(queue: tq) }
}
}
public var label: String {
return String(validatingUTF8: __dispatch_queue_get_label(self))!
}
@available(OSX 10.10, iOS 8.0, *)
public func sync(execute workItem: DispatchWorkItem) {
// _swift_dispatch_sync preserves the @convention(block) for
// work item blocks.
_swift_dispatch_sync(self, workItem._block)
}
@available(OSX 10.10, iOS 8.0, *)
public func async(execute workItem: DispatchWorkItem) {
// _swift_dispatch_{group,}_async preserves the @convention(block)
// for work item blocks.
if let g = workItem._group {
_swift_dispatch_group_async(g, self, workItem._block)
} else {
_swift_dispatch_async(self, workItem._block)
}
}
public func async(group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) {
if group == nil && qos == .unspecified && flags.isEmpty {
// Fast-path route for the most common API usage
__dispatch_async(self, work)
return
}
if #available(OSX 10.10, iOS 8.0, *), (qos != .unspecified || !flags.isEmpty) {
let workItem = DispatchWorkItem(qos: qos, flags: flags, block: work)
if let g = group {
_swift_dispatch_group_async(g, self, workItem._block)
} else {
_swift_dispatch_async(self, workItem._block)
}
} else {
if let g = group {
__dispatch_group_async(g, self, work)
} else {
__dispatch_async(self, work)
}
}
}
private func _syncBarrier(block: @noescape () -> ()) {
__dispatch_barrier_sync(self, block)
}
private func _syncHelper<T>(
fn: (@noescape () -> ()) -> (),
execute work: @noescape () throws -> T,
rescue: ((ErrorProtocol) throws -> (T))) rethrows -> T
{
var result: T?
var error: ErrorProtocol?
fn {
do {
result = try work()
} catch let e {
error = e
}
}
if let e = error {
return try rescue(e)
} else {
return result!
}
}
@available(OSX 10.10, iOS 8.0, *)
private func _syncHelper<T>(
fn: (DispatchWorkItem) -> (),
flags: DispatchWorkItemFlags,
execute work: @noescape () throws -> T,
rescue: ((ErrorProtocol) throws -> (T))) rethrows -> T
{
var result: T?
var error: ErrorProtocol?
let workItem = DispatchWorkItem(flags: flags, noescapeBlock: {
do {
result = try work()
} catch let e {
error = e
}
})
fn(workItem)
if let e = error {
return try rescue(e)
} else {
return result!
}
}
public func sync<T>(execute work: @noescape () throws -> T) rethrows -> T {
return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
}
public func sync<T>(flags: DispatchWorkItemFlags, execute work: @noescape () throws -> T) rethrows -> T {
if flags == .barrier {
return try self._syncHelper(fn: _syncBarrier, execute: work, rescue: { throw $0 })
} else if #available(OSX 10.10, iOS 8.0, *), !flags.isEmpty {
return try self._syncHelper(fn: sync, flags: flags, execute: work, rescue: { throw $0 })
} else {
return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
}
}
public func after(when: DispatchTime, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) {
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: work)
__dispatch_after(when.rawValue, self, item._block)
} else {
__dispatch_after(when.rawValue, self, work)
}
}
@available(OSX 10.10, iOS 8.0, *)
public func after(when: DispatchTime, execute: DispatchWorkItem) {
__dispatch_after(when.rawValue, self, execute._block)
}
public func after(walltime when: DispatchWallTime, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) {
if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty {
let item = DispatchWorkItem(qos: qos, flags: flags, block: work)
__dispatch_after(when.rawValue, self, item._block)
} else {
__dispatch_after(when.rawValue, self, work)
}
}
@available(OSX 10.10, iOS 8.0, *)
public func after(walltime when: DispatchWallTime, execute: DispatchWorkItem) {
__dispatch_after(when.rawValue, self, execute._block)
}
@available(OSX 10.10, iOS 8.0, *)
public var qos: DispatchQoS {
var relPri: Int32 = 0
let cls = DispatchQoS.QoSClass(qosClass: __dispatch_queue_get_qos_class(self, &relPri))!
return DispatchQoS(qosClass: cls, relativePriority: Int(relPri))
}
public func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? {
let k = Unmanaged.passUnretained(key).toOpaque()
if let p = __dispatch_queue_get_specific(self, k) {
let v = Unmanaged<_DispatchSpecificValue<T>>
.fromOpaque(p)
.takeUnretainedValue()
return v.value
}
return nil
}
public func setSpecific<T>(key: DispatchSpecificKey<T>, value: T) {
let v = _DispatchSpecificValue(value: value)
let k = Unmanaged.passUnretained(key).toOpaque()
let p = Unmanaged.passRetained(v).toOpaque()
__dispatch_queue_set_specific(self, k, p, _destructDispatchSpecificValue)
}
}
extension DispatchQueue {
@available(*, deprecated, renamed: "DispatchQueue.sync(self:execute:)")
public func synchronously(execute work: @noescape () -> ()) {
sync(execute: work)
}
@available(OSX, introduced: 10.10, deprecated: 10.12, renamed: "DispatchQueue.sync(self:execute:)")
@available(iOS, introduced: 8.0, deprecated: 10.0, renamed: "DispatchQueue.sync(self:execute:)")
@available(*, deprecated, renamed: "DispatchQueue.sync(self:execute:)")
public func synchronously(execute workItem: DispatchWorkItem) {
sync(execute: workItem)
}
@available(OSX, introduced: 10.10, deprecated: 10.12, renamed: "DispatchQueue.async(self:execute:)")
@available(iOS, introduced: 8.0, deprecated: 10.0, renamed: "DispatchQueue.async(self:execute:)")
@available(*, deprecated, renamed: "DispatchQueue.async(self:execute:)")
public func asynchronously(execute workItem: DispatchWorkItem) {
async(execute: workItem)
}
@available(*, deprecated, renamed: "DispatchQueue.async(self:group:qos:flags:execute:)")
public func asynchronously(group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) {
async(group: group, qos: qos, flags: flags, execute: work)
}
@available(*, deprecated, renamed: "DispatchQueue.sync(self:execute:)")
public func synchronously<T>(execute work: @noescape () throws -> T) rethrows -> T {
return try sync(execute: work)
}
@available(*, deprecated, renamed: "DispatchQueue.sync(self:flags:execute:)")
public func synchronously<T>(flags: DispatchWorkItemFlags, execute work: @noescape () throws -> T) rethrows -> T {
return try sync(flags: flags, execute: work)
}
@available(*, deprecated, renamed: "DispatchQueue.concurrentPerform(iterations:execute:)")
public func apply(applier iterations: Int, execute block: @noescape (Int) -> Void) {
DispatchQueue.concurrentPerform(iterations: iterations, execute: block)
}
@available(*, deprecated, renamed: "DispatchQueue.setTarget(self:queue:)")
public func setTargetQueue(queue: DispatchQueue) {
self.setTarget(queue: queue)
}
}
private func _destructDispatchSpecificValue(ptr: UnsafeMutablePointer<Void>?) {
if let p = ptr {
Unmanaged<AnyObject>.fromOpaque(p).release()
}
}
@_silgen_name("_swift_dispatch_queue_concurrent")
internal func _swift_dispatch_queue_concurrent() -> __OS_dispatch_queue_attr
@_silgen_name("_swift_dispatch_get_main_queue")
internal func _swift_dispatch_get_main_queue() -> DispatchQueue
@_silgen_name("_swift_dispatch_apply_current_root_queue")
internal func _swift_dispatch_apply_current_root_queue() -> DispatchQueue
@_silgen_name("_swift_dispatch_async")
internal func _swift_dispatch_async(_ queue: DispatchQueue, _ block: _DispatchBlock)
@_silgen_name("_swift_dispatch_group_async")
internal func _swift_dispatch_group_async(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: _DispatchBlock)
@_silgen_name("_swift_dispatch_sync")
internal func _swift_dispatch_sync(_ queue: DispatchQueue, _ block: _DispatchBlock)
@_silgen_name("_swift_dispatch_apply_current")
internal func _swift_dispatch_apply_current(_ iterations: Int, _ block: @convention(block) @noescape (Int) -> Void)
| apache-2.0 | c13b2f39e56c22cb8a8f8e0d1e0ebfb8 | 36.671329 | 171 | 0.698595 | 3.457638 | false | false | false | false |
lstn-ltd/lstn-sdk-ios | Example/Tests/Player/PlayerSpec.swift | 1 | 2411 | //
// PlayerSpec.swift
// Lstn
//
// Created by Dan Halliday on 17/10/2016.
// Copyright © 2016 Lstn Ltd. All rights reserved.
//
import Quick
import Nimble
import Foundation
@testable import Lstn
private let timeout = 5.0 // TODO: Implement mock audio engine to avoid reading from disk
class PlayerSpec: QuickSpec {
private let article = "article-id-string"
private let publisher = "publisher-token-string"
override func spec() {
describe("Default Player") {
it("should exist") {
_ = DefaultPlayer.self
}
it("should load a URL") {
DefaultPlayer().load(article: self.article, publisher: self.publisher)
}
describe("callback interface") {
it("should call back after loading a URL") {
let player = DefaultPlayer(resolver: SucceedingArticleResolver())
var result: Bool? = nil
player.load(article: self.article, publisher: self.publisher) {
success in result = success
}
expect(result).toEventually(equal(true), timeout: timeout)
}
}
describe("delegate interface") {
it("should successfully load an article") {
let player = DefaultPlayer(resolver: SucceedingArticleResolver())
let spy = PlayerSpy()
player.delegate = spy
player.load(article: self.article, publisher: self.publisher)
expect(spy.loadingDidStartFired).toEventually(equal(true), timeout: timeout)
expect(spy.loadingDidFinishFired).toEventually(equal(true), timeout: timeout)
}
it("should fail to load an article if article resolution fails") {
let player = DefaultPlayer(resolver: FailingArticleResolver())
let spy = PlayerSpy()
player.delegate = spy
player.load(article: self.article, publisher: self.publisher)
expect(spy.loadingDidStartFired).toEventually(equal(true), timeout: timeout)
expect(spy.loadingDidFailFired).toEventually(equal(true), timeout: timeout)
}
}
}
}
}
| mit | 2e9177bae6ff47d87b6066790c8680f8 | 27.352941 | 97 | 0.551867 | 5.095137 | false | false | false | false |
nua-schroers/mvvm-frp | 41_MVVM_FRP-App_ExplicitSignals/MatchGame/MatchGame/RAC.swift | 2 | 2891 | //
// RAC.swift
//
// This file is based on RAC.swift by:
// Created by Colin Eberhardt on 15/07/2014.
// Copyright (c) 2014 Colin Eberhardt. All rights reserved.
//
// Original source can be found at:
// https://github.com/ColinEberhardt/ReactiveTwitterSearch/blob/master/ReactiveTwitterSearch/Util/UIKitExtensions.swift
//
// Modified for educational use by Wolfram Schroers <[email protected]> on 5/30/2016.
// Released under the MIT license.
//
import Foundation
import ReactiveSwift
import ReactiveCocoa
import UIKit
struct AssociationKey {
static var hidden: UInt8 = 1
static var alpha: UInt8 = 2
static var text: UInt8 = 3
static var enabled: UInt8 = 4
static var selectedSegmentIndex: UInt = 5
}
// lazily creates a gettable associated property via the given factory
func lazyAssociatedProperty<T: AnyObject>(_ host: AnyObject, key: UnsafeRawPointer, factory: ()->T) -> T {
return objc_getAssociatedObject(host, key) as? T ?? {
let associatedProperty = factory()
objc_setAssociatedObject(host, key, associatedProperty, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return associatedProperty
}()
}
func lazyMutableProperty<T>(_ host: AnyObject, key: UnsafeRawPointer, setter: @escaping (T) -> (), getter: @escaping () -> T) -> MutableProperty<T> {
return lazyAssociatedProperty(host, key: key) {
let property = MutableProperty<T>(getter())
property.producer
.startWithValues {
newValue in
setter(newValue)
}
return property
}
}
extension UIControl {
public var rac_enabled: MutableProperty<Bool> {
return lazyMutableProperty(self, key: &AssociationKey.enabled, setter: { self.isEnabled = $0 }, getter: { self.isEnabled })
}
}
extension UILabel {
public var rac_text: MutableProperty<String> {
return lazyMutableProperty(self, key: &AssociationKey.text, setter: { self.text = $0 }, getter: { self.text ?? "" })
}
}
extension UISegmentedControl {
public var rac_selectedSegmentIndex: MutableProperty<Int> {
return lazyMutableProperty(self, key: &AssociationKey.selectedSegmentIndex, setter: { self.selectedSegmentIndex = $0 }, getter: { self.selectedSegmentIndex } )
}
}
extension UITextField {
public var rac_text: MutableProperty<String> {
return lazyAssociatedProperty(self, key: &AssociationKey.text) {
self.addTarget(self, action: #selector(self.changed), for: UIControl.Event.editingChanged)
let property = MutableProperty<String>(self.text ?? "")
property.producer
.startWithValues {
newValue in
self.text = newValue
}
return property
}
}
@IBAction func changed() {
rac_text.value = self.text ?? ""
}
}
| mit | 959d49816388e55c6f93c363ee3f8664 | 32.616279 | 167 | 0.663784 | 4.360483 | false | false | false | false |
dathtcheapgo/Jira-Demo | Driver/MVC/Core/View/CGErrorPopup/ErrorPopup.swift | 1 | 1780 | //
// IssuePopup.swift
// rider
//
// Created by Đinh Anh Huy on 10/20/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
enum DeviceError: String {
case dontHaveInternetConnection = "img_error_popupGPS"
case dontEnableGPS = "img_error_popupInternet"
}
class ErrorPopup: BaseXibView {
@IBOutlet var view: UIView!
@IBOutlet var imageView: UIImageView!
private var blockView = UIView()
override func initControl() {
Bundle.main.loadNibNamed("ErrorPopup", owner: self, options: nil)
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
_ = view.addConstraintFillInView(view: self, commenParrentView: self)
}
func show(issueType: DeviceError, parrentView: UIView) {
if superview == nil {
blockView.removeFromSuperview()
blockView.translatesAutoresizingMaskIntoConstraints = false
parrentView.addSubview(blockView)
_ = blockView.addConstraintFillInView(view: parrentView, commenParrentView: parrentView)
imageView.image = UIImage(named: issueType.rawValue)
isHidden = false
translatesAutoresizingMaskIntoConstraints = false
blockView.addSubview(self)
let margin: CGFloat = 20
_ = leadingMarginToView(view: blockView, commonParrentView: blockView, margin: margin)
_ = trailingMarginToView(view: blockView, commonParrentView: blockView, margin: -margin)
_ = addConstraintCenterYToView(view: blockView, commonParrentView: blockView)
} else { blockView.isHidden = false }
}
func hide() {
blockView.isHidden = true
}
}
| mit | 1943c45025ecc0c5ba9e96193c6ca857 | 32.528302 | 100 | 0.647721 | 4.579897 | false | false | false | false |
DevDragonLi/iOSDevDemo | 3-UIDemos/XTPhotoPicker/XTPhotoPicker_Demo/XTPhotoPicker/TLPhotosPickerViewController.swift | 1 | 36660 | //
// TLPhotosPickerViewController.swift
// TLPhotosPicker
//
// Created by wade.hawk on 2017. 4. 14..
// Copyright © 2017년 wade.hawk. All rights reserved.
//
import UIKit
import Photos
import PhotosUI
import MobileCoreServices
public protocol TLPhotosPickerViewControllerDelegate: class {
func dismissPhotoPicker(withPHAssets: [PHAsset])
func dismissPhotoPicker(withTLPHAssets: [TLPHAsset])
func dismissComplete()
func photoPickerDidCancel()
func didExceedMaximumNumberOfSelection(picker: TLPhotosPickerViewController)
func handleNoAlbumPermissions(picker: TLPhotosPickerViewController)
func handleNoCameraPermissions(picker: TLPhotosPickerViewController)
}
extension TLPhotosPickerViewControllerDelegate {
public func deninedAuthoization() { }
public func dismissPhotoPicker(withPHAssets: [PHAsset]) { }
public func dismissPhotoPicker(withTLPHAssets: [TLPHAsset]) { }
public func dismissComplete() { }
public func photoPickerDidCancel() { }
public func didExceedMaximumNumberOfSelection(picker: TLPhotosPickerViewController) { }
public func handleNoAlbumPermissions(picker: TLPhotosPickerViewController) { }
public func handleNoCameraPermissions(picker: TLPhotosPickerViewController) { }
}
//for log
public protocol TLPhotosPickerLogDelegate: class {
func selectedCameraCell(picker: TLPhotosPickerViewController)
func deselectedPhoto(picker: TLPhotosPickerViewController, at: Int)
func selectedPhoto(picker: TLPhotosPickerViewController, at: Int)
func selectedAlbum(picker: TLPhotosPickerViewController, title: String, at: Int)
}
extension TLPhotosPickerLogDelegate {
func selectedCameraCell(picker: TLPhotosPickerViewController) { }
func deselectedPhoto(picker: TLPhotosPickerViewController, at: Int) { }
func selectedPhoto(picker: TLPhotosPickerViewController, at: Int) { }
func selectedAlbum(picker: TLPhotosPickerViewController, collections: [TLAssetsCollection], at: Int) { }
}
public struct TLPhotosPickerConfigure {
public var defaultCameraRollTitle = "Camera Roll"
public var tapHereToChange = "点击更换相册"
public var cancelTitle = " "
public var usedCameraButton = true
public var usedPrefetch = true
public var allowedLivePhotos = true
public var allowedVideo = false
public var allowedVideoRecording = true
public var recordingVideoQuality: UIImagePickerControllerQualityType = .typeMedium
public var maxVideoDuration:TimeInterval? = nil
public var autoPlay = false
public var muteAudio = false
public var mediaType: PHAssetMediaType? = nil
public var numberOfColumn = 3
public var singleSelectedMode = false
public var maxSelectedAssets: Int? = 9
public var fetchOption: PHFetchOptions? = nil
public var selectedColor = UIColor(red: 88/255, green: 144/255, blue: 255/255, alpha: 1.0)
public var cameraBgColor = UIColor(red: 221/255, green: 223/255, blue: 226/255, alpha: 1)
public var cameraIcon = TLBundle.podBundleImage(named: "camera")
public var videoIcon = TLBundle.podBundleImage(named: "video")
public var placeholderIcon = TLBundle.podBundleImage(named: "insertPhotoMaterial")
public var nibSet: (nibName: String, bundle:Bundle)? = nil
public var cameraCellNibSet: (nibName: String, bundle:Bundle)? = nil
public init() {
}
}
open class TLPhotosPickerViewController: UIViewController {
@IBOutlet weak var sureCountButton: UIButton!
@IBOutlet open var titleLabel: UILabel!
@IBOutlet open var subTitleLabel: UILabel!
@IBOutlet open var subTitleArrowImageView: UIImageView!
@IBOutlet open var albumPopView: TLAlbumPopView!
@IBOutlet open var collectionView: UICollectionView!
@IBOutlet open var indicator: UIActivityIndicatorView!
@IBOutlet open var popArrowImageView: UIImageView!
@IBOutlet open var customNavItem: UINavigationItem!
@IBOutlet open var cancelButton: UIBarButtonItem!
@IBOutlet open var navigationBarTopConstraint: NSLayoutConstraint!
public weak var delegate: TLPhotosPickerViewControllerDelegate? = nil
public weak var logDelegate: TLPhotosPickerLogDelegate? = nil
public var selectedAssets = [TLPHAsset]()
public var configure = TLPhotosPickerConfigure()
fileprivate var usedCameraButton: Bool {
get {
return self.configure.usedCameraButton
}
}
fileprivate var usedPrefetch: Bool {
get {
return self.configure.usedPrefetch
}
set {
self.configure.usedPrefetch = newValue
}
}
@objc open var didExceedMaximumNumberOfSelection: ((TLPhotosPickerViewController) -> Void)? = nil
@objc open var handleNoAlbumPermissions: ((TLPhotosPickerViewController) -> Void)? = nil
@objc open var handleNoCameraPermissions: ((TLPhotosPickerViewController) -> Void)? = nil
@objc open var dismissCompletion: (() -> Void)? = nil
fileprivate var completionWithPHAssets: (([PHAsset]) -> Void)? = nil
fileprivate var completionWithTLPHAssets: (([TLPHAsset]) -> Void)? = nil
fileprivate var didCancel: (() -> Void)? = nil
fileprivate var collections = [TLAssetsCollection]()
fileprivate var focusedCollection: TLAssetsCollection? = nil
fileprivate var requestIds = [IndexPath:PHImageRequestID]()
fileprivate var cloudRequestIds = [IndexPath:PHImageRequestID]()
fileprivate var playRequestId: (indexPath: IndexPath, requestId: PHImageRequestID)? = nil
fileprivate var photoLibrary = TLPhotoLibrary()
fileprivate var queue = DispatchQueue(label: "tilltue.photos.pikcker.queue")
fileprivate var thumbnailSize = CGSize.zero
fileprivate var placeholderThumbnail: UIImage? = nil
fileprivate var cameraImage: UIImage? = nil
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init() {
super.init(nibName: "TLPhotosPickerViewController", bundle: Bundle(for: TLPhotosPickerViewController.self))
self.navigationController?.navigationBar.isHidden = true
}
@objc convenience public init(withPHAssets: (([PHAsset]) -> Void)? = nil, didCancel: (() -> Void)? = nil) {
self.init()
self.completionWithPHAssets = withPHAssets
self.didCancel = didCancel
}
convenience public init(withTLPHAssets: (([TLPHAsset]) -> Void)? = nil, didCancel: (() -> Void)? = nil) {
self.init()
self.completionWithTLPHAssets = withTLPHAssets
self.didCancel = didCancel
}
func updateCountButton(){
self.sureCountButton.setTitle("确定\(self.selectedAssets.count)/9", for: .normal)
if self.selectedAssets.count == 0 {
self.sureCountButton.setTitleColor(UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1.0), for: .normal)
} else {
self.sureCountButton.setTitleColor(UIColor(red: 0/255, green: 127/255, blue: 255/255, alpha: 1.0), for: .normal)
}
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func checkAuthorization() {
switch PHPhotoLibrary.authorizationStatus() {
case .notDetermined:
PHPhotoLibrary.requestAuthorization { [weak self] status in
switch status {
case .authorized:
self?.initPhotoLibrary()
default:
self?.handleDeniedAlbumsAuthorization()
}
}
case .authorized:
self.initPhotoLibrary()
case .restricted: fallthrough
case .denied:
handleDeniedAlbumsAuthorization()
}
}
override open func viewDidLoad() {
super.viewDidLoad()
makeUI()
checkAuthorization()
updateCountButton()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.thumbnailSize == CGSize.zero {
initItemSize()
}
// 判断是否 iPhone X 和 iOS11 处理 ,待调整
if #available(iOS 11.0, *) {
self.navigationBarTopConstraint.constant = 34
}
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.photoLibrary.delegate == nil {
initPhotoLibrary()
}
}
}
// MARK: - UI & UI Action
extension TLPhotosPickerViewController {
@objc public func registerNib(nibName: String, bundle: Bundle) {
self.collectionView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier: nibName)
}
fileprivate func centerAtRect(image: UIImage?, rect: CGRect, bgColor: UIColor = UIColor.white) -> UIImage? {
guard let image = image else { return nil }
UIGraphicsBeginImageContextWithOptions(rect.size, false, image.scale)
bgColor.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height))
image.draw(in: CGRect(x:rect.size.width/2 - image.size.width/2, y:rect.size.height/2 - image.size.height/2, width:image.size.width, height:image.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
fileprivate func initItemSize() {
guard let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let count = CGFloat(self.configure.numberOfColumn)
let width = (self.view.frame.size.width-( 5 * (count-1) ))/count
self.thumbnailSize = CGSize(width: width, height: width)
layout.itemSize = self.thumbnailSize
self.collectionView.collectionViewLayout = layout
self.placeholderThumbnail = centerAtRect(image: self.configure.placeholderIcon, rect: CGRect(x: 0, y: 0, width: width, height: width))
self.cameraImage = centerAtRect(image: self.configure.cameraIcon, rect: CGRect(x: 0, y: 0, width: width, height: width), bgColor: self.configure.cameraBgColor)
}
@objc open func makeUI() {
registerNib(nibName: "TLPhotoCollectionViewCell", bundle: Bundle(for: TLPhotoCollectionViewCell.self))
if let nibSet = self.configure.nibSet {
registerNib(nibName: nibSet.nibName, bundle: nibSet.bundle)
}
if let nibSet = self.configure.cameraCellNibSet {
registerNib(nibName: nibSet.nibName, bundle: nibSet.bundle)
}
self.indicator.startAnimating()
let tapView = UIView.init(frame: CGRect(x: 100, y:20, width: 200, height: 44))
tapView.backgroundColor = UIColor.clear
self.view.addSubview(tapView)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(titleTap))
tapView.addGestureRecognizer(tapGesture)
// 添加返回 image
self.titleLabel.text = self.configure.defaultCameraRollTitle
self.subTitleLabel.text = self.configure.tapHereToChange
self.cancelButton.title = self.configure.cancelTitle
self.albumPopView.tableView.delegate = self
self.albumPopView.tableView.dataSource = self
self.popArrowImageView.image = TLBundle.podBundleImage(named: "pop_arrow")
self.subTitleArrowImageView.image = TLBundle.podBundleImage(named: "arrow")
if #available(iOS 10.0, *), self.usedPrefetch {
self.collectionView.isPrefetchingEnabled = true
self.collectionView.prefetchDataSource = self
} else {
self.usedPrefetch = false
}
}
fileprivate func updateTitle() {
guard self.focusedCollection != nil else { return }
self.titleLabel.text = self.focusedCollection?.title
}
fileprivate func reloadCollectionView() {
guard self.focusedCollection != nil else { return }
self.collectionView.reloadData()
}
fileprivate func reloadTableView() {
let count = min(5, self.collections.count)
var frame = self.albumPopView.popupView.frame
frame.size.height = CGFloat(count * 75)
self.albumPopView.popupViewHeight.constant = CGFloat(count * 75)
UIView.animate(withDuration: self.albumPopView.show ? 0.1:0) {
self.albumPopView.popupView.frame = frame
self.albumPopView.setNeedsLayout()
}
self.albumPopView.tableView.reloadData()
self.albumPopView.setupPopupFrame()
}
fileprivate func initPhotoLibrary() {
if PHPhotoLibrary.authorizationStatus() == .authorized {
self.photoLibrary.delegate = self
self.photoLibrary.fetchCollection(configure: self.configure)
}else{
//self.dismiss(animated: true, completion: nil)
}
}
fileprivate func registerChangeObserver() {
PHPhotoLibrary.shared().register(self)
}
fileprivate func getfocusedIndex() -> Int {
guard let focused = self.focusedCollection, let result = self.collections.index(where: { $0 == focused }) else { return 0 }
return result
}
fileprivate func focused(collection: TLAssetsCollection) {
for (_,requestId) in self.requestIds {
self.photoLibrary.cancelPHImageRequest(requestId: requestId)
}
self.requestIds.removeAll()
self.collections[getfocusedIndex()].recentPosition = self.collectionView.contentOffset
var reloadIndexPaths = [IndexPath(row: getfocusedIndex(), section: 0)]
self.focusedCollection = collection
self.focusedCollection?.fetchResult = self.photoLibrary.fetchResult(collection: collection, configure: self.configure)
reloadIndexPaths.append(IndexPath(row: getfocusedIndex(), section: 0))
self.albumPopView.tableView.reloadRows(at: reloadIndexPaths, with: .none)
self.albumPopView.show(false, duration: 0.2)
self.updateTitle()
self.reloadCollectionView()
self.collectionView.contentOffset = collection.recentPosition
}
// User Action
@objc func titleTap() {
guard collections.count > 0 else { return }
self.albumPopView.show(self.albumPopView.isHidden)
}
@IBAction open func cancelButtonTap() {
self.dismiss(done: false)
}
// MARK : 确定 数字
@IBAction open func doneButtonAction() {
self.dismiss(done: true)
}
fileprivate func dismiss(done: Bool) {
if done {
self.delegate?.dismissPhotoPicker(withPHAssets: self.selectedAssets.compactMap{ $0.phAsset })
self.delegate?.dismissPhotoPicker(withTLPHAssets: self.selectedAssets)
self.completionWithTLPHAssets?(self.selectedAssets)
self.completionWithPHAssets?(self.selectedAssets.compactMap{ $0.phAsset })
}else {
self.delegate?.photoPickerDidCancel()
self.didCancel?()
}
self.dismiss(animated: true) { [weak self] in
self?.delegate?.dismissComplete()
self?.dismissCompletion?()
}
}
fileprivate func maxCheck() -> Bool {
if self.configure.singleSelectedMode {
self.selectedAssets.removeAll()
self.orderUpdateCells()
}
if let max = self.configure.maxSelectedAssets, max <= self.selectedAssets.count {
self.delegate?.didExceedMaximumNumberOfSelection(picker: self)
self.didExceedMaximumNumberOfSelection?(self)
return true
}
return false
}
}
// MARK: - TLPhotoLibraryDelegate
extension TLPhotosPickerViewController: TLPhotoLibraryDelegate {
func loadCameraRollCollection(collection: TLAssetsCollection) {
if let focused = self.focusedCollection, focused == collection {
focusCollection(collection: collection)
}
self.collections = [collection]
self.indicator.stopAnimating()
self.reloadCollectionView()
self.reloadTableView()
}
func loadCompleteAllCollection(collections: [TLAssetsCollection]) {
self.collections = collections
let isEmpty = self.collections.count == 0
self.subTitleLabel.isHidden = isEmpty
self.subTitleArrowImageView.isHidden = isEmpty
self.indicator.stopAnimating()
self.reloadTableView()
self.registerChangeObserver()
}
func focusCollection(collection: TLAssetsCollection) {
self.focusedCollection = collection
self.updateTitle()
}
}
// MARK: - Camera Picker
extension TLPhotosPickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
fileprivate func showCameraIfAuthorized() {
let cameraAuthorization = AVCaptureDevice.authorizationStatus(for: .video)
switch cameraAuthorization {
case .authorized:
self.showCamera()
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video, completionHandler: { [weak self] (authorized) in
DispatchQueue.main.async { [weak self] in
if authorized {
self?.showCamera()
} else {
self?.handleDeniedCameraAuthorization()
}
}
})
case .restricted, .denied:
self.handleDeniedCameraAuthorization()
}
}
fileprivate func showCamera() {
guard !maxCheck() else { return }
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.mediaTypes = [kUTTypeImage as String]
picker.allowsEditing = false
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
fileprivate func handleDeniedAlbumsAuthorization() {
self.delegate?.handleNoAlbumPermissions(picker: self)
self.handleNoAlbumPermissions?(self)
}
fileprivate func handleDeniedCameraAuthorization() {
self.delegate?.handleNoCameraPermissions(picker: self)
self.handleNoCameraPermissions?(self)
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = (info[UIImagePickerControllerOriginalImage] as? UIImage) {
var placeholderAsset: PHObjectPlaceholder? = nil
PHPhotoLibrary.shared().performChanges({
let newAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
placeholderAsset = newAssetRequest.placeholderForCreatedAsset
}, completionHandler: { [weak self] (sucess, error) in
if sucess, let `self` = self, let identifier = placeholderAsset?.localIdentifier {
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil).firstObject else { return }
var result = TLPHAsset(asset: asset)
result.selectedOrder = self.selectedAssets.count + 1
self.selectedAssets.append(result)
}
})
}
else if (info[UIImagePickerControllerMediaType] as? String) == kUTTypeMovie as String {
var placeholderAsset: PHObjectPlaceholder? = nil
PHPhotoLibrary.shared().performChanges({
let newAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: info[UIImagePickerControllerMediaURL] as! URL)
placeholderAsset = newAssetRequest?.placeholderForCreatedAsset
}) { [weak self] (sucess, error) in
if sucess, let `self` = self, let identifier = placeholderAsset?.localIdentifier {
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil).firstObject else { return }
var result = TLPHAsset(asset: asset)
result.selectedOrder = self.selectedAssets.count + 1
self.selectedAssets.append(result)
}
}
}
picker.dismiss(animated: true, completion: nil)
}
}
// MARK: - PHPhotoLibraryChangeObserver
extension TLPhotosPickerViewController: PHPhotoLibraryChangeObserver {
public func photoLibraryDidChange(_ changeInstance: PHChange) {
guard getfocusedIndex() == 0 else { return }
guard let changeFetchResult = self.focusedCollection?.fetchResult else { return }
guard let changes = changeInstance.changeDetails(for: changeFetchResult) else { return }
let addIndex = self.usedCameraButton ? 1 : 0
DispatchQueue.main.sync {
if changes.hasIncrementalChanges {
var deletedSelectedAssets = false
var order = 0
self.selectedAssets = self.selectedAssets.enumerated().compactMap({ (offset,asset) -> TLPHAsset? in
var asset = asset
if let phAsset = asset.phAsset, changes.fetchResultAfterChanges.contains(phAsset) {
order += 1
asset.selectedOrder = order
return asset
}
deletedSelectedAssets = true
return nil
})
if deletedSelectedAssets {
self.focusedCollection?.fetchResult = changes.fetchResultAfterChanges
self.collectionView.reloadData()
}else {
self.collectionView.performBatchUpdates({ [weak self] in
guard let `self` = self else { return }
self.focusedCollection?.fetchResult = changes.fetchResultAfterChanges
if let removed = changes.removedIndexes, removed.count > 0 {
self.collectionView.deleteItems(at: removed.map { IndexPath(item: $0+addIndex, section:0) })
}
if let inserted = changes.insertedIndexes, inserted.count > 0 {
self.collectionView.insertItems(at: inserted.map { IndexPath(item: $0+addIndex, section:0) })
}
if let changed = changes.changedIndexes, changed.count > 0 {
self.collectionView.reloadItems(at: changed.map { IndexPath(item: $0+addIndex, section:0) })
}
})
}
}else {
self.focusedCollection?.fetchResult = changes.fetchResultAfterChanges
self.collectionView.reloadData()
}
if let collection = self.focusedCollection {
self.collections[getfocusedIndex()] = collection
self.albumPopView.tableView.reloadRows(at: [IndexPath(row: getfocusedIndex(), section: 0)], with: .none)
}
}
}
}
// MARK: - UICollectionView delegate & datasource
extension TLPhotosPickerViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDataSourcePrefetching {
fileprivate func getSelectedAssets(_ asset: TLPHAsset) -> TLPHAsset? {
if let index = self.selectedAssets.index(where: { $0.phAsset == asset.phAsset }) {
return self.selectedAssets[index]
}
return nil
}
fileprivate func orderUpdateCells() {
let visibleIndexPaths = self.collectionView.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row })
for indexPath in visibleIndexPaths {
guard let cell = self.collectionView.cellForItem(at: indexPath) as? TLPhotoCollectionViewCell else { continue }
guard let asset = self.focusedCollection?.getTLAsset(at: indexPath.row) else { continue }
if getSelectedAssets(asset) != nil {
cell.selectedAsset = true
}else {
cell.selectedAsset = false
}
}
}
//Delegate
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 更换为点击查看大图
// guard let collection = self.focusedCollection, let cell = self.collectionView.cellForItem(at: indexPath) as? TLPhotoCollectionViewCell else { return }
// if collection.useCameraButton && indexPath.row == 0 {
// if let _ = self.configure.cameraCellNibSet?.nibName {
// cell.selectedCell()
// }else {
// self.logDelegate?.selectedCameraCell(picker: self)
// self.showCameraIfAuthorized()
// }
// }
// guard var asset = collection.getTLAsset(at: indexPath.row) else { return }
// cell.popScaleAnim()
// if let index = self.selectedAssets.index(where: { $0.phAsset == asset.phAsset }) {
// //deselect
// self.logDelegate?.deselectedPhoto(picker: self, at: indexPath.row)
// self.selectedAssets.remove(at: index)
// self.selectedAssets = self.selectedAssets.enumerated().compactMap({ (offset,asset) -> TLPHAsset? in
// var asset = asset
// asset.selectedOrder = offset + 1
// return asset
// })
// cell.selectedAsset = false
// self.orderUpdateCells()
// }else {
// self.logDelegate?.selectedPhoto(picker: self, at: indexPath.row)
// guard !self.maxCheck() else { return }
// asset.selectedOrder = self.selectedAssets.count + 1
// self.selectedAssets.append(asset)
// cell.selectedAsset = true
//
// }
}
open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? TLPhotoCollectionViewCell {
cell.endDisplayingCell()
}
guard let requestId = self.requestIds[indexPath] else { return }
self.requestIds.removeValue(forKey: indexPath)
self.photoLibrary.cancelPHImageRequest(requestId: requestId)
}
//Datasource
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
func makeCell(nibName: String) -> TLPhotoCollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: nibName, for: indexPath) as! TLPhotoCollectionViewCell
// cell.imageView?.image = self.placeholderThumbnail
return cell
}
let nibName = self.configure.nibSet?.nibName ?? "TLPhotoCollectionViewCell"
var cell = makeCell(nibName: nibName)
guard let collection = self.focusedCollection else { return cell }
cell.isCameraCell = collection.useCameraButton && indexPath.row == 0
if cell.isCameraCell {
if let nibName = self.configure.cameraCellNibSet?.nibName {
cell = makeCell(nibName: nibName)
}else{
cell.imageView?.image = self.cameraImage
cell.configCameraItem()
}
cell.willDisplayCell()
return cell
}
guard let asset = collection.getTLAsset(at: indexPath.row) else { return cell }
if getSelectedAssets(asset) != nil {
cell.selectedAsset = true
}else{
cell.selectedAsset = false
}
if asset.state == .progress {
cell.indicator?.startAnimating()
}else {
cell.indicator?.stopAnimating()
}
cell.tapRightChooseBlock = { [weak self] () in
guard let strongSelf = self else {
return
}
guard let collection = strongSelf.focusedCollection, let cell = strongSelf.collectionView.cellForItem(at: indexPath) as? TLPhotoCollectionViewCell else { return }
if collection.useCameraButton && indexPath.row == 0 {
if let _ = strongSelf.configure.cameraCellNibSet?.nibName {
cell.selectedCell()
}else {
strongSelf.logDelegate?.selectedCameraCell(picker: strongSelf)
strongSelf.showCameraIfAuthorized()
}
}
guard var asset = collection.getTLAsset(at: indexPath.row) else { return }
cell.popScaleAnim()
if let index = strongSelf.selectedAssets.index(where: { $0.phAsset == asset.phAsset }) {
//deselect
strongSelf.logDelegate?.deselectedPhoto(picker: strongSelf, at: indexPath.row)
strongSelf.selectedAssets.remove(at: index)
strongSelf.selectedAssets = strongSelf.selectedAssets.enumerated().compactMap({ (offset,asset) -> TLPHAsset? in
var asset = asset
asset.selectedOrder = offset + 1
return asset
})
cell.selectedAsset = false
strongSelf.orderUpdateCells()
}else {
strongSelf.logDelegate?.selectedPhoto(picker: strongSelf, at: indexPath.row)
guard !strongSelf.maxCheck() else { return }
asset.selectedOrder = strongSelf.selectedAssets.count + 1
strongSelf.selectedAssets.append(asset)
cell.selectedAsset = true
}
strongSelf.updateCountButton()
}
if let phAsset = asset.phAsset {
if self.usedPrefetch {
let options = PHImageRequestOptions()
options.deliveryMode = .opportunistic
options.isNetworkAccessAllowed = true
let requestId = self.photoLibrary.imageAsset(asset: phAsset, size: self.thumbnailSize, options: options) { [weak cell] (image,complete) in
DispatchQueue.main.async {
if self.requestIds[indexPath] != nil {
cell?.imageView?.image = image
if complete {
self.requestIds.removeValue(forKey: indexPath)
}
}
}
}
if requestId > 0 {
self.requestIds[indexPath] = requestId
}
}else {
queue.async { [weak self, weak cell] in
guard let `self` = self else { return }
let requestId = self.photoLibrary.imageAsset(asset: phAsset, size: self.thumbnailSize, completionBlock: { (image,complete) in
DispatchQueue.main.async {
if self.requestIds[indexPath] != nil {
cell?.imageView?.image = image
if complete {
self.requestIds.removeValue(forKey: indexPath)
}
}
}
})
if requestId > 0 {
self.requestIds[indexPath] = requestId
}
}
}
}
cell.alpha = 0
UIView.transition(with: cell, duration: 0.1, options: .curveEaseIn, animations: {
cell.alpha = 1
}, completion: nil)
return cell
}
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let collection = self.focusedCollection else { return 0 }
return collection.count
}
//Prefetch
open func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
if self.usedPrefetch {
queue.async { [weak self] in
guard let `self` = self, let collection = self.focusedCollection else { return }
var assets = [PHAsset]()
for indexPath in indexPaths {
if let asset = collection.getAsset(at: indexPath.row) {
assets.append(asset)
}
}
let scale = max(UIScreen.main.scale,2)
let targetSize = CGSize(width: self.thumbnailSize.width*scale, height: self.thumbnailSize.height*scale)
self.photoLibrary.imageManager.startCachingImages(for: assets, targetSize: targetSize, contentMode: .aspectFill, options: nil)
}
}
}
open func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
if self.usedPrefetch {
for indexPath in indexPaths {
guard let requestId = self.requestIds[indexPath] else { continue }
self.photoLibrary.cancelPHImageRequest(requestId: requestId)
self.requestIds.removeValue(forKey: indexPath)
}
queue.async { [weak self] in
guard let `self` = self, let collection = self.focusedCollection else { return }
var assets = [PHAsset]()
for indexPath in indexPaths {
if let asset = collection.getAsset(at: indexPath.row) {
assets.append(asset)
}
}
let scale = max(UIScreen.main.scale,2)
let targetSize = CGSize(width: self.thumbnailSize.width*scale, height: self.thumbnailSize.height*scale)
self.photoLibrary.imageManager.stopCachingImages(for: assets, targetSize: targetSize, contentMode: .aspectFill, options: nil)
}
}
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if self.usedPrefetch, let cell = cell as? TLPhotoCollectionViewCell, let collection = self.focusedCollection, let asset = collection.getTLAsset(at: indexPath.row) {
if getSelectedAssets(asset) != nil {
cell.selectedAsset = true
}else{
cell.selectedAsset = false
}
}
}
}
// MARK: - UITableView datasource & delegate
extension TLPhotosPickerViewController: UITableViewDelegate,UITableViewDataSource {
//delegate
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.logDelegate?.selectedAlbum(picker: self, title: self.collections[indexPath.row].title, at: indexPath.row)
self.focused(collection: self.collections[indexPath.row])
}
//datasource
open func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.collections.count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TLCollectionTableViewCell", for: indexPath) as! TLCollectionTableViewCell
let collection = self.collections[indexPath.row]
cell.titleLabel.text = collection.title
cell.subTitleLabel.text = "\(collection.fetchResult?.count ?? 0)"
if let phAsset = collection.getAsset(at: collection.useCameraButton ? 1 : 0) {
let scale = UIScreen.main.scale
let size = CGSize(width: 80*scale, height: 80*scale)
self.photoLibrary.imageAsset(asset: phAsset, size: size, completionBlock: { [weak cell] (image,complete) in
DispatchQueue.main.async {
cell?.thumbImageView.image = image
}
})
}
cell.accessoryType = getfocusedIndex() == indexPath.row ? .checkmark : .none
cell.selectionStyle = .none
return cell
}
}
| mit | aa360e54948afd927ac9f0d113736fea | 43.347879 | 182 | 0.627053 | 5.182295 | false | false | false | false |
0416354917/FeedMeIOS | FeedMeIOS/NewAddressViewController.swift | 3 | 2578 | //
// NewAddressViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 30/03/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class NewAddressViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var userNameTextField: UITextField!
@IBOutlet weak var addressLine1TextField: UITextField!
@IBOutlet weak var addressLine2TextField: UITextField!
@IBOutlet weak var suburbTextField: UITextField!
@IBOutlet weak var stateTextField: UITextField!
@IBOutlet weak var postalCodeTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var cancelButton: UIBarButtonItem!
@IBOutlet weak var saveButton: UIBarButtonItem!
// MARK: - Properties
var address: Address?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonClicked(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
// Disable the Save button while editing.
saveButton.enabled = false
}
func textFieldDidEndEditing(textField: UITextField) {
validateInput()
}
func validateInput() {
saveButton.enabled = 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.
if saveButton === sender {
let userName = userNameTextField.text!
let addressLine1 = addressLine1TextField.text!
let addressLine2 = addressLine2TextField.text!
let suburb = suburbTextField.text!
let state = stateTextField.text!
let postalCode = postalCodeTextField.text!
let phone = phoneTextField.text!
address = Address(userName: userName, addressLine1: addressLine1, addressLine2: addressLine2, postcode: postalCode, phone: phone, suburb: suburb, state: state, selected: true)
}
}
}
| bsd-3-clause | 3945e7d4a336b6e3ee9d830fab8655d6 | 31.620253 | 187 | 0.674816 | 5.237805 | false | false | false | false |
rzrasel/iOS-Swift-2016-01 | SwiftCLLocationManagerOne/SwiftCLLocationManagerOne/ViewController.swift | 2 | 2823 | //
// ViewController.swift
// SwiftCLLocationManagerOne
//
// Created by NextDot on 2/7/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
//|------------------------------------|
var locationManager: CLLocationManager!
@IBOutlet var sysLabelCoreLocation: UILabel!
//|------------------------------------|
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
sysLabelCoreLocation.text = "Location"
funInitLocationManager()
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func funInitLocationManager()
{
locationManager = CLLocationManager()
locationManager.delegate = self
// check & allow location manager
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined {
locationManager.requestAlwaysAuthorization()
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
var locCounter = 0;
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
locCounter++
let location:CLLocation = locations.last!
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
var latLng: String
//latLng = "Location - Latitude: " + latitude + " - Longitude: " + longitude
latLng = "Location\nLatitude: \(latitude) - Longitude: \(longitude)"
//latLng = sysLabelCoreLocation.text! + "\n" + latLng
sysLabelCoreLocation.text = latLng
if(locCounter % 2 == 0)
{
sysLabelCoreLocation.text = ""
}
print("Location:- \(latitude) - \(longitude)");
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
if (error != "") {
print("Update Location Error : \(error.description)")
}
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func updateLocation(currentLocation:CLLocation){
let latitude = currentLocation.coordinate.latitude
let longitude = currentLocation.coordinate.longitude
print("Location:- \(latitude) - \(longitude)");
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
} | apache-2.0 | b95dd0ca17cb43080ef1d1a6ab079bfe | 37.148649 | 97 | 0.570872 | 5.43738 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Foundation/Extensions/AppDelegateExtension.swift | 2 | 9164 | //
// AppDelegateExtension.swift
// Client
//
// Created by Mahmoud Adam on 2/2/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import UIKit
import Shared
// Cliqz: handel home screen quick actions
extension AppDelegate {
// identifier for the shortcuts
var lastWebsiteIdentifier : String { get { return "com.cliqz.LastWebsite" } }
var topNewsIdentifier : String { get { return "com.cliqz.TopNews" } }
var topSitesIdentifier : String { get { return "com.cliqz.TopSites" } }
var topNewsURL : String { get { return "https://newbeta.cliqz.com/api/v2/rich-header?path=/map&bmresult=rotated-top-news.cliqz.com&locale=\(Locale.current.identifier)" } }
// MARK:- Delegate methods
// Handeling user action when opening the app from home quick action
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
completionHandler(self.handleShortcut(shortcutItem))
}
// MARK: Remote notifications
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
SubscriptionsHandler.sharedInstance.didRegisterForRemoteNotifications(withDeviceToken: deviceTokenString)
}
func application(_ application: UIApplication,didFailToRegisterForRemoteNotificationsWithError error: Error) {
SubscriptionsHandler.sharedInstance.didFailToRegisterForRemoteNotifications(withError: error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
SubscriptionsHandler.sharedInstance.didReceiveRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
}
func application(_ application: UIApplication, willChangeStatusBarOrientation newStatusBarOrientation: UIInterfaceOrientation, duration: TimeInterval) {
self.normalModeBgImage?.image = UIImage.fullBackgroundImage()
}
// MARK:- Public API
// configure the dynamic shortcuts
@available(iOS 9.0, *)
func configureHomeShortCuts() {
var shortcutItems = [UIApplicationShortcutItem]()
// last website shortcut
let lastWebsiteTitle = NSLocalizedString("Last site", tableName: "Cliqz", comment: "Title for `Last site` home shortcut.")
let lastWebsiteIcon = UIApplicationShortcutIcon(templateImageName: "lastVisitedSite")
let lastWebsiteShortcutItem = UIApplicationShortcutItem(type: lastWebsiteIdentifier, localizedTitle: lastWebsiteTitle, localizedSubtitle: nil, icon: lastWebsiteIcon, userInfo: nil)
shortcutItems.append(lastWebsiteShortcutItem)
// top news shortcut
let topNewsTitle = NSLocalizedString("Top news", tableName: "Cliqz", comment: "Title for `Top news` home shortcut.")
let topNewsIcon = UIApplicationShortcutIcon(templateImageName: "topNews")
let topNewsShortcutItem = UIApplicationShortcutItem(type: topNewsIdentifier, localizedTitle: topNewsTitle, localizedSubtitle: nil, icon: topNewsIcon, userInfo: nil)
shortcutItems.append(topNewsShortcutItem)
if self.profile!.history.count() > 0 {
// add shortcuts for 2 top-sites
appendTopSitesWithLimit(2, shortcutItems: shortcutItems)
} else {
// assign the applicaiton shortcut items
UIApplication.shared.shortcutItems = shortcutItems
}
}
// Cliqz: Change the status bar style and color
func changeStatusBarStyle(_ statusBarStyle: UIStatusBarStyle, backgroundColor: UIColor, isNormalMode: Bool) {
UIApplication.shared.statusBarStyle = statusBarStyle
if backgroundColor != UIColor.clear {
self.forgetModeBgImage?.removeFromSuperview()
self.normalModeBgImage?.removeFromSuperview()
UIApplication.shared.delegate?.window??.backgroundColor = backgroundColor
}
}
func changeToBgImage(_ statusBarStyle: UIStatusBarStyle, isNormalMode: Bool) {
UIApplication.shared.statusBarStyle = statusBarStyle
self.forgetModeBgImage?.removeFromSuperview()
self.normalModeBgImage?.removeFromSuperview()
var img = self.forgetModeBgImage
if isNormalMode {
self.normalModeBgImage?.image = UIImage.fullBackgroundImage()
img = self.normalModeBgImage
}
self.window?.addSubview(img!)
self.window?.sendSubview(toBack: img!)
img?.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalTo(self.window!)
}
}
// MARK:- Private methods
// append top sites shortcuts to the application shortcut items
@available(iOS 9.0, *)
fileprivate func appendTopSitesWithLimit(_ limit: Int, shortcutItems: [UIApplicationShortcutItem]) -> Success {
let topSitesIcon = UIApplicationShortcutIcon(templateImageName: "topSites")
var allShortcutItems = shortcutItems
return self.profile!.history.getTopSitesWithLimit(limit).bindQueue(DispatchQueue.main) { result in
if let r = result.successValue {
for site in r {
// top news shortcut
if let url = site?.url,
let domainURL = self.extractDomainUrl(url),
let domainName = self.extractDomainName(url) {
let userInfo = ["url" : domainURL]
let topSiteShortcutItem = UIApplicationShortcutItem(type: self.topSitesIdentifier, localizedTitle: domainName, localizedSubtitle: nil, icon: topSitesIcon, userInfo: userInfo)
allShortcutItems.append(topSiteShortcutItem)
}
}
}
DispatchQueue.main.async(execute: {
// assign the applicaiton shortcut items
UIApplication.shared.shortcutItems = allShortcutItems
})
return succeed()
}
}
// getting the domain name of the url to be used as title for the shortcut
fileprivate func extractDomainName(_ urlString: String) -> String? {
if let url = URL(string: urlString),
let domain = url.host {
return domain.replace("www.", replacement: "")
}
return nil
}
// get the domain url of the top site url to navigate to when user selects this quick action
fileprivate func extractDomainUrl(_ urlString: String) -> String? {
if let url = URL(string: urlString),
let domain = url.host {
return "http://\(domain)"
}
return nil
}
// handel shortcut action
@available(iOS 9.0, *)
fileprivate func handleShortcut(_ shortcutItem:UIApplicationShortcutItem) -> Bool {
let index = UIApplication.shared.shortcutItems?.index(of: shortcutItem)
var succeeded = false
if shortcutItem.type == lastWebsiteIdentifier {
// open last website
browserViewController.navigateToLastWebsite()
TelemetryLogger.sharedInstance.logEvent(.HomeScreenShortcut("last_site", index!))
succeeded = true
} else if shortcutItem.type == topNewsIdentifier {
// open random top news
navigateToRandomTopNews()
TelemetryLogger.sharedInstance.logEvent(.HomeScreenShortcut("top_news", index!))
succeeded = true
} else if shortcutItem.type == topSitesIdentifier {
if let topSiteURL = shortcutItem.userInfo?["url"] as? String {
browserViewController.initialURL = topSiteURL
TelemetryLogger.sharedInstance.logEvent(.HomeScreenShortcut("top_site", index!))
succeeded = true
}
} else {
let eventAttributes = ["title" : shortcutItem.localizedTitle, "type" : shortcutItem.type]
print("UnhandledHomeScreenAction \(eventAttributes)")
}
return succeeded
}
fileprivate func navigateToRandomTopNews() {
ConnectionManager.sharedInstance.sendRequest(.get, url: topNewsURL, parameters: nil, responseType: .jsonResponse, queue: DispatchQueue.main,
onSuccess: { json in
let jsonDict = json as! [String : AnyObject]
let results = jsonDict["results"] as! [[String : AnyObject]]
let articles = results[0]["articles"] as! [AnyObject]
let randomIndex = Int(arc4random_uniform(UInt32(articles.count)))
let randomArticle = articles[randomIndex] as! [String : AnyObject]
let randomURl = randomArticle["url"] as! String
self.browserViewController.initialURL = randomURl
self.browserViewController.loadInitialURL()
},
onFailure: { (data, error) in
let eventAttributes = ["url" : self.topNewsURL, "error" : "\(error)"]
print("TopNewsError\(eventAttributes)")
})
}
}
| mpl-2.0 | 66200050465dc9b5768eb7deb73791ce | 45.75 | 202 | 0.67085 | 5.144862 | false | false | false | false |
Deklo/gallows | Gallows/Gallows/GameViewController.swift | 1 | 2153 | //
// GameViewController.swift
// Gallows
//
// Created by Dylan Sabenfass on 8/20/15.
// Copyright (c) 2015 Dylan Sabenfass. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| cc0-1.0 | 116438223d2cb757d1c02c015a2facf3 | 30.202899 | 104 | 0.62471 | 5.506394 | false | false | false | false |
mtransitapps/mtransit-for-ios | MonTransit/AppDelegate.swift | 1 | 8238 | //
// AppDelegate.swift
// SidebarMenu
//
// Created by Simon Ng on 2/2/15.
// Copyright (c) 2015 Thibault. All rights reserved.
//
import UIKit
import MapKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate, AlertAgencyDelegate {
var backgroundSessionCompletionHandler : (() -> Void)?
private var mUserLocation:CLLocation!
private var mLocationManager: CLLocationManager!
private let mJson = JsonAgencyAlert()
let dispatchingUserPosition = DispatchingValue(CLLocation())
let dispatchingUserAddress = DispatchingValue("")
var mPositionSetted: Bool = false
var window: UIWindow?
func sharedInstance() -> AppDelegate{
return UIApplication.sharedApplication().delegate as! AppDelegate
}
func startLocationManager() {
if CLLocationManager.locationServicesEnabled() {
mLocationManager = CLLocationManager()
mLocationManager.delegate = self
mLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
mLocationManager.requestWhenInUseAuthorization()
mLocationManager.distanceFilter = 10.0
mLocationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error) in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
let wNewPosition = manager.location!
let wDistance = Int(self.mUserLocation.coordinate.distanceInMetersFrom(CLLocationCoordinate2D(latitude: wNewPosition.coordinate.latitude, longitude: wNewPosition.coordinate.longitude)))
if wDistance > 10{
mPositionSetted = true
mUserLocation = manager.location!
dispatchingUserPosition.value = mUserLocation
}
}
func displayLocationInfo(placemark: CLPlacemark) {
dispatchingUserAddress.value = placemark.addressDictionary!["Street"] as? String ?? ""
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error while updating location " + error.localizedDescription)
mPositionSetted = true
dispatchingUserPosition.value = mUserLocation
}
func locationManagerDidPauseLocationUpdates(manager: CLLocationManager) {
}
func getUserLocation() -> CLLocation{
return mUserLocation
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Check if databse created
// debug delete
//File.deleteContentsOfFolder(File.getDocumentFilePath())
parseXmlAgency()
if !File.documentFileExist(NSBundle.mainBundle().releaseVersionNumber!)
{
displayLoadingView()
}
else
{
// set zip path
for wAgency in AgencyManager.getAgencies(){
wAgency.setZipData()
}
SQLProvider.sqlProvider.openDatabase()
displayNearestView()
}
return true
}
private func parseXmlAgency()
{
var wString = File.open(File.getBundleFilePath("Agencies", iOfType: "xml")!)!
wString = wString.stringByReplacingOccurrencesOfString("\n", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "")
let parser=XMLParser(xml: wString, element:"agency")
parser.parse()
let agencies = parser.getAgencies()
AgencyManager.setAgencies(agencies)
if agencies.capacity > 0 {
AgencyManager.setCurrentAgency((agencies.first?.mAgencyId)!)
}
}
private func displayNearestView(){
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let swViewController: SwiftSWRevealViewController = mainStoryboard.instantiateViewControllerWithIdentifier("SWRevealViewController") as! SwiftSWRevealViewController
self.window?.rootViewController = swViewController
self.window?.makeKeyAndVisible()
}
private func displayLoadingView(){
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let swViewController: LoadingViewController = mainStoryboard.instantiateViewControllerWithIdentifier("LoadingViewController") as! LoadingViewController
self.window?.rootViewController = swViewController
self.window?.makeKeyAndVisible()
}
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.
// retrieve user position
mUserLocation = CLLocation(latitude: AgencyManager.getAgency().getLatitude(), longitude: AgencyManager.getAgency().getLongitude())
startLocationManager()
//retrieve alert
mJson.delegate = self
mJson.getJsonAlert(AgencyManager.getAgency().getJsonAlertPath())
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func getJson() -> JsonAgencyAlert{
return mJson
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let events = event!.allTouches()
let touch = events!.first
let location = touch!.locationInView(self.window)
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
if CGRectContainsPoint(statusBarFrame, location) {
NSNotificationCenter.defaultCenter().postNotificationName("statusBarSelected", object: nil)
}
}
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
backgroundSessionCompletionHandler = completionHandler
}
}
| apache-2.0 | 4d7b59f05008de8f542d37f99f0c5a1a | 39.382353 | 285 | 0.673343 | 5.943723 | false | false | false | false |
sundeepgupta/butterfly | butterfly/Settings.swift | 1 | 969 | import UIKit
public struct Settings {
public static func mailSubject() -> String {
let defaults = NSUserDefaults.standardUserDefaults()
let subject = defaults.stringForKey("mailSubject")
return subject ?? ""
}
public static func saveMailSubject(subject: String) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(subject, forKey: "mailSubject")
defaults.synchronize()
}
public static func reminderTime() -> NSDate {
let defaults = NSUserDefaults.standardUserDefaults()
let time = defaults.objectForKey("reminderTime") as? NSDate
return time ?? NSDate()
}
public static func saveReminderTime(time: NSDate) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(time, forKey: "reminderTime")
defaults.synchronize()
ScheduleReminder.perform(time)
}
}
| mit | 59aef2f45e930c3ab49f5f780504de2e | 30.258065 | 67 | 0.646027 | 5.474576 | false | false | false | false |
zenangst/Faker | Source/Generators/Generator.swift | 1 | 1606 | import Foundation
public class Generator {
public struct Constants {
public static let uppercaseLetters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
public static let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
public static let numbers = Array("0123456789")
}
let parser: Parser
let dateFormatter: NSDateFormatter
public required init(parser: Parser) {
self.parser = parser
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
}
public func generate(key: String) -> String {
return parser.fetch(key)
}
// MARK: - Filling
public func numerify(string: String) -> String {
let count = UInt32(Constants.numbers.count)
return String(map(enumerate(string)) {
(index, item) in
let numberIndex = index == 0 ? arc4random_uniform(count - 1) + 1 :
arc4random_uniform(count)
let char = Constants.numbers[Int(numberIndex)]
return item == "#" ? char : item
})
}
public func letterify(string: String) -> String {
return String(map(string.generate()) {
let count = UInt32(Constants.uppercaseLetters.count)
let char = Constants.uppercaseLetters[Int(arc4random_uniform(count))]
return $0 == "?" ? char : $0
})
}
public func bothify(string: String) -> String {
return letterify(numerify(string))
}
public func alphaNumerify(string: String) -> String {
return string.stringByReplacingOccurrencesOfString("[^A-Za-z0-9_]",
withString: "",
options: NSStringCompareOptions.RegularExpressionSearch,
range: nil)
}
}
| mit | 6fd02788d9d2b916e0ecc2d1024b8626 | 27.678571 | 93 | 0.679328 | 4.352304 | false | false | false | false |
tsaievan/XYReadBook | XYReadBook/XYReadBook/Classes/Tools/Extensions/UIImageView+Extension.swift | 1 | 1973 | //
// UIImageView+Extension.swift
// BookRead
//
// Created by fox on 2017/6/5.
// Copyright © 2017年 DZM. All rights reserved.
//
import Foundation
import YYWebImage
extension UIImageView {
convenience init (imageName:String) {
self.init()
self.image = UIImage(named:imageName)
}
func setImageView(urlString:String,placeHolder:String? = nil){
let imageUrl = NSURL.init(string: urlString)
if let placeHolder = placeHolder {
self.yy_setImage(with: imageUrl! as URL, placeholder: UIImage.init(named: placeHolder))
} else {
self.yy_setImage(with: imageUrl! as URL, options: YYWebImageOptions(rawValue: 0))
}
}
}
/// MARK 扩大按钮响应范围
/// 设置此属性即可扩大响应范围, 分别对应上左下右
private var ExtendEdgeInsetsKey: Void?
extension UIButton {
var extendEdgeInsets: UIEdgeInsets {
get {
return objc_getAssociatedObject(self, &ExtendEdgeInsetsKey) as? UIEdgeInsets ?? UIEdgeInsets.zero
}
set {
objc_setAssociatedObject(self, &ExtendEdgeInsetsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if UIEdgeInsetsEqualToEdgeInsets(extendEdgeInsets, .zero) || !self.isEnabled || self.isHidden || self.alpha < 0.01 {
return super.point(inside: point, with: event)
}
let newRect = extendRect(bounds, extendEdgeInsets)
return newRect.contains(point)
}
private func extendRect(_ rect: CGRect, _ edgeInsets: UIEdgeInsets) -> CGRect {
let x = rect.minX - edgeInsets.left
let y = rect.minY - edgeInsets.top
let w = rect.width + edgeInsets.left + edgeInsets.right
let h = rect.height + edgeInsets.top + edgeInsets.bottom
return CGRect(x: x, y: y, width: w, height: h)
}
}
| mit | cfc17f89a338f517f28e835730ed7de2 | 31.40678 | 124 | 0.637029 | 4.138528 | false | false | false | false |
qlongming/shppingCat | shoppingCart-master/shoppingCart/Classes/GoodList/View/MSGoodListCell.swift | 1 | 4330 | //
// JFGoodListCell.swift
// shoppingCart
//
// Created by jianfeng on 15/11/17.
// Copyright © 2015年 六阿哥. All rights reserved.
//
import UIKit
protocol MSGoodListCellDelegate: NSObjectProtocol {
func goodListCell(cell: MSGoodListCell, iconView: UIImageView)
}
class MSGoodListCell: UITableViewCell {
// MARK: - 属性
/// 商品模型
var goodModel: MSGoodModel? {
didSet {
if let iconName = goodModel?.iconName {
iconView.image = UIImage(named: iconName)
}
if let title = goodModel?.title {
titleLabel.text = title
}
if let desc = goodModel?.desc {
descLabel.text = desc
}
// 已经点击的就禁用,这样做是防止cell重用
addCartButton.enabled = !goodModel!.alreadyAddShoppingCart
// 重新布局,会更新frame
layoutIfNeeded()
}
}
/// 代理属性
weak var delegate: MSGoodListCellDelegate?
/// 回调给控制器的商品图标
var callBackIconView: UIImageView?
// MARK: - 构造方法
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// 准备UI
prepareUI()
}
/**
准备UI
*/
private func prepareUI() {
// 添加子控件
contentView.addSubview(iconView)
contentView.addSubview(titleLabel)
contentView.addSubview(descLabel)
contentView.addSubview(addCartButton)
// 约束子控件
iconView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(12)
make.top.equalTo(10)
make.width.equalTo(60)
make.height.equalTo(60)
}
titleLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(contentView.snp_top).offset(10)
make.left.equalTo(iconView.snp_right).offset(12)
}
descLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(titleLabel.snp_bottom).offset(12)
make.left.equalTo(iconView.snp_right).offset(12)
}
addCartButton.snp_makeConstraints { (make) -> Void in
make.right.equalTo(-12)
make.top.equalTo(25)
make.width.equalTo(80)
make.height.equalTo(30)
}
}
// MARK: - 响应事件
/**
点击了购买按钮的事件
- parameter button: 购买按钮
*/
@objc private func didTappedAddCartButton(button: UIButton) {
// 已经购买
goodModel!.alreadyAddShoppingCart = true
// 已经点击的就禁用
button.enabled = !goodModel!.alreadyAddShoppingCart
// 通知代理对象,去处理后续操作
delegate?.goodListCell(self, iconView: iconView)
}
// MARK: - 懒加载
/// 商品图片
private lazy var iconView: UIImageView = {
let iconView = UIImageView()
iconView.layer.cornerRadius = 30
iconView.layer.masksToBounds = true
return iconView
}()
/// 商品标题
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
return titleLabel
}()
/// 商品描述
private lazy var descLabel: UILabel = {
let descLabel = UILabel()
descLabel.textColor = UIColor.grayColor()
return descLabel
}()
/// 添加按钮
private lazy var addCartButton: UIButton = {
let addCartButton = UIButton(type: UIButtonType.Custom)
addCartButton.setBackgroundImage(UIImage(named: "button_cart_add"), forState: UIControlState.Normal)
addCartButton.setTitle("购买", forState: UIControlState.Normal)
// 添加按钮点击事件
addCartButton.addTarget(self, action: "didTappedAddCartButton:", forControlEvents: UIControlEvents.TouchUpInside)
return addCartButton
}()
}
| apache-2.0 | 02d65150951bbcb10eb0646d69874f03 | 25.464052 | 121 | 0.566313 | 4.702671 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyer/Error/DeserializationError.swift | 1 | 1168 | enum DeserializationErrorType {
case missingRequiredData
case invalidInputFormat
case typeMismatch
func description() -> String {
switch(self) {
case .missingRequiredData:
return "MissingRequiredData"
case .invalidInputFormat:
return "InvalidInputFormat"
case .typeMismatch:
return "TypeMismatch"
}
}
}
struct DeserializationError: FFError {
fileprivate(set) var details: String
fileprivate(set) var type: DeserializationErrorType
init(details: String, type: DeserializationErrorType) {
self.details = details
self.type = type
}
var errorDescription: String? {
get {
return description
}
}
}
extension DeserializationError: Equatable { }
func ==(lhs: DeserializationError, rhs: DeserializationError) -> Bool {
return lhs.details == rhs.details && lhs.type == rhs.type
}
extension DeserializationError: CustomStringConvertible {
var description: String {
get {
return "DeserializationError { details: \"\(details)\", type: \"\(type.description())\" }"
}
}
}
| apache-2.0 | b3dd037a0e4c4b3a7cca7654d8be3ecd | 24.391304 | 102 | 0.635274 | 5.168142 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyerTests/Authentication/GitHubAuthViewControllerSpec.swift | 1 | 13958 | import XCTest
import Quick
import Nimble
import Fleet
@testable import FrequentFlyer
class GitHubAuthViewControllerSpec: QuickSpec {
class MockKeychainWrapper: KeychainWrapper {
var capturedTarget: Target?
override func saveTarget(_ target: Target) {
capturedTarget = target
}
}
class MockHTTPSessionUtils: HTTPSessionUtils {
var didDeleteCookies: Bool = false
override func deleteCookies() {
didDeleteCookies = true
}
}
class MockTokenValidationService: TokenValidationService {
var capturedToken: Token?
var capturedConcourseURLString: String?
var capturedCompletion: ((FFError?) -> ())?
override func validate(token: Token, forConcourse concourseURLString: String, completion: ((Error?) -> ())?) {
capturedToken = token
capturedConcourseURLString = concourseURLString
capturedCompletion = completion
}
}
class MockWebViewController: WebViewController {
override func viewDidLoad() { }
}
override func spec() {
describe("GitHubAuthViewController") {
var subject: GitHubAuthViewController!
var mockKeychainWrapper: MockKeychainWrapper!
var mockHTTPSessionUtils: MockHTTPSessionUtils!
var mockTokenValidationService: MockTokenValidationService!
var mockUserTextInputPageOperator: UserTextInputPageOperator!
var mockPipelinesViewController: PipelinesViewController!
var mockWebViewController: WebViewController!
beforeEach {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
mockWebViewController = try! storyboard.mockIdentifier(WebViewController.storyboardIdentifier , usingMockFor: WebViewController.self)
mockPipelinesViewController = try! storyboard.mockIdentifier(PipelinesViewController.storyboardIdentifier, usingMockFor: PipelinesViewController.self)
subject = storyboard.instantiateViewController(withIdentifier: GitHubAuthViewController.storyboardIdentifier) as! GitHubAuthViewController
subject.concourseURLString = "turtle_concourse.com"
subject.teamName = "turtle_team"
subject.gitHubAuthURLString = "turtle_gitHub.com"
mockKeychainWrapper = MockKeychainWrapper()
subject.keychainWrapper = mockKeychainWrapper
mockHTTPSessionUtils = MockHTTPSessionUtils()
subject.httpSessionUtils = mockHTTPSessionUtils
mockTokenValidationService = MockTokenValidationService()
subject.tokenValidationService = mockTokenValidationService
mockUserTextInputPageOperator = UserTextInputPageOperator()
subject.userTextInputPageOperator = mockUserTextInputPageOperator
}
describe("After the view has loaded") {
beforeEach {
let navigationController = UINavigationController(rootViewController: subject)
Fleet.setAsAppWindowRoot(navigationController)
}
it("sets a blank title") {
expect(subject.title).to(equal(""))
}
it("sets itself as its token text field's delegate") {
expect(subject.tokenTextField?.textField?.delegate).to(beIdenticalTo(subject))
}
it("sets itself as its UserTextInputPageOperator's delegate") {
expect(mockUserTextInputPageOperator.delegate).to(beIdenticalTo(subject))
}
describe("As a UserTextInputPageDelegate") {
it("returns text fields") {
expect(subject.textFields.count).to(equal(1))
expect(subject.textFields[0]).to(beIdenticalTo(subject?.tokenTextField?.textField))
}
it("returns a page view") {
expect(subject.pageView).to(beIdenticalTo(subject.view))
}
it("returns a page scrolls view") {
expect(subject.pageScrollView).to(beIdenticalTo(subject.scrollView))
}
}
describe("Availability of the 'Get Token' button") {
it("is always enabled") {
expect(subject.openGitHubAuthPageButton?.isEnabled).to(beTrue())
}
}
describe("Availability of the 'Submit' button") {
it("is disabled just after the view is loaded") {
expect(subject.loginButton!.isEnabled).to(beFalse())
}
describe("When the 'Token' field has text") {
beforeEach {
subject.tokenTextField?.textField?.enter(text: "token of the GitHub Turtle")
}
it("enables the button") {
expect(subject.loginButton!.isEnabled).to(beTrue())
}
describe("When the 'Token' field is cleared") {
beforeEach {
subject.tokenTextField?.textField?.startEditing()
subject.tokenTextField?.textField?.backspaceAll()
subject.tokenTextField?.textField?.stopEditing()
}
it("disables the button") {
expect(subject.loginButton!.isEnabled).to(beFalse())
}
}
}
describe("When pasting text into the 'Token' field") {
beforeEach {
subject.tokenTextField?.textField?.startEditing()
subject.tokenTextField?.textField?.paste(text: "some text")
subject.tokenTextField?.textField?.stopEditing()
}
it("enables the button") {
expect(subject.loginButton!.isEnabled).to(beTrue())
}
}
}
describe("Tapping on the 'Get Token' button") {
beforeEach {
subject.openGitHubAuthPageButton?.tap()
}
it("presents a WebViewController") {
expect(Fleet.getApplicationScreen()?.topmostViewController).toEventually(beIdenticalTo(mockWebViewController))
}
it("disables the button") {
expect(subject.openGitHubAuthPageButton?.isEnabled).toEventually(beFalse())
}
describe("The presented web view") {
it("is loaded with the given auth URL") {
let predicate: () -> Bool = {
guard let webViewController = Fleet.getApplicationScreen()?.topmostViewController as? WebViewController else {
return false
}
let url = webViewController.webPageURL
return url?.absoluteString == "turtle_gitHub.com"
}
expect(predicate()).toEventually(beTrue())
}
}
}
describe("Entering a token and hitting the 'Log In' button") {
beforeEach {
subject.tokenTextField?.textField?.enter(text: "token of the GitHub Turtle")
subject.loginButton?.tap()
}
it("disables the 'Log In' button") {
expect(subject.loginButton?.isEnabled).to(beFalse())
}
it("uses the token verification service to check that the token is valid") {
expect(mockTokenValidationService.capturedToken).to(equal(Token(value: "token of the GitHub Turtle")))
expect(mockTokenValidationService.capturedConcourseURLString).to(equal("turtle_concourse.com"))
}
it("uses the HTTPSessionUtils to delete all cookies") {
expect(mockHTTPSessionUtils.didDeleteCookies).to(beTrue())
}
describe("When the validation call returns with no error") {
describe("When 'Stay Logged In' switch is off") {
beforeEach {
subject.stayLoggedInToggle?.checkBox?.on = false
guard let completion = mockTokenValidationService.capturedCompletion else {
fail("Failed to call TokenValidationService with a completion handler")
return
}
completion(nil)
}
it("does not save anything to the keychain") {
expect(mockKeychainWrapper.capturedTarget).to(beNil())
}
it("replaces itself with the PipelinesViewController") {
expect(Fleet.getApplicationScreen()?.topmostViewController).toEventually(beIdenticalTo(mockPipelinesViewController))
}
it("creates a new target from the entered information and view controller") {
let expectedTarget = Target(name: "target", api: "turtle_concourse.com",
teamName: "turtle_team", token: Token(value: "token of the GitHub Turtle")
)
expect(mockPipelinesViewController.target).toEventually(equal(expectedTarget))
}
}
describe("When 'Stay Logged In' switch is on") {
beforeEach {
subject.stayLoggedInToggle?.checkBox?.on = true
guard let completion = mockTokenValidationService.capturedCompletion else {
fail("Failed to call TokenValidationService with a completion handler")
return
}
completion(nil)
}
it("replaces itself with the PipelinesViewController") {
expect(Fleet.getApplicationScreen()?.topmostViewController).toEventually(beIdenticalTo(mockPipelinesViewController))
}
it("creates a new target from the entered information and sets it on the view controller") {
let expectedTarget = Target(name: "target", api: "turtle_concourse.com",
teamName: "turtle_team", token: Token(value: "token of the GitHub Turtle")
)
expect(mockPipelinesViewController.target).toEventually(equal(expectedTarget))
}
it("asks the KeychainWrapper to save the new target") {
let expectedTarget = Target(name: "target", api: "turtle_concourse.com",
teamName: "turtle_team", token: Token(value: "token of the GitHub Turtle")
)
expect(mockKeychainWrapper.capturedTarget).to(equal(expectedTarget))
}
it("sets a KeychainWrapper on the view controller") {
expect(mockPipelinesViewController.keychainWrapper).toEventuallyNot(beNil())
}
}
}
describe("When the validation call returns with an error") {
beforeEach {
guard let completion = mockTokenValidationService.capturedCompletion else {
fail("Failed to call TokenValidationService with a completion handler")
return
}
completion(BasicError(details: "validation error"))
}
it("displays an alert containing the error that came from the HTTP call") {
expect(subject.presentedViewController).toEventually(beAKindOf(UIAlertController.self))
let screen = Fleet.getApplicationScreen()
expect(screen?.topmostViewController).toEventually(beAKindOf(UIAlertController.self))
let alert = screen?.topmostViewController as? UIAlertController
expect(alert?.title).toEventually(equal("Authorization Failed"))
expect(alert?.message).toEventually(equal("validation error"))
}
it("re-enables the 'Log In' button") {
expect(subject.loginButton?.isEnabled).toEventually(beTrue())
}
}
}
}
}
}
}
| apache-2.0 | 6c9020943393c8ec290b9b8075f7fa60 | 45.682274 | 166 | 0.508167 | 6.782313 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyerTests/Error/DeserializationErrorSpec.swift | 1 | 2501 | import XCTest
import Quick
import Nimble
@testable import FrequentFlyer
class DeserializationErrorSpec: QuickSpec {
override func spec() {
describe("DeserializationError") {
it("can be converted into a string") {
let error = DeserializationError(details: "error details", type: .missingRequiredData)
let errorString = String(describing: error)
expect(errorString).to(equal("DeserializationError { details: \"error details\", type: \"MissingRequiredData\" }")
)
}
describe("Equality operator") {
context("When the details and types of the DeserializationError objects are equal") {
let errorOne = DeserializationError(details: "error", type: .invalidInputFormat)
let errorTwo = DeserializationError(details: "error", type: .invalidInputFormat)
it("returns true") {
expect(errorOne).to(equal(errorTwo))
}
}
context("When the details of the DeserializationError objects are equal and types are different") {
let errorOne = DeserializationError(details: "error", type: .invalidInputFormat)
let errorTwo = DeserializationError(details: "error", type: .missingRequiredData)
it("returns false") {
expect(errorOne).toNot(equal(errorTwo))
}
}
context("When the details of the DeserializationError objects are different and types are equal") {
let errorOne = DeserializationError(details: "error", type: .invalidInputFormat)
let errorTwo = DeserializationError(details: "some other error", type: .invalidInputFormat)
it("returns false") {
expect(errorOne).toNot(equal(errorTwo))
}
}
context("When the details and types of the DeserializationError objects are different") {
let errorOne = DeserializationError(details: "error", type: .invalidInputFormat)
let errorTwo = DeserializationError(details: "some other error", type: .missingRequiredData)
it("returns false") {
expect(errorOne).toNot(equal(errorTwo))
}
}
}
}
}
}
| apache-2.0 | 0c6f249ef33c96f545857d50a02648ca | 43.660714 | 130 | 0.563774 | 5.898585 | false | false | false | false |
keyeMyria/wikipedia-ios | WikipediaUnitTests/WMFImageControllerTests.swift | 1 | 4335 | //
// WMFImageControllerCancellationTests.swift
// Wikipedia
//
// Created by Brian Gerstle on 8/11/15.
// Copyright (c) 2015 Wikimedia Foundation. All rights reserved.
//
import UIKit
import XCTest
import Wikipedia
class WMFImageControllerTests: XCTestCase {
var imageController: WMFImageController!
override func setUp() {
super.setUp()
imageController = WMFImageController.temporaryController()
}
override func tearDown() {
super.tearDown()
imageController.deleteAllImages()
LSNocilla.sharedInstance().stop()
}
func testReceivingDataResponseResolves() {
let testURL = NSURL(string: "https://upload.wikimedia.org/foo")!
let stubbedData = UIImagePNGRepresentation(UIImage(named: "lead-default"))
LSNocilla.sharedInstance().start()
stubRequest("GET", testURL.absoluteString).andReturnRawResponse(stubbedData)
expectPromise(toResolve(),
pipe: { imgDownload in
XCTAssertEqual(UIImagePNGRepresentation(imgDownload.image), stubbedData)
}) { () -> Promise<WMFImageDownload> in
self.imageController.fetchImageWithURL(testURL)
}
}
func testReceivingErrorResponseRejects() {
let testURL = NSURL(string: "https://upload.wikimedia.org/foo")!
let stubbedError = NSError(domain: "test", code: 0, userInfo: nil)
LSNocilla.sharedInstance().start()
stubRequest("GET", testURL.absoluteString).andFailWithError(stubbedError)
expectPromise(toCatch(),
pipe: { error in
XCTAssertEqual(error.code, stubbedError.code)
XCTAssertEqual(error.domain, stubbedError.domain)
let failingURL = error.userInfo![NSURLErrorFailingURLErrorKey] as! NSURL
XCTAssertEqual(failingURL, testURL)
}) { () -> Promise<WMFImageDownload> in
self.imageController.fetchImageWithURL(testURL)
}
}
func testCancelUnresolvedRequestCatchesWithCancellationError() {
/*
try to download an image from our repo on GH (as opposed to some external URL which might change)
at least if this changes, we can easily point to another image in the repo
*/
let testURL = NSURL(string:"https://github.com/wikimedia/wikipedia-ios/blob/master/WikipediaUnitTests/Fixtures/golden-gate.jpg?raw=true")!
expectPromise(toCatch(policy: CatchPolicy.AllErrors),
pipe: { err in
XCTAssert(err.cancelled, "Expected promise error to be cancelled but was \(err)")
},
timeout: 2) { () -> Promise<WMFImageDownload> in
let promise = self.imageController.fetchImageWithURL(testURL)
self.imageController.cancelFetchForURL(testURL)
return promise
}
}
func testCancelCacheRequestCatchesWithCancellationError() {
// copy some test fixture image to a temp location
let testFixtureDataPath = wmf_bundle().resourcePath!.stringByAppendingPathComponent("golden-gate.jpg")
let tempPath = WMFRandomTemporaryFileOfType("jpg")
NSFileManager.defaultManager().copyItemAtPath(testFixtureDataPath,
toPath: tempPath,
error: nil)
let testURL = NSURL(string: "//foo/bar")!
expectPromise(toCatch(policy: CatchPolicy.AllErrors),
pipe: { err in
XCTAssert(err.cancelled, "Expected promise error to be cancelled but was \(err)")
},
timeout: 2) { () -> Promise<WMFImageDownload> in
self.imageController
// import temp fixture data into image controller's disk cache
.importImage(fromFile: tempPath, withURL: testURL)
// then, attempt to retrieve it from the cache
.then() {
let promise = self.imageController.cachedImageWithURL(testURL)
// but, cancel before the data is retrieved
self.imageController.cancelFetchForURL(testURL)
return promise
}
}
// remove temporarily copied test data
NSFileManager.defaultManager().removeItemAtPath(tempPath, error: nil)
}
}
| mit | 7104818fd9c9420b6da979474cc2acc3 | 39.138889 | 146 | 0.633218 | 5.210337 | false | true | false | false |
yonaskolb/SwagGen | Sources/Swagger/Component/Component.swift | 1 | 1176 | import Foundation
import JSONUtilities
public struct ComponentObject<T: Component> {
public let name: String
public let value: T
}
public protocol Component: JSONObjectConvertible {
static var componentType: ComponentType { get }
}
public enum ComponentType: String {
case schema = "schemas"
case response = "responses"
case parameter = "parameters"
case example = "examples"
case requestBody = "requestBodies"
case header = "headers"
case securityScheme = "securitySchemes"
case link = "links"
case callback = "callbacks"
}
extension Parameter: Component {
public static let componentType: ComponentType = .parameter
}
extension Response: Component {
public static let componentType: ComponentType = .response
}
extension Schema: Component {
public static let componentType: ComponentType = .schema
}
extension SecurityScheme: Component {
public static let componentType: ComponentType = .securityScheme
}
extension RequestBody: Component {
public static let componentType: ComponentType = .requestBody
}
extension Header: Component {
public static let componentType: ComponentType = .header
}
| mit | 29b4734b9acc5780e885fc99900f4300 | 24.021277 | 68 | 0.740646 | 4.8 | false | false | false | false |
hilen/TSWeChat | TSWeChat/General/TSLogger.swift | 1 | 4519 | //
// TSLogger.swift
// TSWeChat
//
// Created by Hilen on 12/3/15.
// Copyright © 2015 Hilen. All rights reserved.
//
import Foundation
import XCGLogger
let XCCacheDirectory: URL = {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls[urls.endIndex - 1]
}()
let log: XCGLogger = {
// Setup XCGLogger
let log = XCGLogger.default
#if USE_NSLOG // Set via Build Settings, under Other Swift Flags
log.remove(destinationWithIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier)
log.add(destination: AppleSystemLogDestination(identifier: XCGLogger.Constants.systemLogDestinationIdentifier))
log.logAppDetails()
#else
let logPath: URL = XCCacheDirectory.appendingPathComponent("XCGLogger_Log.txt")
log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath)
// Add colour (using the ANSI format) to our file log, you can see the colour when `cat`ing or `tail`ing the file in Terminal on macOS
// This is mostly useful when testing in the simulator, or if you have the app sending you log files remotely
if let fileDestination: FileDestination = log.destination(withIdentifier: XCGLogger.Constants.fileDestinationIdentifier) as? FileDestination {
let ansiColorLogFormatter: ANSIColorLogFormatter = ANSIColorLogFormatter()
ansiColorLogFormatter.colorize(level: .verbose, with: .colorIndex(number: 244), options: [.faint])
ansiColorLogFormatter.colorize(level: .debug, with: .black)
ansiColorLogFormatter.colorize(level: .info, with: .blue, options: [.underline])
ansiColorLogFormatter.colorize(level: .warning, with: .red, options: [.faint])
ansiColorLogFormatter.colorize(level: .error, with: .red, options: [.bold])
ansiColorLogFormatter.colorize(level: .severe, with: .white, on: .red)
fileDestination.formatters = [ansiColorLogFormatter]
}
// Add colour to the console destination.
// - Note: You need the XcodeColors Plug-in https://github.com/robbiehanson/XcodeColors installed in Xcode
// - to see colours in the Xcode console. Plug-ins have been disabled in Xcode 8, so offically you can not see
// - coloured logs in Xcode 8.
//if let consoleDestination: ConsoleDestination = log.destination(withIdentifier: XCGLogger.Constants.baseConsoleDestinationIdentifier) as? ConsoleDestination {
// let xcodeColorsLogFormatter: XcodeColorsLogFormatter = XcodeColorsLogFormatter()
// xcodeColorsLogFormatter.colorize(level: .verbose, with: .lightGrey)
// xcodeColorsLogFormatter.colorize(level: .debug, with: .darkGrey)
// xcodeColorsLogFormatter.colorize(level: .info, with: .blue)
// xcodeColorsLogFormatter.colorize(level: .warning, with: .orange)
// xcodeColorsLogFormatter.colorize(level: .error, with: .red)
// xcodeColorsLogFormatter.colorize(level: .severe, with: .white, on: .red)
// consoleDestination.formatters = [xcodeColorsLogFormatter]
//}
#endif
// You can also change the labels for each log level, most useful for alternate languages, French, German etc, but Emoji's are more fun
// log.levelDescriptions[.verbose] = "🗯"
// log.levelDescriptions[.debug] = "🔹"
// log.levelDescriptions[.info] = "ℹ️"
// log.levelDescriptions[.warning] = "⚠️"
// log.levelDescriptions[.error] = "‼️"
// log.levelDescriptions[.severe] = "💣"
// Alternatively, you can use emoji to highlight log levels (you probably just want to use one of these methods at a time).
let emojiLogFormatter = PrePostFixLogFormatter()
emojiLogFormatter.apply(prefix: "🗯🗯🗯 ", postfix: " 🗯🗯🗯", to: .verbose)
emojiLogFormatter.apply(prefix: "🔹🔹🔹 ", postfix: " 🔹🔹🔹", to: .debug)
emojiLogFormatter.apply(prefix: "ℹ️ℹ️ℹ️ ", postfix: " ℹ️ℹ️ℹ️", to: .info)
emojiLogFormatter.apply(prefix: "⚠️⚠️⚠️ ", postfix: " ⚠️⚠️⚠️", to: .warning)
emojiLogFormatter.apply(prefix: "‼️‼️‼️ ", postfix: " ‼️‼️‼️", to: .error)
emojiLogFormatter.apply(prefix: "💣💣💣 ", postfix: " 💣💣💣", to: .severe)
log.formatters = [emojiLogFormatter]
return log
}()
| mit | b3bc1c42d5f7ca3d7b139eb43278b36a | 56.513158 | 168 | 0.678334 | 4.327723 | false | false | false | false |
ljshj/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Group/Cells/AAGroupMemberCell.swift | 1 | 3635 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
public class AAGroupMemberCell: AATableViewCell {
// Views
public var nameLabel = UILabel()
public var onlineLabel = UILabel()
public var avatarView = AAAvatarView()
public var adminLabel = UILabel()
// Binder
public var binder = AABinder()
// Contstructors
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
adminLabel.text = AALocalized("GroupMemberAdmin")
adminLabel.sizeToFit()
contentView.addSubview(avatarView)
nameLabel.font = UIFont.systemFontOfSize(18.0)
nameLabel.textColor = appStyle.cellTextColor
contentView.addSubview(nameLabel)
onlineLabel.font = UIFont.systemFontOfSize(14.0)
contentView.addSubview(onlineLabel)
adminLabel.font = UIFont.systemFontOfSize(14.0)
adminLabel.textColor = appStyle.cellDestructiveColor
contentView.addSubview(adminLabel)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Binding
public func setUsername(username: String) {
nameLabel.text = username
}
public func bind(user: ACUserVM, isAdmin: Bool) {
// Bind name and avatar
let name = user.getNameModel().get()
nameLabel.text = name
avatarView.bind(name, id: Int(user.getId()), avatar: user.getAvatarModel().get())
// Bind admin flag
adminLabel.hidden = !isAdmin
// Bind onlines
if user.isBot() {
self.onlineLabel.textColor = self.appStyle.userOnlineColor
self.onlineLabel.text = "bot"
self.onlineLabel.alpha = 1
} else {
binder.bind(user.getPresenceModel()) { (value: ACUserPresence?) -> () in
if value != nil {
self.onlineLabel.showView()
self.onlineLabel.text = Actor.getFormatter().formatPresence(value!, withSex: user.getSex())
if value!.state.ordinal() == ACUserPresence_State.ONLINE().ordinal() {
self.onlineLabel.textColor = self.appStyle.userOnlineColor
} else {
self.onlineLabel.textColor = self.appStyle.userOfflineColor
}
} else {
self.onlineLabel.alpha = 0
self.onlineLabel.text = ""
}
}
}
}
public override func prepareForReuse() {
super.prepareForReuse()
binder.unbindAll()
}
// Layouting
public override func layoutSubviews() {
super.layoutSubviews()
let userAvatarViewFrameSize: CGFloat = CGFloat(44)
avatarView.frame = CGRect(x: 14.0, y: (contentView.bounds.size.height - userAvatarViewFrameSize) / 2.0, width: userAvatarViewFrameSize, height: userAvatarViewFrameSize)
var w: CGFloat = contentView.bounds.size.width - 65.0 - 8.0
if !adminLabel.hidden {
adminLabel.frame = CGRect(x: contentView.width - adminLabel.width - 8, y: 5, width: adminLabel.width, height: 42)
w -= adminLabel.width + 8
}
nameLabel.frame = CGRect(x: 65.0, y: 5, width: w, height: 22)
onlineLabel.frame = CGRect(x: 65.0, y: 27, width: w, height: 16)
}
}
| mit | 5fcf775c8d952940944a809b699f3e64 | 32.045455 | 176 | 0.579917 | 4.720779 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/TextToSpeechV1/TextToSpeechDecoder.swift | 1 | 16684 | /**
* (C) Copyright IBM Corp. 2016, 2021.
*
* 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
#if canImport(Clibogg)
import Clibogg
#endif
#if canImport(Clibopus)
import Clibopus
#endif
#if canImport(Copustools)
import Copustools
#endif
internal class TextToSpeechDecoder {
var pcmDataWithHeaders = Data() // object containing the decoded pcm data with wav headers
// swiftlint:disable:next type_name
private typealias opus_decoder = OpaquePointer
// swiftlint:disable:next identifier_name
private let MAX_FRAME_SIZE = Int32(960 * 6)
private var streamState: ogg_stream_state // state of ogg stream
private var page: ogg_page // encapsulates the data for an Ogg page
private var syncState: ogg_sync_state // tracks the status of data during decoding
private var packet: ogg_packet // packet within a stream passing information
private var header: OpusHeader // header of the Opus file to decode
private var decoder: opus_decoder // decoder to convert opus to pcm
private var packetCount: Int64 = 0 // number of packets read during decoding
private var beginStream = true // if decoding of stream has begun
private var pageGranulePosition: Int64 = 0 // position of the packet data at page
private var hasOpusStream = false // whether or not the opus stream has been created
private var hasTagsPacket = false // whether or not the tags packet has been read
private var opusSerialNumber: Int = 0 // the assigned serial number of the opus stream
private var linkOut: Int32 = 0 // total number of bytes written from opus stream to pcmData
private var totalLinks: Int = 0 // a count of the number of opus streams
private var numChannels: Int32 = 1 // number of channels
private var pcmDataBuffer = UnsafeMutablePointer<Float>.allocate(capacity: 0)
private var sampleRate: Int32 = 48000 // sample rate for decoding. default value by Opus is 48000
private var preSkip: Int32 = 0 // number of samples to be skipped at beginning of stream
private var granOffset: Int32 = 0 // where to begin reading the data from Opus
private var frameSize: Int32 = 0 // number of samples decoded
private var pcmData = Data() // decoded pcm data
init(audioData: Data) throws {
// set properties
streamState = ogg_stream_state()
page = ogg_page()
syncState = ogg_sync_state()
packet = ogg_packet()
header = OpusHeader()
// status to catch errors when creating decoder
var status = Int32(0)
decoder = opus_decoder_create(sampleRate, numChannels, &status)
// initialize ogg sync state
ogg_sync_init(&syncState)
var processedByteCount = 0
while processedByteCount < audioData.count {
// determine the size of the buffer to ask for
var bufferSize: Int
if audioData.count - processedByteCount > 200 {
bufferSize = 200
} else {
bufferSize = audioData.count - processedByteCount
}
// obtain a buffer from the syncState
var bufferData: UnsafeMutablePointer<Int8>
bufferData = ogg_sync_buffer(&syncState, bufferSize)
// write data from the service into the syncState buffer
bufferData.withMemoryRebound(to: UInt8.self, capacity: bufferSize) { bufferDataUInt8 in
audioData.copyBytes(to: bufferDataUInt8, from: processedByteCount..<processedByteCount + bufferSize)
}
processedByteCount += bufferSize
// notify syncState of number of bytes we actually wrote
ogg_sync_wrote(&syncState, bufferSize)
// attempt to get a page from the data that we wrote
while ogg_sync_pageout(&syncState, &page) == 1 {
if beginStream {
// assign stream's number with the page.
ogg_stream_init(&streamState, ogg_page_serialno(&page))
beginStream = false
}
if ogg_page_serialno(&page) != Int32(streamState.serialno) {
ogg_stream_reset_serialno(&streamState, ogg_page_serialno(&page))
}
// add page to the ogg stream
ogg_stream_pagein(&streamState, &page)
// save position of the current decoding process
pageGranulePosition = ogg_page_granulepos(&page)
// extract packets from the ogg stream until no packets are left
try extractPacket(&streamState, &packet)
}
}
if totalLinks == 0 {
NSLog("Does not look like an opus file.")
throw OpusError.invalidState
}
// add wav header
addWAVHeader()
// perform cleanup
opus_multistream_decoder_destroy(decoder)
if !beginStream {
ogg_stream_clear(&streamState)
}
ogg_sync_clear(&syncState)
}
// Extract a packet from the ogg stream and store the extracted data within the packet object.
private func extractPacket(_ streamState: inout ogg_stream_state, _ packet: inout ogg_packet) throws {
// attempt to extract a packet from the ogg stream
while ogg_stream_packetout(&streamState, &packet) == 1 {
// execute if initial stream header
if packet.b_o_s != 0 && packet.bytes >= 8 && memcmp(packet.packet, "OpusHead", 8) == 0 {
// check if there's another opus head to see if stream is chained without EOS
if hasOpusStream && hasTagsPacket {
hasOpusStream = false
opus_multistream_decoder_destroy(decoder)
}
// set properties if we are in a new opus stream
if !hasOpusStream {
if packetCount > 0 && opusSerialNumber == streamState.serialno {
NSLog("Apparent chaining without changing serial number. Something bad happened.")
throw OpusError.internalError
}
opusSerialNumber = streamState.serialno
hasOpusStream = true
hasTagsPacket = false
linkOut = 0
packetCount = 0
totalLinks += 1
} else {
NSLog("Warning: ignoring opus stream.")
}
}
if !hasOpusStream || streamState.serialno != opusSerialNumber {
break
}
// if first packet in logical stream, process header
if packetCount == 0 {
// create decoder from information in Opus header
decoder = try processHeader(&packet, &numChannels, &preSkip)
// Check that there are no more packets in the first page.
let lastElementIndex = page.header_len - 1
let lacingValue = page.header[lastElementIndex]
// A lacing value of 255 would suggest that the packet continues on the next page.
if ogg_stream_packetout(&streamState, &packet) != 0 || lacingValue == 255 {
throw OpusError.invalidPacket
}
granOffset = preSkip
pcmDataBuffer = UnsafeMutablePointer<Float>.allocate(capacity: MemoryLayout<Float>.stride * Int(MAX_FRAME_SIZE) * Int(numChannels))
// deallocate pcmDataBuffer when the function ends, regardless if the function ended normally or with an error.
defer {
pcmDataBuffer.deallocate()
}
} else if packetCount == 1 {
hasTagsPacket = true
let lastElementIndex = page.header_len - 1
let lacingValue = page.header[lastElementIndex]
if ogg_stream_packetout(&streamState, &packet) != 0 || lacingValue == 255 {
NSLog("Extra packets on initial tags page. Invalid stream.")
throw OpusError.invalidPacket
}
} else {
var numberOfSamplesDecoded: Int32
var maxOut: Int64
var outSample: Int64
// Decode opus packet.
numberOfSamplesDecoded = opus_multistream_decode_float(decoder, packet.packet, Int32(packet.bytes), pcmDataBuffer, MAX_FRAME_SIZE, 0)
if numberOfSamplesDecoded < 0 {
NSLog("Decoding error: \(String(describing: opus_strerror(numberOfSamplesDecoded)))")
throw OpusError.internalError
}
frameSize = numberOfSamplesDecoded
// Make sure the output duration follows the final end-trim
// Output sample count should not be ahead of granpos value.
maxOut = ((pageGranulePosition - Int64(granOffset)) * Int64(sampleRate) / 48000) - Int64(linkOut)
outSample = try audioWrite(&pcmDataBuffer, numChannels, frameSize, &preSkip, &maxOut)
linkOut += Int32(outSample)
}
packetCount += 1
}
}
// Process the Opus header and create a decoder with these values
private func processHeader(_ packet: inout ogg_packet, _ channels: inout Int32, _ preskip: inout Int32) throws -> opus_decoder {
// create status to capture errors
var status = Int32(0)
if opus_header_parse(packet.packet, Int32(packet.bytes), &header) == 0 {
throw OpusError.invalidPacket
}
channels = header.channels
preskip = header.preskip
// update the sample rate if a reasonable one is specified in the header
let rate = Int32(header.input_sample_rate)
if rate >= 8000 && rate <= 192000 {
sampleRate = rate
}
decoder = opus_multistream_decoder_create(sampleRate, channels, header.nb_streams, header.nb_coupled, &header.stream_map.0, &status)
if status != OpusError.okay.rawValue {
throw OpusError.badArgument
}
return decoder
}
// Write the decoded Opus data (now PCM) to the pcmData object
private func audioWrite(_ pcmDataBuffer: inout UnsafeMutablePointer<Float>,
_ channels: Int32,
_ frameSize: Int32,
_ skip: inout Int32,
_ maxOut: inout Int64) throws -> Int64 {
var sampOut: Int64 = 0
var tmpSkip: Int32
var outLength: UInt
var shortOutput: UnsafeMutablePointer<CShort>
var floatOutput: UnsafeMutablePointer<Float>
shortOutput = UnsafeMutablePointer<CShort>.allocate(capacity: MemoryLayout<CShort>.stride * Int(MAX_FRAME_SIZE) * Int(channels))
if maxOut < 0 {
maxOut = 0
}
if skip != 0 {
if skip > frameSize {
tmpSkip = frameSize
} else {
tmpSkip = skip
}
skip -= tmpSkip
} else {
tmpSkip = 0
}
floatOutput = pcmDataBuffer.advanced(by: Int(channels) * Int(tmpSkip))
outLength = UInt(frameSize) - UInt(tmpSkip)
let maxLoop = Int(outLength) * Int(channels)
for count in 0..<maxLoop {
let maxMin = max(-32768, min(floatOutput.advanced(by: count).pointee * Float(32768), 32767))
let float2int = CShort((floor(0.5 + maxMin)))
shortOutput.advanced(by: count).initialize(to: float2int)
}
shortOutput.withMemoryRebound(to: UInt8.self, capacity: Int(outLength) * Int(channels)) { shortOutputUint8 in
if maxOut > 0 {
pcmData.append(shortOutputUint8, count: Int(outLength) * 2)
sampOut += Int64(outLength)
}
}
return sampOut
}
// Add WAV headers to the decoded PCM data.
// Refer to the documentation here for details: http://soundfile.sapp.org/doc/WaveFormat/
private func addWAVHeader() {
var header = Data()
let headerSize = 44
let pcmDataLength = pcmData.count
let bitsPerSample = Int32(16)
// RIFF chunk descriptor
let chunkID = [UInt8]("RIFF".utf8)
header.append(chunkID, count: 4)
var chunkSize = Int32(pcmDataLength + headerSize - 4).littleEndian
let chunkSizePointer = UnsafeBufferPointer(start: &chunkSize, count: 1)
header.append(chunkSizePointer)
let format = [UInt8]("WAVE".utf8)
header.append(format, count: 4)
// "fmt" sub-chunk
let subchunk1ID = [UInt8]("fmt ".utf8)
header.append(subchunk1ID, count: 4)
var subchunk1Size = Int32(16).littleEndian
let subchunk1SizePointer = UnsafeBufferPointer(start: &subchunk1Size, count: 1)
header.append(subchunk1SizePointer)
var audioFormat = Int16(1).littleEndian
let audioFormatPointer = UnsafeBufferPointer(start: &audioFormat, count: 1)
header.append(audioFormatPointer)
var headerNumChannels = Int16(numChannels).littleEndian
let headerNumChannelsPointer = UnsafeBufferPointer(start: &headerNumChannels, count: 1)
header.append(headerNumChannelsPointer)
var headerSampleRate = Int32(sampleRate).littleEndian
let headerSampleRatePointer = UnsafeBufferPointer(start: &headerSampleRate, count: 1)
header.append(headerSampleRatePointer)
var byteRate = Int32(sampleRate * numChannels * bitsPerSample / 8).littleEndian
let byteRatePointer = UnsafeBufferPointer(start: &byteRate, count: 1)
header.append(byteRatePointer)
var blockAlign = Int16(numChannels * bitsPerSample / 8).littleEndian
let blockAlignPointer = UnsafeBufferPointer(start: &blockAlign, count: 1)
header.append(blockAlignPointer)
var headerBitsPerSample = Int16(bitsPerSample).littleEndian
let headerBitsPerSamplePointer = UnsafeBufferPointer(start: &headerBitsPerSample, count: 1)
header.append(headerBitsPerSamplePointer)
// "data" sub-chunk
let subchunk2ID = [UInt8]("data".utf8)
header.append(subchunk2ID, count: 4)
var subchunk2Size = Int32(pcmDataLength).littleEndian
let subchunk2SizePointer = UnsafeBufferPointer(start: &subchunk2Size, count: 1)
header.append(subchunk2SizePointer)
pcmDataWithHeaders.append(header)
pcmDataWithHeaders.append(pcmData)
}
}
// MARK: - OpusError
internal enum OpusError: Error {
case okay
case badArgument
case bufferTooSmall
case internalError
case invalidPacket
case unimplemented
case invalidState
case allocationFailure
var rawValue: Int32 {
switch self {
case .okay: return OPUS_OK
case .badArgument: return OPUS_BAD_ARG
case .bufferTooSmall: return OPUS_BUFFER_TOO_SMALL
case .internalError: return OPUS_INTERNAL_ERROR
case .invalidPacket: return OPUS_INVALID_PACKET
case .unimplemented: return OPUS_UNIMPLEMENTED
case .invalidState: return OPUS_INVALID_STATE
case .allocationFailure: return OPUS_ALLOC_FAIL
}
}
init?(rawValue: Int32) {
switch rawValue {
case OPUS_OK: self = .okay
case OPUS_BAD_ARG: self = .badArgument
case OPUS_BUFFER_TOO_SMALL: self = .bufferTooSmall
case OPUS_INTERNAL_ERROR: self = .internalError
case OPUS_INVALID_PACKET: self = .invalidPacket
case OPUS_UNIMPLEMENTED: self = .unimplemented
case OPUS_INVALID_STATE: self = .invalidState
case OPUS_ALLOC_FAIL: self = .allocationFailure
default: return nil
}
}
}
// MARK: - OggError
internal enum OggError: Error {
case outOfSync
case internalError
}
| apache-2.0 | 16df143060846f2ec9288eb2e2703da3 | 40.093596 | 149 | 0.612023 | 4.55598 | false | false | false | false |
avenwu/swift-demo | PlayAudio/PlayAudio/AppDelegate.swift | 1 | 3993 | //
// AppDelegate.swift
// PlayAudio
//
// Created by aven wu on 10/16/15.
// Copyright (c) 2015 avenwu. All rights reserved.
//
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, AVAudioPlayerDelegate {
var window: UIWindow?
var audioPlayer: AVAudioPlayer?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatchQueue, { [weak self] in
NSNotificationCenter.defaultCenter().addObserver(self!, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: nil)
var audioSessionError: NSError?
let audioSession = AVAudioSession.sharedInstance()
audioSession.setActive(true, error: nil)
if audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &audioSessionError) {
println("Sucessfully set the audio session" )
} else {
println("Could not set the audio session")
}
let filePatch = NSBundle.mainBundle().pathForResource("song", ofType: "mp3")
let fileData = NSData(contentsOfFile: filePatch!, options: .DataReadingMappedIfSafe,
error: nil)
var error: NSError?
self?.audioPlayer = AVAudioPlayer(data: fileData, error: &error)
if let theAudioPlayer = self?.audioPlayer {
theAudioPlayer.delegate = self
if theAudioPlayer.prepareToPlay() && theAudioPlayer.play() {
println("Successfully started playing")
} else {
println("Failed to play")
}
}
})
return true
}
func handleInterruption(notification: NSNotification) {
let interruptionTypeAsObject = notification.userInfo![AVAudioSessionInterruptionOptionKey] as! NSNumber
let interruptionType = AVAudioSessionInterruptionType(rawValue: interruptionTypeAsObject.unsignedLongValue)
if let type = interruptionType {
if type == .Ended {
}
}
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 5fe7da4dc7843c66d6821cf1ccd6b398 | 45.976471 | 285 | 0.686952 | 5.786957 | false | false | false | false |
kbelter/BubblePictures | BubblePictures/Classes/Extensions/ImageExtensions.swift | 1 | 1676 | //
// ImageExtensions.swift
// Pods
//
// Created by Kevin Belter on 1/2/17.
//
//
import Foundation
import SDWebImage
extension UIImageView {
func setImageWithURLAnimated(_ anURL:URL, completitionBlock:(() -> ())? = nil) {
let image = UIImage(color: UIColor.gray)
sd_setImage(with: anURL, placeholderImage: image, options: SDWebImageOptions()) { (_, _, _, _) in
completitionBlock?()
}
}
}
extension UIImage {
func resizeWith(width: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
var jpegRepresentation:Data? {
return self.jpegData(compressionQuality: 0.8)
}
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
| mit | 271e10b87bd670e1526a31d0fc54ede4 | 33.204082 | 148 | 0.655131 | 4.707865 | false | false | false | false |
eswick/StreamKit | Sources/Stream.swift | 1 | 1702 |
public enum StreamError: ErrorType {
case ReadFailed(Int)
case WriteFailed(Int)
case SeekFailed(Int)
case CloseFailed(Int)
case TimedOut
case Closed
}
public enum SeekOrigin {
case Beginning
case Current
case End
}
public protocol Stream {
var canRead: Bool { get }
var canWrite: Bool { get }
var canTimeout: Bool { get }
var canSeek: Bool { get }
var position: Int64 { get }
var readTimeout: UInt { get set } // milliseconds
var writeTimeout: UInt { get set } // milliseconds
func read(count: Int64) throws -> [UInt8]
func write(bytes: [UInt8]) throws -> Int
func seek(offset: Int64, origin: SeekOrigin) throws
func close() throws
}
public extension Stream {
public func write<T>(value: T) throws {
var tmpValue = value
try withUnsafePointer(&tmpValue) { pointer in
let int8ptr = unsafeBitCast(pointer, UnsafePointer<UInt8>.self)
let buf = UnsafeBufferPointer(start: int8ptr, count: sizeof(T))
try self.write(Array(buf))
}
}
public func read<T>() throws -> T {
let byteArray = try read(Int64(sizeof(T)))
return byteArray.withUnsafeBufferPointer() { pointer in
UnsafePointer<T>(pointer.baseAddress).memory
}
}
public func readAll() throws -> [UInt8] {
try seek(0, origin: .End)
let end = position
try seek(0, origin: .Beginning)
return try read(end)
}
}
func << <T>(left: Stream, right: T) throws {
try left.write(right)
}
func >> <T>(left: Stream, inout right: T) throws {
right = try left.read()
}
| mit | aa12daa64735e408a94f46d8ea57c3e9 | 24.029412 | 75 | 0.599882 | 4.014151 | false | false | false | false |
cache0928/CCWeibo | CCWeibo/CCWeibo/Classes/Utils/NSDate+WeiboDate.swift | 1 | 1870 | //
// NSDate+WeiboDate.swift
// CCWeibo
//
// Created by 徐才超 on 16/2/11.
// Copyright © 2016年 徐才超. All rights reserved.
//
import Foundation
extension NSDate {
/// 从微博服务端字符串获取日期
class func dateFromeWeiboDateStr(dateString: String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
dateFormatter.locale = NSLocale(localeIdentifier: "en")
return dateFormatter.dateFromString(dateString)!
}
/// 返回日期的描述文字,1分钟内:刚刚,1小时内:xx分钟前,1天内:HH:mm,昨天:昨天 HH:mm,1年内:MM-dd HH:mm,更早时间:yyyy-MM-dd HH:mm
func weiboDescriptionDate() -> String {
let calendar = NSCalendar.currentCalendar()
var dateFormat = "HH:mm"
// 如果是一天之内
if calendar.isDateInToday(self) {
let since = NSDate().timeIntervalSinceDate(self)
//一分钟内
if since < 60.0 {
return "刚刚"
}
if since < 3600.0 {
return "\(Int(since/60))分钟前"
}
return "\(Int(since/3600.0))小时前"
}
// 如果是昨天
if calendar.isDateInYesterday(self) {
dateFormat = "昨天 " + dateFormat
} else {
dateFormat = "MM-dd " + dateFormat
let component = calendar.components([NSCalendarUnit.Year], fromDate: self, toDate: NSDate(), options: [])
if component.year > 1 {
dateFormat = "yyyy-" + dateFormat
}
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en")
return dateFormatter.stringFromDate(self)
}
} | mit | 8d57c5d76a9a2f6b3837ae7af8ab9f92 | 33.489796 | 117 | 0.582593 | 4.191067 | false | true | false | false |
sigito/material-components-ios | components/ButtonBar/examples/ButtonBarTypicalUseExample.swift | 2 | 3315 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import MaterialComponents
class ButtonBarTypicalUseSwiftExample: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let buttonBar = MDCButtonBar()
buttonBar.backgroundColor = self.buttonBarBackgroundColor()
// MDCButtonBar ignores the style of UIBarButtonItem.
let ignored: UIBarButtonItemStyle = .done
let actionItem = UIBarButtonItem(
title: "Action",
style: ignored,
target: self,
action: #selector(didTapActionButton)
)
let secondActionItem = UIBarButtonItem(
title: "Second action",
style: ignored,
target: self,
action: #selector(didTapActionButton)
)
let items = [actionItem, secondActionItem]
// Set the title text attributes before assigning to buttonBar.items
// because of https://github.com/material-components/material-components-ios/issues/277
for item in items {
item.setTitleTextAttributes(self.itemTitleTextAttributes(), for: UIControlState())
}
buttonBar.items = items
// MDCButtonBar's sizeThatFits gives a "best-fit" size of the provided items.
let size = buttonBar.sizeThatFits(self.view.bounds.size)
let x = (self.view.bounds.size.width - size.width) / 2
let y = self.view.bounds.size.height / 2 - size.height
buttonBar.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
buttonBar.autoresizingMask =
[.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
self.view.addSubview(buttonBar)
// Ensure that the controller's view isn't transparent.
view.backgroundColor = UIColor(white: 0.9, alpha:1.0)
}
@objc func didTapActionButton(_ sender: Any) {
print("Did tap action item: \(sender)")
}
// MARK: Typical application code (not Material-specific)
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Button Bar"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: Catalog by convention
extension ButtonBarTypicalUseSwiftExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Button Bar", "Button Bar (Swift)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
@objc class func catalogIsPresentable() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
extension ButtonBarTypicalUseSwiftExample {
func buttonBarBackgroundColor() -> UIColor {
return UIColor(white: 0.1, alpha: 1.0)
}
func itemTitleTextAttributes () -> [String: Any] {
let textColor = UIColor(white: 1, alpha: 0.8)
return [NSForegroundColorAttributeName: textColor]
}
}
| apache-2.0 | a5e94882ac1b47b064f229c1671854a5 | 29.136364 | 92 | 0.716139 | 4.40239 | false | false | false | false |
sydvicious/firefox-ios | Storage/SQL/SQLiteBookmarks.swift | 2 | 10579 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = XCGLogger.defaultInstance()
class SQLiteBookmarkFolder: BookmarkFolder {
private let cursor: Cursor<BookmarkNode>
override var count: Int {
return cursor.count
}
override subscript(index: Int) -> BookmarkNode {
let bookmark = cursor[index]
if let item = bookmark as? BookmarkItem {
return item
}
// TODO: this is fragile.
return bookmark as! BookmarkFolder
}
init(guid: String, title: String, children: Cursor<BookmarkNode>) {
self.cursor = children
super.init(guid: guid, title: title)
}
}
public class SQLiteBookmarks: BookmarksModelFactory {
let db: BrowserDB
let favicons: FaviconsTable<Favicon>
public init(db: BrowserDB) {
self.db = db
self.favicons = FaviconsTable<Favicon>()
}
private class func itemFactory(row: SDRow) -> BookmarkItem {
let id = row["id"] as! Int
let guid = row["guid"] as! String
let url = row["url"] as! String
let title = row["title"] as? String ?? url
let bookmark = BookmarkItem(guid: guid, title: title, url: url)
// TODO: share this logic with SQLiteHistory.
if let faviconUrl = row["iconURL"] as? String,
let date = row["iconDate"] as? Double,
let faviconType = row["iconType"] as? Int {
bookmark.favicon = Favicon(url: faviconUrl,
date: NSDate(timeIntervalSince1970: date),
type: IconType(rawValue: faviconType)!)
}
bookmark.id = id
return bookmark
}
private class func folderFactory(row: SDRow) -> BookmarkFolder {
let id = row["id"] as! Int
let guid = row["guid"] as! String
let title = row["title"] as? String ??
NSLocalizedString("Untitled", tableName: "Storage", comment: "The default name for bookmark folders without titles.")
let folder = BookmarkFolder(guid: guid, title: title)
folder.id = id
return folder
}
private class func factory(row: SDRow) -> BookmarkNode {
if let typeCode = row["type"] as? Int, type = BookmarkNodeType(rawValue: typeCode) {
switch type {
case .Bookmark:
return itemFactory(row)
case .Folder:
return folderFactory(row)
case .DynamicContainer:
assert(false, "Should never occur.")
case .Separator:
assert(false, "Separators not yet supported.")
}
}
assert(false, "Invalid bookmark data.")
}
private func getChildrenWhere(whereClause: String, args: Args, includeIcon: Bool) -> Cursor<BookmarkNode> {
var err: NSError? = nil
return db.withReadableConnection(&err) { (conn, err) -> Cursor<BookmarkNode> in
let inner = "SELECT id, type, guid, url, title, faviconID FROM \(TableBookmarks) WHERE \(whereClause)"
if includeIcon {
let sql =
"SELECT bookmarks.id AS id, bookmarks.type AS type, guid, bookmarks.url AS url, title, " +
"favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType " +
"FROM (\(inner)) AS bookmarks " +
"LEFT OUTER JOIN favicons ON bookmarks.faviconID = favicons.id"
return conn.executeQuery(sql, factory: SQLiteBookmarks.factory, withArgs: args)
} else {
return conn.executeQuery(inner, factory: SQLiteBookmarks.factory, withArgs: args)
}
}
}
private func getRootChildren() -> Cursor<BookmarkNode> {
let args: Args = [BookmarkRoots.RootID, BookmarkRoots.RootID]
let sql = "parent = ? AND id IS NOT ?"
return self.getChildrenWhere(sql, args: args, includeIcon: true)
}
private func getChildren(guid: String) -> Cursor<BookmarkNode> {
let args: Args = [guid]
let sql = "parent IS NOT NULL AND parent = (SELECT id FROM \(TableBookmarks) WHERE guid = ?)"
return self.getChildrenWhere(sql, args: args, includeIcon: true)
}
private func modelForFolder(guid: String, title: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
let children = getChildren(guid)
if children.status == .Failure {
failure(children.statusMessage)
return
}
// We add some suggested sites to the mobile bookmarks folder.
let f = SQLiteBookmarkFolder(guid: guid, title: title, children: children)
let extended = BookmarkFolderWithDefaults(folder: f, sites: SuggestedSites)
success(BookmarksModel(modelFactory: self, root: extended))
}
public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
self.modelForFolder(folder.guid, title: folder.title, success: success, failure: failure)
}
public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
self.modelForFolder(guid, title: "", success: success, failure: failure)
}
public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) {
let children = getRootChildren()
if children.status == .Failure {
failure(children.statusMessage)
return
}
let folder = SQLiteBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: children)
success(BookmarksModel(modelFactory: self, root: folder))
}
public var nullModel: BookmarksModel {
let children = Cursor<BookmarkNode>(status: .Failure, msg: "Null model")
let folder = SQLiteBookmarkFolder(guid: "Null", title: "Null", children: children)
return BookmarksModel(modelFactory: self, root: folder)
}
public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) {
var err: NSError?
let sql = "SELECT id FROM \(TableBookmarks) WHERE url = ? LIMIT 1"
let args: Args = [url]
let c = db.withReadableConnection(&err) { (conn, err) -> Cursor<Int> in
return conn.executeQuery(sql, factory: { $0["id"] as! Int }, withArgs: args)
}
if c.status == .Success {
success(c.count > 0)
} else {
failure(err)
}
}
public func clearBookmarks() -> Success {
return self.db.run([
("DELETE FROM \(TableBookmarks) WHERE parent IS NOT ?", [BookmarkRoots.RootID]),
self.favicons.getCleanupCommands()
])
}
public func removeByURL(url: String) -> Success {
log.debug("Removing bookmark \(url).")
return self.db.run([
("DELETE FROM \(TableBookmarks) WHERE url = ?", [url]),
])
}
public func remove(bookmark: BookmarkNode) -> Success {
if let item = bookmark as? BookmarkItem {
log.debug("Removing bookmark \(item.url).")
}
let sql: String
let args: Args
if let id = bookmark.id {
sql = "DELETE FROM \(TableBookmarks) WHERE id = ?"
args = [id]
} else {
sql = "DELETE FROM \(TableBookmarks) WHERE guid = ?"
args = [bookmark.guid]
}
return self.db.run([
(sql, args),
])
}
}
extension SQLiteBookmarks: ShareToDestination {
public func addToMobileBookmarks(url: NSURL, title: String, favicon: Favicon?) -> Success {
var err: NSError?
return self.db.withWritableConnection(&err) { (conn, err) -> Success in
func insertBookmark(icon: Int) -> Success {
log.debug("Inserting bookmark with specified icon \(icon).")
let urlString = url.absoluteString!
var args: Args = [
Bytes.generateGUID(),
BookmarkNodeType.Bookmark.rawValue,
urlString,
title,
BookmarkRoots.MobileID,
]
// If the caller didn't provide an icon (and they usually don't!),
// do a reverse lookup in history. We use a view to make this simple.
let iconValue: String
if icon == -1 {
iconValue = "(SELECT iconID FROM \(ViewIconForURL) WHERE url = ?)"
args.append(urlString)
} else {
iconValue = "?"
args.append(icon)
}
let sql = "INSERT INTO \(TableBookmarks) (guid, type, url, title, parent, faviconID) VALUES (?, ?, ?, ?, ?, \(iconValue))"
err = conn.executeChange(sql, withArgs: args)
if let err = err {
log.error("Error inserting \(urlString). Got \(err).")
return deferResult(DatabaseError(err: err))
}
return succeed()
}
// Insert the favicon.
if let icon = favicon {
if let id = self.favicons.insertOrUpdate(conn, obj: icon) {
return insertBookmark(id)
}
}
return insertBookmark(-1)
}
}
public func shareItem(item: ShareItem) {
// We parse here in anticipation of getting real URLs at some point.
if let url = item.url.asURL {
let title = item.title ?? url.absoluteString!
self.addToMobileBookmarks(url, title: title, favicon: item.favicon)
}
}
}
extension SQLiteBookmarks: SearchableBookmarks {
public func bookmarksByURL(url: NSURL) -> Deferred<Result<Cursor<BookmarkItem>>> {
let inner = "SELECT id, type, guid, url, title, faviconID FROM \(TableBookmarks) WHERE type = \(BookmarkNodeType.Bookmark.rawValue) AND url = ?"
let sql =
"SELECT bookmarks.id AS id, bookmarks.type AS type, guid, bookmarks.url AS url, title, " +
"favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType " +
"FROM (\(inner)) AS bookmarks " +
"LEFT OUTER JOIN favicons ON bookmarks.faviconID = favicons.id"
let args: Args = [url.absoluteString]
return db.runQuery(sql, args: args, factory: SQLiteBookmarks.itemFactory)
}
} | mpl-2.0 | 168cbd14af0c9535b1fd56d4dc086267 | 37.897059 | 152 | 0.58446 | 4.605572 | false | false | false | false |
Kgiberson/zen-doodle | ZenDoodle/SecondViewController.swift | 1 | 3187 | //
// SecondViewController.swift
// ZenDoodle
//
// Copyright © 2016 ZenDoodle. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var embeddedSecondViewController: UIView!
var drawingView: ACEDrawingView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 0.980, green: 0.941, blue: 0.902, alpha: 1) // app
self.drawingView = ACEDrawingView(frame: self.embeddedSecondViewController.bounds);
self.embeddedSecondViewController.addSubview(self.drawingView!)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
@IBAction func resetScreen(sender: AnyObject) {
self.drawingView?.clear()
}
@IBAction func undoButton(sender: UIButton) {
self.drawingView?.undoLatestStep()
}
@IBAction func takeScreenShot(sender: UIButton) {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.Text
hud.detailsLabel.text = "You've saved your doodle"
hud.hideAnimated(true, afterDelay: 1.5)
UIGraphicsBeginImageContext(drawingView!.frame.size)
drawingView!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let sourceImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(sourceImage,nil,nil,nil)
}
// Draw Space Notification Buttons
@IBAction func hubButton1(sender: UIButton) {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.Text
hud.detailsLabel.text = "Draw your ZenDoodle in this space"
hud.hideAnimated(true, afterDelay: 1.5)
}
@IBAction func hubButton2(sender: UIButton) {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.Text
hud.detailsLabel.text = "Draw your ZenDoodle in this space"
hud.hideAnimated(true, afterDelay: 1.5)
}
@IBAction func hubButton3(sender: UIButton) {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.Text
hud.detailsLabel.text = "Draw your ZenDoodle in this space"
hud.hideAnimated(true, afterDelay: 1.5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 443b1ebeefdd6a98ad308930a17002e0 | 29.056604 | 106 | 0.648776 | 5.065183 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Main/Extension/UIImageView+Extension.swift | 1 | 2465 | //
// UIImageView+Extension.swift
// LiveBroadcast
//
// Created by 朱双泉 on 2018/12/17.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
//import GPUImage
extension UIImageView {
// func blurImageNamed(_ name: String) {
// guard let sourceImage = UIImage(named: name) else { return }
// let picProcess = GPUImagePicture(image: sourceImage)
// let blurFilter = GPUImageGaussianBlurFilter()
// blurFilter.texelSpacingMultiplier = 5
// blurFilter.blurRadiusInPixels = 5
// picProcess?.addTarget(blurFilter)
// blurFilter.useNextFrameForImageCapture()
// picProcess?.processImage()
// let newImage = blurFilter.imageFromCurrentFramebuffer()
// self.image = newImage
// }
// func processImageNamed(_ name: String, filter: GPUImageFilter) {
// let picProcess = GPUImagePicture(image: image)
// picProcess?.addTarget(filter)
// filter.useNextFrameForImageCapture()
// picProcess?.processImage()
// self.image = filter.imageFromCurrentFramebuffer()
// }
func gifImageNamed(_ name: String) {
guard let path = Bundle.main.path(forResource: name, ofType: "gif") else {
return
}
guard let data = NSData(contentsOfFile: path) else { return }
guard let imageSource = CGImageSourceCreateWithData(data, nil) else {
return
}
let imageCount = CGImageSourceGetCount(imageSource)
var images = [UIImage]()
var totalDuration: TimeInterval = 0
for i in 0..<imageCount {
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {
continue
}
let image = UIImage(cgImage: cgImage)
if i == 0 {
self.image = image
}
images.append(image)
guard let properties: NSDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else { continue }
guard let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else { continue }
guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
totalDuration += frameDuration.doubleValue
}
self.animationImages = images
self.animationDuration = totalDuration
self.animationRepeatCount = 0
self.startAnimating()
}
}
| mit | 9daa8db398ebe6294d6e5e8e3fd0150c | 36.242424 | 122 | 0.631001 | 4.88668 | false | false | false | false |
justin999/gitap | gitap/PhotosTableViewDataSource.swift | 1 | 2668 | //
// PhotosTableViewDataSource.swift
// gitap
//
// Created by Koichi Sato on 2017/02/04.
// Copyright © 2017 Koichi Sato. All rights reserved.
//
import UIKit
import Photos
// MARK: Types for managing sectionsa and cell
enum Section: Int {
case allPhotos = 0
case smartAlbums
case userCollections
static let count = 3
}
enum CellIdentifier: String {
case allPhotos, collection
}
class PhotosTableViewDataSource: NSObject {
var stateController: StateController
let photoManager = PhotoManager.shared
let sectionLocalizedTitles = ["", NSLocalizedString("Smart Albums", comment: ""), NSLocalizedString("Albums", comment: "")]
init(tableView: UITableView, stateController: StateController) {
self.stateController = stateController
super.init()
tableView.dataSource = self
}
}
extension PhotosTableViewDataSource: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionLocalizedTitles[section]
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .allPhotos: return 1
case .smartAlbums: return photoManager.smartAlbums.count
case .userCollections: return photoManager.userCollections.count
}
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
switch Section(rawValue: indexPath.section)! {
case .allPhotos:
// let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.allPhotos.rawValue, for: indexPath)
cell.textLabel!.text = NSLocalizedString("All Photos", comment: "")
return cell
case .smartAlbums:
// let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.collection.rawValue, for: indexPath)
let collection = photoManager.smartAlbums.object(at: indexPath.row)
cell.textLabel!.text = collection.localizedTitle
return cell
case .userCollections:
// let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.collection.rawValue, for: indexPath)
let collection = photoManager.userCollections.object(at: indexPath.row)
cell.textLabel!.text = collection.localizedTitle
return cell
}
}
}
| mit | 4a229a951998ff68870e961f08426aad | 30.376471 | 127 | 0.67679 | 5.239686 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/CheckoutCompleteWithTokenizedPaymentV3Payload.swift | 1 | 7070 | //
// CheckoutCompleteWithTokenizedPaymentV3Payload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Return type for `checkoutCompleteWithTokenizedPaymentV3` mutation.
open class CheckoutCompleteWithTokenizedPaymentV3PayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CheckoutCompleteWithTokenizedPaymentV3Payload
/// The checkout on which the payment was applied.
@discardableResult
open func checkout(alias: String? = nil, _ subfields: (CheckoutQuery) -> Void) -> CheckoutCompleteWithTokenizedPaymentV3PayloadQuery {
let subquery = CheckoutQuery()
subfields(subquery)
addField(field: "checkout", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func checkoutUserErrors(alias: String? = nil, _ subfields: (CheckoutUserErrorQuery) -> Void) -> CheckoutCompleteWithTokenizedPaymentV3PayloadQuery {
let subquery = CheckoutUserErrorQuery()
subfields(subquery)
addField(field: "checkoutUserErrors", aliasSuffix: alias, subfields: subquery)
return self
}
/// A representation of the attempted payment.
@discardableResult
open func payment(alias: String? = nil, _ subfields: (PaymentQuery) -> Void) -> CheckoutCompleteWithTokenizedPaymentV3PayloadQuery {
let subquery = PaymentQuery()
subfields(subquery)
addField(field: "payment", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `checkoutUserErrors` instead.")
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CheckoutCompleteWithTokenizedPaymentV3PayloadQuery {
let subquery = UserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `checkoutCompleteWithTokenizedPaymentV3` mutation.
open class CheckoutCompleteWithTokenizedPaymentV3Payload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CheckoutCompleteWithTokenizedPaymentV3PayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "checkout":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CheckoutCompleteWithTokenizedPaymentV3Payload.self, field: fieldName, value: fieldValue)
}
return try Checkout(fields: value)
case "checkoutUserErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CheckoutCompleteWithTokenizedPaymentV3Payload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CheckoutUserError(fields: $0) }
case "payment":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CheckoutCompleteWithTokenizedPaymentV3Payload.self, field: fieldName, value: fieldValue)
}
return try Payment(fields: value)
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CheckoutCompleteWithTokenizedPaymentV3Payload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UserError(fields: $0) }
default:
throw SchemaViolationError(type: CheckoutCompleteWithTokenizedPaymentV3Payload.self, field: fieldName, value: fieldValue)
}
}
/// The checkout on which the payment was applied.
open var checkout: Storefront.Checkout? {
return internalGetCheckout()
}
func internalGetCheckout(alias: String? = nil) -> Storefront.Checkout? {
return field(field: "checkout", aliasSuffix: alias) as! Storefront.Checkout?
}
/// The list of errors that occurred from executing the mutation.
open var checkoutUserErrors: [Storefront.CheckoutUserError] {
return internalGetCheckoutUserErrors()
}
func internalGetCheckoutUserErrors(alias: String? = nil) -> [Storefront.CheckoutUserError] {
return field(field: "checkoutUserErrors", aliasSuffix: alias) as! [Storefront.CheckoutUserError]
}
/// A representation of the attempted payment.
open var payment: Storefront.Payment? {
return internalGetPayment()
}
func internalGetPayment(alias: String? = nil) -> Storefront.Payment? {
return field(field: "payment", aliasSuffix: alias) as! Storefront.Payment?
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `checkoutUserErrors` instead.")
open var userErrors: [Storefront.UserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "checkout":
if let value = internalGetCheckout() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutUserErrors":
internalGetCheckoutUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "payment":
if let value = internalGetPayment() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 0424bb738d70378471f38a64e637773a | 37.010753 | 155 | 0.736634 | 4.238609 | false | false | false | false |
nguyenhuy/AsyncMessagesViewController | Source/Views/MessageCellNode.swift | 1 | 4185 | //
// MessageCellNode.swift
// AsyncMessagesViewController
//
// Created by Huy Nguyen on 12/02/15.
// Copyright (c) 2015 Huy Nguyen. All rights reserved.
//
import UIKit
import AsyncDisplayKit
public let kAMMessageCellNodeAvatarImageSize: CGFloat = 34
public let kAMMessageCellNodeTopTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.lightGray,
NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]
public let kAMMessageCellNodeContentTopTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.lightGray, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]
public let kAMMessageCellNodeBottomTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.lightGray, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 11)]
open class MessageCellNode: ASCellNode {
private let isOutgoing: Bool
private let topTextNode: ASTextNode?
private let contentTopTextNode: ASTextNode?
private let bottomTextNode: ASTextNode?
private let bubbleNode: ASDisplayNode
private let avatarImageSize: CGFloat
private let avatarImageNode: ASNetworkImageNode?
public init(isOutgoing: Bool, topText: NSAttributedString?, contentTopText: NSAttributedString?, bottomText: NSAttributedString?, senderAvatarURL: URL?, senderAvatarImageSize: CGFloat = kAMMessageCellNodeAvatarImageSize, bubbleNode: ASDisplayNode) {
self.isOutgoing = isOutgoing
topTextNode = topText != nil ? ASTextNode() : nil
topTextNode?.isLayerBacked = true
topTextNode?.attributedText = topText
topTextNode?.style.alignSelf = .center
contentTopTextNode = contentTopText != nil ? ASTextNode() : nil
contentTopTextNode?.isLayerBacked = true
contentTopTextNode?.attributedText = contentTopText
avatarImageSize = senderAvatarImageSize
avatarImageNode = avatarImageSize > 0 ? ASNetworkImageNode() : nil
avatarImageNode?.style.preferredSize = CGSize(width: avatarImageSize, height: avatarImageSize)
avatarImageNode?.backgroundColor = UIColor.clear
avatarImageNode?.imageModificationBlock = ASImageNodeRoundBorderModificationBlock(0, nil)
avatarImageNode?.url = senderAvatarURL
self.bubbleNode = bubbleNode
self.bubbleNode.style.flexShrink = 1
bottomTextNode = bottomText != nil ? ASTextNode() : nil
bottomTextNode?.isLayerBacked = true
bottomTextNode?.attributedText = bottomText
super.init()
if let node = topTextNode { addSubnode(node) }
if let node = contentTopTextNode { addSubnode(node) }
if let node = avatarImageNode { addSubnode(node) }
addSubnode(bubbleNode)
if let node = bottomTextNode { addSubnode(node) }
selectionStyle = .none
}
open override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let unfilteredChildren: [ASLayoutElement?] = [
topTextNode,
(contentTopTextNode != nil)
? ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 22 + avatarImageSize, 0, 0), child: contentTopTextNode!)
: nil,
ASStackLayoutSpec(
direction: .horizontal,
spacing: 2,
justifyContent: .start, // Never used
alignItems: .end,
children: Array.filterNils(from: isOutgoing ? [bubbleNode, avatarImageNode] : [avatarImageNode, bubbleNode])),
bottomTextNode]
return ASInsetLayoutSpec(
insets: UIEdgeInsetsMake(1, 4, 1, 4),
child: ASStackLayoutSpec(
direction: .vertical,
spacing: 0,
justifyContent: .start, // Never used
alignItems: isOutgoing ? .end : .start,
children: Array.filterNils(from: unfilteredChildren)))
}
}
private extension Array {
// Credits: http://stackoverflow.com/a/28190873/1136669
static func filterNils(from array: [Element?]) -> [Element] {
return array.filter { $0 != nil }.map { $0! }
}
}
| mit | 90cb20fe7aafacd60e0b3a49e1f6b500 | 41.704082 | 253 | 0.675269 | 5.097442 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/View/Main/VSpinner.swift | 1 | 1158 | import UIKit
class VSpinner:UIImageView
{
private let kAnimationDuration:TimeInterval = 5
init()
{
super.init(frame:CGRect.zero)
let images:[UIImage] = [
#imageLiteral(resourceName: "assetGenericSpinner0"),
#imageLiteral(resourceName: "assetGenericSpinner1"),
#imageLiteral(resourceName: "assetGenericSpinner2"),
#imageLiteral(resourceName: "assetGenericSpinner3"),
#imageLiteral(resourceName: "assetGenericSpinner4"),
#imageLiteral(resourceName: "assetGenericSpinner5"),
#imageLiteral(resourceName: "assetGenericSpinner6"),
#imageLiteral(resourceName: "assetGenericSpinner7"),
#imageLiteral(resourceName: "assetGenericSpinner8")
]
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
animationDuration = kAnimationDuration
animationImages = images
contentMode = UIViewContentMode.center
startAnimating()
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | 43620cecb1fdb90bc5b773714dedf323 | 31.166667 | 64 | 0.643351 | 6 | false | false | false | false |
skvasov/motem-ios | motem-ios/Classes/User Interface/Places/PlaceCellController.swift | 1 | 1291 | //
// PlaceCellController.swift
// motem-ios
//
// Created by Sergei Kvasov on 11/22/16.
// Copyright © 2016 Mobexs.com. All rights reserved.
//
import UIKit
import AlamofireImage
protocol PlaceCellControllerDelegate: class {
}
class PlaceCellController: PlaceCellDelegate {
private(set) var place: Place
weak var delegate: PlaceCellControllerDelegate?
var cell: PlaceCell? {
didSet {
if let cell = self.cell {
cell.delegate = self
}
self.updateContents()
}
}
init(place: Place) {
self.place = place
}
func updateContents() {
if let cell = self.cell {
cell.nameLabel?.text = self.place.name
if let imageURL = self.place.imageURL, let url = URL(string: imageURL) {
cell.backgroundImageView?.af_setImage(withURL: url)
}
}
}
// MARK: - PlaceCellDelegate
func placeCellWillPrepareForReuse(cell: PlaceCell) {
if let cell = self.cell {
cell.nameLabel?.text = ""
cell.backgroundImageView?.image = nil
}
self.cell = nil
}
}
| mit | fc77033f6d232271ad14ae8a62635400 | 20.147541 | 85 | 0.527907 | 4.607143 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Plans/PlanListViewModel.swift | 2 | 2647 | import Foundation
import WordPressShared
import WordPressUI
enum PlanListViewModel {
case loading
case ready([Plan], [PlanFeature])
case error
var noResultsViewModel: NoResultsViewController.Model? {
switch self {
case .loading:
return NoResultsViewController.Model(title: NSLocalizedString("Loading Plans...", comment: "Text displayed while loading plans details"),
accessoryView: PlansLoadingIndicatorView())
case .ready:
return nil
case .error:
return NoResultsViewController.Model(title: NSLocalizedString("Oops", comment: "An informal exclaimation that means `something went wrong`."),
subtitle: NSLocalizedString("There was an error loading plans", comment: "Text displayed when there is a failure loading the plan list"),
buttonText: NSLocalizedString("Contact support", comment: "Button label for contacting support"))
}
}
func tableViewModelWithPresenter(_ presenter: ImmuTablePresenter?) -> ImmuTable {
switch self {
case .loading, .error:
return ImmuTable.Empty
case .ready(let plans, let features):
let rows: [ImmuTableRow] = plans.map({ plan in
var action: ImmuTableAction? = nil
if let presenter = presenter {
action = presenter.present(self.controllerForPlanDetails(plans, plan: plan, features: features))
}
return PlanListRow(
title: plan.name,
description: plan.tagline,
icon: plan.icon,
action: action
)
})
return ImmuTable(sections: [
ImmuTableSection(
headerText: NSLocalizedString("WordPress.com Plans", comment: "Title for the Plans list header"),
rows: rows,
footerText: String())
])
}
}
func controllerForPlanDetails(_ plans: [Plan], plan: Plan, features: [PlanFeature]) -> ImmuTableRowControllerGenerator {
return { row in
WPAppAnalytics.track(.openedPlansComparison)
let planVC = PlanComparisonViewController(plans: plans, initialPlan: plan, features: features)
let navigationVC = RotationAwareNavigationViewController(rootViewController: planVC)
navigationVC.modalPresentationStyle = .formSheet
return navigationVC
}
}
}
| gpl-2.0 | f1050d341fc0c598267c3036c3f226c0 | 38.507463 | 186 | 0.585569 | 5.908482 | false | false | false | false |
Megatron1000/MacPrompter | MacPrompter/Classes/Prompter.swift | 1 | 9219 | //
// MacPrompter
//
// Created by Mark Bridges on 05/05/2017.
//
// 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 AppKit
import Foundation
import StoreKit
public class Prompter {
public struct PromptResult {
public enum PromptType {
case rate
case viewOtherApp(otherApp: OtherAppPromptInfo)
}
public let promptType: PromptType
public let wasSelected: Bool
public let isPromptsToBeSuppressedInFuture: Bool
}
// MARK: Enum
enum PrompterError: Error {
case unableToParsePlist
}
// MARK: Keys
private let ConfigFileName: String = "PrompterConfig"
private let RunCountKey: String = "runCount"
private let StopRateKey: String = "stopRate"
private let RateAppIntervalKey: String = "rateAppPromptInterval"
private let AppURLKey: String = "appURL"
private let OtherAppsKey: String = "otherApps"
// MARK: Logging Classes
let eventLogger: EventTrackingLogger.Type?
let debugLogger: DebugLogger.Type?
// MARK: Private Properties
private let persistantData = UserDefaults.standard
private let appName: String = NSRunningApplication.current.localizedName ?? ""
private let otherAppPromptInfos: [OtherAppPromptInfo]
private let appURL: URL
private let rateAppPromptInterval: Int
private let delay: TimeInterval = 1
private var runCount: Int {
get {
return persistantData.integer(forKey: RunCountKey)
} set {
persistantData.set(newValue, forKey: RunCountKey)
}
}
// MARK: Initialiser
public init(eventLogger: EventTrackingLogger.Type? = nil, debugLogger: DebugLogger.Type? = nil) throws {
guard
let url: URL = Bundle.main.url(forResource: self.ConfigFileName, withExtension: "plist"),
let config = NSDictionary(contentsOf: url) as? [String : Any],
let otherAppDictionaries = config[OtherAppsKey] as? [[String : Any]],
let rateAppPromptInterval = config[RateAppIntervalKey] as? Int,
let appURLString = config[AppURLKey] as? String,
let appURL = URL(string: appURLString) else {
throw PrompterError.unableToParsePlist
}
self.otherAppPromptInfos = try otherAppDictionaries.map{ try OtherAppPromptInfo(dictionary: $0) }
self.appURL = appURL
self.rateAppPromptInterval = rateAppPromptInterval
self.eventLogger = eventLogger
self.debugLogger = debugLogger
}
// MARK: Functions
public func run(withCompletion completion: ((PromptResult) -> Void)? = nil) {
runCount = runCount + 1
debugLogger?.log("Prompter has been run \(runCount) times")
if !persistantData.bool(forKey: StopRateKey) && ((runCount % rateAppPromptInterval) == 0) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay,
execute: { [weak self] in
self?.showRateAppPromptWithCompletion(completion: completion)
})
}
else {
let shuffledOtherAppPromptInfos = otherAppPromptInfos.shuffled()
for otherAppPromptInfo in shuffledOtherAppPromptInfos {
if otherAppPromptInfo.promptInterval > 0 {
if !persistantData.bool(forKey: otherAppPromptInfo.stopKey) && ((runCount % otherAppPromptInfo.promptInterval) == 0) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay,
execute: { [weak self] in
self?.showOtherAppPrompt(for: otherAppPromptInfo, withCompletion: completion)
})
break
}
}
}
}
}
private func showRateAppPromptWithCompletion(completion: ((PromptResult) -> Void)?) {
if #available(OSX 10.14, *) {
SKStoreReviewController.requestReview()
} else {
let alert = NSAlert()
alert.messageText = appName
alert.informativeText = String(format: "prompter.rateAppAlert.title".localized, appName)
alert.showsSuppressionButton = true
alert.suppressionButton?.title = "prompter.alert.dontAskAgain".localized
alert.addButton(withTitle: "prompter.alert.rateNow".localized)
alert.addButton(withTitle: "prompter.alert.noThanks".localized)
alert.window.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(CGWindowLevelKey.popUpMenuWindow)))
let result: NSApplication.ModalResponse = alert.runModal()
let alertWasSuppressed = alert.suppressionButton?.state == .on
if alertWasSuppressed {
persistantData.set(true, forKey: StopRateKey)
debugLogger?.log("Suppressed")
eventLogger?.logEvent("rate_app_suppressed")
}
switch result {
case .alertFirstButtonReturn:
debugLogger?.log("Will Rate")
NSWorkspace.shared.open(appURL)
persistantData.set(true, forKey: StopRateKey)
eventLogger?.logEvent("rate_app_selected")
completion?(PromptResult(promptType: .rate, wasSelected: true, isPromptsToBeSuppressedInFuture: alertWasSuppressed))
default:
eventLogger?.logEvent("rate_app_dismissed")
completion?(PromptResult(promptType: .rate, wasSelected: false, isPromptsToBeSuppressedInFuture: alertWasSuppressed))
}
}
}
private func showOtherAppPrompt(for otherAppPromptInfo: OtherAppPromptInfo, withCompletion completion: ((PromptResult) -> Void)? ) {
let alert = NSAlert()
alert.messageText = otherAppPromptInfo.name
alert.informativeText = String(format: "prompter.viewOtherAppsAlert.title".localized, appName, otherAppPromptInfo.name)
alert.showsSuppressionButton = true
alert.suppressionButton?.title = "prompter.alert.dontAskAgain".localized
alert.addButton(withTitle: "prompter.alert.viewInStore".localized)
alert.addButton(withTitle: "prompter.alert.noThanks".localized)
alert.icon = otherAppPromptInfo.image
alert.window.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(CGWindowLevelKey.popUpMenuWindow)))
let result: NSApplication.ModalResponse = alert.runModal()
let alertWasSuppressed = alert.suppressionButton?.state == .on
if alertWasSuppressed {
persistantData.set(true, forKey: otherAppPromptInfo.stopKey)
debugLogger?.log("Suppressed")
eventLogger?.logEvent("view_other_app_suppressed", parameters: ["app_name" : otherAppPromptInfo.name])
}
switch result {
case .alertFirstButtonReturn:
debugLogger?.log("Will Rate")
NSWorkspace.shared.open(otherAppPromptInfo.url)
persistantData.set(true, forKey: otherAppPromptInfo.stopKey)
eventLogger?.logEvent("view_other_app_selected", parameters: ["app_name" : otherAppPromptInfo.name])
completion?(PromptResult(promptType: .viewOtherApp(otherApp: otherAppPromptInfo),
wasSelected: true,
isPromptsToBeSuppressedInFuture: alertWasSuppressed))
default:
eventLogger?.logEvent("view_other_app_dismissed", parameters: ["app_name" : otherAppPromptInfo.name])
completion?(PromptResult(promptType: .viewOtherApp(otherApp: otherAppPromptInfo),
wasSelected: false,
isPromptsToBeSuppressedInFuture: alertWasSuppressed))
}
}
}
| mit | 4a61c662d4a70fcc52e35927a9139cf8 | 43.110048 | 138 | 0.625231 | 4.951128 | false | false | false | false |
yoichitgy/BWWalkthrough | BWWalkthroughExample/CustomPageViewController.swift | 1 | 1092 | //
// CustomPageViewController.swift
// BWWalkthroughExample
//
// Created by Yari D'areglia on 18/09/14.
// Copyright (c) 2014 Yari D'areglia. All rights reserved.
//
import UIKit
import BWWalkthrough
class CustomPageViewController: UIViewController,BWWalkthroughPage {
@IBOutlet var imageView:UIImageView?
@IBOutlet var titleLabel:UILabel?
@IBOutlet var textLabel:UILabel?
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: BWWalkThroughPage protocol
func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {
var tr = CATransform3DIdentity
tr.m34 = -1/500.0
titleLabel?.layer.transform = CATransform3DRotate(tr, CGFloat(M_PI) * (1.0 - offset), 1, 1, 1)
textLabel?.layer.transform = CATransform3DRotate(tr, CGFloat(M_PI) * (1.0 - offset), 1, 1, 1)
var tmpOffset = offset
if(tmpOffset > 1.0){
tmpOffset = 1.0 + (1.0 - tmpOffset)
}
imageView?.layer.transform = CATransform3DTranslate(tr, 0 , (1.0 - tmpOffset) * 200, 0)
}
}
| mit | d8b22a04741b5196afa21629bfed9d10 | 27.736842 | 102 | 0.642857 | 3.831579 | false | false | false | false |
CarlosMChica/swift-dojos | MarsRoverKata/MarsRoverKata/Action.swift | 1 | 413 | protocol Action {
func canExecute(command: Command) -> Bool
func execute(command: Command) throws -> Position
}
struct Command: Equatable {
let input: String
let position: Position
init(input: String = "", position: Position) {
self.input = input
self.position = position
}
}
func ==(lhs: Command, rhs: Command) -> Bool {
return lhs.input == rhs.input && lhs.position == rhs.position
}
| apache-2.0 | f7a788c4de6b050755023c11500c833c | 19.65 | 63 | 0.670702 | 3.859813 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | SwiftKit/extension/UIView+extension.swift | 1 | 4271 | //
// UIView+extension.swift
// swift4.2Demo
//
// Created by baiqiang on 2018/10/6.
// Copyright © 2018年 baiqiang. All rights reserved.
//
import UIKit
private let KBgRoundLayer = "KBgRoundLayer"
//MARK:- ***** 视图位置调整 *****
extension UIView {
//MARK:- ***** publice var and function *****
var top : CGFloat {
get {
return self.frame.origin.y
}
set(top) {
self.frame.origin = CGPoint(x: self.frame.origin.x, y: top)
}
}
var left : CGFloat {
get {
return self.frame.origin.x
}
set(left) {
self.frame.origin = CGPoint(x: left, y: self.frame.origin.y)
}
}
var bottom : CGFloat {
get {
return self.frame.maxY
}
set(bottom) {
self.top = bottom - self.sizeH
}
}
var right : CGFloat {
get {
return self.frame.maxX
}
set(right) {
self.left = right - self.sizeW
}
}
var sizeW : CGFloat {
get {
return self.bounds.size.width
}
set(sizeW) {
self.frame.size = CGSize(width: sizeW, height: self.frame.height)
}
}
var sizeH : CGFloat {
get {
return self.bounds.size.height
}
set(height) {
self.frame.size = CGSize(width: self.sizeW, height: height)
}
}
var size: CGSize {
get {
return self.bounds.size
}
set(size) {
self.frame.size = size
}
}
var origin : CGPoint {
get {
return self.frame.origin;
}
set(origin) {
self.frame.origin = origin
}
}
func setCorner(readius:CGFloat) {
self.layer.allowsEdgeAntialiasing = true
self.layer.cornerRadius = readius
self.clipsToBounds = true
}
func toRound() {
self.setCorner(readius: self.bounds.size.width * 0.5)
}
func setBordColor(color:UIColor) {
self.layer.borderColor = color.cgColor
self.layer.borderWidth = 1.0
}
func addTapGes(action:@escaping (_ view: UIView) -> ()) {
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGestureAction))
self.isUserInteractionEnabled = true
self.action = action
self.addGestureRecognizer(gesture)
}
func setRoundCorners( readius:CGFloat, corners:UIRectCorner) {
var bgColor = self.backgroundColor
self.backgroundColor = .clear
if let subLayers = self.layer.sublayers {
for subLayer in subLayers {
if subLayer.name == KBgRoundLayer {
bgColor = UIColor(cgColor: (subLayer as! CAShapeLayer).fillColor!)
subLayer.removeFromSuperlayer()
break
}
}
}
let beizPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: readius, height: readius))
let roundPath = CAShapeLayer()
roundPath.frame = self.bounds
roundPath.name = KBgRoundLayer
roundPath.path = beizPath.cgPath
roundPath.fillColor = bgColor?.cgColor
self.layer.insertSublayer(roundPath, at: 0)
}
//MARK:- ***** Override function *****
//MARK:- ***** Private tapGesture *****
typealias addBlock = (_ imageView: UIView) -> Void
private struct AssociatedKeys {
static var actionKey = "actionBlock"
}
private var action: addBlock? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.actionKey) as? addBlock
}
set (newValue){
objc_setAssociatedObject(self, &AssociatedKeys.actionKey, newValue!, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
@objc private func tapGestureAction(sender: UITapGestureRecognizer) {
guard let actionBlock = self.action else {
return
}
if sender.state == .ended {
actionBlock(self)
}
}
}
| apache-2.0 | c54a323f0dc463bd89b4014ccc159496 | 24.638554 | 143 | 0.534539 | 4.484721 | false | false | false | false |
FitGenerator/Source | Source/SourceTests/TableView/CombinedTableViewDataSourceTests.swift | 1 | 8631 | //
// CombinedTableViewDataSourceTests.swift
// Source
//
// Created by Jakub Gert on 06/10/2016.
// Copyright (c) 2016 FitGenerator. All rights reserved.
//
import XCTest
import Nimble
@testable import Source
class CombinedTableViewSingleDataSourceTests: XCTestCase {
var dataSource = CombinedTableViewDataSource()
override func setUp() {
super.setUp()
self.dataSource = CombinedTableViewDataSource()
}
func testNoSectionNoRows() {
let emptyDataSource = MockedTableViewDataSource(
sectionsCount: 0,
rowsCount: 0)
dataSource.dataSources = [emptyDataSource]
expect(self.dataSource.numberOfSections()).to(equal(0))
}
func testSingleSectionNoRows() {
let mockedDataSource = MockedTableViewDataSource(
sectionsCount: 1,
rowsCount: 0)
dataSource.dataSources = [mockedDataSource]
expect(self.dataSource.numberOfSections()).to(equal(1))
expect(self.dataSource.numberOfRows(inSection: 0)).to(equal(0))
}
func testSingleSectionMultipleRows() {
let mockedDataSource = MockedTableViewDataSource(
sectionsCount: 1,
rowsCount: 10)
dataSource.dataSources = [mockedDataSource]
expect(self.dataSource.numberOfSections()).to(equal(1))
expect(self.dataSource.numberOfRows(inSection: 0)).to(equal(10))
}
func testMultipleSectionsNoRows() {
let mockedDataSource = MockedTableViewDataSource(
sectionsCount: 10,
rowsCount: 0)
dataSource.dataSources = [mockedDataSource]
expect(self.dataSource.numberOfSections()).to(equal(10))
for a in 0 ..< 10 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(0))
}
}
func testMultipleSectionsSingleRow() {
let mockedDataSource = MockedTableViewDataSource(
sectionsCount: 10,
rowsCount: 1)
dataSource.dataSources = [mockedDataSource]
expect(self.dataSource.numberOfSections()).to(equal(10))
for a in 0 ..< 10 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(1))
}
}
func testMultipleSectionsMultipleRows() {
let mockedDataSource = MockedTableViewDataSource(
sectionsCount: 10,
rowsCount: 10)
dataSource.dataSources = [mockedDataSource]
expect(self.dataSource.numberOfSections()).to(equal(10))
for a in 0 ..< 10 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(10))
}
}
}
class CombinedTableViewDataSourceMultipleDataSourceTestCase: XCTestCase {
var dataSource = CombinedTableViewDataSource()
override func setUp() {
super.setUp()
dataSource = CombinedTableViewDataSource()
}
func testNoSectionNoRows() {
let mockedDataSource1 = MockedTableViewDataSource(
sectionsCount: 0,
rowsCount: 0)
let mockedDataSource2 = MockedTableViewDataSource(
sectionsCount: 0,
rowsCount: 0)
let mockedDataSource3 = MockedTableViewDataSource(
sectionsCount: 0,
rowsCount: 0)
dataSource.dataSources = [
mockedDataSource1,
mockedDataSource2,
mockedDataSource3
]
expect(self.dataSource.numberOfSections()).to(equal(0))
expect(self.dataSource.numberOfRows(inSection: 0)).to(equal(0))
expect(self.dataSource.numberOfRows(inSection: 1)).to(equal(0))
expect(self.dataSource.numberOfRows(inSection: 2)).to(equal(0))
}
func testSingleSectionNoRows() {
let mockedDataSource1 = MockedTableViewDataSource(sectionsCount: 1, rowsCount: 0)
let mockedDataSource2 = MockedTableViewDataSource(sectionsCount: 1, rowsCount: 0)
let mockedDataSource3 = MockedTableViewDataSource(sectionsCount: 1, rowsCount: 0)
dataSource.dataSources = [mockedDataSource1, mockedDataSource2, mockedDataSource3]
expect(self.dataSource.numberOfSections()).to(equal(3))
expect(self.dataSource.numberOfRows(inSection: 0)).to(equal(0))
expect(self.dataSource.numberOfRows(inSection: 1)).to(equal(0))
expect(self.dataSource.numberOfRows(inSection: 2)).to(equal(0))
}
func testSingleSectionMultipleRows() {
let mockedDataSource1 = MockedTableViewDataSource(sectionsCount: 1, rowsCount: 10)
let mockedDataSource2 = MockedTableViewDataSource(sectionsCount: 1, rowsCount: 5)
let mockedDataSource3 = MockedTableViewDataSource(sectionsCount: 1, rowsCount: 25)
dataSource.dataSources = [mockedDataSource1, mockedDataSource2, mockedDataSource3]
expect(self.dataSource.numberOfSections()).to(equal(3))
expect(self.dataSource.numberOfRows(inSection: 0)).to(equal(10))
expect(self.dataSource.numberOfRows(inSection: 1)).to(equal(5))
expect(self.dataSource.numberOfRows(inSection: 2)).to(equal(25))
}
func testMultipleSectionsNoRows() {
let mockedDataSource1 = MockedTableViewDataSource(sectionsCount: 10, rowsCount: 0)
let mockedDataSource2 = MockedTableViewDataSource(sectionsCount: 5, rowsCount: 0)
let mockedDataSource3 = MockedTableViewDataSource(sectionsCount: 15, rowsCount: 0)
dataSource.dataSources = [mockedDataSource1, mockedDataSource2, mockedDataSource3]
expect(self.dataSource.numberOfSections()).to(equal(30))
for a in 0 ..< 30 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(0))
}
}
func testMultipleSectionsSingleRow() {
let mockedDataSource1 = MockedTableViewDataSource(sectionsCount: 10, rowsCount: 1)
let mockedDataSource2 = MockedTableViewDataSource(sectionsCount: 5, rowsCount: 1)
let mockedDataSource3 = MockedTableViewDataSource(sectionsCount: 15, rowsCount: 1)
dataSource.dataSources = [mockedDataSource1, mockedDataSource2, mockedDataSource3]
expect(self.dataSource.numberOfSections()).to(equal(30))
for a in 0 ..< 30 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(1))
}
}
func testMultipleSectionsMultipleRows() {
let mockedDataSource1 = MockedTableViewDataSource(sectionsCount: 10, rowsCount: 10)
let mockedDataSource2 = MockedTableViewDataSource(sectionsCount: 5, rowsCount: 5)
let mockedDataSource3 = MockedTableViewDataSource(sectionsCount: 15, rowsCount: 20)
dataSource.dataSources = [mockedDataSource1, mockedDataSource2, mockedDataSource3]
expect(self.dataSource.numberOfSections()).to(equal(30))
XCTAssertEqual(dataSource.numberOfSections(), 30)
for a in 0 ..< 10 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(10))
}
for a in 10 ..< 15 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(5))
}
for a in 15 ..< 30 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(20))
}
}
}
class CombinedTableViewDataSourceNestedCombinedDataSourceTestCase: XCTestCase {
var dataSource = CombinedTableViewDataSource()
override func setUp() {
super.setUp()
dataSource = CombinedTableViewDataSource()
}
func testNestedCombinedDataSource() {
let mockedDataSource1 = MockedTableViewDataSource(sectionsCount: 10, rowsCount: 10)
let mockedDataSource2 = MockedTableViewDataSource(sectionsCount: 5, rowsCount: 5)
let mockedDataSource3 = MockedTableViewDataSource(sectionsCount: 5, rowsCount: 5)
let mockedDataSource4 = MockedTableViewDataSource(sectionsCount: 10, rowsCount: 10)
let innerCombinedDataSource = CombinedTableViewDataSource()
innerCombinedDataSource.dataSources = [mockedDataSource2, mockedDataSource3]
dataSource.dataSources = [mockedDataSource1, innerCombinedDataSource, mockedDataSource4]
expect(self.dataSource.numberOfSections()).to(equal(30))
for a in 0 ..< 10 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(10))
}
for a in 10 ..< 15 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(5))
}
for a in 15 ..< 20 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(5))
}
for a in 20 ..< 30 {
expect(self.dataSource.numberOfRows(inSection: a)).to(equal(10))
}
}
} | mit | 2f01a1d12c99a94b80645ad02af3dd8d | 35.731915 | 96 | 0.666551 | 4.760618 | false | true | false | false |
priyax/RecipeRater | RecipeRater/RecipeRater/Meal.swift | 1 | 1653 | //
// Meal.swift
// RecipeRater
//
// Created by Priya Xavier on 9/16/16.
// Copyright © 2016 Guild/SA. All rights reserved.
//
import UIKit
class Meal: NSObject, NSCoding {
// MARK: Properties
// MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("meals")
// MARK: Types
struct PropertyKey
{
static let nameKey = "name"
static let photoKey = "photo"
static let ratingKey = "rating"
}
var name: String
var photo: UIImage?
var rating: Int
init?(name: String, photo: UIImage?, rating: Int) {
self.name = name
self.photo = photo
self.rating = rating
super.init()
if name.isEmpty || rating < 0 {
return nil
}
}
//Mark: NSEncoding
func encode(with aCoder: NSCoder)
{ aCoder.encode(name, forKey: PropertyKey.nameKey)
aCoder.encode(photo, forKey: PropertyKey.photoKey)
aCoder.encode(rating, forKey: PropertyKey.ratingKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: PropertyKey.nameKey) as! String
// Because photo is an optional property of Meal, use conditional cast.
let photo = aDecoder.decodeObject(forKey: PropertyKey.photoKey) as? UIImage
let rating = aDecoder.decodeInteger(forKey: PropertyKey.ratingKey)
// Must call designated initializer.
self.init(name: name, photo: photo, rating: rating)
}
}
| mit | 28fa13b67feef5f68dc3b3d6e76617f7 | 29.592593 | 107 | 0.639225 | 4.393617 | false | false | false | false |
movinpixel/Promise | Pod/Promise.swift | 1 | 31214 | //
// Promise.swift
// Heroes.II.Model
//
// Created by Julio Flores on 10/8/15.
// Copyright © 2015 Movinpixel Ltd. All rights reserved.
//
//
// public methods (run, then, when)
//
import Foundation
public extension Promise {
/**
Instantiate a new `Promise`, running the passed block immediately.
```
Promise.run { () -> Any? in
// some asynchronously block of code.
return "the value for the next Promise in the chain that can be started with .then(), or with the 'result' property if the 'Promise' already 'isCopmlete' and doesn't 'hasErrors'"
}
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promise.
*/
public static func run (task: Task) -> Promise {
return Promise(task: task, errorHandler: nil)
}
/**
Instantiate a new `Promise`, running the passed block immediately.
```
Promise.run(task: {
// some asynchronous block of code that might throw an error
return "the value for the next Promise in the chain that can be started with .then(), or with the 'result' property if the 'Promise' already 'isCopmlete' and doesn't 'hasErrors'"
}, errorHandler: { (error) -> Void in
// some block of code that will handle the error.
})
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Parameter errorHandler: The block of code that will handle the possibly thrown errors. This block runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promise.
*/
public static func run (task: Task, errorHandler: Failure?) -> Promise {
return Promise(task: task, errorHandler: errorHandler)
}
/**
Instantiate a new `Promise`, running the passed block immediately.
```
Promise.run {
// some asynchronously block of code.
}
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promise.
*/
public static func run (task: TaskNoReturn) -> Promise {
return Promise(taskWithNoReturn: task, errorHandler: nil)
}
/**
Instantiate a new `Promise`, running the passed block immediately.
```
Promise.run(task: {
// some asynchronously block of code that might throw an error
}, errorHandler: { (error) -> Void in
// some block of code that will handle the error.
})
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Parameter errorHandler: The block of code that will handle the possibly thrown errors. It runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promise.
*/
public static func run (task: TaskNoReturn, errorHandler: Failure?) -> Promise {
return Promise(taskWithNoReturn: task, errorHandler: errorHandler)
}
/**
Instantiate a new `Promise`, running the passed block immediately.
```
Promise.run {
// some code that returns anything that will be passed to the next Promise (in this example, called with .then()).
return "some value to the next chained Promise"
}.then { (previousPromiseResult: Any?) -> Any in
// waits the end of the previous `Promise`, and starts the execution immediately after the completion (that is, fired serially)
// the parameter `previousPromiseResult` holds the value that was returned in the previous `Promise` (in this example, passed in Promise.run())
return "the value for the next Promise in the chain that can be started with .then(), or with the 'result' property if the 'Promise' already 'isCopmlete' and doesn't 'hasErrors'"
}
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
The parameter it receives is the value returned by the previous `Promise` in the chain.
It returns a value that will be passed to the next `Promise` that will be chained.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: (previousPromiseResult: Any?) throws -> Any) -> Promise {
return Promise(previousPromise: self, task: task, errorHandler: nil)
}
/**
Executes the passed block immediately after the end of the execution of the previous chained `Promise`.
```
Promise.run {
// runs some code that returns anything that will be passed to the Promise, called with .then().
return "some value to the next chained Promise"
}.then({ (previousPromiseResult: Any?) -> Any in
// waits the end of the previous `Promise`, and starts the execution immediately after the completion.
// the parameter `previousPromiseResult` holds the value that was returned in the previous `Promise` (in this example, it was passed in Promise.run())
return "the value for the next Promise in the chain that can be started with .then(), or with the 'result' property if the 'Promise' already 'isCopmlete' and doesn't 'hasErrors'"
}, errorHandler: {(error) -> Void in
// some block of code that will handle the error.
})
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
The parameter it receives is the value returned by the previous `Promise` in the chain.
It returns a value that will be passed to the next `Promise` that will be chained.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Parameter errorHandler: The block of code that will handle the possible thrown errors. It runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: (previousPromiseResult: Any?) throws -> Any, errorHandler: Failure?) -> Promise {
return Promise(previousPromise: self, task: task, errorHandler: errorHandler)
}
/**
Executes the passed block immediately after the end of the execution of the previous chained `Promise`.
```
Promise.run {
// some code that returns anything that will be passed to the next Promise (in this example, called with .then()).
return "some value to the next chained Promise"
}.then { (previousPromiseResult: Any?) -> Void in
// waits the end of the previous `Promise`, and starts the execution immediately after the completion (that is, fired serially)
// the parameter `previousPromiseResult` holds the value that was returned in the previous `Promise` (in this example, passed in Promise.run())
}
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
The parameter it receives is the value returned by the previous `Promise` in the chain.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: (previousPromiseResult: Any?) throws -> Void) -> Promise {
return Promise(previousPromise: self, taskNoReturn: task, errorHandler: nil)
}
/**
Executes the passed block immediately after the end of the execution of the previous chained `Promise`.
```
Promise.run {
// runs some code that returns anything that will be passed to the Promise, called with .then().
return "some value to the next chained Promise"
}.then({ (previousPromiseResult: Any?) -> Void in
// waits the end of the previous `Promise`, and starts the execution immediately after the completion.
// the parameter `previousPromiseResult` holds the value that was returned in the previous `Promise` (in this example, it was passed in Promise.run())
}, errorHandler: {(error) -> Void in
// some block of code that will handle the error.
})
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
The parameter it receives is the value returned by the previous `Promise` in the chain.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Parameter errorHandler: The block of code that will handle the possible thrown errors. It runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: (previousPromiseResult: Any?) throws -> Void, errorHandler: Failure?) -> Promise {
return Promise(previousPromise: self, taskNoReturn: task, errorHandler: errorHandler)
}
/**
Instantiate a new `Promise`, running the passed block immediately.
```
Promise.run {
// some code that returns anything that will be passed to the next Promise (in this example, called with .then()).
}.then {
// waits the end of the previous `Promise`, and starts the execution immediately after the completion (that is, fired serially)
return "the value for the next Promise in the chain that can be started with .then(), or with the 'result' property if the 'Promise' already 'isCopmlete' and doesn't 'hasErrors'"
}
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
It returns a value that will be passed to the next `Promise` that will be chained.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: () throws -> Any) -> Promise {
return Promise(previousPromise: self, taskNoArguments: task, errorHandler: nil)
}
/**
Executes the passed block immediately after the end of the execution of the previous chained `Promise`.
```
Promise.run {
// runs some code that returns anything that will be passed to the Promise, called with .then().
}.then({
// waits the end of the previous `Promise`, and starts the execution immediately after the completion.
return "the value for the next Promise in the chain that can be started with .then(), or with the 'result' property if the 'Promise' already 'isCopmlete' and doesn't 'hasErrors'"
}, errorHandler: {(error) -> Void in
// some block of code that will handle the error.
})
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
It returns a value that will be passed to the next `Promise` that will be chained.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Parameter errorHandler: The block of code that will handle the possible thrown errors. It runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: () throws -> Any, errorHandler: Failure?) -> Promise {
return Promise(previousPromise: self, taskNoArguments: task, errorHandler: errorHandler)
}
/**
Executes the passed block immediately after the end of the execution of the previous chained `Promise`.
```
Promise.run {
// runs some code that returns anything that will be passed to the Promise, called with .then().
return "some value to the next chained Promise"
}.then {
// waits the end of the previous `Promise`, and starts the execution immediately after the completion.
}
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: () throws -> Void) -> Promise {
return Promise(previousPromise: self, taskNoArgumentsNoReturn: task, errorHandler: nil)
}
/**
Executes the passed block immediately after the end of the execution of the previous chained `Promise`.
```
Promise.run {
// runs some code that returns anything that will be passed to the Promise, called with .then().
}.then({
// waits the end of the previous `Promise`, and starts the execution immediately after the completion.
}, errorHandler: {(error) -> Void in
// some block of code that will handle the error.
})
```
- Parameter task: The block of code that you wish to run asynchronously.
The block starts immediately.
It runs in a separate thread, making the code block completely asynchronous.
If an error is thrown, the next `Promises` in the chain won't start. You can catch the error passing a block to the `errorHandler` parameter, at any point in the chain.
- Parameter errorHandler: The block of code that will handle the possible thrown errors. It runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public func then(_ task: () throws -> Void, errorHandler: Failure?) -> Promise {
return Promise(previousPromise: self, taskNoArgumentsNoReturn: task, errorHandler: errorHandler)
}
/**
Executes an array of Promises, all concurrently.
```
let promise1 = Promise.run {
// some asynchronous and concurrent task.
}
let promise2 = Promise.run {
// some asynchronous and concurrent task.
return 3 // a dummy value just for representation
}.then {(previousPromiseReturn: Any?) -> Void in
// some asynchronous task, but serial with the previous chained 'Promise'
}
let promise3 = Promise.run {
// another asynchronous and concurrent task.
}
Promise.when([promise1, promise2, promise3])
```
- Param promises: all the promises that will run concurrently. If an error is thrown, the other concurrent `Promises` will NOT stop.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public static func when(_ promises: [Promise]) -> Promise {
return when(promises, errorHandler: nil)
}
/**
Executes an array of Promises, all concurrently.
```
let promise1 = Promise.run {
// some asynchronous and concurrent task.
}
let promise2 = Promise.run {
// some asynchronous and concurrent task.
return 3 // a dummy value just for representation
}.then {(previousPromiseReturn: Any?) -> Void in
// some asynchronous task, but serial with the previous chained 'Promise'
}
let promise3 = Promise.run {
// another asynchronous and concurrent task.
}
Promise.when([promise1, promise2, promise3], errorHandler: {(error) -> Void in
// some block of code that will handle the error.
})
```
- Param promises: all the promises that will run concurrently. If an error is thrown, the other concurrent `Promises` will NOT stop.
- Parameter errorHandler: The block of code that will handle the possible thrown errors. It runs in the main thread.
- Returns: the Promise, which allows you to get the value of the result at any point you wish, and/or allows you to chain to another promises.
*/
public static func when(_ promises: [Promise], errorHandler: Failure?) -> Promise {
return Promise.run (task: { () -> Void in
for promise in promises {
pthread_mutex_lock(promise.mutex)
if promise.shouldWait {
pthread_cond_wait(promise.condition, promise.mutex)
}
pthread_mutex_unlock(promise.mutex)
if promise.hasError {
throw promise.pool.currentError!
}
}
}, errorHandler: errorHandler)
}
}
/**
Promise is designed to hold and run immediately a block of code. You always start a Promise by using .run() in many ways. For example:
```
Promise.run {
// here goes some asynchronous code.
}
```
If you want to use this promise somewhere else in the future, for example for taking the result, that could be like that:
```
let myPromise = Promise.run {
//some method that returns 3
return 3
}
...
// somewhere in the future
var myPromiseResult = 0
if myPromise.isCompleted {
myPromiseResult = myPromise.result as! Int
}
```
You can also provide an error handler for the Promise:
```
Promise.run(task: {() throws -> Void in
// some meaningful code that might throw an error
}, errorHandler: {(error) -> Void in
// your own error handler
})
```
The above error handler might not be too useful if you prefer to use the swift way of handling errors, for example by using do...catch inside the block itself.
However, it shows very powerful in the next sections.
As a great part of the Promise flexibility, there comes the magic of chaining tasks. They can depend one upon the other.
You chain them by using .then():
```
Promise.run {
// some important task that returns "lala lones"
return "lala lones"
}.then {(previousPromiseResult: Any?) -> Void in
// previousPromiseResult contains the value "lala lones" that came from the previous Promise.
// you can extract it by many Swift ways, for example:
let importantString = previousPromiseResult as! String
...
// some important use for the importantString
}.then {
// notice that the previous Promise doesn't return anything. As so, this block doesn't receive any parameter.
// in fact, you can also use the previousPromiseResult overload, however the value passed to this parameter
// is an object of type Void. You can't do anything meaningful with Void.
}
```
You can also handle errors at any point in the Promise chain. All blocks are throwable, so you can safely use try or throw your own exceptions
```
Promise.run {
// some meaningful code
}.then {
try someMeaningfulMethod() //let's say this method threw an error
}.then {
// some meaningful code. This code won't be executed because the previous promise threw an error.
}.then({
// some meaningful code. This code won't be executed because the previous promise threw an error.
}, errorHandler: { (error) throws -> Void in
// the 'error' parameter contains the error thrown at the second Promise.
// notice that this block is also throwable, which means that you if you don't want to make this the end,
// you can rethrow the error, or forward another error if you will.
// the error that this method throws will continue down the chain in the same way that .then() does
// let's say that the error was fully handled here
}).then {
// as you can see, you can continue the chain even if there was an error handler before.
// this method WILL be executed, because the previous Promise contained the 'errorHandler' which fully handled the error.
}.then({
// some meaningful code
}, errorHandler: {(error) -> Void in
// another last error handler.
// if you don't provide an error handler and an error is thrown, the error is simply discarded and the following
// Promises after the error are not executed.
})
```
Finally, you can execute many Promises concurrently. Actually, every Promise that you intantiate will already run concurrently,
but you can know when all of the desired Promises have finished with the use of .when(). And, of course, you can also have an `errorHandler`.
```
let promise1 = Promise.run {
// some asynchronous and concurrent task.
}
let promise2 = Promise.run {
// some asynchronous and concurrent task.
return 3 // a dummy value just for representation
}.then {(previousPromiseReturn: Any?) -> Void in
// some asynchronous task, but serial with the previous chained 'Promise'
// notice that variable 'promise2' refers to THIS promise. Always to the last promise of the chain.
}
let promise3 = Promise.run {
// another asynchronous and concurrent task.
}
Promise.when([promise1, promise2, promise3], errorHandler: {(error) -> Void in
// some block of code that will handle the error.
})
```
For the purpose of giving you more control, you can know when a Promise already has a result available by consulting the `result` property.
If `result` is nil, the Promise hasn't yet a result available.
Alternatively, you can also consult the boolean `isCompleted` and `hasErrors` methods to check whether the Promise is still running.
In case any of them are true, the Promise is already stopped and, as Promises can't be reused, this Promise can be discarded.
However, as using these three properties manually is more error-prone, their use is discouraged.
*/
public class Promise : NSObject {
//
// Public Properties
//
/**
The result returned by the block that this Promise holds, if the Promise `isComplete`
*/
public private(set) var result: Any?
/**
Whether an error was thrown in the block this Promise holds, or at any Promise that is part of this chain.
*/
public var hasError: Bool {
return self.pool.currentError != nil
}
/**
Whether the block this Promise holds has finished its execution
*/
public var isCompleted: Bool {
return self.result != nil
}
//
// Private Properties
//
private let pool: PromisePool
private let mutex: UnsafeMutablePointer<pthread_mutex_t>
private let condition: UnsafeMutablePointer<pthread_cond_t>
private var shouldWait: Bool
// Initialisers are private only. Use Promise.run() to make your call
private convenience init(task: Task, errorHandler: Failure?) {
self.init(previousPromise: nil, execution: { try task() }, errorHandler: errorHandler)
}
private convenience init(taskWithNoReturn: TaskNoReturn, errorHandler: Failure?) {
self.init(previousPromise: nil, execution: { try taskWithNoReturn() }, errorHandler: errorHandler)
}
private convenience init(previousPromise: Promise, taskNoArgumentsNoReturn: () throws -> Void, errorHandler: Failure?) {
self.init(previousPromise: previousPromise, execution: { try taskNoArgumentsNoReturn() as Any }, errorHandler: errorHandler)
}
private convenience init(previousPromise: Promise, taskNoArguments: () throws -> Any, errorHandler: Failure?) {
self.init(previousPromise: previousPromise, execution: {
let returnValue = try taskNoArguments()
try Promise.waitReturnValue(returnValue)
return returnValue
}, errorHandler: errorHandler)
}
private convenience init(previousPromise: Promise, taskNoReturn: (Any?) throws -> Void, errorHandler: Failure?) {
self.init(previousPromise: previousPromise, execution: {
return try taskNoReturn(previousPromise.result)
}, errorHandler: errorHandler)
}
private convenience init(previousPromise: Promise, task: (Any?) throws -> Any, errorHandler: Failure?) {
self.init(previousPromise: previousPromise, execution: {
let returnValue = try task(previousPromise.result)
try Promise.waitReturnValue(returnValue)
return returnValue
}, errorHandler: errorHandler)
}
private init(previousPromise: Promise?, execution: () throws -> Any, errorHandler: Failure?) {
if let previousPromise = previousPromise {
self.pool = previousPromise.pool
} else {
self.pool = PromisePool(queue: DispatchQueue(label: PROMISE_QUEUE_NAME))
}
self.mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
self.condition = UnsafeMutablePointer<pthread_cond_t>.allocate(capacity: 1)
self.shouldWait = true
super.init()
pthread_mutex_init(self.mutex, nil)
pthread_cond_init(self.condition, nil)
self.errorHandler = errorHandler
self.exec(execution)
}
deinit {
pthread_mutex_destroy(self.mutex)
pthread_cond_destroy(self.condition)
self.condition.deallocate(capacity: 1)
self.mutex.deallocate(capacity: 1)
}
private static func waitReturnValue(_ returnValue: Any?) throws {
if let promise = returnValue as? Promise {
pthread_mutex_lock(promise.mutex)
if promise.shouldWait {
pthread_cond_wait(promise.condition, promise.mutex)
}
pthread_mutex_unlock(promise.mutex)
if promise.hasError {
throw promise.pool.currentError!
}
try waitReturnValue(promise.result)
}
}
}
//
// internal implementation
//
private let PROMISE_QUEUE_NAME = "com.movinpixel.Heroes.II.PromiseQueue"
// type aliases
public extension Promise {
public typealias Task = () throws -> Any
public typealias TaskNoReturn = () throws -> Void
public typealias Failure = (error: Error) throws -> Void
}
// execution
private extension Promise {
private var errorHandler: Promise.Failure? {
get
{
return self.pool.errorHandlerForPromise(self)
}
set
{
self.pool.setErrorHandlerForPromise(self, errorHandler: newValue)
}
}
private func exec(_ theTask: () throws -> Any) {
self.pool.queue.async {
pthread_mutex_lock(self.mutex)
do {
if self.pool.currentError == nil {
self.result = try theTask()
} else {
throw self.pool.currentError!
}
} catch {
if let errorHandlerForPromise = self.errorHandler {
DispatchQueue.main.async(execute: { () -> Void in
self.pool.currentError = nil
do {
try errorHandlerForPromise(error: error)
} catch {
self.pool.currentError = error
}
})
} else {
self.pool.currentError = error
}
}
pthread_cond_broadcast(self.condition)
self.shouldWait = false
pthread_mutex_unlock(self.mutex)
}
}
}
private class PromisePool : NSObject {
private var currentError: Error?
private var queue: DispatchQueue
private var queueErrorHandlers: [Promise : Promise.Failure]
private init (queue: DispatchQueue) {
self.queue = queue
self.queueErrorHandlers = [:]
}
private func errorHandlerForPromise(_ promise: Promise) -> Promise.Failure? {
return self.queueErrorHandlers[promise]
}
private func setErrorHandlerForPromise(_ promise: Promise, errorHandler: Promise.Failure?) {
queueErrorHandlers[promise] = errorHandler
}
}
| bsd-3-clause | c734db9ac38b5bff1ca32b4ba696fa14 | 45.447917 | 186 | 0.663185 | 4.748669 | false | false | false | false |
Otbivnoe/Framezilla | Tests/MakerStackTests.swift | 1 | 3977 | //
// MakerStackTests.swift
// Framezilla
//
// Created by Nikita Ermolenko on 19/02/2017.
//
//
import XCTest
@testable import Framezilla
class MakerStackTests: BaseTest {
private let containterView = UIView()
private var view1: UIView!
private var view2: UIView!
private var view3: UIView!
override func setUp() {
super.setUp()
view1 = UIView()
view2 = UIView()
view3 = UIView()
containterView.addSubview(view1)
containterView.addSubview(view2)
containterView.addSubview(view3)
}
override func tearDown() {
containterView.frame = .zero
view1.removeFromSuperview()
view2.removeFromSuperview()
view3.removeFromSuperview()
super.tearDown()
}
/* horizontal */
func testThatCorrectlyConfigures_horizontal_stack_withoutSpacing() {
containterView.frame = CGRect(x: 0, y: 0, width: 90, height: 200)
[view1, view2, view3].stack(axis: .horizontal)
XCTAssertEqual(view1.frame, CGRect(x: 0, y: 0, width: 30, height: 200))
XCTAssertEqual(view2.frame, CGRect(x: 30, y: 0, width: 30, height: 200))
XCTAssertEqual(view3.frame, CGRect(x: 60, y: 0, width: 30, height: 200))
}
func testThatCorrectlyConfigures_horizontal_stack_withSpacing() {
containterView.frame = CGRect(x: 0, y: 0, width: 96, height: 200)
[view1, view2, view3].stack(axis: .horizontal, spacing: 3)
XCTAssertEqual(view1.frame, CGRect(x: 0, y: 0, width: 30, height: 200))
XCTAssertEqual(view2.frame, CGRect(x: 33, y: 0, width: 30, height: 200))
XCTAssertEqual(view3.frame, CGRect(x: 66, y: 0, width: 30, height: 200))
}
/* vertical */
func testThatCorrectlyConfigures_vertical_stack_withoutSpacing() {
containterView.frame = CGRect(x: 0, y: 0, width: 200, height: 90)
[view1, view2, view3].stack(axis: .vertical)
XCTAssertEqual(view1.frame, CGRect(x: 0, y: 0, width: 200, height: 30))
XCTAssertEqual(view2.frame, CGRect(x: 0, y: 30, width: 200, height: 30))
XCTAssertEqual(view3.frame, CGRect(x: 0, y: 60, width: 200, height: 30))
}
func testThatCorrectlyConfigures_vertical_stack_withSpacing() {
containterView.frame = CGRect(x: 0, y: 0, width: 200, height: 96)
[view1, view2, view3].stack(axis: .vertical, spacing: 3)
XCTAssertEqual(view1.frame, CGRect(x: 0, y: 0, width: 200, height: 30))
XCTAssertEqual(view2.frame, CGRect(x: 0, y: 33, width: 200, height: 30))
XCTAssertEqual(view3.frame, CGRect(x: 0, y: 66, width: 200, height: 30))
}
/* state */
func testThatCorrectlyConfiguresStackForOtherStates() {
containterView.frame = CGRect(x: 0, y: 0, width: 90, height: 200)
containterView.nx_state = "STATE"
configuresFrames()
XCTAssertEqual(view1.frame, CGRect(x: 0, y: 0, width: 30, height: 200))
XCTAssertEqual(view2.frame, CGRect(x: 30, y: 0, width: 30, height: 200))
XCTAssertEqual(view3.frame, CGRect(x: 60, y: 0, width: 30, height: 200))
containterView.frame = CGRect(x: 0, y: 0, width: 200, height: 90)
containterView.nx_state = DEFAULT_STATE
configuresFrames()
XCTAssertEqual(view1.frame, CGRect(x: 0, y: 0, width: 200, height: 30))
XCTAssertEqual(view2.frame, CGRect(x: 0, y: 30, width: 200, height: 30))
XCTAssertEqual(view3.frame, CGRect(x: 0, y: 60, width: 200, height: 30))
}
private func configuresFrames() {
view1.frame = .zero
view2.frame = .zero
view3.frame = .zero
[view1, view2, view3].stack(axis: .vertical)
[view1, view2, view3].stack(axis: .horizontal, state: "STATE")
}
}
| mit | 2432380e6f4fc64a451f9e39b39f9207 | 31.598361 | 80 | 0.594669 | 3.751887 | false | true | false | false |
justindarc/firefox-ios | Client/Frontend/Settings/CustomSearchViewController.swift | 1 | 10035 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import SnapKit
import Storage
import SDWebImage
private let log = Logger.browserLogger
class CustomSearchError: MaybeErrorType {
enum Reason {
case DuplicateEngine, FormInput
}
var reason: Reason!
internal var description: String {
return "Search Engine Not Added"
}
init(_ reason: Reason) {
self.reason = reason
}
}
class CustomSearchViewController: SettingsTableViewController {
fileprivate var urlString: String?
fileprivate var engineTitle = ""
fileprivate lazy var spinnerView: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView(style: .gray)
spinner.hidesWhenStopped = true
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsAddCustomEngineTitle
view.addSubview(spinnerView)
spinnerView.snp.makeConstraints { make in
make.center.equalTo(self.view.snp.center)
}
}
var successCallback: (() -> Void)?
fileprivate func addSearchEngine(_ searchQuery: String, title: String) {
spinnerView.startAnimating()
let trimmedQuery = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
createEngine(forQuery: trimmedQuery, andName: trimmedTitle).uponQueue(.main) { result in
self.spinnerView.stopAnimating()
guard let engine = result.successValue else {
let alert: UIAlertController
let error = result.failureValue as? CustomSearchError
alert = (error?.reason == .DuplicateEngine) ?
ThirdPartySearchAlerts.duplicateCustomEngine() : ThirdPartySearchAlerts.incorrectCustomEngineForm()
self.navigationItem.rightBarButtonItem?.isEnabled = true
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(engine)
CATransaction.begin() // Use transaction to call callback after animation has been completed
CATransaction.setCompletionBlock(self.successCallback)
_ = self.navigationController?.popViewController(animated: true)
CATransaction.commit()
}
}
func createEngine(forQuery query: String, andName name: String) -> Deferred<Maybe<OpenSearchEngine>> {
let deferred = Deferred<Maybe<OpenSearchEngine>>()
guard let template = getSearchTemplate(withString: query),
let url = URL(string: template.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!), url.isWebPage() else {
deferred.fill(Maybe(failure: CustomSearchError(.FormInput)))
return deferred
}
// ensure we haven't already stored this template
guard engineExists(name: name, template: template) == false else {
deferred.fill(Maybe(failure: CustomSearchError(.DuplicateEngine)))
return deferred
}
FaviconFetcher.fetchFavImageForURL(forURL: url, profile: profile).uponQueue(.main) { result in
let image = result.successValue ?? FaviconFetcher.getDefaultFavicon(url)
let engine = OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)
//Make sure a valid scheme is used
let url = engine.searchURLForQuery("test")
let maybe = (url == nil) ? Maybe(failure: CustomSearchError(.FormInput)) : Maybe(success: engine)
deferred.fill(maybe)
}
return deferred
}
private func engineExists(name: String, template: String) -> Bool {
return profile.searchEngines.orderedEngines.contains { (engine) -> Bool in
return engine.shortName == name || engine.searchTemplate == template
}
}
func getSearchTemplate(withString query: String) -> String? {
let SearchTermComponent = "%s" //Placeholder in User Entered String
let placeholder = "{searchTerms}" //Placeholder looked for when using Custom Search Engine in OpenSearch.swift
if query.contains(SearchTermComponent) {
return query.replacingOccurrences(of: SearchTermComponent, with: placeholder)
}
return nil
}
override func generateSettings() -> [SettingSection] {
func URLFromString(_ string: String?) -> URL? {
guard let string = string else {
return nil
}
return URL(string: string)
}
let titleField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineTitlePlaceholder, settingIsValid: { text in
return text != nil && text != ""
}, settingDidChange: {fieldText in
guard let title = fieldText else {
return
}
self.engineTitle = title
})
titleField.textField.accessibilityIdentifier = "customEngineTitle"
let urlField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineURLPlaceholder, height: 133, settingIsValid: { text in
//Can check url text text validity here.
return true
}, settingDidChange: {fieldText in
self.urlString = fieldText
})
urlField.textField.autocapitalizationType = .none
urlField.textField.accessibilityIdentifier = "customEngineUrl"
let settings: [SettingSection] = [
SettingSection(title: NSAttributedString(string: Strings.SettingsAddCustomEngineTitleLabel), children: [titleField]),
SettingSection(title: NSAttributedString(string: Strings.SettingsAddCustomEngineURLLabel), footerTitle: NSAttributedString(string: "http://youtube.com/search?q=%s"), children: [urlField])
]
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.addCustomSearchEngine))
self.navigationItem.rightBarButtonItem?.accessibilityIdentifier = "customEngineSaveButton"
return settings
}
@objc func addCustomSearchEngine(_ nav: UINavigationController?) {
self.view.endEditing(true)
navigationItem.rightBarButtonItem?.isEnabled = false
if let url = self.urlString {
self.addSearchEngine(url, title: self.engineTitle)
}
}
}
class CustomSearchEngineTextView: Setting, UITextViewDelegate {
fileprivate let Padding: CGFloat = 8
fileprivate let TextLabelHeight: CGFloat = 44
fileprivate var TextFieldHeight: CGFloat = 44
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
let textField = UITextView()
let placeholderLabel = UILabel()
init(defaultValue: String? = nil, placeholder: String, height: CGFloat = 44, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.TextFieldHeight = height
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
textField.addSubview(placeholderLabel)
super.init(cellHeight: TextFieldHeight)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
placeholderLabel.adjustsFontSizeToFitWidth = true
placeholderLabel.textColor = UIColor.theme.general.settingsTextPlaceholder ?? UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
placeholderLabel.text = placeholder
placeholderLabel.frame = CGRect(width: textField.frame.width, height: TextLabelHeight)
textField.font = placeholderLabel.font
textField.textContainer.lineFragmentPadding = 0
textField.keyboardType = .URL
textField.autocorrectionType = .no
textField.delegate = self
textField.backgroundColor = UIColor.theme.tableView.rowBackground
textField.textColor = UIColor.theme.tableView.rowText
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraits.none
cell.contentView.addSubview(textField)
cell.selectionStyle = .none
textField.snp.makeConstraints { make in
make.height.equalTo(TextFieldHeight)
make.left.right.equalTo(cell.contentView).inset(Padding)
}
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
func prepareValidValue(userInput value: String?) -> String? {
return value
}
func textViewDidBeginEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
}
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
let color = isValid(textField.text) ? UIColor.theme.tableView.rowText : UIColor.theme.general.destructiveRed
textField.textColor = color
}
func textViewDidEndEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
}
}
| mpl-2.0 | a6e0629f7edcee3e29f758c6d8d2141e | 38.664032 | 199 | 0.673244 | 5.386473 | false | false | false | false |
ManuelAurora/RxQuickbooksService | Example/Pods/OAuthSwift/Sources/OAuth2Swift.swift | 2 | 15306 | //
// OAuth2Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
open class OAuth2Swift: OAuthSwift {
// If your oauth provider need to use basic authentification
// set value to true (default: false)
open var accessTokenBasicAuthentification = false
// Set to true to deactivate state check. Be careful of CSRF
open var allowMissingStateCheck: Bool = false
// Encode callback url. Default false
// issue #339, pr ##325
open var encodeCallbackURL: Bool = false
var consumerKey: String
var consumerSecret: String
var authorizeUrl: String
var accessTokenUrl: String?
var responseType: String
var contentType: String?
// MARK: init
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.accessTokenUrl = accessTokenUrl
}
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String, contentType: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.accessTokenUrl = accessTokenUrl
self.contentType = contentType
}
public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.authorizeUrl = authorizeUrl
self.responseType = responseType
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .oauth2
}
public convenience init?(parameters: ConfigParameters) {
guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"],
let responseType = parameters["responseType"], let authorizeUrl = parameters["authorizeUrl"] else {
return nil
}
if let accessTokenUrl = parameters["accessTokenUrl"] {
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl, responseType: responseType)
} else {
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, responseType: responseType)
}
}
open var parameters: ConfigParameters {
return [
"consumerKey": consumerKey,
"consumerSecret": consumerSecret,
"authorizeUrl": authorizeUrl,
"accessTokenUrl": accessTokenUrl ?? "",
"responseType": responseType
]
}
// MARK: functions
@discardableResult
open func authorize(withCallbackURL callbackURL: URL, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
self.observeCallback { [weak self] url in
guard let this = self else { OAuthSwift.retainError(failure); return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString
}
if let fragment = url.fragment, !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString
}
if let accessToken = responseParameters["access_token"] {
this.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding
if let expiresIn: String = responseParameters["expires_in"], let offset = Double(expiresIn) {
this.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date())
}
success(this.client.credential, nil, responseParameters)
} else if let code = responseParameters["code"] {
if !this.allowMissingStateCheck {
guard let responseState = responseParameters["state"] else {
failure?(OAuthSwiftError.missingState)
return
}
if responseState != state {
failure?(OAuthSwiftError.stateNotEqual(state: state, responseState: responseState))
return
}
}
if let handle = this.postOAuthAccessTokenWithRequestToken(
byCode: code.safeStringByRemovingPercentEncoding,
callbackURL: callbackURL, headers: headers, success: success, failure: failure) {
this.putHandle(handle, withKey: UUID().uuidString)
}
} else if let error = responseParameters["error"] {
let description = responseParameters["error_description"] ?? ""
let message = NSLocalizedString(error, comment: description)
failure?(OAuthSwiftError.serverError(message: message))
} else {
let message = "No access_token, no code and no error provided by server"
failure?(OAuthSwiftError.serverError(message: message))
}
}
var queryString = "client_id=\(self.consumerKey)"
if encodeCallbackURL {
queryString += "&redirect_uri=\(callbackURL.absoluteString.urlEncodedString)"
} else {
queryString += "&redirect_uri=\(callbackURL.absoluteString)"
}
queryString += "&response_type=\(self.responseType)"
if !scope.isEmpty {
queryString += "&scope=\(scope)"
}
if !state.isEmpty {
queryString += "&state=\(state)"
}
for param in parameters {
queryString += "&\(param.0)=\(param.1)"
}
var urlString = self.authorizeUrl
urlString += (self.authorizeUrl.contains("?") ? "&" : "?")
if let encodedQuery = queryString.urlQueryEncoded, let queryURL = URL(string: urlString + encodedQuery) {
self.authorizeURLHandler.handle(queryURL)
return self
} else {
self.cancel() // ie. remove the observer.
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
}
@discardableResult
open func authorize(withCallbackURL urlString: String, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
guard let url = URL(string: urlString) else {
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
return authorize(withCallbackURL: url, scope: scope, state: state, parameters: parameters, headers: headers, success: success, failure: failure)
}
func postOAuthAccessTokenWithRequestToken(byCode code: String, callbackURL: URL, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["code"] = code
parameters["grant_type"] = "authorization_code"
parameters["redirect_uri"] = callbackURL.absoluteString.safeStringByRemovingPercentEncoding
return requestOAuthAccessToken(withParameters: parameters, headers: headers, success: success, failure: failure)
}
@discardableResult
open func renewAccessToken(withRefreshToken refreshToken: String, parameters: OAuthSwift.Parameters? = nil, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
var parameters = parameters ?? OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["refresh_token"] = refreshToken
parameters["grant_type"] = "refresh_token"
return requestOAuthAccessToken(withParameters: parameters, headers: headers, success: success, failure: failure)
}
fileprivate func requestOAuthAccessToken(withParameters parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
let successHandler: OAuthSwiftHTTPRequest.SuccessHandler = { [unowned self]
response in
let responseJSON: Any? = try? response.jsonObject(options: .mutableContainers)
let responseParameters: OAuthSwift.Parameters
if let jsonDico = responseJSON as? [String:Any] {
responseParameters = jsonDico
} else {
responseParameters = response.string?.parametersFromQueryString ?? [:]
}
guard let accessToken = responseParameters["access_token"] as? String else {
let message = NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")
failure?(OAuthSwiftError.serverError(message: message))
return
}
if let refreshToken = responseParameters["refresh_token"] as? String {
self.client.credential.oauthRefreshToken = refreshToken.safeStringByRemovingPercentEncoding
}
if let expiresIn = responseParameters["expires_in"] as? String, let offset = Double(expiresIn) {
self.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date())
} else if let expiresIn = responseParameters["expires_in"] as? Double {
self.client.credential.oauthTokenExpiresAt = Date(timeInterval: expiresIn, since: Date())
}
self.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding
success(self.client.credential, response, responseParameters)
}
guard let accessTokenUrl = accessTokenUrl else {
let message = NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth")
failure?(OAuthSwiftError.configurationError(message: message))
return nil
}
if self.contentType == "multipart/form-data" {
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
return self.client.postMultiPartRequest(accessTokenUrl, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, success: successHandler, failure: failure)
} else {
// special headers
var finalHeaders: OAuthSwift.Headers? = nil
if accessTokenBasicAuthentification {
let authentification = "\(self.consumerKey):\(self.consumerSecret)".data(using: String.Encoding.utf8)
if let base64Encoded = authentification?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
finalHeaders += ["Authorization": "Basic \(base64Encoded)"] as OAuthSwift.Headers
}
}
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
return self.client.request(accessTokenUrl, method: .POST, parameters: parameters, headers: finalHeaders, checkTokenExpiration: false, success: successHandler, failure: failure)
}
}
/**
Convenience method to start a request that must be authorized with the previously retrieved access token.
Since OAuth 2 requires support for the access token refresh mechanism, this method will take care to automatically
refresh the token if needed such that the developer only has to be concerned about the outcome of the request.
- parameter url: The url for the request.
- parameter method: The HTTP method to use.
- parameter parameters: The request's parameters.
- parameter headers: The request's headers.
- parameter onTokenRenewal: Optional callback triggered in case the access token renewal was required in order to properly authorize the request.
- parameter success: The success block. Takes the successfull response and data as parameter.
- parameter failure: The failure block. Takes the error as parameter.
*/
@discardableResult
open func startAuthorizedRequest(_ url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, onTokenRenewal: TokenRenewedHandler? = nil, success: @escaping OAuthSwiftHTTPRequest.SuccessHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? {
// build request
return self.client.request(url, method: method, parameters: parameters, headers: headers, success: success) { (error) in
switch error {
case OAuthSwiftError.tokenExpired:
_ = self.renewAccessToken(withRefreshToken: self.client.credential.oauthRefreshToken, headers: headers, success: { (credential, _, _) in // Ommit response parameters so they don't override the original ones
// We have successfully renewed the access token.
// If provided, fire the onRenewal closure
if let renewalCallBack = onTokenRenewal {
renewalCallBack(credential)
}
// Reauthorize the request again, this time with a brand new access token ready to be used.
_ = self.startAuthorizedRequest(url, method: method, parameters: parameters, headers: headers, onTokenRenewal: onTokenRenewal, success: success, failure: failure)
}, failure: failure)
default:
failure(error)
}
}
}
@discardableResult
open func authorize(deviceToken deviceCode: String, grantType: String = "http://oauth.net/grant_type/device/1.0", success: @escaping TokenRenewedHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["code"] = deviceCode
parameters["grant_type"] = grantType
return requestOAuthAccessToken(
withParameters: parameters,
success: { (credential, _, _) in
success(credential)
}, failure: failure
)
}
}
| mit | e8f8e786ea3c1f846efce2a082f9ea98 | 51.417808 | 348 | 0.660003 | 5.563795 | false | false | false | false |
samwyndham/DictateSRS | Pods/CSV.swift/Sources/CSV.swift | 1 | 8654 | //
// CSV.swift
// CSV
//
// Created by Yasuhiro Hatta on 2016/06/11.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
private let LF = UnicodeScalar("\n")!
private let CR = UnicodeScalar("\r")!
private let DQUOTE = UnicodeScalar("\"")!
internal let defaultHasHeaderRow = false
internal let defaultTrimFields = false
internal let defaultDelimiter = UnicodeScalar(",")!
extension CSV: Sequence { }
extension CSV: IteratorProtocol {
// TODO: Documentation
/// No overview available.
public mutating func next() -> [String]? {
return readRow()
}
}
// TODO: Documentation
/// No overview available.
public struct CSV {
private var iterator: AnyIterator<UnicodeScalar>
private let trimFields: Bool
private let delimiter: UnicodeScalar
private var back: UnicodeScalar? = nil
internal var currentRow: [String]? = nil
/// CSV header row. To set a value for this property, you set `true` to `hasHeaerRow` in initializer.
public var headerRow: [String]? { return _headerRow }
private var _headerRow: [String]? = nil
private let whitespaces: CharacterSet
internal init<T: IteratorProtocol>(
iterator: T,
hasHeaderRow: Bool,
trimFields: Bool,
delimiter: UnicodeScalar)
throws
where T.Element == UnicodeScalar
{
self.iterator = AnyIterator(iterator)
self.trimFields = trimFields
self.delimiter = delimiter
var whitespaces = CharacterSet.whitespaces
whitespaces.remove(delimiter)
self.whitespaces = whitespaces
if hasHeaderRow {
guard let headerRow = next() else {
throw CSVError.cannotReadHeaderRow
}
_headerRow = headerRow
}
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
where T.CodeUnit == UInt8
{
let reader = try BinaryReader(stream: stream, endian: .unknown, closeOnDeinit: true)
let iterator = UnicodeIterator(input: reader.makeUInt8Iterator(), inputEncodingType: codecType)
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter endian: Endian to use when reading a stream. Default: `.big`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
endian: Endian = .big,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
where T.CodeUnit == UInt16
{
let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true)
let iterator = UnicodeIterator(input: reader.makeUInt16Iterator(), inputEncodingType: codecType)
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open, initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter endian: Endian to use when reading a stream. Default: `.big`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
endian: Endian = .big,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
where T.CodeUnit == UInt32
{
let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true)
let iterator = UnicodeIterator(input: reader.makeUInt32Iterator(), inputEncodingType: codecType)
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
fileprivate mutating func readRow() -> [String]? {
currentRow = nil
var next = moveNext()
if next == nil {
return nil
}
var row = [String]()
var field: String
var end: Bool
while true {
if trimFields {
// Trim the leading spaces
while next != nil && whitespaces.contains(next!) {
next = moveNext()
}
}
if next == nil {
(field, end) = ("", true)
}
else if next == DQUOTE {
(field, end) = readField(quoted: true)
}
else {
back = next
(field, end) = readField(quoted: false)
if trimFields {
// Trim the trailing spaces
field = field.trimmingCharacters(in: whitespaces)
}
}
row.append(field)
if end {
break
}
next = moveNext()
}
currentRow = row
return row
}
private mutating func readField(quoted: Bool) -> (String, Bool) {
var field = ""
var next = moveNext()
while let c = next {
if quoted {
if c == DQUOTE {
var cNext = moveNext()
if trimFields {
// Trim the trailing spaces
while cNext != nil && whitespaces.contains(cNext!) {
cNext = moveNext()
}
}
if cNext == nil || cNext == CR || cNext == LF {
if cNext == CR {
let cNextNext = moveNext()
if cNextNext != LF {
back = cNextNext
}
}
// END ROW
return (field, true)
}
else if cNext == delimiter {
// END FIELD
return (field, false)
}
else if cNext == DQUOTE {
// ESC
field.append(String(DQUOTE))
}
else {
// ERROR?
field.append(String(c))
}
}
else {
field.append(String(c))
}
}
else {
if c == CR || c == LF {
if c == CR {
let cNext = moveNext()
if cNext != LF {
back = cNext
}
}
// END ROW
return (field, true)
}
else if c == delimiter {
// END FIELD
return (field, false)
}
else {
field.append(String(c))
}
}
next = moveNext()
}
// END FILE
return (field, true)
}
private mutating func moveNext() -> UnicodeScalar? {
if back != nil {
defer { back = nil }
return back
}
return iterator.next()
}
}
| mit | 89ef881fff7dde6bd3e5fc7100d45449 | 32.280769 | 115 | 0.515775 | 5.381219 | false | false | false | false |
sweetkk/SWMusic | SWMusic/Pods/ReactiveCocoa/ReactiveCocoa/NSObject+Intercepting.swift | 6 | 15074 | import Foundation
import ReactiveSwift
import enum Result.NoError
/// Whether the runtime subclass has already been prepared for method
/// interception.
fileprivate let interceptedKey = AssociationKey(default: false)
/// Holds the method signature cache of the runtime subclass.
fileprivate let signatureCacheKey = AssociationKey<SignatureCache>()
/// Holds the method selector cache of the runtime subclass.
fileprivate let selectorCacheKey = AssociationKey<SelectorCache>()
extension Reactive where Base: NSObject {
/// Create a signal which sends a `next` event at the end of every invocation
/// of `selector` on the object.
///
/// It completes when the object deinitializes.
///
/// - note: Observers to the resulting signal should not call the method
/// specified by the selector.
///
/// - parameters:
/// - selector: The selector to observe.
///
/// - returns:
/// A trigger signal.
public func trigger(for selector: Selector) -> Signal<(), NoError> {
return base.intercept(selector).map { _ in }
}
/// Create a signal which sends a `next` event, containing an array of bridged
/// arguments, at the end of every invocation of `selector` on the object.
///
/// It completes when the object deinitializes.
///
/// - note: Observers to the resulting signal should not call the method
/// specified by the selector.
///
/// - parameters:
/// - selector: The selector to observe.
///
/// - returns:
/// A signal that sends an array of bridged arguments.
public func signal(for selector: Selector) -> Signal<[Any?], NoError> {
return base.intercept(selector).map(unpackInvocation)
}
}
extension NSObject {
/// Setup the method interception.
///
/// - parameters:
/// - object: The object to be intercepted.
/// - selector: The selector of the method to be intercepted.
///
/// - returns:
/// A signal that sends the corresponding `NSInvocation` after every
/// invocation of the method.
@nonobjc fileprivate func intercept(_ selector: Selector) -> Signal<AnyObject, NoError> {
guard let method = class_getInstanceMethod(objcClass, selector) else {
fatalError("Selector `\(selector)` does not exist in class `\(String(describing: objcClass))`.")
}
let typeEncoding = method_getTypeEncoding(method)!
assert(checkTypeEncoding(typeEncoding))
return synchronized {
let alias = selector.alias
let stateKey = AssociationKey<InterceptingState?>(alias)
let interopAlias = selector.interopAlias
if let state = associations.value(forKey: stateKey) {
return state.signal
}
let subclass: AnyClass = swizzleClass(self)
let subclassAssociations = Associations(subclass as AnyObject)
// FIXME: Compiler asks to handle a mysterious throw.
try! ReactiveCocoa.synchronized(subclass) {
let isSwizzled = subclassAssociations.value(forKey: interceptedKey)
let signatureCache: SignatureCache
let selectorCache: SelectorCache
if isSwizzled {
signatureCache = subclassAssociations.value(forKey: signatureCacheKey)
selectorCache = subclassAssociations.value(forKey: selectorCacheKey)
} else {
signatureCache = SignatureCache()
selectorCache = SelectorCache()
subclassAssociations.setValue(signatureCache, forKey: signatureCacheKey)
subclassAssociations.setValue(selectorCache, forKey: selectorCacheKey)
subclassAssociations.setValue(true, forKey: interceptedKey)
enableMessageForwarding(subclass, selectorCache)
setupMethodSignatureCaching(subclass, signatureCache)
}
selectorCache.cache(selector)
if signatureCache[selector] == nil {
let signature = NSMethodSignature.signature(withObjCTypes: typeEncoding)
signatureCache[selector] = signature
}
// If an immediate implementation of the selector is found in the
// runtime subclass the first time the selector is intercepted,
// preserve the implementation.
//
// Example: KVO setters if the instance is swizzled by KVO before RAC
// does.
if !class_respondsToSelector(subclass, interopAlias) {
let immediateImpl = class_getImmediateMethod(subclass, selector)
.flatMap(method_getImplementation)
.flatMap { $0 != _rac_objc_msgForward ? $0 : nil }
if let impl = immediateImpl {
class_addMethod(subclass, interopAlias, impl, typeEncoding)
}
}
}
let state = InterceptingState(lifetime: reactive.lifetime)
associations.setValue(state, forKey: stateKey)
// Start forwarding the messages of the selector.
_ = class_replaceMethod(subclass, selector, _rac_objc_msgForward, typeEncoding)
return state.signal
}
}
}
/// Swizzle `realClass` to enable message forwarding for method interception.
///
/// - parameters:
/// - realClass: The runtime subclass to be swizzled.
private func enableMessageForwarding(_ realClass: AnyClass, _ selectorCache: SelectorCache) {
let perceivedClass: AnyClass = class_getSuperclass(realClass)
typealias ForwardInvocationImpl = @convention(block) (Unmanaged<NSObject>, AnyObject) -> Void
let newForwardInvocation: ForwardInvocationImpl = { objectRef, invocation in
let selector = invocation.selector!
let alias = selectorCache.alias(for: selector)
let interopAlias = selectorCache.interopAlias(for: selector)
defer {
let stateKey = AssociationKey<InterceptingState?>(alias)
if let state = objectRef.takeUnretainedValue().associations.value(forKey: stateKey) {
state.observer.send(value: invocation)
}
}
let method = class_getInstanceMethod(perceivedClass, selector)!
let typeEncoding = method_getTypeEncoding(method)
if class_respondsToSelector(realClass, interopAlias) {
// RAC has preserved an immediate implementation found in the runtime
// subclass that was supplied by an external party.
//
// As the KVO setter relies on the selector to work, it has to be invoked
// by swapping in the preserved implementation and restore to the message
// forwarder afterwards.
//
// However, the IMP cache would be thrashed due to the swapping.
let interopImpl = class_getMethodImplementation(realClass, interopAlias)
let previousImpl = class_replaceMethod(realClass, selector, interopImpl, typeEncoding)
invocation.invoke()
_ = class_replaceMethod(realClass, selector, previousImpl, typeEncoding)
return
}
if let impl = method_getImplementation(method), impl != _rac_objc_msgForward {
// The perceived class, or its ancestors, responds to the selector.
//
// The implementation is invoked through the selector alias, which
// reflects the latest implementation of the selector in the perceived
// class.
if class_getMethodImplementation(realClass, alias) != impl {
// Update the alias if and only if the implementation has changed, so as
// to avoid thrashing the IMP cache.
_ = class_replaceMethod(realClass, alias, impl, typeEncoding)
}
invocation.setSelector(alias)
invocation.invoke()
return
}
// Forward the invocation to the closest `forwardInvocation(_:)` in the
// inheritance hierarchy, or the default handler returned by the runtime
// if it finds no implementation.
typealias SuperForwardInvocation = @convention(c) (Unmanaged<NSObject>, Selector, AnyObject) -> Void
let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.forwardInvocation)
let forwardInvocation = unsafeBitCast(impl, to: SuperForwardInvocation.self)
forwardInvocation(objectRef, ObjCSelector.forwardInvocation, invocation)
}
_ = class_replaceMethod(realClass,
ObjCSelector.forwardInvocation,
imp_implementationWithBlock(newForwardInvocation as Any),
ObjCMethodEncoding.forwardInvocation)
}
/// Swizzle `realClass` to accelerate the method signature retrieval, using a
/// signature cache that covers all known intercepted selectors of `realClass`.
///
/// - parameters:
/// - realClass: The runtime subclass to be swizzled.
/// - signatureCache: The method signature cache.
private func setupMethodSignatureCaching(_ realClass: AnyClass, _ signatureCache: SignatureCache) {
let perceivedClass: AnyClass = class_getSuperclass(realClass)
let newMethodSignatureForSelector: @convention(block) (Unmanaged<NSObject>, Selector) -> AnyObject? = { objectRef, selector in
if let signature = signatureCache[selector] {
return signature
}
typealias SuperMethodSignatureForSelector = @convention(c) (Unmanaged<NSObject>, Selector, Selector) -> AnyObject?
let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.methodSignatureForSelector)
let methodSignatureForSelector = unsafeBitCast(impl, to: SuperMethodSignatureForSelector.self)
return methodSignatureForSelector(objectRef, ObjCSelector.methodSignatureForSelector, selector)
}
_ = class_replaceMethod(realClass,
ObjCSelector.methodSignatureForSelector,
imp_implementationWithBlock(newMethodSignatureForSelector as Any),
ObjCMethodEncoding.methodSignatureForSelector)
}
/// The state of an intercepted method specific to an instance.
private final class InterceptingState {
let (signal, observer) = Signal<AnyObject, NoError>.pipe()
/// Initialize a state specific to an instance.
///
/// - parameters:
/// - lifetime: The lifetime of the instance.
init(lifetime: Lifetime) {
lifetime.ended.observeCompleted(observer.sendCompleted)
}
}
private final class SelectorCache {
private var map: [Selector: (main: Selector, interop: Selector)] = [:]
init() {}
/// Cache the aliases of the specified selector in the cache.
///
/// - warning: Any invocation of this method must be synchronized against the
/// runtime subclass.
@discardableResult
func cache(_ selector: Selector) -> (main: Selector, interop: Selector) {
if let pair = map[selector] {
return pair
}
let aliases = (selector.alias, selector.interopAlias)
map[selector] = aliases
return aliases
}
/// Get the alias of the specified selector.
///
/// - parameters:
/// - selector: The selector alias.
func alias(for selector: Selector) -> Selector {
if let (main, _) = map[selector] {
return main
}
return selector.alias
}
/// Get the secondary alias of the specified selector.
///
/// - parameters:
/// - selector: The selector alias.
func interopAlias(for selector: Selector) -> Selector {
if let (_, interop) = map[selector] {
return interop
}
return selector.interopAlias
}
}
// The signature cache for classes that have been swizzled for method
// interception.
//
// Read-copy-update is used here, since the cache has multiple readers but only
// one writer.
private final class SignatureCache {
// `Dictionary` takes 8 bytes for the reference to its storage and does CoW.
// So it should not encounter any corrupted, partially updated state.
private var map: [Selector: AnyObject] = [:]
init() {}
/// Get or set the signature for the specified selector.
///
/// - warning: Any invocation of the setter must be synchronized against the
/// runtime subclass.
///
/// - parameters:
/// - selector: The method signature.
subscript(selector: Selector) -> AnyObject? {
get {
return map[selector]
}
set {
if map[selector] == nil {
map[selector] = newValue
}
}
}
}
/// Assert that the method does not contain types that cannot be intercepted.
///
/// - parameters:
/// - types: The type encoding C string of the method.
///
/// - returns:
/// `true`.
private func checkTypeEncoding(_ types: UnsafePointer<CChar>) -> Bool {
// Some types, including vector types, are not encoded. In these cases the
// signature starts with the size of the argument frame.
assert(types.pointee < Int8(UInt8(ascii: "1")) || types.pointee > Int8(UInt8(ascii: "9")),
"unknown method return type not supported in type encoding: \(String(cString: types))")
assert(types.pointee != Int8(UInt8(ascii: "(")), "union method return type not supported")
assert(types.pointee != Int8(UInt8(ascii: "{")), "struct method return type not supported")
assert(types.pointee != Int8(UInt8(ascii: "[")), "array method return type not supported")
assert(types.pointee != Int8(UInt8(ascii: "j")), "complex method return type not supported")
return true
}
/// Extract the arguments of an `NSInvocation` as an array of objects.
///
/// - parameters:
/// - invocation: The `NSInvocation` to unpack.
///
/// - returns:
/// An array of objects.
private func unpackInvocation(_ invocation: AnyObject) -> [Any?] {
let invocation = invocation as AnyObject
let methodSignature = invocation.objcMethodSignature!
let count = UInt(methodSignature.numberOfArguments!)
var bridged = [Any?]()
bridged.reserveCapacity(Int(count - 2))
// Ignore `self` and `_cmd` at index 0 and 1.
for position in 2 ..< count {
let rawEncoding = methodSignature.argumentType(at: position)
let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined
func extract<U>(_ type: U.Type) -> U {
let pointer = UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<U>.size,
alignedTo: MemoryLayout<U>.alignment)
defer {
pointer.deallocate(bytes: MemoryLayout<U>.size,
alignedTo: MemoryLayout<U>.alignment)
}
invocation.copy(to: pointer, forArgumentAt: Int(position))
return pointer.assumingMemoryBound(to: type).pointee
}
let value: Any?
switch encoding {
case .char:
value = NSNumber(value: extract(CChar.self))
case .int:
value = NSNumber(value: extract(CInt.self))
case .short:
value = NSNumber(value: extract(CShort.self))
case .long:
value = NSNumber(value: extract(CLong.self))
case .longLong:
value = NSNumber(value: extract(CLongLong.self))
case .unsignedChar:
value = NSNumber(value: extract(CUnsignedChar.self))
case .unsignedInt:
value = NSNumber(value: extract(CUnsignedInt.self))
case .unsignedShort:
value = NSNumber(value: extract(CUnsignedShort.self))
case .unsignedLong:
value = NSNumber(value: extract(CUnsignedLong.self))
case .unsignedLongLong:
value = NSNumber(value: extract(CUnsignedLongLong.self))
case .float:
value = NSNumber(value: extract(CFloat.self))
case .double:
value = NSNumber(value: extract(CDouble.self))
case .bool:
value = NSNumber(value: extract(CBool.self))
case .object:
value = extract((AnyObject?).self)
case .type:
value = extract((AnyClass?).self)
case .selector:
value = extract((Selector?).self)
case .undefined:
var size = 0, alignment = 0
NSGetSizeAndAlignment(rawEncoding, &size, &alignment)
let buffer = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: alignment)
defer { buffer.deallocate(bytes: size, alignedTo: alignment) }
invocation.copy(to: buffer, forArgumentAt: Int(position))
value = NSValue(bytes: buffer, objCType: rawEncoding)
}
bridged.append(value)
}
return bridged
}
| mit | 2329b55b1f1bb012f691d21d83182e3f | 33.893519 | 127 | 0.71421 | 4.233081 | false | false | false | false |
BruceFight/JHB_HUDView | JHB_HUDView/JHB_HUDDiyProgressView.swift | 1 | 10899 | /****************** JHB_HUDDiyProgressView.swift ****************/
/******* (JHB) ************************************************/
/******* Created by Leon_pan on 16/6/15. ***********************/
/******* Copyright © 2016年 CoderBala. All rights reserved.*****/
/****************** JHB_HUDDiyProgressView.swift ****************/
import UIKit
class JHB_HUDDiyProgressView: UIView {
// MARK: - Params
/*自定义图片*//*DiyImageView*/
var diyImageView = UIImageView()
/*预备自定义图片*//*DiySpareImageView*/
var diySpareImageView = UIImageView()
/*自定义信息标签*//*DiyMsgLabel*/
var diyMsgLabel = UILabel()
/*用于展示图片*//*TheImageNeededToShow*/
var diyShowImage = NSString()
/*图片展示类型*//*TheTypeOfImageShow*/
var diyHudType = NSInteger()
/*判断是否使用预备ImageView*//*TheJudgementOfUsingSpareImageView*/
var ifChangeImgView = Bool()
/*动画速度*//*TheSpeedOfAnimation*/
var diySpeed = CFTimeInterval()
/*实现动画的图片个数*//*TheNumberOfImagesThatWithAnimation-Type*/
var diyImgsNumber = NSInteger()
/*信息标签长度*//*TheLengthOfMessageLabel*/
var diyMsgLabelWidth = CGFloat()
/*信息标签高度*//*TheHeightOfMessageLabel*/
var diyMsgLabelHeight = CGFloat()
/*两边的间隔*//*TheMarginOfLeftAndRight*/
var kMargin : CGFloat = 10
/*两边的间隔*//*TheMarginOfLeftAndRight*/
var kContent = NSString.init()
// MARK: - Interface
override init(frame: CGRect) {
super.init(frame: frame)
ifChangeImgView = false
diyImgsNumber = 0
self.setSubViews()
NotificationCenter.default.addObserver(self, selector: #selector(JHB_HUDDiyProgressView.resetSubViewsForJHB_DIYHUD_haveNoMsg), name: NSNotification.Name(rawValue: "JHB_DIYHUD_haveNoMsg"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(JHB_HUDDiyProgressView.resetSubViewsForJHB_DIYHUD_haveNoMsgWithScale(_:)), name: NSNotification.Name(rawValue: "JHB_DIYHUD_haveNoMsgWithScale"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(JHB_HUDDiyProgressView.resetSubViewsForJHB_DIYHUD_haveMsg), name: NSNotification.Name(rawValue: "JHB_DIYHUD_haveMsg"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(JHB_HUDDiyProgressView.resetSubViewsForJHB_DIYHUD_haveMsgWithScale(_:)), name: NSNotification.Name(rawValue: "JHB_DIYHUD_haveMsg_WithScale"), object: nil)
self.addSubview(self.diyImageView)
self.addSubview(self.diyMsgLabel)
self.addSubview(self.diySpareImageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setSubViews(){
self.diyImageView = UIImageView.init()
self.diyImageView.clipsToBounds = true
self.diyImageView.sizeToFit()
self.diyImageView.contentMode = UIViewContentMode.scaleAspectFit
self.diyMsgLabel = UILabel.init()
self.diyMsgLabel.textColor = UIColor.white
self.diyMsgLabel.font = UIFont.systemFont(ofSize: 15.0)
self.diyMsgLabel.textAlignment = NSTextAlignment.center
self.diyMsgLabel.sizeToFit()
self.diySpareImageView = UIImageView.init()
self.diySpareImageView.isHidden = true
self.diySpareImageView.clipsToBounds = true
self.diySpareImageView.sizeToFit()
self.diySpareImageView.contentMode = UIViewContentMode.scaleAspectFit
}
func resetSubViews() {
self.diyImageView.frame = CGRect(x: self.bounds.size.width/2-25 ,y: self.bounds.midY-35 ,width: 50 ,height: 50 )
self.diyMsgLabel.frame = CGRect(x: (self.bounds.size.width - (diyMsgLabelWidth - 2 * kMargin))/2, y: self.bounds.midY+25, width: diyMsgLabelWidth - 2 * kMargin, height: 18)
self.diySpareImageView.frame = CGRect(x: 0 ,y: 0 ,width: 50 ,height: 50 )
self.diySpareImageView.center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2)
}
override func layoutSubviews() {
super.layoutSubviews()
self.resetSubViews()
}
// MARK: - NotificationCenter
func resetSubViewsForJHB_DIYHUD_haveNoMsg() {
ifChangeImgView = true
self.diyImageView.isHidden = true
self.diyMsgLabel.isHidden = true
self.diySpareImageView.isHidden = false
self.JudgeIfNeedAnimation()
}
func resetSubViewsForJHB_DIYHUD_haveNoMsgWithScale(_ noti:Notification) {
ifChangeImgView = true
self.diyImageView.isHidden = true
self.diyMsgLabel.isHidden = true
self.diySpareImageView.isHidden = false
self.JudgeIfNeedAnimation()
self.diySpareImageView.transform = self.diySpareImageView.transform.scaledBy(x: 1, y: 1)
}
func resetSubViewsForJHB_DIYHUD_haveMsg() {
ifChangeImgView = false
self.diyImageView.isHidden = false
self.diyMsgLabel.isHidden = false
self.diySpareImageView.isHidden = true
self.JudgeIfNeedAnimation()
}
func resetSubViewsForJHB_DIYHUD_haveMsgWithScale(_ noti:Notification) {
ifChangeImgView = false
self.diyImageView.isHidden = false
self.diyMsgLabel.isHidden = false
self.diySpareImageView.isHidden = true
let obValue = noti.object as! CGFloat
self.diyImageView.transform = self.diyImageView.transform.scaledBy(x: 1/obValue, y: 1/obValue)
self.diyMsgLabel.transform = self.diyMsgLabel.transform.scaledBy(x: 1/obValue, y: 1/obValue)
self.JudgeIfNeedAnimation()
}
// MARK: - Judge Different Show-Type
func JudgeIfNeedAnimation() {
if self.diyShowImage.hasSuffix(".png") {
self.diyShowImage.substring(to: self.diyShowImage.length-4)
}
if self.diyImgsNumber == 0 {
if ifChangeImgView == true {
self.diySpareImageView.image = UIImage.init(named: "\(self.diyShowImage)" + ".png" as String)
self.RealizeEffectOfImageView()
}else if ifChangeImgView == false {
self.diyImageView.image = UIImage.init(named: "\(self.diyShowImage)" + ".png" as String)
self.RealizeEffectOfImageView()
}
}else {
self.RealizeAnimationOfImageView()
}
}
// MARK: - Realize The Effect Of ImageView
func RealizeEffectOfImageView() {
switch self.diyHudType {
case DiyHUDType.kDiyHUDTypeDefault.hashValue:// 单纯展示
break
case DiyHUDType.kDiyHUDTypeRotateWithY.hashValue:
//绕哪个轴,那么就改成什么:这里是绕y轴 ---> transform.rotation.y
let rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.y")
//旋转角度
rotationAnimation.toValue = NSNumber.init(value: Double.pi)
//每次旋转的时间(单位秒)
rotationAnimation.duration = self.diySpeed
rotationAnimation.isCumulative = true
//重复旋转的次数,如果你想要无数次,那么设置成MAXFLOAT
rotationAnimation.repeatCount = MAXFLOAT
if ifChangeImgView == true {
self.diySpareImageView.layer.add(rotationAnimation, forKey: "transform.rotation.y")
}else if ifChangeImgView == false {
self.diyImageView.layer.add(rotationAnimation, forKey: "transform.rotation.y")
}
break
case DiyHUDType.kDiyHUDTypeRotateWithZ.hashValue:
//绕哪个轴,那么就改成什么:这里是z轴 ---> transform.rotation.y
let rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
//旋转角度
rotationAnimation.toValue = NSNumber.init(value: Double.pi)
//每次旋转的时间(单位秒)
rotationAnimation.duration = self.diySpeed
rotationAnimation.isCumulative = true
//重复旋转的次数,如果你想要无数次,那么设置成MAXFLOAT
rotationAnimation.repeatCount = MAXFLOAT
if ifChangeImgView == true {
self.diySpareImageView.layer.add(rotationAnimation, forKey: "transform.rotation.z")
}else if ifChangeImgView == false {
self.diyImageView.layer.add(rotationAnimation, forKey: "transform.rotation.z")
}
break
case DiyHUDType.kDiyHUDTypeShakeWithX.hashValue:
let shakeAnimation = CAKeyframeAnimation.init(keyPath: "transform.translation.x")
var currentTx = CGFloat()
if ifChangeImgView == true {
currentTx = self.diySpareImageView.transform.tx
}else if ifChangeImgView == false {
currentTx = self.diyImageView.transform.tx
}
// shakeAnimation.delegate = self
shakeAnimation.duration = self.diySpeed
shakeAnimation.repeatCount = MAXFLOAT
// currentTx + 8, currentTx - 8, currentTx + 5, currentTx - 5,currentTx + 2, currentTx - 2, currentTx
shakeAnimation.values = [currentTx,currentTx + 10,currentTx, currentTx - 10,currentTx,currentTx + 10,currentTx,currentTx - 10]
shakeAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
if ifChangeImgView == true {
self.diySpareImageView.layer.add(shakeAnimation, forKey: "transform.translation.x")
}else if ifChangeImgView == false {
self.diyImageView.layer.add(shakeAnimation, forKey: "transform.translation.x")
}
break
default:
break
}
}
// MARK: - Realize The Effect Of Animation
func RealizeAnimationOfImageView() {
_ = 0
var images=[UIImage]()
for num in 1 ... self.diyImgsNumber {
guard let img=UIImage(named: "\(self.diyShowImage)" + "\(num)"+".png") else {return}
images.append(img)
}
if ifChangeImgView == true {
self.diySpareImageView.animationImages = images
self.diySpareImageView.animationDuration = self.diySpeed
self.diySpareImageView.animationRepeatCount = 0
self.diySpareImageView.startAnimating()
}else if ifChangeImgView == false {
self.diyImageView.animationImages = images
self.diyImageView.animationDuration = self.diySpeed
self.diyImageView.animationRepeatCount = 0
self.diyImageView.startAnimating()
}
}
}
| mit | 982740eda3ddc1b8e27387f4a1137459 | 45.131579 | 230 | 0.635102 | 4.105386 | false | false | false | false |
greenlaw110/FrameworkBenchmarks | frameworks/Swift/swift-nio/app/Sources/main.swift | 1 | 4615 | import Foundation
import NIO
import NIOHTTP1
struct JSONTestResponse: Encodable {
let message = "Hello, World!"
}
enum Constants {
static let httpVersion = HTTPVersion(major: 1, minor: 1)
static let serverName = "SwiftNIO"
static let plainTextResponse: StaticString = "Hello, World!"
static let plainTextResponseLength = plainTextResponse.utf8CodeUnitCount
static let plainTextResponseLengthString = String(plainTextResponseLength)
static let jsonResponseLength = try! JSONEncoder().encode(JSONTestResponse()).count
static let jsonResponseLengthString = String(jsonResponseLength)
}
private final class HTTPHandler: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart
let jsonEncoder: JSONEncoder
let dateCache: RFC1123DateCache
var plaintextBuffer: ByteBuffer
var jsonBuffer: ByteBuffer
init(channel: Channel) {
let allocator = ByteBufferAllocator()
self.plaintextBuffer = allocator.buffer(capacity: Constants.plainTextResponseLength)
self.plaintextBuffer.writeStaticString(Constants.plainTextResponse)
self.jsonBuffer = allocator.buffer(capacity: Constants.jsonResponseLength)
self.jsonEncoder = .init()
self.dateCache = .on(channel.eventLoop)
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case .head(let request):
switch request.uri {
case "/p":
self.processPlaintext(context: context)
case "/j":
do {
try self.processJSON(context: context)
} catch {
context.close(promise: nil)
}
default:
context.close(promise: nil)
}
case .body:
break
case .end:
context.write(self.wrapOutboundOut(.end(nil)), promise: nil)
}
}
func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
context.fireChannelReadComplete()
}
private func processPlaintext(context: ChannelHandlerContext) {
let responseHead = self.responseHead(contentType: "text/plain", contentLength: Constants.plainTextResponseLengthString)
context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
context.write(self.wrapOutboundOut(.body(.byteBuffer(self.plaintextBuffer))), promise: nil)
}
private func processJSON(context: ChannelHandlerContext) throws {
let responseHead = self.responseHead(contentType: "application/json", contentLength: Constants.jsonResponseLengthString)
context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
self.jsonBuffer.clear()
try self.jsonBuffer.writeBytes(self.jsonEncoder.encode(JSONTestResponse()))
context.write(self.wrapOutboundOut(.body(.byteBuffer(self.jsonBuffer))), promise: nil)
}
private func responseHead(contentType: String, contentLength: String) -> HTTPResponseHead {
var headers = HTTPHeaders()
headers.add(name: "content-type", value: contentType)
headers.add(name: "content-length", value: contentLength)
headers.add(name: "server", value: Constants.serverName)
headers.add(name: "date", value: self.dateCache.currentTimestamp())
return HTTPResponseHead(
version: Constants.httpVersion,
status: .ok,
headers: headers
)
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 8192)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMap {
channel.pipeline.addHandler(HTTPHandler(channel: channel))
}
}
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16)
defer {
try! group.syncShutdownGracefully()
}
let channel = try bootstrap.bind(host: "0.0.0.0", port: 8080).wait()
guard let localAddress = channel.localAddress else {
fatalError("Address was unable to bind. Please check that the socket was not closed or that the address family was understood.")
}
try channel.closeFuture.wait()
| bsd-3-clause | 832824ba0d76cce2faa3102fd5747cc3 | 38.444444 | 132 | 0.698158 | 4.978425 | false | false | false | false |
yomajkel/RingGraph | RingGraph/RingGraph/ProgressTextView.swift | 1 | 3009 | //
// ProgressTextView.swift
// RingMeter
//
// Created by Michał Kreft on 12/04/15.
// Copyright (c) 2015 Michał Kreft. All rights reserved.
//
import UIKit
private let counterDescriptionRatio: CGFloat = 0.7
internal class ProgressTextView: UIView {
private let counterHostView: UIView
private let counterLabel: UILabel
private let descriptionLabel: UILabel
private let fadeAnimationHelper: RangeAnimationHelper
private let slideAnimationHelper: RangeAnimationHelper
required init(frame: CGRect, ringMeter: RingMeter) {
counterLabel = UILabel(frame: CGRect())
descriptionLabel = UILabel(frame: CGRect())
counterHostView = UIView(frame: CGRect())
fadeAnimationHelper = RangeAnimationHelper(animationStart: 0.3, animationEnd: 0.5)
slideAnimationHelper = RangeAnimationHelper(animationStart: 0.4, animationEnd: 0.7)
super.init(frame: frame)
setupSubviews(ringMeter: ringMeter)
}
required init?(coder aDecoder: NSCoder) { //ugh!
fatalError("init(coder:) has not been implemented")
}
func setAnimationProgress(progress: Float) {
setFadeAnimationState(progress: progress)
setSlideAnimationProgress(progress: progress)
}
}
private extension ProgressTextView {
func setupSubviews(ringMeter: RingMeter) {
setupSubviewFrames()
setupSubviewVisuals(ringMeter: ringMeter)
}
func setupSubviewFrames() {
var frame = self.frame
frame.origin = CGPoint.zero
frame.size.height *= counterDescriptionRatio
counterHostView.frame = frame
counterLabel.frame = frame
counterHostView.addSubview(counterLabel)
frame.origin.y = frame.size.height
frame.size.height = self.frame.size.height - frame.size.height
descriptionLabel.frame = frame
addSubview(counterHostView)
addSubview(descriptionLabel)
}
func setupSubviewVisuals(ringMeter: RingMeter) {
counterLabel.font = UIFont.systemFont(ofSize: 90)
counterLabel.text = String(ringMeter.value)
descriptionLabel.font = UIFont.systemFont(ofSize: 28)
descriptionLabel.text = "OF \(ringMeter.maxValue) \(ringMeter.title.uppercased())" //TODO lozalize
counterLabel.textAlignment = .center
descriptionLabel.textAlignment = .center
let color = UIColor.white
counterLabel.textColor = color
descriptionLabel.textColor = color
counterHostView.clipsToBounds = true
}
func setFadeAnimationState(progress: Float) {
alpha = CGFloat(fadeAnimationHelper.normalizedProgress(progress))
}
func setSlideAnimationProgress(progress: Float) {
let positionMultiplier = 1.0 - slideAnimationHelper.normalizedProgress(progress)
counterLabel.frame.origin.y = counterHostView.frame.height * CGFloat(positionMultiplier)
}
}
| mit | 66458a0f8ac64ff65b81aa1149263139 | 32.411111 | 106 | 0.68008 | 4.757911 | false | false | false | false |
chrisjmendez/swift-exercises | Basic/ActionSheet/ActionSheet/ViewController.swift | 1 | 1968 | //
// ViewController.swift
// ActionSheet
//
// Created by tommy trojan on 5/16/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var actionSheetBtn: UIButton!
@IBAction func showActionSheetTapped(sender: AnyObject) {
//Create the AlertController
let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! Choose an option!", preferredStyle: .ActionSheet)
//Cancel
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
//Camera
let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .Default) { action -> Void in
//Code for launching the camera goes here
}
actionSheetController.addAction(takePictureAction)
//Camera Roll
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Camera Roll", style: .Default) { action -> Void in
//Code for picking from camera roll goes here
}
actionSheetController.addAction(choosePictureAction)
//We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = sender as? UIView;
//Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
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 | 3c33cdf60069c42fa5e7e88cbc39f53b | 33.526316 | 168 | 0.667175 | 5.466667 | false | false | false | false |
kesun421/firefox-ios | Extensions/ShareTo/ShareViewController.swift | 2 | 11003 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
struct ShareDestination {
let code: String
let name: String
let image: String
}
// TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values.
let ShareDestinationBookmarks: String = "Bookmarks"
let ShareDestinationReadingList: String = "ReadingList"
let ShareDestinations = [
ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"),
ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks")
]
protocol ShareControllerDelegate {
func shareControllerDidCancel(_ shareController: ShareDialogController)
func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet)
}
private struct ShareDialogControllerUX {
static let CornerRadius: CGFloat = 4 // Corner radius of the dialog
static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar
static let NavigationBarCancelButtonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize) // System default
static let NavigationBarAddButtonFont = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize) // System default
static let NavigationBarIconSize = 40 // Width and height of the icon
static let NavigationBarBottomPadding = 12
static let ItemTitleFontMedium = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium)
static let ItemTitleFont = UIFont.systemFont(ofSize: 15)
static let ItemTitleMaxNumberOfLines = 2
static let ItemTitleLeftPadding = 44
static let ItemTitleRightPadding = 44
static let ItemTitleBottomPadding = 12
static let ItemLinkFont = UIFont.systemFont(ofSize: 12)
static let ItemLinkMaxNumberOfLines = 3
static let ItemLinkLeftPadding = 44
static let ItemLinkRightPadding = 44
static let ItemLinkBottomPadding = 14
static let DividerColor = UIColor.lightGray // Divider between the item and the table with destinations
static let DividerHeight = 0.5
static let TableRowHeight: CGFloat = 44 // System default
static let TableRowFont = UIFont.systemFont(ofSize: 14)
static let TableRowFontMinScale: CGFloat = 0.8
static let TableRowTintColor = UIColor(red: 0.427, green: 0.800, blue: 0.102, alpha: 1.0) // Green tint for the checkmark
static let TableRowTextColor = UIColor(rgb: 0x555555)
static let TableHeight = 88 // Height of 2 standard 44px cells
}
class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var delegate: ShareControllerDelegate!
var item: ShareItem!
var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks)
var selectedShareDestinations: NSMutableSet = NSMutableSet()
var navBar: UINavigationBar!
var navItem: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
selectedShareDestinations = NSMutableSet(set: initialShareDestinations)
self.view.backgroundColor = UIColor.white
self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius
self.view.clipsToBounds = true
// Setup the NavigationBar
navBar = UINavigationBar()
navBar.translatesAutoresizingMaskIntoConstraints = false
navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor
navBar.isTranslucent = false
self.view.addSubview(navBar)
// Setup the NavigationItem
navItem = UINavigationItem()
navItem.leftBarButtonItem = UIBarButtonItem(
title: Strings.ShareToCancelButton,
style: .plain,
target: self,
action: #selector(ShareDialogController.cancel)
)
navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], for: UIControlState())
navItem.leftBarButtonItem?.accessibilityIdentifier = "ShareDialogController.navigationItem.leftBarButtonItem"
navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.done, target: self, action: #selector(ShareDialogController.add))
navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], for: UIControlState())
let logo = UIImageView(image: UIImage(named: "Icon-Small"))
logo.contentMode = UIViewContentMode.scaleAspectFit // TODO Can go away if icon is provided in correct size
navItem.titleView = logo
navBar.pushItem(navItem, animated: false)
// Setup the title view
let titleView = UILabel()
titleView.translatesAutoresizingMaskIntoConstraints = false
titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines
titleView.lineBreakMode = NSLineBreakMode.byTruncatingTail
titleView.text = item.title
titleView.font = ShareDialogControllerUX.ItemTitleFontMedium
view.addSubview(titleView)
// Setup the link view
let linkView = UILabel()
linkView.translatesAutoresizingMaskIntoConstraints = false
linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines
linkView.lineBreakMode = NSLineBreakMode.byTruncatingTail
linkView.text = item.url
linkView.font = ShareDialogControllerUX.ItemLinkFont
view.addSubview(linkView)
// Setup the icon
let iconView = UIImageView()
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.image = UIImage(named: "defaultFavicon")
view.addSubview(iconView)
// Setup the divider
let dividerView = UIView()
dividerView.translatesAutoresizingMaskIntoConstraints = false
dividerView.backgroundColor = ShareDialogControllerUX.DividerColor
view.addSubview(dividerView)
// Setup the table with destinations
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
tableView.isUserInteractionEnabled = true
tableView.delegate = self
tableView.allowsSelection = true
tableView.dataSource = self
tableView.isScrollEnabled = false
view.addSubview(tableView)
// Setup constraints
let views = [
"nav": navBar,
"title": titleView,
"link": linkView,
"icon": iconView,
"divider": dividerView,
"table": tableView
]
// TODO See Bug 1102516 - Use Snappy to define share extension layout constraints
let constraints = [
"H:|[nav]|",
"V:|[nav]",
"H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|",
"V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]",
"H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|",
"V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]",
"H:|[divider]|",
"V:[divider(\(ShareDialogControllerUX.DividerHeight))]",
"V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]",
"H:|[table]|",
"V:[divider][table]",
"V:[table(\(ShareDialogControllerUX.TableHeight))]|"
]
for constraint in constraints {
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views))
}
}
// UITabBarItem Actions that map to our delegate methods
func cancel() {
delegate?.shareControllerDidCancel(self)
}
func add() {
delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations))
}
// UITableView Delegate and DataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ShareDestinations.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return ShareDialogControllerUX.TableRowHeight
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGray : ShareDialogControllerUX.TableRowTextColor
cell.textLabel?.font = ShareDialogControllerUX.TableRowFont
cell.accessoryType = selectedShareDestinations.contains(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none
cell.tintColor = ShareDialogControllerUX.TableRowTintColor
cell.layoutMargins = UIEdgeInsets.zero
cell.textLabel?.text = ShareDestinations[indexPath.row].name
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = ShareDialogControllerUX.TableRowFontMinScale
cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let code = ShareDestinations[indexPath.row].code
if selectedShareDestinations.contains(code) {
selectedShareDestinations.remove(code)
} else {
selectedShareDestinations.add(code)
}
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
navItem.rightBarButtonItem?.isEnabled = (selectedShareDestinations.count != 0)
}
}
| mpl-2.0 | 4cc552ac18ef812598ca50086b9e0407 | 43.910204 | 244 | 0.696356 | 5.944354 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCILELongTermKeyRequestNegativeReply.swift | 1 | 2715 | //
// HCILELongTermKeyRequestNegativeReply.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Long Term Key Request Negative Reply Command
///
/// The command is used to reply to an LE Long Term Key Request event from
/// the Controller if the Host cannot provide a Long Term Key for this Connection_Handle.
func lowEnergyLongTermKeyRequestNegativeReply(handle: UInt16, timeout: HCICommandTimeout = .default) async throws -> UInt16 {
let parameters = HCILELongTermKeyRequestNegativeReply(connectionHandle: handle)
let returnParameters = try await deviceRequest(parameters, HCILELongTermKeyRequestNegativeReplyReturn.self, timeout: timeout)
return returnParameters.connectionHandle
}
}
// MARK: - Command
/// LE Long Term Key Request Negative Reply Command
///
/// The command is used to reply to an LE Long Term Key Request event
/// from the Controller if the Host cannot provide a Long Term Key for this Connection_Handle.
@frozen
public struct HCILELongTermKeyRequestNegativeReply: HCICommandParameter {
public static let command = HCILowEnergyCommand.longTermKeyNegativeReply //0x001B
/// Range 0x0000-0x0EFF (all other values reserved for future use)
public let connectionHandle: UInt16 //Connection_Handle
public init(connectionHandle: UInt16) {
self.connectionHandle = connectionHandle
}
public var data: Data {
let connectionHandleBytes = connectionHandle.littleEndian.bytes
return Data([
connectionHandleBytes.0,
connectionHandleBytes.1
])
}
}
// MARK: - Return parameter
/// LE Long Term Key Request Negative Reply Command
///
/// The command is used to reply to an LE Long Term Key Request event
/// from the Controller if the Host cannot provide a Long Term Key for this Connection_Handle.
@frozen
public struct HCILELongTermKeyRequestNegativeReplyReturn: HCICommandReturnParameter {
public static let command = HCILowEnergyCommand.longTermKeyNegativeReply //0x001B
public static let length: Int = 2
/// Connection_Handle
/// Range 0x0000-0x0EFF (all other values reserved for future use)
public let connectionHandle: UInt16 // Connection_Handle
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
connectionHandle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))
}
}
| mit | 746d512e640d5e73d6020c83ed61ee4e | 31.698795 | 133 | 0.6986 | 4.538462 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/ViewControllers/BottomSheet3DS2ViewController.swift | 1 | 3506 | //
// BottomSheet3DS2ViewController.swift
// StripePaymentSheet
//
// Created by Cameron Sabol on 1/20/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripePaymentsUI
@_spi(STP) import StripePayments
protocol BottomSheet3DS2ViewControllerDelegate: AnyObject {
func bottomSheet3DS2ViewControllerDidCancel(
_ bottomSheet3DS2ViewController: BottomSheet3DS2ViewController)
}
/// For internal SDK use only
@objc(STP_Internal_BottomSheet3DS2ViewController)
class BottomSheet3DS2ViewController: UIViewController {
weak var delegate: BottomSheet3DS2ViewControllerDelegate? = nil
lazy var navigationBar: SheetNavigationBar = {
let navBar = SheetNavigationBar(isTestMode: isTestMode,
appearance: appearance)
navBar.setStyle(.back)
navBar.delegate = self
return navBar
}()
let challengeViewController: UIViewController
let appearance: PaymentSheet.Appearance
let isTestMode: Bool
required init(challengeViewController: UIViewController, appearance: PaymentSheet.Appearance, isTestMode: Bool) {
self.challengeViewController = challengeViewController
self.appearance = appearance
self.isTestMode = isTestMode
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
addChild(challengeViewController)
let headerLabel = PaymentSheetUI.makeHeaderLabel(appearance: appearance)
headerLabel.text =
STPThreeDSNavigationBarCustomization.defaultSettings().navigationBarCustomization
.headerText
view.addSubview(headerLabel)
headerLabel.translatesAutoresizingMaskIntoConstraints = false
let challengeView: UIView! = challengeViewController.view
view.addSubview(challengeView)
challengeView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
headerLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
view.layoutMarginsGuide.trailingAnchor.constraint(equalTo: headerLabel.trailingAnchor),
headerLabel.topAnchor.constraint(equalTo: view.topAnchor),
challengeView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
view.trailingAnchor.constraint(equalTo: challengeView.trailingAnchor),
challengeView.topAnchor.constraint(equalTo: headerLabel.bottomAnchor),
view.bottomAnchor.constraint(equalTo: challengeView.bottomAnchor),
])
}
}
// MARK: - BottomSheetContentViewController
/// :nodoc:
extension BottomSheet3DS2ViewController: BottomSheetContentViewController {
var allowsDragToDismiss: Bool {
return false
}
func didTapOrSwipeToDismiss() {
// no-op
}
var requiresFullScreen: Bool {
return true
}
}
// MARK: - SheetNavigationBarDelegate
/// :nodoc:
extension BottomSheet3DS2ViewController: SheetNavigationBarDelegate {
func sheetNavigationBarDidClose(_ sheetNavigationBar: SheetNavigationBar) {
delegate?.bottomSheet3DS2ViewControllerDidCancel(self)
}
func sheetNavigationBarDidBack(_ sheetNavigationBar: SheetNavigationBar) {
delegate?.bottomSheet3DS2ViewControllerDidCancel(self)
}
}
| mit | 0909630fd484393f3818031fb9cbe644 | 33.362745 | 117 | 0.72582 | 5.375767 | false | true | false | false |
priyax/TextToSpeech | textToTableViewController/textToTableViewController/SavedRecipesController.swift | 1 | 13103 | //
// SavedRecipesController.swift
// textToTableViewController
//
// Created by Priya Xavier on 10/6/16.
// Copyright © 2016 Guild/SA. All rights reserved.
//
import UIKit
class SavedRecipesController: UIViewController,UITableViewDelegate, UITableViewDataSource {
//MARK: Properties
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var welcomeLabel: UILabel!
@IBOutlet weak var notLoggedInLabel: UILabel!
// @IBOutlet weak var logOutBtn: UIButton!
var recipes = [RecipeData]()
override func viewDidLoad() {
super.viewDidLoad()
if (BackendlessManager.sharedInstance.isUserLoggedIn()){
//force image to keep original color
var logOutImage = UIImage(named: "logout")
logOutImage = logOutImage!.withRenderingMode(.alwaysOriginal)
navigationItem.leftBarButtonItem = UIBarButtonItem(image: logOutImage, style: .plain, target: self, action: #selector(logout(_:)))
self.notLoggedInLabel.isHidden = true
//// load archived recipedata object and save it to BE
if let archivedRecipe = NSKeyedUnarchiver.unarchiveObject(withFile: RecipeData.ArchiverUrl.path) as? RecipeData {
BackendlessManager.sharedInstance.saveRecipe(recipeData: archivedRecipe,
completion: {
//delete archived data
do {
try FileManager().removeItem(atPath: RecipeData.ArchiverUrl.path) }
catch {
print("No recipe stored in archiver")
}
//load data that's in BE, including presaved recipes
BackendlessManager.sharedInstance.loadRecipes {recipesData in
self.recipes += recipesData
self.tableView.reloadData()
if self.recipes.count == 0
{
self.welcomeLabel.isHidden = false
} else {
self.welcomeLabel.isHidden = true
} }}, error: {
let alertController = UIAlertController(title: "Save Error",
message: "Oops! We couldn't save your recipe at this time.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction) })
} else {
BackendlessManager.sharedInstance.loadRecipes { recipesData in
self.recipes += recipesData
self.tableView.reloadData()
if self.recipes.count == 0
{
self.welcomeLabel.isHidden = false
} else {
self.welcomeLabel.isHidden = true
}
}
}
}
else {
var backBtnImage = UIImage(named: "backBtn")
backBtnImage = backBtnImage!.withRenderingMode(.alwaysOriginal)
navigationItem.leftBarButtonItem = UIBarButtonItem(image: backBtnImage, style: .plain, target: self, action: #selector(backToLogin(_:)))
self.notLoggedInLabel.isHidden = false
self.welcomeLabel.isHidden = true
// self.logOutBtn.isEnabled = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Alert view to navigate to website or manual input of recipe
@IBAction func addRecipe(_ sender: UIButton) {
//
// UIAlertController - Action Sheet
//
// https://developer.apple.com/ios/human-interface-guidelines/ui-views/action-sheets/
//
let alertController = UIAlertController(title: nil,
message: "Get your recipe on the clipboard",
preferredStyle: .actionSheet)
let extractFromWeb = UIAlertAction(title: "Recipe from Web", style: .default) { action in
self.performSegue(withIdentifier: "gotoExtractRecipe", sender: self)
}
alertController.addAction(extractFromWeb)
let manualEntry = UIAlertAction(title: "Recipe By Typing", style: .default) { action in
self.performSegue(withIdentifier: "gotoTypingRecipe", sender: self)
}
alertController.addAction(manualEntry)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in
}
alertController.addAction(cancelAction)
//self.present(alertController, animated: true) {
// }
alertController.popoverPresentationController?.sourceView = self.view
alertController.popoverPresentationController?.sourceRect = sender.bounds
self.present(alertController, animated: true, completion: nil)
}
// @IBOutlet weak var searchBar: UISearchBar!
///////
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "savedRecipesCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! SavedRecipesTableViewCell
cell.recipePic.image = nil
cell.RecipeTitle.text = recipes[indexPath.row].title
// Fetches the appropriate recipe for the data source layout.
let recipe = recipes[(indexPath as NSIndexPath).row]
if let thumbnailUrl = recipe.thumbnailUrl {
if thumbnailUrl != "" {
loadImageFromUrl(cell: cell, thumbnailUrl: thumbnailUrl)
}
}
return cell
}
// Override to support editing the table view.
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Find the Recipe Data in the data source that we wish to delete.
let recipeToRemove = recipes[indexPath.row]
BackendlessManager.sharedInstance.removeRecipe(recipeToRemove: recipeToRemove,
completion: {
// It was removed from the database, now delete the row from the data source.
self.recipes.remove(at: (indexPath as NSIndexPath).row)
tableView.deleteRows(at: [indexPath], with: .fade)
if self.recipes.count == 0
{
self.welcomeLabel.isHidden = false
} else {
self.welcomeLabel.isHidden = true
}
},
error: {
// It was NOT removed - tell the user and DON'T delete the row from the data source.
let alertController = UIAlertController(title: "Remove Failed",
message: "Oops! We couldn't remove your Recipe at this time.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
)
}
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "gotoReadRecipesFromTableVC" {
let readRecipesTableViewController = segue.destination as! ReadRecipesController
// Get the cell that generated this segue.
if let selectedRecipesCell = sender as? SavedRecipesTableViewCell {
let indexPath = tableView.indexPath(for: selectedRecipesCell)!
let selectedRecipe = recipes[(indexPath as NSIndexPath).row]
readRecipesTableViewController.recipeToLoad = selectedRecipe
}
}
}
func loadImageFromUrl(cell: SavedRecipesTableViewCell, thumbnailUrl: String) {
let url = URL(string: thumbnailUrl)
let session = URLSession.shared
let task = session.dataTask(with: url!, completionHandler: { (data,response,error) in
if error == nil {
do {
let data = try Data(contentsOf: url!, options: [])
DispatchQueue.main.sync {
cell.recipePic.image = UIImage(data: data)
}
}catch
{ print("NSData Error \(error)")
}
} else { print("NSURLSession error: \(String(describing: error))")
}
})
task.resume()
}
@IBAction func unwindToSavedRecipes(_ sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ReadRecipesController, let recipe = sourceViewController.recipeToLoad {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
recipes[(selectedIndexPath as NSIndexPath).row] = recipe
tableView.reloadRows(at: [selectedIndexPath], with: .none)
} else {
// Add a new meal.
let newIndexPath = IndexPath(row: recipes.count, section: 0)
recipes.append(recipe)
tableView.insertRows(at: [newIndexPath], with: .bottom)
self.welcomeLabel.isHidden = true
}
}
}
//LogOut
func logout(_ sender: UIButton) {
let alertController = UIAlertController(title: nil,
message: "Are you sure you want to log out?",
preferredStyle: .actionSheet)
let logOutApp = UIAlertAction(title: "Log Out", style: .default) { action in
BackendlessManager.sharedInstance.logoutUser(
completion: {
//add segue programatically
self.performSegue(withIdentifier: "gotoLoginFromSavedRecipes", sender: sender)
},
error: { message in
Utility.showAlert(viewController: self, title: "Logout Error", message: message)
})
}
alertController.addAction(logOutApp)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in
}
alertController.addAction(cancelAction)
//self.present(alertController, animated: true) {
// }
alertController.popoverPresentationController?.sourceView = self.view
alertController.popoverPresentationController?.sourceRect = sender.bounds
self.present(alertController, animated: true, completion: nil)
}
func backToLogin(_ sender: UIButton){
self.performSegue(withIdentifier: "gotoLoginFromSavedRecipes", sender: sender)
}
}
| mit | 72fb6eef184e9b43d2f32d16372b8116 | 37.763314 | 158 | 0.514273 | 6.347868 | false | false | false | false |
MA806P/SwiftDemo | SwiftTestDemo/SwiftTestDemo/Functions.swift | 1 | 3066 | //
// Functions.swift
// SwiftTestDemo
//
// Created by MA806P on 2018/7/29.
// Copyright © 2018年 myz. All rights reserved.
//
import Foundation
class FunctionsTest {
func funcDemoTestAction() {
func greet(_ person: String, day: String) -> String {
return "hello \(person) , today is \(day)"
}
print("\(greet("123", day: "1"))")
}
}
//--------------- Functions and Closures -----------------
//func makeIncrementer() -> ((Int) -> Int) {
// func addOne(number: Int) -> Int {
// return 1+number
// }
// return addOne
//}
//var increment = makeIncrementer()
//var test = increment(2)
//var numberArray = [1, 2, 3]
//numberArray.map ({ (number: Int) -> Int in
// return number + 1
//})
////let mappedNumberArray = numberArray.map{number in 3 * number}
//let mappedNumberArray = numberArray.map{$0 * 3}
//print(mappedNumberArray) //3, 6, 9
//let sortedNumberArray = numberArray.sorted { $0 > $1 }
//print(sortedNumberArray) //3, 2, 1
//Specifying Argument Labels
//You write an argument label before the parameter name, separated by a space
//The use of argument labels can allow a function to be called in an expressive, sentence-like manner,
//while still providing a function body that is readable and clear in intent.
//func greet(person: String, from hometown: String) -> String {
// return "Hello \(person)! Glad you could visit from \(hometown)."
//}
//print(greet(person: "Bill", from: "Cupertino"))
//// Prints "Hello Bill! Glad you could visit from Cupertino."
//Default Parameter Values
//func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
// // If you omit the second argument when calling this function, then
// // the value of parameterWithDefault is 12 inside the function body.
//}
//someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6
//someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12
//Variadic Parameters
//func arithmeticMean(_ numbers: Double...) -> Double {
// var total: Double = 0
// for number in numbers {
// total += number
// }
// return total / Double(numbers.count)
//}
//arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
//arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers
////In-Out Parameters
////If you want a function to modify a parameter’s value,
////and you want those changes to persist after the function call has ended,
////define that parameter as an in-out parameter instead.
//func swapTwoInts(_ a: inout Int, _ b: inout Int) {
// let temporaryA = a
// a = b
// b = temporaryA
//}
//var a = 1
//var b = 2
//swap(&a, &b)
//print("\(a), \(b)")//2, 1
////Function Types
//// () -> void
//// (Int, Int) -> Int
//func addTwoInts(_ a: Int, _ b: Int) -> Int {
// return a + b
//}
//var mathFunction: (Int, Int) -> Int = addTwoInts
//print("Result: \(mathFunction(2, 3))")
| apache-2.0 | aa7da921074d5a16e6e67105dd694021 | 26.088496 | 102 | 0.640314 | 3.652745 | false | false | false | false |
imex94/KCLTech-iOS-2015 | Hackalendar/Hackalendar/Hackalendar/HackathonItem.swift | 1 | 2868 | //
// HackathonItem.swift
// Hackalendar
//
// Created by Clarence Ji on 11/17/15.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import Foundation
import CoreData
class HackathonItem: NSManagedObject {
private static let entityName = "HackathonItem"
/**
Class function to create a new HackathonItem instance in the database
insertIntoManagedObjectConext will insert the new HackathonItem row into the
current database. Initially the item is empty, we have to directly assign the variables
*/
class func item() -> HackathonItem {
if let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: HCDataManager.managedObjectContext()) {
return HackathonItem(entity: entityDescription, insertIntoManagedObjectContext: HCDataManager.managedObjectContext())
}
return HackathonItem()
}
/**
Convenience method to fetch hackathons based on the format given
without any sorting.
*/
class func fetchHackathons(format: String, args: [AnyObject]?) -> [HackathonItem] {
return fetchHackathons(format, args: args, sortKeywords: [])
}
/**
Class method to fetch hackathons from the local storage based on
the boolean expression format given and also sort them based on the keywords provided
*/
class func fetchHackathons(format: String, args: [AnyObject]?, sortKeywords: [String]) -> [HackathonItem] {
let request = NSFetchRequest(entityName: entityName)
let predicate = NSPredicate(format: format, argumentArray: args)
request.predicate = predicate
var sortArray = [NSSortDescriptor]()
for keyword in sortKeywords {
let sort = NSSortDescriptor(key: keyword, ascending: false)
sortArray.append(sort)
}
request.sortDescriptors = sortArray
do {
if let hackathons = try HCDataManager.managedObjectContext().executeFetchRequest(request) as? [HackathonItem] {
return hackathons
}
} catch {
print("Error fetching hackathons: \(error)")
}
return []
}
/**
Class function for removing hackathons from the database for the given yearn and month
For instance, 2015-12, will remove all the hackathons in 2015-December.
*/
class func removeHackathons(year: Int, month: Int) {
let toDelete = fetchHackathons("year == %@ && month == %@", args: [year, month])
for hackathon in toDelete {
HCDataManager.managedObjectContext().deleteObject(hackathon)
}
}
}
| mit | 04cd1aefb3d72a81972b96a39fa82bfd | 31.579545 | 144 | 0.61737 | 5.212727 | false | false | false | false |
BBRick/wp | wp/Model/CreditModel.swift | 2 | 674 | //
// CreditModel.swift
// wp
//
// Created by macbook air on 17/1/4.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class CreditModel: BaseModel {
dynamic var rid: Int64 = 0 //充值订单流水号
dynamic var id: Int64 = 0 //用户id
dynamic var amount: Double = 0.0 //充值金额
dynamic var depositTime: Int64 = 0 //入金时间
dynamic var depositType: Int8 = 0 //入金方式:1.微信 2.银行卡
dynamic var depositName: String? //微信
dynamic var status: Int8 = 0 //1-处理中, 2-成功, 3-失败
}
| apache-2.0 | 47391fe469bd61522fc6a805ff040b0a | 27.619048 | 67 | 0.539101 | 3.376404 | false | false | false | false |
muxianer/FaceBook-Shimmer-Demo | Facebook Shimmer Demo/Facebook Shimmer Demo/ViewController.swift | 1 | 3686 | //
// ViewController.swift
// Facebook Shimmer Demo
//
// Created by Arivn Ren on 15/8/4.
// Copyright (c) 2015年 Arivn Ren. All rights reserved.
//
import UIKit
import QuartzCore
class ViewController: UIViewController {
var timer: NSTimer!
var dateFormatter: NSDateFormatter!
@IBOutlet var clockLabel: UILabel!
@IBOutlet var tapGestureRecognizer: UITapGestureRecognizer!
@IBOutlet var shimmeringView: FBShimmeringView!
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateClock"), userInfo: nil, repeats: true)
dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
shimmeringView.contentView = clockLabel
shimmeringView.shimmering = true
// 两次划过之间的时间间隔
shimmeringView.shimmeringPauseDuration = 1
// 高亮划过时的不透明度
shimmeringView.shimmeringAnimationOpacity = 0.5
// 不透明度
shimmeringView.shimmeringOpacity = 1.0
// 高亮部分滑动的速度
shimmeringView.shimmeringSpeed = 250
// 高亮部分的宽度
shimmeringView.shimmeringHighlightLength = 1.0
// 高亮部分滑动的方向
shimmeringView.shimmeringDirection = FBShimmerDirection.Right
//FBShimmerDirection.Right, Shimmer animation goes from left to right
//FBShimmerDirection.Left, Shimmer animation goes from right to left
//FBShimmerDirection.Up, Shimmer animation goes from below to above
//FBShimmerDirection.Down, Shimmer animation goes from above to below
shimmeringView.shimmeringBeginFadeDuration = 0.1
shimmeringView.shimmeringEndFadeDuration = 0.3
}
override func viewWillAppear(animated: Bool) {
updateClock()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// 每次要显示这个页面之前重置时间
UIApplication.sharedApplication().idleTimerDisabled = true
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
// 页面在显示期间不允许重置时间
UIApplication.sharedApplication().idleTimerDisabled = false
}
// 隐藏状态栏
override func prefersStatusBarHidden() -> Bool {
return true
}
func updateClock() {
var timeToDisplay = dateFormatter.stringFromDate(NSDate())
clockLabel.text = timeToDisplay
}
// 点击屏幕时调用
@IBAction func didTapView() {
tapGestureRecognizer.enabled = false
// 切换状态
shimmeringView.shimmering = !shimmeringView.shimmering
UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .CurveEaseIn, animations: {
// label显示的内容放大
self.clockLabel.transform = CGAffineTransformMakeScale(1.2, 1.2)
}, completion: { (finished) -> Void in
UIView.animateWithDuration(0.25, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .CurveEaseOut, animations: {
self.clockLabel.transform = CGAffineTransformIdentity
}, completion: {
(finished) -> Void in
self.tapGestureRecognizer.enabled = true
})
})
}
}
| mit | fa77df601f10e3732d8ff5827ba5609a | 33.8 | 153 | 0.647701 | 5.272727 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | AppEdadDeMiPerro/AppEdadDeMiPerro/ViewController.swift | 1 | 1853 | //
// ViewController.swift
// App_EdadDeMiPerro
//
// Created by cice on 9/5/16.
// Copyright © 2016 Cice. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK: -VARIABLES LOCALES GLOBALES
var insertNewAge : Int?
//MARK: - IDOUTLET
@IBOutlet weak var myTextFieldTF: UITextField!
@IBOutlet weak var showMyDogAge: UILabel!
//MARK: -IBACTION
@IBAction func showNewAge(sender: AnyObject) {
insertNewAge = Int(myTextFieldTF.text!)
/* if let newAge = insertNewAge{
let showNewAge = newAge * 7
showMyDogAge.text = "La edad de mi perro siendo calculada por mi Dueño es \(showNewAge)"
}else{
print("Coloca la edad de tu perrillo por favor")
}*/
if insertNewAge != nil{
let showNewAge = insertNewAge! * 7
showMyDogAge.text = "La edad de mi perro siendo calculada por mi Dueño es \(showNewAge)"
}else{
displayAVC()
}
}
//MARK: - LIVE VC
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.
}
//MARK:- UTILS
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func displayAVC(){
let alertVC = UIAlertController(title: "hey", message: "Por favor introduce la edad de tu perro", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertVC.addAction(alertAction)
presentViewController(alertVC, animated: true, completion: nil)
}
}
| apache-2.0 | 1d8de4a0496cd85c1699adad49c2a572 | 27.461538 | 129 | 0.63027 | 4.176072 | false | false | false | false |
wbaumann/SmartReceiptsiOS | SmartReceipts/Common/UI/NumberKeyboard.swift | 2 | 2043 | //
// NumberKeyboard.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 06/03/2018.
// Copyright © 2018 Will Baumann. All rights reserved.
//
import UIKit
protocol NumberKeyboardDelegate: class {
func didRemove()
func didInsert(char: String)
}
class NumberKeyboard: UIView, UIInputViewAudioFeedback {
var delegate: NumberKeyboardDelegate?
@IBOutlet weak var decimalSeparator: UIButton!
@IBOutlet var roundedViews: [UIButton]!
class func create(delegate: NumberKeyboardDelegate? = nil) -> NumberKeyboard {
let nib = "NumberKeyboard"
let keyboard = Bundle.main.loadNibNamed(nib, owner: nil, options: nil)!.first! as! NumberKeyboard
keyboard.delegate = delegate
return keyboard
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
private func initialize() {
decimalSeparator.setTitle(Locale.current.decimalSeparator, for: .normal)
for view in roundedViews {
view.layer.cornerRadius = AppTheme.buttonCornerRadius
view.layer.borderColor = #colorLiteral(red: 0.9137254902, green: 0.9098039216, blue: 0.9254901961, alpha: 1)
view.layer.borderWidth = 1
}
}
//MARK: - Actions
@IBAction func charTap(button: UIButton) {
guard let char = button.titleLabel?.text else { return }
UIDevice.current.playInputClick()
delegate?.didInsert(char: char)
}
@IBAction func removeTap() {
delegate?.didRemove()
UIDevice.current.playInputClick()
}
var enableInputClicksWhenVisible: Bool {
return true
}
}
extension UITextField: NumberKeyboardDelegate {
func didRemove() {
deleteBackward()
}
func didInsert(char: String) {
insertText(char)
}
}
| agpl-3.0 | 77cb825eef2feeebc646071ab86822c9 | 25.519481 | 120 | 0.63859 | 4.507726 | false | false | false | false |
smartystreets/smartystreets-ios-sdk | samples/Sources/swiftExamples/InternationalStreetExample.swift | 1 | 2481 | import Foundation
import SmartyStreets
class InternationalStreetExample {
func run() -> String {
let id = "ID"
let hostname = "Hostname"
// The appropriate license values to be used for your subscriptions
// can be found on the Subscriptions page of the account dashboard.
// https://www.smartystreets.com/docs/cloud/licensing
let client = ClientBuilder(id: id, hostname: hostname).withLicenses(licenses: ["international-global-plus-cloud"]).buildInternationalStreetApiClient()
// Documentation for input fields can be found at:
// https://smartystreets.com/docs/cloud/international-street-api#http-input-fields
var lookup = InternationalStreetLookup()
lookup.inputId = "ID-8675309"
lookup.organization = "John Doe"
lookup.address1 = "Rua Padre Antonio D'Angelo 121"
lookup.address2 = "Casa Verde"
lookup.locality = "Sao Paulo"
lookup.administrativeArea = "SP"
lookup.country = "Brazil"
lookup.postalCode = "02516-050"
lookup.enableGeocode(geocode: true)
var error: NSError! = nil
_ = client.sendLookup(lookup: &lookup, error:&error)
if let error = error {
let output = """
Domain: \(error.domain)
Error Code: \(error.code)
Description:\n\(error.userInfo[NSLocalizedDescriptionKey] as! NSString)
"""
NSLog(output)
return output
}
let results:[InternationalStreetCandidate] = lookup.result ?? []
var output = "Results:\n"
if results.count == 0 {
return "Error. Address is not valid"
}
let candidate = results[0]
if let analysis = candidate.analysis, let metadata = candidate.metadata {
output.append("""
\nAddress is \(analysis.verificationStatus ?? "")
\nAddress precision: \(analysis.addressPrecision ?? "")\n
\nFirst Line: \(candidate.address1 ?? "")
\nSecond Line: \(candidate.address2 ?? "")
\nThird Line: \(candidate.address3 ?? "")
\nFourth Line: \(candidate.address4 ?? "")
\nLatitude: \(metadata.latitude ?? 0)
\nLongitude: \(metadata.longitude ?? 0)
""")
}
return output
}
}
| apache-2.0 | 4386627b521b32fe326e140cdc0d9c36 | 39.016129 | 158 | 0.564289 | 4.725714 | false | false | false | false |
MobileToolkit/Tesseract | TesseractTests/Extensions.swift | 2 | 918 | //
// Extensions.swift
// Tesseract
//
// Created by Sebastian Owodzin on 12/09/2015.
// Copyright © 2015 mobiletoolkit.org. All rights reserved.
//
import Foundation
extension Bootstrap: Equatable {}
func ==(lhs: Bootstrap, rhs: Bootstrap) -> Bool {
return lhs.intParam == rhs.intParam && lhs.stringParam == rhs.stringParam && lhs.floatParam == rhs.floatParam && lhs.boolParam == rhs.boolParam
}
extension Config: Equatable {}
func ==(lhs: Config, rhs: Config) -> Bool {
return lhs.appName == rhs.appName && lhs.appBundle == rhs.appBundle && lhs.appVersion == rhs.appVersion
}
extension Product: Equatable {}
func ==(lhs: Product, rhs: Product) -> Bool {
return lhs.id == rhs.id && lhs.name == rhs.name && lhs.price == rhs.price
}
extension Setting: Equatable {}
func ==(lhs: Setting, rhs: Setting) -> Bool {
return lhs.id == rhs.id && lhs.title == rhs.title && lhs.value == rhs.value
}
| mit | c43e9cc0b13a130e620b381b4bfd00b2 | 26.787879 | 147 | 0.667394 | 3.421642 | false | true | false | false |
antigp/Alamofire | Tests/UploadTests.swift | 1 | 31693 | //
// UploadTests.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
import XCTest
#if !SWIFT_PACKAGE
final class UploadFileInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndFile() {
// Given
let requestURL = Endpoint.method(.post).url
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
let expectation = self.expectation(description: "upload should complete")
// When
let request = AF.upload(imageURL, to: requestURL).response { _ in
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url, requestURL, "request URL should be equal")
XCTAssertNotNil(request.response, "response should not be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndFile() {
// Given
let requestURL = Endpoint.method(.post).url
let headers: HTTPHeaders = ["Authorization": "123456"]
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
let expectation = self.expectation(description: "upload should complete")
// When
let request = AF.upload(imageURL, to: requestURL, method: .post, headers: headers).response { _ in
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url, requestURL, "request URL should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNotNil(request.response, "response should not be nil")
}
}
#endif
// MARK: -
final class UploadDataInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndData() {
// Given
let url = Endpoint.method(.post).url
let expectation = self.expectation(description: "upload should complete")
// When
let request = AF.upload(Data(), to: url).response { _ in
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url, url, "request URL should be equal")
XCTAssertNotNil(request.response, "response should not be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndData() {
// Given
let url = Endpoint.method(.post).url
let headers: HTTPHeaders = ["Authorization": "123456"]
let expectation = self.expectation(description: "upload should complete")
// When
let request = AF.upload(Data(), to: url, headers: headers).response { _ in
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url, url, "request URL should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNotNil(request.response, "response should not be nil")
}
}
// MARK: -
#if !SWIFT_PACKAGE
final class UploadStreamInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndStream() {
// Given
let requestURL = Endpoint.method(.post).url
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
let imageStream = InputStream(url: imageURL)!
let expectation = self.expectation(description: "upload should complete")
// When
let request = AF.upload(imageStream, to: requestURL).response { _ in
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url, requestURL, "request URL should be equal")
XCTAssertNotNil(request.response, "response should not be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndStream() {
// Given
let requestURL = Endpoint.method(.post).url
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
let headers: HTTPHeaders = ["Authorization": "123456"]
let imageStream = InputStream(url: imageURL)!
let expectation = self.expectation(description: "upload should complete")
// When
let request = AF.upload(imageStream, to: requestURL, headers: headers).response { _ in
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url, requestURL, "request URL should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNotNil(request.response, "response should not be nil, tasks: \(request.tasks)")
}
}
#endif
// MARK: -
final class UploadDataTestCase: BaseTestCase {
func testUploadDataRequest() {
// Given
let url = Endpoint.method(.post).url
let data = Data("Lorem ipsum dolor sit amet".utf8)
let expectation = self.expectation(description: "Upload request should succeed: \(url)")
var response: DataResponse<Data?, AFError>?
// When
AF.upload(data, to: url)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNil(response?.error)
}
func testUploadDataRequestWithProgress() {
// Given
let url = Endpoint.method(.post).url
let string = String(repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ", count: 300)
let data = Data(string.utf8)
let expectation = self.expectation(description: "Bytes upload progress should be reported: \(url)")
var uploadProgressValues: [Double] = []
var downloadProgressValues: [Double] = []
var response: DataResponse<Data?, AFError>?
// When
AF.upload(data, to: url)
.uploadProgress { progress in
uploadProgressValues.append(progress.fractionCompleted)
}
.downloadProgress { progress in
downloadProgressValues.append(progress.fractionCompleted)
}
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0
for progress in uploadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousUploadProgress)
previousUploadProgress = progress
}
if let lastProgressValue = uploadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in uploadProgressValues should not be nil")
}
var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0
for progress in downloadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress)
previousDownloadProgress = progress
}
if let lastProgressValue = downloadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in downloadProgressValues should not be nil")
}
}
}
// MARK: -
final class UploadMultipartFormDataTestCase: BaseTestCase {
// MARK: Tests
func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
// Given
let url = Endpoint.method(.post).url
let uploadData = Data("upload_data".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var formData: MultipartFormData?
var response: DataResponse<Data?, AFError>?
// When
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "upload_data")
formData = multipartFormData
},
to: url)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
if
let request = response?.request,
let multipartFormData = formData,
let contentType = request.value(forHTTPHeaderField: "Content-Type") {
XCTAssertEqual(contentType, multipartFormData.contentType)
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatCustomBoundaryCanBeSetWhenUploadingMultipartFormData() throws {
// Given
let uploadData = Data("upload_data".utf8)
let formData = MultipartFormData(fileManager: .default, boundary: "custom-test-boundary")
formData.append(uploadData, withName: "upload_data")
let expectation = self.expectation(description: "multipart form data upload should succeed")
var response: DataResponse<Data?, AFError>?
// When
AF.upload(multipartFormData: formData, with: Endpoint.method(.post)).response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
if let request = response?.request, let contentType = request.value(forHTTPHeaderField: "Content-Type") {
XCTAssertEqual(contentType, formData.contentType)
XCTAssertTrue(contentType.contains("boundary=custom-test-boundary"))
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
// Given
let frenchData = Data("français".utf8)
let japaneseData = Data("日本語".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var response: DataResponse<Data?, AFError>?
// When
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(frenchData, withName: "french")
multipartFormData.append(japaneseData, withName: "japanese")
},
to: Endpoint.method(.post))
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
}
func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
// Given
let frenchData = Data("français".utf8)
let japaneseData = Data("日本語".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var response: DataResponse<Data?, AFError>?
// When
let request = AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(frenchData, withName: "french")
multipartFormData.append(japaneseData, withName: "japanese")
},
to: Endpoint.method(.post))
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
guard let uploadable = request.uploadable, case .data = uploadable else {
XCTFail("Uploadable is not .data")
return
}
XCTAssertTrue(response?.result.isSuccess == true)
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
// Given
let uploadData = Data("upload_data".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var formData: MultipartFormData?
var response: DataResponse<Data?, AFError>?
// When
let request = AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "upload_data")
formData = multipartFormData
},
to: Endpoint.method(.post))
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
guard let uploadable = request.uploadable, case .data = uploadable else {
XCTFail("Uploadable is not .data")
return
}
if
let request = response?.request,
let multipartFormData = formData,
let contentType = request.value(forHTTPHeaderField: "Content-Type") {
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
// Given
let frenchData = Data("français".utf8)
let japaneseData = Data("日本語".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var response: DataResponse<Data?, AFError>?
// When
let request = AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(frenchData, withName: "french")
multipartFormData.append(japaneseData, withName: "japanese")
},
to: Endpoint.method(.post),
usingThreshold: 0).response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
guard let uploadable = request.uploadable, case let .file(url, _) = uploadable else {
XCTFail("Uploadable is not .file")
return
}
XCTAssertTrue(response?.result.isSuccess == true)
XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
// Given
let uploadData = Data("upload_data".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var response: DataResponse<Data?, AFError>?
var formData: MultipartFormData?
// When
let request = AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "upload_data")
formData = multipartFormData
},
to: Endpoint.method(.post),
usingThreshold: 0).response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
guard let uploadable = request.uploadable, case .file = uploadable else {
XCTFail("Uploadable is not .file")
return
}
XCTAssertTrue(response?.result.isSuccess == true)
if
let request = response?.request,
let multipartFormData = formData,
let contentType = request.value(forHTTPHeaderField: "Content-Type") {
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataWithNonexistentFileThrowsAnError() {
// Given
let imageURL = URL(fileURLWithPath: "does_not_exist.jpg")
let expectation = self.expectation(description: "multipart form data upload from nonexistent file should fail")
var response: DataResponse<Data?, AFError>?
// When
let request = AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageURL, withName: "upload_file")
},
to: Endpoint.method(.post),
usingThreshold: 0).response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNil(request.uploadable)
XCTAssertTrue(response?.result.isSuccess == false)
}
#if os(macOS)
func disabled_testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
// Given
let manager: Session = {
let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)"
let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
return Session(configuration: configuration)
}()
let french = Data("français".utf8)
let japanese = Data("日本語".utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: AFError?
// When
let upload = manager.upload(multipartFormData: { multipartFormData in
multipartFormData.append(french, withName: "french")
multipartFormData.append(japanese, withName: "japanese")
},
to: Endpoint.method(.post))
.response { defaultResponse in
request = defaultResponse.request
response = defaultResponse.response
data = defaultResponse.data
error = defaultResponse.error
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
guard let uploadable = upload.uploadable, case .file = uploadable else {
XCTFail("Uploadable is not .file")
return
}
}
#endif
// MARK: Combined Test Execution
private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
// Given
let loremData1 = Data(String(repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
count: 100).utf8)
let loremData2 = Data(String(repeating: "Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.",
count: 100).utf8)
let expectation = self.expectation(description: "multipart form data upload should succeed")
var uploadProgressValues: [Double] = []
var downloadProgressValues: [Double] = []
var response: DataResponse<Data?, AFError>?
// When
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(loremData1, withName: "lorem1")
multipartFormData.append(loremData2, withName: "lorem2")
},
to: Endpoint.method(.post),
usingThreshold: streamFromDisk ? 0 : 100_000_000)
.uploadProgress { progress in
uploadProgressValues.append(progress.fractionCompleted)
}
.downloadProgress { progress in
downloadProgressValues.append(progress.fractionCompleted)
}
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0
for progress in uploadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousUploadProgress)
previousUploadProgress = progress
}
if let lastProgressValue = uploadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in uploadProgressValues should not be nil")
}
var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0
for progress in downloadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress)
previousDownloadProgress = progress
}
if let lastProgressValue = downloadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in downloadProgressValues should not be nil")
}
}
}
final class UploadRetryTests: BaseTestCase {
func testThatDataUploadRetriesCorrectly() {
// Given
let endpoint = Endpoint(path: .delay(interval: 1),
method: .post,
headers: [.contentType("text/plain")],
timeout: 0.1)
let retrier = InspectorInterceptor(SingleRetrier())
let didRetry = expectation(description: "request did retry")
retrier.onRetry = { _ in didRetry.fulfill() }
let session = Session(interceptor: retrier)
let body = "body"
let data = Data(body.utf8)
var response: AFDataResponse<TestResponse>?
let completion = expectation(description: "upload should complete")
// When
session.upload(data, with: endpoint).responseDecodable(of: TestResponse.self) {
response = $0
completion.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(retrier.retryCalledCount, 1)
XCTAssertTrue(response?.result.isSuccess == true)
XCTAssertEqual(response?.value?.data, body)
}
}
final class UploadRequestEventsTestCase: BaseTestCase {
func testThatUploadRequestTriggersAllAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(eventMonitors: [eventMonitor])
let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
let didCreateTask = expectation(description: "didCreateTask should fire")
let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
let didComplete = expectation(description: "didComplete should fire")
let didFinish = expectation(description: "didFinish should fire")
let didResume = expectation(description: "didResume should fire")
let didResumeTask = expectation(description: "didResumeTask should fire")
let didCreateUploadable = expectation(description: "didCreateUploadable should fire")
let didParseResponse = expectation(description: "didParseResponse should fire")
let responseHandler = expectation(description: "responseHandler should fire")
eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
eventMonitor.requestDidResume = { _ in didResume.fulfill() }
eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() }
eventMonitor.requestDidCreateUploadable = { _, _ in didCreateUploadable.fulfill() }
eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
// When
let request = session.upload(Data("PAYLOAD".utf8),
with: Endpoint.method(.post)).response { _ in
responseHandler.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .finished)
}
func testThatCancelledUploadRequestTriggersAllAppropriateLifetimeEvents() {
// Given
let eventMonitor = ClosureEventMonitor()
let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor])
let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire")
let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire")
let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire")
let didCreateTask = expectation(description: "didCreateTask should fire")
let didGatherMetrics = expectation(description: "didGatherMetrics should fire")
let didComplete = expectation(description: "didComplete should fire")
let didFinish = expectation(description: "didFinish should fire")
let didResume = expectation(description: "didResume should fire")
let didResumeTask = expectation(description: "didResumeTask should fire")
let didCreateUploadable = expectation(description: "didCreateUploadable should fire")
let didParseResponse = expectation(description: "didParseResponse should fire")
let didCancel = expectation(description: "didCancel should fire")
let didCancelTask = expectation(description: "didCancelTask should fire")
let responseHandler = expectation(description: "responseHandler should fire")
eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() }
eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() }
eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() }
eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() }
eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() }
eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() }
eventMonitor.requestDidFinish = { _ in didFinish.fulfill() }
eventMonitor.requestDidResume = { _ in didResume.fulfill() }
eventMonitor.requestDidCreateUploadable = { _, _ in didCreateUploadable.fulfill() }
eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() }
eventMonitor.requestDidCancel = { _ in didCancel.fulfill() }
eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() }
// When
let request = session.upload(Data("PAYLOAD".utf8),
with: Endpoint.delay(5).modifying(\.method, to: .post)).response { _ in
responseHandler.fulfill()
}
eventMonitor.requestDidResumeTask = { [unowned request] _, _ in
request.cancel()
didResumeTask.fulfill()
}
request.resume()
waitForExpectations(timeout: timeout)
// Then
XCTAssertEqual(request.state, .cancelled)
}
}
| mit | ff1bb6a3d90ce14f9298e53ed8230ae7 | 39.33758 | 119 | 0.637518 | 5.537775 | false | true | false | false |
ZezhouLi/Virtual-Keyboard | Virtual Keyboard/VKFFT.swift | 1 | 15218 | //
// VKFFT.swift
// Virtual Keyboard
//
// Created by Zezhou Li on 12/15/16.
// Copyright © 2016 Zezhou Li. All rights reserved.
//
// Framework
import Foundation
import Accelerate
enum VKFFTWindowType: NSInteger {
case none
case hanning
case hamming
}
class VKFFT : NSObject {
/// The length of the sample buffer we'll be analyzing.
private(set) var size: Int
/// The sample rate provided at init time.
private(set) var sampleRate: Float
/// The Nyquist frequency is ```sampleRate``` / 2
var nyquistFrequency: Float {
get {
return sampleRate / 2.0
}
}
// After performing the FFT, contains size/2 magnitudes, one for each frequency band.
private var magnitudes: [Float]!
/// After calling calculateLinearBands() or calculateLogarithmicBands(), contains a magnitude for each band.
private(set) var bandMagnitudes: [Float]!
/// After calling calculateLinearBands() or calculateLogarithmicBands(), contains the average frequency for each band
private(set) var bandFrequencies: [Float]!
/// The average bandwidth throughout the spectrum (nyquist / magnitudes.count)
var bandwidth: Float {
get {
return self.nyquistFrequency / Float(self.magnitudes.count)
}
}
/// The number of calculated bands (must call calculateLinearBands() or calculateLogarithmicBands() first).
private(set) var numberOfBands: Int = 0
/// The minimum and maximum frequencies in the calculated band spectrum (must call calculateLinearBands() or calculateLogarithmicBands() first).
private(set) var bandMinFreq, bandMaxFreq: Float!
/// Supplying a window type (hanning or hamming) smooths the edges of the incoming waveform and reduces output errors from the FFT function (aka "spectral leakage" - ewww).
var windowType = VKFFTWindowType.none
private var halfSize:Int
private var log2Size:Int
private var window:[Float]!
private var fftSetup:FFTSetup
private var hasPerformedFFT: Bool = false
private var complexBuffer: DSPSplitComplex!
private var FFTNormFactor: Float32
private final var kAdjust0DB: Float32 = 1.5849e-13
private var kAdjustDB: Float32 = 128.0
private var fftresult = [[Float]]()
/// Instantiate the FFT.
/// - Parameter withSize: The length of the sample buffer we'll be analyzing. Must be a power of 2. The resulting ```magnitudes``` are of length ```inSize/2```.
/// - Parameter sampleRate: Sampling rate of the provided audio data.
init(withSize inSize:Int, sampleRate inSampleRate: Float) {
let sizeFloat: Float = Float(inSize)
self.sampleRate = inSampleRate
// Check if the size is a power of two
let lg2 = logbf(sizeFloat)
assert(remainderf(sizeFloat, powf(2.0, lg2)) == 0, "size must be a power of 2")
self.size = inSize
self.halfSize = inSize / 2
self.FFTNormFactor = 1.0/Float32(2*inSize)
// create fft setup
self.log2Size = Int(log2f(sizeFloat))
self.fftSetup = vDSP_create_fftsetup(UInt(log2Size), FFTRadix(FFT_RADIX2))!
// Init the complexBuffer
var real = [Float](repeating: 0.0, count: self.halfSize)
var imaginary = [Float](repeating: 0.0, count: self.halfSize)
self.complexBuffer = DSPSplitComplex(realp: &real, imagp: &imaginary)
}
deinit {
// destroy the fft setup object
vDSP_destroy_fftsetup(fftSetup)
}
/// Perform a forward FFT on the provided single-channel audio data. When complete, the instance can be queried for information about the analysis or the magnitudes can be accessed directly.
/// - Parameter inMonoBuffer: Audio data in mono format
func fftForward(_ inMonoBuffer:[Float]) {
let analysisBuffer = inMonoBuffer
// If we have a window, apply it now. Since 99.9% of the time the window array will be exactly the same, an optimization would be to create it once and cache it, possibly caching it by size.
// if self.windowType != .none {
//
// if self.window == nil {
// self.window = [Float](repeating: 0.0, count: size)
//
// switch self.windowType {
// case .hamming:
// vDSP_hann_window(&self.window!, UInt(size), Int32(vDSP_HANN_NORM))
// case .hanning:
// vDSP_hamm_window(&self.window!, UInt(size), 0)
// default:
// break
// }
// }
//
// // Apply the window
// vDSP_vmul(inMonoBuffer, 1, self.window, 1, &analysisBuffer, 1, UInt(inMonoBuffer.count))
// }
// Doing the job of vDSP_ctoz. (See below.)
var reals = [Float]()
var imags = [Float]()
for (idx, element) in analysisBuffer.enumerated() {
if idx % 2 == 0 {
reals.append(element)
} else {
imags.append(element)
}
}
self.complexBuffer = DSPSplitComplex(realp: UnsafeMutablePointer(mutating: reals), imagp: UnsafeMutablePointer(mutating: imags))
// Perform a forward FFT
vDSP_fft_zrip(self.fftSetup, &(self.complexBuffer!), 1, UInt(self.log2Size), Int32(FFT_FORWARD))
vDSP_vsmul(complexBuffer.realp, 1, &FFTNormFactor, complexBuffer.realp, 1, vDSP_Length(halfSize))
vDSP_vsmul(complexBuffer.imagp, 1, &FFTNormFactor, complexBuffer.imagp, 1, vDSP_Length(halfSize))
complexBuffer.imagp[0] = 0.0
// Store and square (for better visualization & conversion to db) the magnitudes
self.magnitudes = [Float](repeating: 0.0, count: self.halfSize)
vDSP_zvmags(&(self.complexBuffer!), 1, &self.magnitudes!, 1, UInt(self.halfSize))
self.hasPerformedFFT = true
}
/// Applies logical banding on top of the spectrum data. The bands are spaced linearly throughout the spectrum.
func calculateLinearBands(minFrequency: Float, maxFrequency: Float, numberOfBands: Int) {
assert(hasPerformedFFT, "*** Perform the FFT first.")
let actualMaxFrequency = min(self.nyquistFrequency, maxFrequency)
self.numberOfBands = numberOfBands
self.bandMagnitudes = [Float](repeating: 0.0, count: numberOfBands)
self.bandFrequencies = [Float](repeating: 0.0, count: numberOfBands)
let magLowerRange = magIndexForFreq(minFrequency)
let magUpperRange = magIndexForFreq(actualMaxFrequency)
let ratio: Float = Float(magUpperRange - magLowerRange) / Float(numberOfBands)
for i in 0..<numberOfBands {
let magsStartIdx: Int = Int(floorf(Float(i) * ratio)) + magLowerRange
let magsEndIdx: Int = Int(floorf(Float(i + 1) * ratio)) + magLowerRange
var magsAvg: Float
if magsEndIdx == magsStartIdx {
// Can happen when numberOfBands < # of magnitudes. No need to average anything.
magsAvg = self.magnitudes[magsStartIdx]
} else {
magsAvg = fastAverage(self.magnitudes, magsStartIdx, magsEndIdx)
}
self.bandMagnitudes[i] = magsAvg
self.bandFrequencies[i] = self.averageFrequencyInRange(magsStartIdx, magsEndIdx)
}
self.bandMinFreq = self.bandFrequencies[0]
self.bandMaxFreq = self.bandFrequencies.last
}
/// Applies logical banding on top of the spectrum data. The bands are grouped by octave throughout the spectrum. Note that the actual min and max frequencies in the resulting band may be lower/higher than the minFrequency/maxFrequency because the band spectrum <i>includes</i> those frequencies but isn't necessarily bounded by them.
func calculateLogarithmicBands(minFrequency: Float, maxFrequency: Float, bandsPerOctave: Int) {
assert(hasPerformedFFT, "*** Perform the FFT first.")
// The max can't be any higher than the nyquist
let actualMaxFrequency = min(self.nyquistFrequency, maxFrequency)
// The min can't be 0 otherwise we'll divide octaves infinitely
let actualMinFrequency = max(1, minFrequency)
// Define the octave frequencies we'll be working with. Note that in order to always include minFrequency, we'll have to set the lower boundary to the octave just below that frequency.
var octaveBoundaryFreqs: [Float] = [Float]()
var curFreq = actualMaxFrequency
octaveBoundaryFreqs.append(curFreq)
repeat {
curFreq /= 2
octaveBoundaryFreqs.append(curFreq)
} while curFreq > actualMinFrequency
octaveBoundaryFreqs = octaveBoundaryFreqs.reversed()
self.bandMagnitudes = [Float]()
self.bandFrequencies = [Float]()
// Break up the spectrum by octave
for i in 0..<octaveBoundaryFreqs.count - 1 {
let lowerFreq = octaveBoundaryFreqs[i]
let upperFreq = octaveBoundaryFreqs[i+1]
let mags = self.magsInFreqRange(lowerFreq, upperFreq)
let ratio = Float(mags.count) / Float(bandsPerOctave)
// Now that we have the magnitudes within this octave, cluster them into bandsPerOctave groups and average each group.
for j in 0..<bandsPerOctave {
let startIdx = Int(ratio * Float(j))
var stopIdx = Int(ratio * Float(j+1)) - 1 // inclusive
stopIdx = max(0, stopIdx)
if stopIdx <= startIdx {
self.bandMagnitudes.append(mags[startIdx])
} else {
let avg = fastAverage(mags, startIdx, stopIdx + 1)
self.bandMagnitudes.append(avg)
}
let startMagnitudesIdx = Int(lowerFreq / self.bandwidth) + startIdx
let endMagnitudesIdx = startMagnitudesIdx + (stopIdx - startIdx)
self.bandFrequencies.append(self.averageFrequencyInRange(startMagnitudesIdx, endMagnitudesIdx))
}
}
self.numberOfBands = self.bandMagnitudes.count
self.bandMinFreq = self.bandFrequencies[0]
self.bandMaxFreq = self.bandFrequencies.last
}
private func magIndexForFreq(_ freq: Float) -> Int {
return Int(Float(self.magnitudes.count) * freq / self.nyquistFrequency)
}
// On arrays of 1024 elements, this is ~35x faster than an iterational algorithm. Thanks Accelerate.framework!
@inline(__always) private func fastAverage(_ array:[Float], _ startIdx: Int, _ stopIdx: Int) -> Float {
var mean: Float = 0
let ptr = UnsafePointer<Float>(array)
vDSP_meanv(ptr + startIdx, 1, &mean, UInt(stopIdx - startIdx))
return mean
}
@inline(__always) private func magsInFreqRange(_ lowFreq: Float, _ highFreq: Float) -> [Float] {
let lowIndex = Int(lowFreq / self.bandwidth)
var highIndex = Int(highFreq / self.bandwidth)
if (lowIndex == highIndex) {
// Occurs when both params are so small that they both fall into the first index
highIndex += 1
}
return Array(self.magnitudes[lowIndex..<highIndex])
}
@inline(__always) private func averageFrequencyInRange(_ startIndex: Int, _ endIndex: Int) -> Float {
return (self.bandwidth * Float(startIndex) + self.bandwidth * Float(endIndex)) / 2
}
/// Get the magnitude for the specified frequency band.
/// - Parameter inBand: The frequency band you want a magnitude for.
func magnitudeAtBand(_ inBand: Int) -> Float {
assert(hasPerformedFFT, "*** Perform the FFT first.")
assert(bandMagnitudes != nil, "*** Call calculateLinearBands() or calculateLogarithmicBands() first")
return bandMagnitudes[inBand]
}
/// Get the magnitude of the requested frequency in the spectrum.
/// - Parameter inFrequency: The requested frequency. Must be less than the Nyquist frequency (```sampleRate/2```).
/// - Returns: A magnitude.
func magnitudeAtFrequency(_ inFrequency: Float) -> Float {
assert(hasPerformedFFT, "*** Perform the FFT first.")
let index = Int(floorf(inFrequency / self.bandwidth ))
return self.magnitudes[index]
}
/// Get the middle frequency of the Nth band.
/// - Parameter inBand: An index where 0 <= inBand < size / 2.
/// - Returns: The middle frequency of the provided band.
func frequencyAtBand(_ inBand: Int) -> Float {
assert(hasPerformedFFT, "*** Perform the FFT first.")
assert(bandMagnitudes != nil, "*** Call calculateLinearBands() or calculateLogarithmicBands() first")
return self.bandFrequencies[inBand]
}
/// Calculate the average magnitude of the frequency band bounded by lowFreq and highFreq, inclusive
func averageMagnitude(lowFreq: Float, highFreq: Float) -> Float {
var curFreq = lowFreq
var total: Float = 0
var count: Int = 0
while curFreq <= highFreq {
total += magnitudeAtFrequency(curFreq)
curFreq += self.bandwidth
count += 1
}
return total / Float(count)
}
/// Sum magnitudes across bands bounded by lowFreq and highFreq, inclusive
func sumMagnitudes(lowFreq: Float, highFreq: Float, useDB: Bool) -> Float {
var curFreq = lowFreq
var total: Float = 0
while curFreq <= highFreq {
var mag = magnitudeAtFrequency(curFreq)
if (useDB) {
mag = max(0, VKFFT.toDB(mag))
}
total += mag
curFreq += self.bandwidth
}
return total
}
/// A convenience function that converts a linear magnitude (like those stored in ```magnitudes```) to db (which is log 10).
class func toDB(_ inMagnitude: Float) -> Float {
// ceil to 128db in order to avoid log10'ing 0
let magnitude = max(inMagnitude, 0.000000000001)
return 10 * log10f(magnitude)
}
private func ReturnMagnitudes() -> [Float] {
return magnitudes
}
func GetFFTResult(_ TotalFrames: Int, _ AudioSample: [Float]) {
let newFrames = Int(powf(2.0, Float(Int(log2(Float(TotalFrames))))))
windowType = VKFFTWindowType.hanning
let newarray = Array(AudioSample[0..<newFrames])
var currentFrame = 0
for i in 0..<newFrames / 4096 / 10 {
currentFrame = i*4096*10
if currentFrame > newFrames {
break
}
fftForward(Array(newarray[currentFrame..<currentFrame+4096*10]))
fftresult.append(ReturnMagnitudes())
}
}
func ReturnFFTResult() -> [[Float]] {
return fftresult
}
}
| apache-2.0 | 101be7e92afb8b3498d6d963cf53a6ab | 41.035912 | 338 | 0.618124 | 4.50607 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.