repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
IngmarStein/swift | refs/heads/master | stdlib/public/core/ReflectionLegacy.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// How children of this value should be presented in the IDE.
public enum _MirrorDisposition {
/// As a struct.
case `struct`
/// As a class.
case `class`
/// As an enum.
case `enum`
/// As a tuple.
case tuple
/// As a miscellaneous aggregate with a fixed set of children.
case aggregate
/// As a container that is accessed by index.
case indexContainer
/// As a container that is accessed by key.
case keyContainer
/// As a container that represents membership of its values.
case membershipContainer
/// As a miscellaneous container with a variable number of children.
case container
/// An Optional which can have either zero or one children.
case optional
/// An Objective-C object imported in Swift.
case objCObject
}
/// The type returned by `_reflect(x)`; supplies an API for runtime
/// reflection on `x`.
public protocol _Mirror {
/// The instance being reflected.
var value: Any { get }
/// Identical to `type(of: value)`.
var valueType: Any.Type { get }
/// A unique identifier for `value` if it is a class instance; `nil`
/// otherwise.
var objectIdentifier: ObjectIdentifier? { get }
/// The count of `value`'s logical children.
var count: Int { get }
/// Get a name and mirror for the `i`th logical child.
subscript(i: Int) -> (String, _Mirror) { get }
/// A string description of `value`.
var summary: String { get }
/// A rich representation of `value` for an IDE, or `nil` if none is supplied.
var quickLookObject: PlaygroundQuickLook? { get }
/// How `value` should be presented in an IDE.
var disposition: _MirrorDisposition { get }
}
/// An entry point that can be called from C++ code to get the summary string
/// for an arbitrary object. The memory pointed to by "out" is initialized with
/// the summary string.
@_silgen_name("swift_getSummary")
public // COMPILER_INTRINSIC
func _getSummary<T>(_ out: UnsafeMutablePointer<String>, x: T) {
out.initialize(to: String(reflecting: x))
}
/// Produce a mirror for any value. The runtime produces a mirror that
/// structurally reflects values of any type.
@_silgen_name("swift_reflectAny")
internal func _reflect<T>(_ x: T) -> _Mirror
// -- Implementation details for the runtime's _Mirror implementation
@_silgen_name("swift_MagicMirrorData_summary")
func _swift_MagicMirrorData_summaryImpl(
_ metadata: Any.Type, _ result: UnsafeMutablePointer<String>
)
@_fixed_layout
public struct _MagicMirrorData {
let owner: Builtin.NativeObject
let ptr: Builtin.RawPointer
let metadata: Any.Type
var value: Any {
@_silgen_name("swift_MagicMirrorData_value")get
}
var valueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_valueType")get
}
public var objcValue: Any {
@_silgen_name("swift_MagicMirrorData_objcValue")get
}
public var objcValueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_objcValueType")get
}
var summary: String {
let (_, result) = _withUninitializedString {
_swift_MagicMirrorData_summaryImpl(self.metadata, $0)
}
return result
}
public func _loadValue<T>(ofType _: T.Type) -> T {
return Builtin.load(ptr) as T
}
}
struct _OpaqueMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String { return data.summary }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .aggregate }
}
@_silgen_name("swift_TupleMirror_count")
func _getTupleCount(_: _MagicMirrorData) -> Int
// Like the other swift_*Mirror_subscript functions declared here and
// elsewhere, this is implemented in the runtime. The Swift CC would
// normally require the String to be returned directly and the _Mirror
// indirectly. However, Clang isn't currently capable of doing that
// reliably because the size of String exceeds the normal direct-return
// ABI rules on most platforms. Therefore, we make this function generic,
// which has the disadvantage of passing the String type metadata as an
// extra argument, but does force the string to be returned indirectly.
@_silgen_name("swift_TupleMirror_subscript")
func _getTupleChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
internal struct _TupleMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
return _getTupleCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getTupleChild(i, data)
}
var summary: String { return "(\(count) elements)" }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .tuple }
}
@_silgen_name("swift_StructMirror_count")
func _getStructCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_StructMirror_subscript")
func _getStructChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
struct _StructMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
return _getStructCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getStructChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`struct` }
}
@_silgen_name("swift_EnumMirror_count")
func _getEnumCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_EnumMirror_subscript")
func _getEnumChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
@_silgen_name("swift_EnumMirror_caseName")
func _swift_EnumMirror_caseName(
_ data: _MagicMirrorData) -> UnsafePointer<CChar>
struct _EnumMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
return _getEnumCount(data)
}
var caseName: UnsafePointer<CChar> {
return _swift_EnumMirror_caseName(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getEnumChild(i, data)
}
var summary: String {
let maybeCaseName = String(validatingUTF8: self.caseName)
let typeName = _typeName(valueType)
if let caseName = maybeCaseName {
return typeName + "." + caseName
}
return typeName
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`enum` }
}
@_silgen_name("swift_ClassMirror_count")
func _getClassCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_ClassMirror_subscript")
func _getClassChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
#if _runtime(_ObjC)
@_silgen_name("swift_ClassMirror_quickLookObject")
public func _swift_ClassMirror_quickLookObject(_: _MagicMirrorData) -> AnyObject
@_silgen_name("_swift_stdlib_NSObject_isKindOfClass")
internal func _swift_NSObject_isImpl(_ object: AnyObject, kindOf: AnyObject) -> Bool
internal func _is(_ object: AnyObject, kindOf `class`: String) -> Bool {
return _swift_NSObject_isImpl(object, kindOf: `class` as AnyObject)
}
func _getClassPlaygroundQuickLook(_ object: AnyObject) -> PlaygroundQuickLook? {
if _is(object, kindOf: "NSNumber") {
let number: _NSNumber = unsafeBitCast(object, to: _NSNumber.self)
switch UInt8(number.objCType[0]) {
case UInt8(ascii: "d"):
return .double(number.doubleValue)
case UInt8(ascii: "f"):
return .float(number.floatValue)
case UInt8(ascii: "Q"):
return .uInt(number.unsignedLongLongValue)
default:
return .int(number.longLongValue)
}
} else if _is(object, kindOf: "NSAttributedString") {
return .attributedString(object)
} else if _is(object, kindOf: "NSImage") ||
_is(object, kindOf: "UIImage") ||
_is(object, kindOf: "NSImageView") ||
_is(object, kindOf: "UIImageView") ||
_is(object, kindOf: "CIImage") ||
_is(object, kindOf: "NSBitmapImageRep") {
return .image(object)
} else if _is(object, kindOf: "NSColor") ||
_is(object, kindOf: "UIColor") {
return .color(object)
} else if _is(object, kindOf: "NSBezierPath") ||
_is(object, kindOf: "UIBezierPath") {
return .bezierPath(object)
} else if _is(object, kindOf: "NSString") {
return .text(_forceBridgeFromObjectiveC(object, String.self))
}
return .none
}
#endif
struct _ClassMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue(ofType: ObjectIdentifier.self)
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? {
#if _runtime(_ObjC)
let object = _swift_ClassMirror_quickLookObject(data)
return _getClassPlaygroundQuickLook(object)
#else
return nil
#endif
}
var disposition: _MirrorDisposition { return .`class` }
}
struct _ClassSuperMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
// Suppress the value identifier for super mirrors.
var objectIdentifier: ObjectIdentifier? {
return nil
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(data.metadata)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`class` }
}
struct _MetatypeMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue(ofType: ObjectIdentifier.self)
}
var count: Int {
return 0
}
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String {
return _typeName(data._loadValue(ofType: Any.Type.self))
}
var quickLookObject: PlaygroundQuickLook? { return nil }
// Special disposition for types?
var disposition: _MirrorDisposition { return .aggregate }
}
| da7e3126e0a499c3e40c063c2cec494a | 30.241667 | 84 | 0.68516 | false | false | false | false |
EgzonArifi/ToDoList | refs/heads/master | Sources/App/Models/Acronym.swift | mit | 1 | import Vapor
final class Acronym: Model {
var exist: Bool = false
var id: Node?
var short: String
var long: String
init(short: String, long: String) {
self.id = nil
self.short = short
self.long = long
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
short = try node.extract("short")
long = try node.extract("long")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id" : id,
"short" : short,
"long": long
])
}
static func prepare(_ database: Database) throws {
try database.create("acronyms") { users in
users.id()
users.string("short")
users.string("long")
}
}
static func revert(_ database: Database) throws {
try database.delete("acronyms")
}
}
| b406c7914db828a5e36465d922a78dfd | 21.166667 | 54 | 0.52739 | false | false | false | false |
azimin/Rainbow | refs/heads/master | Rainbow/Color.swift | mit | 1 | //
// ColorBase.swift
// Rainbow
//
// Created by Alex Zimin on 18/01/16.
// Copyright © 2016 Alex Zimin. All rights reserved.
//
import UIKit
enum RGB: String {
case Red
case Blue
case Green
}
struct ColorCollection {
var baseColor: UIColor
var rule: (() -> ())?
}
public struct Color {
var RGBVector: Vector3D
var alpha: Float = 1.0
init() {
RGBVector = Vector3D(x: 1.0, y: 1.0, z: 1.0)
}
init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1.0) {
RGBVector = Vector3D(x: red.toFloat(), y: green.toFloat(), z: blue.toFloat())
self.alpha = alpha.toFloat()
}
init(red: Double, green: Double, blue: Double, alpha: Double = 1.0) {
RGBVector = Vector3D(x: red.toFloat(), y: green.toFloat(), z: blue.toFloat())
self.alpha = alpha.toFloat()
}
init(red: Float, green: Float, blue: Float, alpha: Float = 1.0) {
RGBVector = Vector3D(x: red, y: green, z: blue)
self.alpha = alpha
}
init(color: UIColor) {
let cgColor = color.CGColor
let numberOfComponents = CGColorGetNumberOfComponents(cgColor)
let components = CGColorGetComponents(cgColor)
let red, green, blue, alpha: CGFloat
if numberOfComponents == 4 {
red = components[0]
green = components[1]
blue = components[2]
alpha = components[3]
} else {
red = components[0]
green = components[0]
blue = components[0]
alpha = components[1]
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
init?(color: UIColor?) {
guard let color = color else {
return nil
}
self.init(color: color)
}
init(hexString: String) {
var hex = hexString
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1))
}
if Color.isHexString(hex) {
if hex.characters.count == 3 {
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1))
let greenHex = hex.substringWithRange(Range<String.Index>(hex.startIndex.advancedBy(1)..<hex.startIndex.advancedBy(2)))
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2))
let greenHex = hex.substringWithRange(Range<String.Index>(hex.startIndex.advancedBy(2)..<hex.startIndex.advancedBy(4)))
let blueHex = hex.substringWithRange(Range<String.Index>(hex.startIndex.advancedBy(4)..<hex.startIndex.advancedBy(6)))
var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0
NSScanner(string: redHex).scanHexInt(&redInt)
NSScanner(string: greenHex).scanHexInt(&greenInt)
NSScanner(string: blueHex).scanHexInt(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: 1.0)
} else {
self.init()
}
}
static func isHexString(hexString: String) -> Bool {
var hex = hexString
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1))
}
return (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) != nil)
}
func colorWithAlphaComponent(alpha: Float) -> Color {
return Color(red: self.red(), green: self.green(), blue: self.blue(), alpha: alpha)
}
var name: String {
return ColorNamesCollection.getColorName(self)
}
var hexString: String {
let r: Float = self.red()
let g: Float = self.green()
let b: Float = self.blue()
return String(format: "%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
var UIColorValue: UIColor {
return UIColor(red: red(), green: green(), blue: blue(), alpha: alpha.toCGFloat())
}
var CGColorValue: CGColor {
return CGColorCreate(CGColorSpaceCreateDeviceRGB(), [self.red(), self.green(), self.blue(), self.alpha.toCGFloat()])!
}
var RGBClass: RGB {
var result: RGB = .Red
var minimalValue = ColorCompare(firstColor: self, secondColor: Color.redColor()).CIE76
let greenValue = ColorCompare(firstColor: self, secondColor: Color.greenColor()).CIE76
if greenValue < minimalValue {
minimalValue = greenValue
result = .Green
}
let blueValue = ColorCompare(firstColor: self, secondColor: Color.blueColor()).CIE76
if blueValue < minimalValue {
minimalValue = greenValue
result = .Blue
}
return result
}
} | 1784e300fb725791de7bdcc470474821 | 27.98125 | 127 | 0.631363 | false | false | false | false |
AKIRA-MIYAKE/OpenWeatherMapper | refs/heads/develop | 223-227. SelfSizingTabelViewCells/Pods/Alamofire/Source/Manager.swift | agpl-3.0 | 126 | // Manager.swift
//
// Copyright (c) 2014–2015 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 Foundation
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in (NSLocale.preferredLanguages() as [String]).enumerate() {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return components.joinWithSeparator(",")
}()
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
return mutableUserAgent as String
}
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
public var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
*/
public init(
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/**
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
- parameter session: The URL session.
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
*/
public init?(
session: NSURLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = Request(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) {
subdelegate = self.subdelegates[task.taskIdentifier]
}
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
}
/**
Initializes the `SessionDelegate` instance.
- returns: The new `SessionDelegate` instance.
*/
public override init() {
super.init()
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the session has been invalidated.
- parameter session: The session object that was invalidated.
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
*/
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/**
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
- parameter session: The session containing the task that requested authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
/**
Tells the delegate that all messages enqueued for a session have been delivered.
- parameter session: The session that no longer has any outstanding requests.
*/
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the remote server requested an HTTP redirect.
- parameter session: The session containing the task whose request resulted in a redirect.
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the server’s response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void))
{
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
- parameter session: The session containing the task whose request requires authentication.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge))
} else if let delegate = self[task] {
delegate.URLSession(
session,
task: task,
didReceiveChallenge: challenge,
completionHandler: completionHandler
)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
/**
Tells the delegate when a task requires a new request body stream to send to the remote server.
- parameter session: The session containing the task that needs a new body stream.
- parameter task: The task that needs a new body stream.
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
{
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/**
Periodically informs the delegate of the progress of sending body content to the server.
- parameter session: The session containing the data task.
- parameter task: The data task.
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
- parameter totalBytesSent: The total number of bytes sent so far.
- parameter totalBytesExpectedToSend: The expected length of the body data.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/**
Tells the delegate that the task finished transferring data.
- parameter session: The session containing the task whose request finished transferring data.
- parameter task: The task whose request finished transferring data.
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
*/
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
self[task] = nil
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
// MARK: Delegate Methods
/**
Tells the delegate that the data task received the initial reply (headers) from the server.
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
{
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/**
Tells the delegate that the data task was changed to a download task.
- parameter session: The session containing the task that was replaced by a download task.
- parameter dataTask: The data task that was replaced by a download task.
- parameter downloadTask: The new download task that replaced the data task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
/**
Tells the delegate that the data task has received some of the expected data.
- parameter session: The session containing the data task that provided data.
- parameter dataTask: The data task that provided data.
- parameter data: A data object containing the transferred data.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
/**
Asks the delegate whether the data (or upload) task should store the response in the cache.
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void))
{
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that a download task has finished downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your app’s sandbox
container directory before returning from this delegate method.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
/**
Periodically informs the delegate about the download’s progress.
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/**
Tells the delegate that the download task has resumed downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
// MARK: - NSURLSessionStreamDelegate
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return taskWillPerformHTTPRedirection != nil
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != nil
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
| 343017b30f1af2565baf766fd1d384f4 | 47.573446 | 169 | 0.640506 | false | false | false | false |
tomquist/ReverseJson | refs/heads/master | Tests/ReverseJsonModelExportTests/ModelToJsonTest.swift | mit | 1 |
import XCTest
import ReverseJsonCore
@testable import ReverseJsonModelExport
class ModelToJsonTest: XCTestCase {
func testSimpleString() {
let type: FieldType = .text
let json = type.toJSON(isRoot: false)
XCTAssertEqual("string", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testSimpleInt() {
let type: FieldType = .number(.int)
let json = type.toJSON(isRoot: false)
XCTAssertEqual("int", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testSimpleFloat() {
let type: FieldType = .number(.float)
let json = type.toJSON(isRoot: false)
XCTAssertEqual("float", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testSimpleDouble() {
let type: FieldType = .number(.double)
let json = type.toJSON(isRoot: false)
XCTAssertEqual("double", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testSimpleBool() {
let type: FieldType = .number(.bool)
let json = type.toJSON(isRoot: false)
XCTAssertEqual("bool", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testEmptyObject() {
let type: FieldType = .unnamedObject([])
let json = type.toJSON(isRoot: false)
XCTAssertEqual("object", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testNamedEmptyObject() {
let type: FieldType = .object(name: "Object", [])
let json = type.toJSON()
XCTAssertEqual([
"type": "object",
"name": "Object"
], json)
}
func testEmptyEnum() {
let type: FieldType = .unnamedEnum([])
let json = type.toJSON(isRoot: false)
XCTAssertEqual("any", json)
let rootJson = type.toJSON(isRoot: true)
XCTAssertEqual([
"type": json,
"$schema": .string(ModelExportTranslator.schemaIdentifier)
], rootJson)
}
func testNamedEmptyEnum() {
let type: FieldType = .enum(name: "Enum", [])
let json = type.toJSON()
XCTAssertEqual([
"type": "any",
"name": "Enum"
], json)
}
func testTextList() {
let type: FieldType = .list(.text)
let json = type.toJSON()
XCTAssertEqual([
"type": "list",
"content": "string"
], json)
}
func testListOfTextList() {
let type: FieldType = .list(.list(.text))
let json = type.toJSON()
XCTAssertEqual([
"type": "list",
"content": [
"type": "list",
"content": "string"
]
], json)
}
func testUnknownType() {
let type: FieldType = .unnamedUnknown
let json = type.toJSON()
XCTAssertEqual("any", json)
}
func testOptionalUnknown() {
let type: FieldType = .optional(.unnamedUnknown)
let json = type.toJSON()
XCTAssertEqual("any?", json)
}
func testListOfUnknown() {
let type: FieldType = .list(.unnamedUnknown)
let json = type.toJSON()
XCTAssertEqual([
"type": "list",
"content": "any"
], json)
}
func testOptionalText() {
let type: FieldType = .optional(.text)
let json = type.toJSON()
XCTAssertEqual("string?", json)
}
func testListOfEmptyObject() {
let type: FieldType = .list(.unnamedObject([]))
let json = type.toJSON()
XCTAssertEqual([
"type": "list",
"content": "object"
], json)
}
func testObjectWithSingleTextField() {
let type: FieldType = .unnamedObject([.init(name: "text", type: .text)])
let json = type.toJSON()
XCTAssertEqual([
"type": "object",
"properties": [
"text": "string"
]
], json)
}
func testObjectWithFieldContainingListOfText() {
let type: FieldType = .unnamedObject([.init(name: "texts", type: .list(.text))])
let json = type.toJSON()
XCTAssertEqual([
"type": "object",
"properties": [
"texts": [
"type": "list",
"content": "string"
]
]
], json)
}
func testObjectWithTwoSimpleFields() {
let type: FieldType = .unnamedObject([
.init(name: "number", type: .number(.double)),
.init(name: "texts", type: .list(.text))
])
let json = type.toJSON()
XCTAssertEqual([
"type": "object",
"properties": [
"number": "double",
"texts": [
"type": "list",
"content": "string"
]
]
], json)
}
func testObjectWithOneFieldWithSubDeclaration() {
let type: FieldType = .unnamedObject([
.init(name: "subObject", type: .unnamedObject([]))
])
let json = type.toJSON()
XCTAssertEqual([
"type": "object",
"properties": [
"subObject": "object"
]
], json)
}
func testEnumWithOneCase() {
let type: FieldType = .unnamedEnum([.text])
let json = type.toJSON()
XCTAssertEqual([
"type": "any",
"of": [
"string"
]
], json)
}
func testEnumWithTwoCases() {
let type: FieldType = .unnamedEnum([.text, .number(.int)])
let json = type.toJSON()
XCTAssertEqual([
"type": "any",
"of": [
"int",
"string"
]
], json)
}
func testEnumWithOneSubDeclarationCase() {
let type: FieldType = .unnamedEnum([.unnamedObject([])])
let json = type.toJSON()
XCTAssertEqual([
"type": "any",
"of": [
"object"
]
], json)
}
}
#if os(Linux)
extension ModelToJsonTest {
static var allTests: [(String, (ModelToJsonTest) -> () throws -> Void)] {
return [
("testEmptyEnum", testEmptyEnum),
("testSimpleString", testSimpleString),
("testListOfEmptyObject", testListOfEmptyObject),
("testNamedEmptyEnum", testNamedEmptyEnum),
("testEnumWithOneCase", testEnumWithOneCase),
("testObjectWithTwoSimpleFields", testObjectWithTwoSimpleFields),
("testObjectWithOneFieldWithSubDeclaration", testObjectWithOneFieldWithSubDeclaration),
("testListOfTextList", testListOfTextList),
("testEnumWithTwoCases", testEnumWithTwoCases),
("testListOfUnknown", testListOfUnknown),
("testObjectWithSingleTextField", testObjectWithSingleTextField),
("testNamedEmptyObject", testNamedEmptyObject),
("testSimpleDouble", testSimpleDouble),
("testSimpleBool", testSimpleBool),
("testOptionalText", testOptionalText),
("testTextList", testTextList),
("testEnumWithOneSubDeclarationCase", testEnumWithOneSubDeclarationCase),
("testSimpleInt", testSimpleInt),
("testOptionalUnknown", testOptionalUnknown),
("testSimpleFloat", testSimpleFloat),
("testObjectWithFieldContainingListOfText", testObjectWithFieldContainingListOfText),
("testEmptyObject", testEmptyObject),
("testUnknownType", testUnknownType),
]
}
}
#endif
| 33ea1360d8883c5ab27eb6138b615d26 | 29.349823 | 99 | 0.529398 | false | true | false | false |
GarenChen/SunshineAlbum | refs/heads/master | SunshineAlbum/Classes/AssetsManager.swift | mit | 1 | //
// AssetsManager.swift
// Pods
//
// Created by Garen on 2017/9/7.
//
//
import Foundation
import Photos
class AssetsManager: NSObject {
static let shared = AssetsManager()
static let videoCacheName = "SunshineVideo.mp4"
var assetFetchOptions: PHFetchOptions {
let options = PHFetchOptions()
switch SASelectionManager.shared.containType {
case .photo:
options.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue)
case .video:
options.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue)
case .both:
break
}
options.sortDescriptors = Array(arrayLiteral: NSSortDescriptor(key: "creationDate", ascending: true))
return options
}
lazy var imageFetchOptions: PHImageRequestOptions = {
let options = PHImageRequestOptions()
options.resizeMode = .exact
options.isNetworkAccessAllowed = false
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
return options
}()
let imageManager: PHCachingImageManager = {
return PHCachingImageManager()
}()
private override init() {
super.init()
}
/// 获取所有相册
///
/// - Returns: 本地所有相册
func fetchAllAlbums() -> [AlbumsModel] {
//系统智能相册
let smartResult = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: .any, options: nil)
let smarts = handleCollectionFetchResult(smartResult)
//用户相册
let userResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .smartAlbumUserLibrary, options: nil)
let users = handleCollectionFetchResult(userResult)
return (smarts + users)
}
/// 获取相机胶卷
///
/// - Returns: 相机胶卷的模型 AlbumsModel
func fetchCameraRoll() -> AlbumsModel? {
let cameraRollResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
let cameraRolls = handleCollectionFetchResult(cameraRollResult)
debuglog(cameraRolls.description)
return cameraRolls.first
}
/// 获取输出照片
///
/// - Parameters:
/// - asset: PHAsset
/// - complition: 回调
func fetchResultImage(asset: PHAsset, isFullImage: Bool = false, complition: @escaping (UIImage) -> Void) {
var size: CGSize = .zero
if !isFullImage {
let scale = UIScreen.ScreenScale
let aspectRatio = CGFloat(asset.pixelWidth) / CGFloat(asset.pixelHeight)
let pixelWidth = UIScreen.ScreenWidth * scale
let pixelHeight = pixelWidth / aspectRatio
size = CGSize(width: pixelWidth, height: pixelHeight)
}
fetchImage(asset: asset, targetSize: size, options: imageFetchOptions, success: complition)
}
/// 获取照片预览图
///
/// - Parameters:
/// - asset: PHAsset
/// - complition: 回调
func fetchPreviewImage(asset: PHAsset, complition: @escaping (UIImage) -> Void) {
let scale = UIScreen.ScreenScale
let aspectRatio = CGFloat(asset.pixelWidth) / CGFloat(asset.pixelHeight)
let pixelWidth = UIScreen.ScreenWidth * scale
let pixelHeight = pixelWidth / aspectRatio
let size = CGSize(width: pixelWidth, height: pixelHeight)
fetchImage(asset: asset,
targetSize: size,
options: imageFetchOptions,
contentMode: .aspectFit,
success: complition)
}
/// 获取资源缩略图
///
/// - Parameters:
/// - asset: asset
/// - width: 宽
/// - height: 高
/// - complition: 获取成功后回调,获取失败时不调用
func fetchThumbnailImage(asset: PHAsset, width: CGFloat, height: CGFloat, complition: @escaping (UIImage) -> Void) {
let size = CGSize(width: width * UIScreen.main.scale, height: height * UIScreen.main.scale)
fetchImage(asset: asset,
targetSize: size,
options: imageFetchOptions,
success: complition)
}
/// 获取特定尺寸图片
func fetchImage(asset: PHAsset,
targetSize: CGSize,
options: PHImageRequestOptions,
contentMode: PHImageContentMode = .aspectFill,
success: @escaping (UIImage) -> Void,
failure: ((Error?) -> Void)? = nil) {
imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: contentMode, options: options) { (image, info) in
guard let resultImage = image else {
failure?(info?[PHImageErrorKey] as? Error)
return
}
success(resultImage)
}
}
/// 获取照片原数据
///
/// - Parameters:
/// - asset: PHAsset
/// - complition: 回调
func caculateOriginalDataLength(asset: PHAsset, complition: @escaping (Data, String) -> Void) {
let options = PHImageRequestOptions()
options.resizeMode = .exact
options.isNetworkAccessAllowed = false
imageManager.requestImageData(for: asset, options: imageFetchOptions) { (data, string, orientation, info) in
debuglog("data: \(String(describing: data)), string: \(String(describing: string)), orientation:\(orientation), info: \(String(describing: info))")
guard let data = data else { return }
let length = (data.count) / (1024 * 1024)
let lenghtStr = String(format: "%.2fM", length)
complition(data, lenghtStr)
}
}
/// 获取视频资源
func fetchAVPlayerItem(asset: PHAsset, success:@escaping (AVPlayerItem) -> Void, failure: (([AnyHashable: Any]?) -> Void)? = nil) {
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = false
options.version = .original
self.imageManager.requestPlayerItem(forVideo: asset, options: options) { (item, info) in
if item != nil {
success(item!)
} else {
failure?(info)
}
}
}
/// 构建相册model
///
/// - Parameter result: 资源集合 PHFetchResult<PHAssetCollection>
/// - Returns: 相册模型 Array<AlbumsModel>
private func handleCollectionFetchResult(_ result: PHFetchResult<PHAssetCollection>) -> Array<AlbumsModel> {
var models: [AlbumsModel] = []
result.enumerateObjects({ (collection, index, _) in
let assetResult = PHAsset.fetchAssets(in: collection, options: self.assetFetchOptions)
if assetResult.count > 0 {
let model = AlbumsModel(assetResult: assetResult, name: collection.localizedTitle)
models.append(model)
}
})
return models
}
func cropVideo(asset: PHAsset, startTime: CMTime, endTime: CMTime, success: ((URL) -> Void)?) {
imageManager.requestAVAsset(forVideo: asset, options: nil) {(avAsset, audioMix, info) in
guard let asset = avAsset as? AVURLAsset else { return }
let range = CMTimeRange(start: startTime, end: endTime)
let mixComposition = AVMutableComposition()
let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
let compositionAudioTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)
let assetVideoTrack = asset.tracks(withMediaType: AVMediaType.video).first!
let assetAudioTrack = asset.tracks(withMediaType: AVMediaType.audio).first!
do {
try compositionVideoTrack?.insertTimeRange(range, of: assetVideoTrack, at: kCMTimeZero)
try compositionAudioTrack?.insertTimeRange(range, of: assetAudioTrack, at: kCMTimeZero)
} catch let e {
print(e)
}
compositionVideoTrack?.preferredTransform = assetVideoTrack.preferredTransform
let assetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetPassthrough)
let outPutPath = NSTemporaryDirectory().appending(AssetsManager.videoCacheName)
print("outPutPath \(outPutPath)")
let url = URL(fileURLWithPath: outPutPath)
assetExportSession?.outputFileType = AVFileType.mp4
assetExportSession?.outputURL = url
assetExportSession?.shouldOptimizeForNetworkUse = true
if FileManager.default.fileExists(atPath: outPutPath) {
do {
try FileManager.default.removeItem(atPath: outPutPath)
} catch let e {
print(e)
}
}
assetExportSession?.exportAsynchronously(completionHandler: {
print("assetExportSession export finished")
AssetsManager.saveToPhotoWithUrl(url: url)
success?(url)
})
}
}
/// 保存视频到相册
///
/// - Parameter url: 视频URL
static func saveToPhotoWithUrl(url: URL) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
}, completionHandler: nil)
}
}
| 4bc9717c36c2c0f6eafefd0faf5c2f78 | 30.362319 | 159 | 0.672135 | false | false | false | false |
sergdort/CleanArchitectureRxSwift | refs/heads/master | Domain/Entries/Todo.swift | mit | 1 | //
// Todo.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Foundation
public struct Todo: Decodable {
public let completed: Bool
public let title: String
public let uid: String
public let userId: String
public init(completed: Bool,
title: String,
uid: String,
userId: String) {
self.completed = completed
self.title = title
self.uid = uid
self.userId = userId
}
private enum CodingKeys: String, CodingKey {
case completed
case title
case uid
case userId
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
completed = try container.decode(Bool.self, forKey: .completed)
title = try container.decode(String.self, forKey: .title)
if let userId = try container.decodeIfPresent(Int.self, forKey: .userId) {
self.userId = "\(userId)"
} else {
userId = try container.decode(String.self, forKey: .userId)
}
if let uid = try container.decodeIfPresent(Int.self, forKey: .uid) {
self.uid = "\(uid)"
} else {
uid = try container.decodeIfPresent(String.self, forKey: .uid) ?? ""
}
}
}
extension Todo: Equatable {
public static func == (lhs: Todo, rhs: Todo) -> Bool {
return lhs.uid == rhs.uid &&
lhs.title == rhs.title &&
lhs.completed == rhs.completed &&
lhs.userId == rhs.userId
}
}
| 5f49ee2c0fa5f02bdd2bef264c9d6183 | 26.262295 | 82 | 0.580878 | false | false | false | false |
khoren93/SwiftHub | refs/heads/master | SwiftHub/Modules/Pull Requests/PullRequestsViewModel.swift | mit | 1 | //
// PullRequestsViewModel.swift
// SwiftHub
//
// Created by Sygnoos9 on 11/30/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
class PullRequestsViewModel: ViewModel, ViewModelType {
struct Input {
let headerRefresh: Observable<Void>
let footerRefresh: Observable<Void>
let segmentSelection: Observable<PullRequestSegments>
let selection: Driver<PullRequestCellViewModel>
}
struct Output {
let navigationTitle: Driver<String>
let items: BehaviorRelay<[PullRequestCellViewModel]>
let pullRequestSelected: Driver<PullRequestViewModel>
let userSelected: Driver<UserViewModel>
}
let repository: BehaviorRelay<Repository>
let segment = BehaviorRelay<PullRequestSegments>(value: .open)
let userSelected = PublishSubject<User>()
init(repository: Repository, provider: SwiftHubAPI) {
self.repository = BehaviorRelay(value: repository)
super.init(provider: provider)
}
func transform(input: Input) -> Output {
let elements = BehaviorRelay<[PullRequestCellViewModel]>(value: [])
input.segmentSelection.bind(to: segment).disposed(by: rx.disposeBag)
input.headerRefresh.flatMapLatest({ [weak self] () -> Observable<[PullRequestCellViewModel]> in
guard let self = self else { return Observable.just([]) }
self.page = 1
return self.request()
.trackActivity(self.headerLoading)
})
.subscribe(onNext: { (items) in
elements.accept(items)
}).disposed(by: rx.disposeBag)
input.footerRefresh.flatMapLatest({ [weak self] () -> Observable<[PullRequestCellViewModel]> in
guard let self = self else { return Observable.just([]) }
self.page += 1
return self.request()
.trackActivity(self.footerLoading)
})
.subscribe(onNext: { (items) in
elements.accept(elements.value + items)
}).disposed(by: rx.disposeBag)
let navigationTitle = repository.map({ (repository) -> String in
return repository.fullname ?? ""
}).asDriver(onErrorJustReturn: "")
let pullRequestSelected = input.selection.map { (cellViewModel) -> PullRequestViewModel in
let viewModel = PullRequestViewModel(repository: self.repository.value, pullRequest: cellViewModel.pullRequest, provider: self.provider)
return viewModel
}
let userDetails = userSelected.asDriver(onErrorJustReturn: User())
.map({ (user) -> UserViewModel in
let viewModel = UserViewModel(user: user, provider: self.provider)
return viewModel
})
return Output(navigationTitle: navigationTitle,
items: elements,
pullRequestSelected: pullRequestSelected,
userSelected: userDetails)
}
func request() -> Observable<[PullRequestCellViewModel]> {
let fullname = repository.value.fullname ?? ""
let state = segment.value.state.rawValue
return provider.pullRequests(fullname: fullname, state: state, page: page)
.trackActivity(loading)
.trackError(error)
.map { $0.map({ (pullRequest) -> PullRequestCellViewModel in
let viewModel = PullRequestCellViewModel(with: pullRequest)
viewModel.userSelected.bind(to: self.userSelected).disposed(by: self.rx.disposeBag)
return viewModel
})}
}
}
| 9a8c37cee4c8fd7d0dd25be8a8b346df | 37.125 | 148 | 0.634699 | false | false | false | false |
tcliff111/TipR | refs/heads/master | Tip Calculator/SettingsViewController.swift | apache-2.0 | 1 | //
// SettingsViewController.swift
// Tip Calculator
//
// Created by Thomas Clifford on 12/9/15.
// Copyright © 2015 Thomas Clifford. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var firstTip: UITextField!
@IBOutlet weak var secondTip: UITextField!
@IBOutlet weak var thirdTip: UITextField!
var key1 = "firstKey"
var key2 = "secondKey"
var key3 = "thirdKey"
@IBAction func screenTapped(sender: AnyObject) {
view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
firstTip.text=defaults.objectForKey(key1) as? String
secondTip.text=defaults.objectForKey(key2) as? String
thirdTip.text=defaults.objectForKey(key3) as? String
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveDefaults(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(firstTip.text, forKey: key1)
defaults.setObject(secondTip.text, forKey: key2)
defaults.setObject(thirdTip.text, forKey: key3)
defaults.synchronize()
}
/*
// 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.
}
*/
}
| 0d45979e43813599e650762652dd1059 | 29.655172 | 106 | 0.683352 | false | false | false | false |
AlbertXYZ/HDCP | refs/heads/dev | 11-time-based-operators/final/RxSwiftPlayground/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift | apache-2.0 | 120 | //
// UIBarButtonItem+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
fileprivate var rx_tap_key: UInt8 = 0
extension Reactive where Base: UIBarButtonItem {
/// Bindable sink for `enabled` property.
public var isEnabled: UIBindingObserver<Base, Bool> {
return UIBindingObserver(UIElement: self.base) { UIElement, value in
UIElement.isEnabled = value
}
}
/// Bindable sink for `title` property.
public var title: UIBindingObserver<Base, String> {
return UIBindingObserver(UIElement: self.base) { UIElement, value in
UIElement.title = value
}
}
/// Reactive wrapper for target action pattern on `self`.
public var tap: ControlEvent<Void> {
let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<Void> in
Observable.create { [weak control = self.base] observer in
guard let control = control else {
observer.on(.completed)
return Disposables.create()
}
let target = BarButtonItemTarget(barButtonItem: control) {
observer.on(.next())
}
return target
}
.takeUntil(self.deallocated)
.share()
}
return ControlEvent(events: source)
}
}
@objc
final class BarButtonItemTarget: RxTarget {
typealias Callback = () -> Void
weak var barButtonItem: UIBarButtonItem?
var callback: Callback!
init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) {
self.barButtonItem = barButtonItem
self.callback = callback
super.init()
barButtonItem.target = self
barButtonItem.action = #selector(BarButtonItemTarget.action(_:))
}
override func dispose() {
super.dispose()
#if DEBUG
MainScheduler.ensureExecutingOnScheduler()
#endif
barButtonItem?.target = nil
barButtonItem?.action = nil
callback = nil
}
func action(_ sender: AnyObject) {
callback()
}
}
#endif
| 0e8a0aa1fce08deca6a1ea97ac4e5e01 | 25.033708 | 84 | 0.592145 | false | false | false | false |
alblue/swift | refs/heads/master | stdlib/public/core/PrefixWhile.swift | apache-2.0 | 2 | //===-- PrefixWhile.swift - Lazy views for prefix(while:) -----*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence whose elements consist of the initial consecutive elements of
/// some base sequence that satisfy a given predicate.
@_fixed_layout // lazy-performance
public struct LazyPrefixWhileSequence<Base: Sequence> {
public typealias Element = Base.Element
@inlinable // lazy-performance
internal init(_base: Base, predicate: @escaping (Element) -> Bool) {
self._base = _base
self._predicate = predicate
}
@usableFromInline // lazy-performance
internal var _base: Base
@usableFromInline // lazy-performance
internal let _predicate: (Element) -> Bool
}
extension LazyPrefixWhileSequence {
/// An iterator over the initial elements traversed by a base iterator that
/// satisfy a given predicate.
///
/// This is the associated iterator for the `LazyPrefixWhileSequence`,
/// `LazyPrefixWhileCollection`, and `LazyPrefixWhileBidirectionalCollection`
/// types.
@_fixed_layout // lazy-performance
public struct Iterator {
public typealias Element = Base.Element
@usableFromInline // lazy-performance
internal var _predicateHasFailed = false
@usableFromInline // lazy-performance
internal var _base: Base.Iterator
@usableFromInline // lazy-performance
internal let _predicate: (Element) -> Bool
@inlinable // lazy-performance
internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) {
self._base = _base
self._predicate = predicate
}
}
}
extension LazyPrefixWhileSequence.Iterator: IteratorProtocol, Sequence {
@inlinable // lazy-performance
public mutating func next() -> Element? {
// Return elements from the base iterator until one fails the predicate.
if !_predicateHasFailed, let nextElement = _base.next() {
if _predicate(nextElement) {
return nextElement
} else {
_predicateHasFailed = true
}
}
return nil
}
}
extension LazyPrefixWhileSequence: Sequence {
public typealias SubSequence = AnySequence<Element> // >:(
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), predicate: _predicate)
}
}
extension LazyPrefixWhileSequence: LazySequenceProtocol {
public typealias Elements = LazyPrefixWhileSequence
}
extension LazySequenceProtocol {
/// Returns a lazy sequence of the initial consecutive elements that satisfy
/// `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns `true` if the element should be included or
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
@inlinable // lazy-performance
public __consuming func prefix(
while predicate: @escaping (Elements.Element) -> Bool
) -> LazyPrefixWhileSequence<Self.Elements> {
return LazyPrefixWhileSequence(_base: self.elements, predicate: predicate)
}
}
/// A lazy `${Collection}` wrapper that includes the initial consecutive
/// elements of an underlying collection that satisfy a predicate.
///
/// - Note: The performance of accessing `endIndex`, `last`, any methods that
/// depend on `endIndex`, or moving an index depends on how many elements
/// satisfy the predicate at the start of the collection, and may not offer
/// the usual performance given by the `Collection` protocol. Be aware,
/// therefore, that general operations on `${Self}` instances may not have
/// the documented complexity.
@_fixed_layout // lazy-performance
public struct LazyPrefixWhileCollection<Base: Collection> {
public typealias Element = Base.Element
public typealias SubSequence = Slice<LazyPrefixWhileCollection<Base>>
@inlinable // lazy-performance
internal init(_base: Base, predicate: @escaping (Element) -> Bool) {
self._base = _base
self._predicate = predicate
}
@usableFromInline // lazy-performance
internal var _base: Base
@usableFromInline // lazy-performance
internal let _predicate: (Element) -> Bool
}
extension LazyPrefixWhileCollection: Sequence {
public typealias Iterator = LazyPrefixWhileSequence<Base>.Iterator
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), predicate: _predicate)
}
}
extension LazyPrefixWhileCollection {
/// A position in the base collection of a `LazyPrefixWhileCollection` or the
/// end of that collection.
@_frozen // lazy-performance
@usableFromInline
internal enum _IndexRepresentation {
case index(Base.Index)
case pastEnd
}
/// A position in a `LazyPrefixWhileCollection` or
/// `LazyPrefixWhileBidirectionalCollection` instance.
@_fixed_layout // lazy-performance
public struct Index {
/// The position corresponding to `self` in the underlying collection.
@usableFromInline // lazy-performance
internal let _value: _IndexRepresentation
/// Creates a new index wrapper for `i`.
@inlinable // lazy-performance
internal init(_ i: Base.Index) {
self._value = .index(i)
}
/// Creates a new index that can represent the `endIndex` of a
/// `LazyPrefixWhileCollection<Base>`. This is not the same as a wrapper
/// around `Base.endIndex`.
@inlinable // lazy-performance
internal init(endOf: Base) {
self._value = .pastEnd
}
}
}
extension LazyPrefixWhileCollection.Index: Comparable {
@inlinable // lazy-performance
public static func == (
lhs: LazyPrefixWhileCollection<Base>.Index,
rhs: LazyPrefixWhileCollection<Base>.Index
) -> Bool {
switch (lhs._value, rhs._value) {
case let (.index(l), .index(r)):
return l == r
case (.pastEnd, .pastEnd):
return true
case (.pastEnd, .index), (.index, .pastEnd):
return false
}
}
@inlinable // lazy-performance
public static func < (
lhs: LazyPrefixWhileCollection<Base>.Index,
rhs: LazyPrefixWhileCollection<Base>.Index
) -> Bool {
switch (lhs._value, rhs._value) {
case let (.index(l), .index(r)):
return l < r
case (.index, .pastEnd):
return true
case (.pastEnd, _):
return false
}
}
}
extension LazyPrefixWhileCollection.Index: Hashable where Base.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
switch _value {
case .index(let value):
hasher.combine(value)
case .pastEnd:
hasher.combine(Int.max)
}
}
}
extension LazyPrefixWhileCollection: Collection {
@inlinable // lazy-performance
public var startIndex: Index {
return Index(_base.startIndex)
}
@inlinable // lazy-performance
public var endIndex: Index {
// If the first element of `_base` satisfies the predicate, there is at
// least one element in the lazy collection: Use the explicit `.pastEnd` index.
if let first = _base.first, _predicate(first) {
return Index(endOf: _base)
}
// `_base` is either empty or `_predicate(_base.first!) == false`. In either
// case, the lazy collection is empty, so `endIndex == startIndex`.
return startIndex
}
@inlinable // lazy-performance
public func index(after i: Index) -> Index {
_precondition(i != endIndex, "Can't advance past endIndex")
guard case .index(let i) = i._value else {
_preconditionFailure("Invalid index passed to index(after:)")
}
let nextIndex = _base.index(after: i)
guard nextIndex != _base.endIndex && _predicate(_base[nextIndex]) else {
return Index(endOf: _base)
}
return Index(nextIndex)
}
@inlinable // lazy-performance
public subscript(position: Index) -> Element {
switch position._value {
case .index(let i):
return _base[i]
case .pastEnd:
_preconditionFailure("Index out of range")
}
}
}
extension LazyPrefixWhileCollection: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable // lazy-performance
public func index(before i: Index) -> Index {
switch i._value {
case .index(let i):
_precondition(i != _base.startIndex, "Can't move before startIndex")
return Index(_base.index(before: i))
case .pastEnd:
// Look for the position of the last element in a non-empty
// prefix(while:) collection by searching forward for a predicate
// failure.
// Safe to assume that `_base.startIndex != _base.endIndex`; if they
// were equal, `_base.startIndex` would be used as the `endIndex` of
// this collection.
_sanityCheck(!_base.isEmpty)
var result = _base.startIndex
while true {
let next = _base.index(after: result)
if next == _base.endIndex || !_predicate(_base[next]) {
break
}
result = next
}
return Index(result)
}
}
}
extension LazyPrefixWhileCollection: LazyCollectionProtocol {
public typealias Elements = LazyPrefixWhileCollection
}
extension LazyCollectionProtocol {
/// Returns a lazy collection of the initial consecutive elements that
/// satisfy `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns `true` if the element should be included
/// or `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
@inlinable // lazy-performance
public __consuming func prefix(
while predicate: @escaping (Element) -> Bool
) -> LazyPrefixWhileCollection<Elements> {
return LazyPrefixWhileCollection(
_base: self.elements, predicate: predicate)
}
}
| ee9c6dc3065c30fa45151e65ec19752e | 31.942492 | 83 | 0.683251 | false | false | false | false |
jhurliman/NeuralSwift | refs/heads/master | NeuralSwift/NeuralSwift/DataLoader/MNISTLoader.swift | mit | 1 | //
// MNISTLoader.swift
// NeuralSwift
//
// Created by John Hurliman on 7/17/15.
// Copyright (c) 2015 John Hurliman. All rights reserved.
//
import Foundation
public class MNISTLoader {
public let samples: [TrainingSample]
public init?(imageFile: String, labelFile: String) {
// Image loading
////////////////////////////////////////////////////////////////////////
var images = [NSData]()
var labels = [Int]()
if let imageData = NSData(contentsOfFile: imageFile) {
let reader = BinaryDataScanner(data: imageData, littleEndian: false, encoding: NSUTF8StringEncoding)
// Magic number
let magicNum = reader.read32()
if 2051 != magicNum { self.samples = []; return nil }
let count = Int(reader.read32() ?? 0)
let rows = Int(reader.read32() ?? 0)
let columns = Int(reader.read32() ?? 0)
images.reserveCapacity(count)
// Read all of the images
for i in 0..<count {
if let imageBytes = reader.readData(rows * columns) {
images.append(imageBytes)
} else {
break
}
}
} else {
self.samples = []; return nil
}
// Label loading
////////////////////////////////////////////////////////////////////////
if let labelData = NSData(contentsOfFile: labelFile) {
let reader = BinaryDataScanner(data: labelData, littleEndian: false, encoding: NSUTF8StringEncoding)
// Magic number
let magicNum = reader.read32()
if 2049 != magicNum { self.samples = []; return nil }
let count = Int(reader.read32() ?? 0)
labels.reserveCapacity(count)
for i in 0..<count {
if let labelByte = reader.readByte() {
labels.append(Int(labelByte))
} else {
break
}
}
} else {
self.samples = []; return nil
}
if images.count != labels.count {
self.samples = []; return nil
}
var samples = [TrainingSample]()
samples.reserveCapacity(images.count)
for pair in Zip2(images, labels) {
let imageBytes = pair.0
let label = pair.1
var pixels = [Float]()
pixels.reserveCapacity(imageBytes.length)
var current = UnsafePointer<UInt8>(imageBytes.bytes)
for _ in 0..<imageBytes.length {
let value = Float(current.memory) / 255.0
pixels.append(value)
current = current.successor()
}
let output = MNISTLoader.makeOutput(label)
samples.append(TrainingSample(inputs: pixels, outputs: output))
}
self.samples = samples
}
static func makeOutput(label: Int) -> [Float] {
var output = [Float](count: 10, repeatedValue: 0.0)
output[label] = 1.0
return output
}
}
| 088ed38c76b2ccf459cd0ca4c984c902 | 31.633663 | 112 | 0.473301 | false | false | false | false |
smoope/ios-sdk | refs/heads/master | Example/Tests/UserTests.swift | apache-2.0 | 1 | /*
* Copyright 2016 smoope GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
import SmoopeSDK
class UserTests: BaseTests {
func testSingle() {
let resource = getResource("user")
let result = SPUser(data: resource)
XCTAssertNotNil(result, "Mapped object shouldn't be nil")
XCTAssertEqual(result.id, resource["id"] as? String)
XCTAssert(result.states.count == 1)
XCTAssert(result.links.count == 7)
}
func testCollection() {
testCollection(SPUserList(data: getResource("users")))
}
}
| 8a7662046fad892472c0f0b56cb5143a | 28.942857 | 74 | 0.722328 | false | true | false | false |
gfpacheco/BigBrother | refs/heads/master | BigBrother/BigBrother.swift | mit | 1 | //
// BigBrother.swift
// BigBrother
//
// Created by Marcelo Fabri on 01/01/15.
// Copyright (c) 2015 Marcelo Fabri. All rights reserved.
//
import Foundation
import UIKit
public class BigBrother: NSObject {
/**
Registers BigBrother to the shared NSURLSession (and to NSURLConnection).
*/
public class func addToSharedSession() {
NSURLProtocol.registerClass(BigBrotherURLProtocol.self)
}
/**
Adds BigBrother to a NSURLSessionConfiguration that will be used to create a custom NSURLSession.
- parameter configuration: The configuration on which BigBrother will be added
*/
public class func addToSessionConfiguration(configuration: NSURLSessionConfiguration) {
// needs to be inserted at the beginning (see https://github.com/AliSoftware/OHHTTPStubs/issues/65 )
let arr: [AnyClass]
if let classes = configuration.protocolClasses {
arr = [BigBrotherURLProtocol.self] + classes
} else {
arr = [BigBrotherURLProtocol.self]
}
configuration.protocolClasses = arr
}
/**
Removes BigBrother from the shared NSURLSession (and to NSURLConnection).
*/
public class func removeFromSharedSession() {
NSURLProtocol.unregisterClass(BigBrotherURLProtocol.self)
}
/**
Removes BigBrother from a NSURLSessionConfiguration.
You must create a new NSURLSession from the updated configuration to stop using BigBrother.
- parameter configuration: The configuration from which BigBrother will be removed (if present)
*/
public class func removeFromSessionConfiguration(configuration: NSURLSessionConfiguration) {
configuration.protocolClasses = configuration.protocolClasses?.filter { $0 !== BigBrotherURLProtocol.self }
}
}
/**
* A custom NSURLProtocol that automatically manages UIApplication.sharedApplication().networkActivityIndicatorVisible.
*/
public class BigBrotherURLProtocol: NSURLProtocol {
var connection: NSURLConnection?
var mutableData: NSMutableData?
var response: NSURLResponse?
/// The singleton instance.
public static var manager = BigBrotherManager.sharedInstance
// MARK: NSURLProtocol
override public class func canInitWithRequest(request: NSURLRequest) -> Bool {
if NSURLProtocol.propertyForKey(NSStringFromClass(self), inRequest: request) != nil {
return false
}
return true
}
override public class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override public class func requestIsCacheEquivalent(aRequest: NSURLRequest, toRequest bRequest: NSURLRequest) -> Bool {
return super.requestIsCacheEquivalent(aRequest, toRequest:bRequest)
}
override public func startLoading() {
BigBrotherURLProtocol.manager.incrementActivityCount()
let newRequest = request.mutableCopy() as! NSMutableURLRequest
NSURLProtocol.setProperty(true, forKey: NSStringFromClass(self.dynamicType), inRequest: newRequest)
connection = NSURLConnection(request: newRequest, delegate: self)
}
override public func stopLoading() {
connection?.cancel()
connection = nil
BigBrotherURLProtocol.manager.decrementActivityCount()
}
// MARK: NSURLConnectionDelegate
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
let policy = NSURLCacheStoragePolicy(rawValue: request.cachePolicy.rawValue) ?? .NotAllowed
client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: policy)
self.response = response
mutableData = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
client?.URLProtocol(self, didLoadData: data)
mutableData?.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
client?.URLProtocolDidFinishLoading(self)
}
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
client?.URLProtocol(self, didFailWithError: error)
}
}
| 0b3cd2afa47abf0fb7c79d3d38656b8f | 33.95935 | 123 | 0.699767 | false | true | false | false |
LunarLincoln/nodekit-darwin-lite | refs/heads/master | src/nodekit/NKScriptingLite/NKJSTimer.swift | apache-2.0 | 1 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
* Portions Copyright 2015 XWebView
* Portions Copyright (c) 2014 Intel Corporation. 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 JavaScriptCore
@objc protocol TimerJSExport: JSExport {
func setTimeout(_ callback: JSValue, _ milliseconds: Double) -> String
func setInterval(_ callback: JSValue, _ milliseconds: Double) -> String
func clearTimeout(_ identifier: String)
}
@objc class NKJSTimer: NSObject, TimerJSExport {
var timers = [String: Timer]()
var callbacks = [String: JSValue]()
func clearTimeout(_ identifier: String) {
let timer = timers.removeValue(forKey: identifier)
timer?.invalidate()
callbacks.removeValue(forKey: identifier)
}
func setInterval(_ callback: JSValue, _ milliseconds: Double) -> String {
return createTimer(callback, milliseconds: milliseconds, repeats: true)
}
func setTimeout(_ callback: JSValue, _ milliseconds: Double) -> String {
return createTimer(callback, milliseconds: milliseconds , repeats: false)
}
func invalidateAll() {
timers.forEach({$0.1.invalidate()})
timers.removeAll()
callbacks.removeAll()
}
fileprivate func createTimer(_ callback: JSValue, milliseconds: Double, repeats : Bool) -> String {
let timeInterval = milliseconds / 1000.0
let uuid = UUID().uuidString
DispatchQueue.main.async {
let userInfo: [String: AnyObject] = [
"repeats": NSNumber(value: repeats as Bool),
"uuid": uuid as AnyObject
]
self.callbacks[uuid] = callback
let timer = Timer.scheduledTimer(timeInterval: timeInterval,
target: self,
selector: #selector(self.callJsCallback),
userInfo: userInfo,
repeats: repeats)
self.timers[uuid] = timer
}
return uuid
}
@objc func callJsCallback(_ timer: Timer) {
guard let userInfo = timer.userInfo as? [String: AnyObject],
let uuid = userInfo["uuid"] as? String,
let callback = callbacks[uuid],
let repeats = userInfo["repeats"] as? NSNumber else {
return
}
callback.call(withArguments: [])
if !repeats.boolValue {
clearTimeout(uuid)
}
}
}
| c518dac62487eb01efc3f78fa32c3c49 | 30 | 104 | 0.561584 | false | false | false | false |
Swift-Kit/JZHoverNSButton | refs/heads/master | JZHoverNSButton.swift | mit | 1 | //
// JZHoverNSButton.swift
//
// Created by Joey on 8/28/15.
// Copyright (c) 2015 Joey Zhou. All rights reserved.
//
import Cocoa
class JZHoverNSButton: NSButton {
var trackingArea:NSTrackingArea!
var hoverBackgroundColor: NSColor = NSColor.grayColor()
var originalBackgroundColor: NSColor = NSColor.whiteColor()
var hoverBackgroundImage: NSImage!
var originalBackgroundImage: NSImage!
var attributedStr: NSMutableAttributedString!
// MARK: - Initializers
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
// set tracking area
let opts: NSTrackingAreaOptions = ([NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveAlways])
trackingArea = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
// set tracking area
let opts: NSTrackingAreaOptions = ([NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveAlways])
trackingArea = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
// MARK: mouse events
override func mouseEntered(theEvent: NSEvent) {
let cell = self.cell as! NSButtonCell
cell.backgroundColor = hoverBackgroundColor
cell.image = hoverBackgroundImage
}
override func mouseExited(theEvent: NSEvent) {
let cell = self.cell as! NSButtonCell
cell.backgroundColor = originalBackgroundColor
cell.image = originalBackgroundImage
}
// MARK: background setters
func setImages(bgColor: NSColor, imageOriginal: NSImage, imageHover: NSImage) {
self.hoverBackgroundColor = bgColor
self.originalBackgroundColor = bgColor
self.originalBackgroundImage = imageOriginal
self.hoverBackgroundImage = imageHover
}
func setColors(originalBgColor: NSColor, hoverBgColor:NSColor) {
self.hoverBackgroundColor = hoverBgColor
self.originalBackgroundColor = originalBgColor
self.originalBackgroundImage = nil
self.hoverBackgroundImage = nil
}
// MARK: attributed text setters
func setText(str: String, color: NSColor, size: Int64) {
attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length:attributedStr.length))
attributedStr.addAttribute(NSFontSizeAttribute, value: size.description, range: NSRange(location: 0, length:attributedStr.length))
self.attributedTitle = attributedStr
}
func setText(str: String, color: NSColor) {
attributedStr = NSMutableAttributedString(string: str)
attributedStr.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length:attributedStr.length))
self.attributedTitle = attributedStr
}
} | 190d7e0b0158fc3aa355a138c0428eeb | 35.931818 | 138 | 0.694983 | false | false | false | false |
tanuva/wled | refs/heads/master | WLED/WLED/GradientSlider.swift | gpl-3.0 | 1 | //
// GradientSlider.swift
// WLED
//
// Created by Marcel on 16.08.15.
// Copyright © 2015 Marcel Brüggebors. All rights reserved.
//
import Foundation
import UIKit
class GradientSlider : UISlider {
func setTrackGradient(colors: [UIColor]) {
// Source: http://iostricks-ipreencekmr.blogspot.de/2013/07/setting-gradient-colors-to-uislider-bar.html
let view = self.subviews[0]
let maxTrackImageView = view.subviews[0]
// Configure the gradient layer
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.whiteColor().CGColor, UIColor.grayColor().CGColor, UIColor.blackColor().CGColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
var rect = maxTrackImageView.frame
rect.origin.x = view.frame.origin.x // Wtf?
gradientLayer.frame = rect
maxTrackImageView.layer.insertSublayer(gradientLayer, atIndex: 0)
}
}
| bcd933a1bc93e8bbb08acae08da71fc9 | 30.241379 | 114 | 0.737307 | false | false | false | false |
Electrode-iOS/ELDispatch | refs/heads/master | ELDispatch/DispatchTimer.swift | mit | 2 | //
// DispatchTimer.swift
// ELDispatch
//
// Created by Brandon Sneed on 2/15/15.
// Copyright (c) 2015 WalmartLabs. All rights reserved.
//
import Foundation
#if NOFRAMEWORKS
#else
import ELFoundation
#endif
/// Represents a GCD timer.
public class DispatchTimer {
/// Initializes a new dispatch timer.
public init () {
// nothing to do here. yet.
}
/// The state of the timer. `true` means the timer is suspended. `false` means that it isn't.
public var suspended: Bool {
get {
return lock.around {
return self.isSuspended
}
}
set(value) {
lock.around {
self.isSuspended = value
}
}
}
private var rawTimer: dispatch_source_t? = nil
private let lock: Spinlock = Spinlock()
private var isSuspended: Bool = false
/**
Schedules a GCD timer on the specified queue.
- parameter queue: The target queue.
- parameter interval: The interval at which to execute the closure, in seconds.
- parameter delay: The time to wait before the timer beings, in seconds. The default is 0.
- parameter leeway: A hint as to the leeway by which GCD may have to execute the closure. The default is 0.2.
- parameter suspended: The timer will be created in a suspended state.
- parameter closure: The closure to execute.
*/
public func schedule(queue: DispatchQueue, interval: NSTimeInterval, delay: NSTimeInterval = 0, leeway: NSTimeInterval = 1, suspended: Bool = false, _ closure: () -> Void) -> DispatchClosure {
// if we have a timer object already, lets bolt.
if self.rawTimer != nil {
exceptionFailure("A timer has already been scheduled!")
}
// set this to the opposite of the 'suspeded' var that came in.
// it'll get set to the proper state after.
isSuspended = suspended
let rawTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue.dispatchQueue())
self.rawTimer = rawTimer
var startTime: dispatch_time_t
if delay == 0 {
startTime = DISPATCH_TIME_NOW
} else {
startTime = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * NSTimeInterval(NSEC_PER_SEC)))
}
let repeatInterval = UInt64(interval * NSTimeInterval(NSEC_PER_SEC))
let leewayTime = UInt64(leeway * NSTimeInterval(NSEC_PER_SEC))
dispatch_source_set_event_handler(rawTimer, closure)
dispatch_source_set_timer(rawTimer, startTime, repeatInterval, leewayTime)
if suspended == false {
dispatch_resume(rawTimer)
}
return DispatchClosure(closure)
}
/**
Cancels the timer.
*/
public func cancel() {
if let timer = rawTimer {
dispatch_source_cancel(timer)
rawTimer = nil;
}
}
/**
Suspends execution of the timer. Call `resume()` to begin again.
*/
public func suspend() {
if let timer = rawTimer {
if !suspended {
dispatch_suspend(timer)
suspended = true
}
} else {
// throw an error?
}
}
/**
Resumes a timer. Call `suspend()` to suspend it.
*/
public func resume() {
if let timer = rawTimer {
if suspended {
dispatch_resume(timer)
suspended = false
}
} else {
// throw an error?
}
}
}
| d2db133f9706aebdd2f7d0ff331b6868 | 28.861789 | 196 | 0.5682 | false | false | false | false |
chipsandtea/MarineBioViewController | refs/heads/master | MarineBioViewController/MarineBioViewController.swift | gpl-3.0 | 1 | //
// MarineBioViewController.swift
// HackUCSC2015
//
// Created by Arjun Gopisetty on 1/10/15.
// Copyright (c) 2015 HackUCSC2015Team. All rights reserved.
//
import UIKit
class MarineBioViewController: ResponsiveTextFieldViewController, UIPickerViewDelegate {
@IBOutlet var schoolGroupLabel: UILabel!
var GroupName = String()
var SchoolName = String()
//water
@IBOutlet var TEMP: UITextField!
@IBOutlet var VISIB: UITextField!
@IBOutlet var DEPTH: UITextField!
@IBOutlet var SALIN: UITextField!
@IBOutlet var PLANKSPEC: UITextField!
@IBOutlet var TempLabel: UILabel!
@IBOutlet var VisLabel: UILabel!
@IBOutlet var DepthLabel: UILabel!
@IBOutlet var SalLabel: UILabel!
// water color options
@IBOutlet var WCLabel: UILabel!
@IBOutlet var BROWN: UIButton!
@IBOutlet var BLUE: UIButton!
@IBOutlet var RED: UIButton!
@IBOutlet var GREEN: UIButton!
@IBOutlet var YELLGREEN: UIButton!
@IBOutlet var BLUGREEN: UIButton!
// plankton descriptions
@IBOutlet var PSNLabel: UILabel!
@IBOutlet var MZP: UIButton!
@IBOutlet var MPP: UIButton!
@IBOutlet var AHH: UIButton!
@IBOutlet var planktonSelection: UILabel!
@IBOutlet var colorSelection: UILabel!
@IBOutlet var PlankSLabel: UILabel!
//Buttons
@IBOutlet var WPButton: UIButton!
@IBOutlet var WCButton: UIButton!
@IBOutlet var PSNButton: UIButton!
@IBOutlet var PSButton: UIButton!
@IBOutlet var Done: UIButton!
// COLORS
@IBAction func brownChosen(sender: UIButton) {
colorSelection.text = "brown"
colorSelection.textColor = UIColor.brownColor()
}
@IBAction func blueChosen(sender: UIButton) {
colorSelection.text = "blue"
colorSelection.textColor = UIColor.blueColor()
}
@IBAction func redChosen(sender: UIButton) {
colorSelection.text = "red"
colorSelection.textColor = UIColor.redColor()
}
@IBAction func greenChosen(sender: UIButton) {
colorSelection.text = "green"
colorSelection.textColor = UIColor.greenColor()
}
@IBAction func yelGreenChosen(sender: UIButton) {
colorSelection.text = "yellow-green"
colorSelection.textColor = YELLGREEN.titleColorForState(UIControlState.Normal)
}
@IBAction func blueGreenChosen(sender: UIButton) {
colorSelection.text = "blue-green"
colorSelection.textColor = BLUGREEN.titleColorForState(UIControlState.Normal)
}
@IBAction func MZPChosen(sender: UIButton) {
planktonSelection.text = "mostly zooplankton"
}
@IBAction func MPPChosen(sender: UIButton) {
planktonSelection.text = "mostly phytoplankton"
}
@IBAction func AHHChosen(sender: UIButton) {
planktonSelection.text = "about half and half"
}
override func viewDidLoad() {
super.viewDidLoad()
schoolGroupLabel.text = "School: " + SchoolName + " || Group: " + GroupName
WPButton.layer.borderWidth = 1
WCButton.layer.borderWidth = 1
PSNButton.layer.borderWidth = 1
PSButton.layer.borderWidth = 1
hidePSN(true)
hideWaterCol(true)
hidePS(true)
Done.hidden = true
TEMP.keyboardType = UIKeyboardType.NumberPad
VISIB.keyboardType = UIKeyboardType.NumberPad
DEPTH.keyboardType = UIKeyboardType.NumberPad
SALIN.keyboardType = UIKeyboardType.NumberPad
// Do any additional setup after loading
WPButton.backgroundColor = UIColor.lightGrayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func WPPressed(sender: UIButton) {
hideWaterCol(true)
hidePSN(true)
hidePS(true)
hideWaterQ(false)
if(!Done.hidden){
Done.hidden = true
}
WPButton.backgroundColor = UIColor.lightGrayColor()
WCButton.backgroundColor = UIColor.clearColor()
PSNButton.backgroundColor = UIColor.clearColor()
PSButton.backgroundColor = UIColor.clearColor()
}
@IBAction func WCPressed(sender: UIButton) {
hidePSN(true)
hidePS(true)
hideWaterQ(true)
hideWaterCol(false)
if(!Done.hidden){
Done.hidden = true
}
WPButton.backgroundColor = UIColor.clearColor()
WCButton.backgroundColor = UIColor.lightGrayColor()
PSNButton.backgroundColor = UIColor.clearColor()
PSButton.backgroundColor = UIColor.clearColor()
}
@IBOutlet weak var saveDataDict: UIButton!
@IBAction func saveDataDict(sender: AnyObject) {
self.gatherAllData()
}
@IBAction func PSNPressed(sender: UIButton) {
hideWaterCol(true)
hidePS(true)
hideWaterQ(true)
hidePSN(false)
if(!Done.hidden){
Done.hidden = true
}
WPButton.backgroundColor = UIColor.clearColor()
WCButton.backgroundColor = UIColor.clearColor()
PSNButton.backgroundColor = UIColor.lightGrayColor()
PSButton.backgroundColor = UIColor.clearColor()
}
@IBAction func PSPressed(sender: UIButton) {
hideWaterCol(true)
hidePSN(true)
hideWaterQ(true)
hidePS(false)
Done.hidden = false
WPButton.backgroundColor = UIColor.clearColor()
WCButton.backgroundColor = UIColor.clearColor()
PSNButton.backgroundColor = UIColor.clearColor()
PSButton.backgroundColor = UIColor.lightGrayColor()
}
func hidePS(sender:Bool){
if(sender){
PlankSLabel.hidden = true
PLANKSPEC.hidden = true
}else{
PlankSLabel.hidden = false
PLANKSPEC.hidden = false
}
}
func hideWaterQ(sender:Bool){
if(sender){
TEMP.hidden = true
VISIB.hidden = true
DEPTH.hidden = true
SALIN.hidden = true
TempLabel.hidden = true
VisLabel.hidden = true
DepthLabel.hidden = true
SalLabel.hidden = true
}else{
TEMP.hidden = false
VISIB.hidden = false
DEPTH.hidden = false
SALIN.hidden = false
TempLabel.hidden = false
VisLabel.hidden = false
DepthLabel.hidden = false
SalLabel.hidden = false
}
}
func hideWaterCol(sender:Bool){
if(sender){
WCLabel.hidden = true
BROWN.hidden = true
BLUE.hidden = true
RED.hidden = true
GREEN.hidden = true
YELLGREEN.hidden = true
BLUGREEN.hidden = true
colorSelection.hidden = true
}else{
WCLabel.hidden = false
BROWN.hidden = false
BLUE.hidden = false
RED.hidden = false
GREEN.hidden = false
YELLGREEN.hidden = false
BLUGREEN.hidden = false
colorSelection.hidden = false
}
}
func hidePSN(sender:Bool){
if(sender){
PSNLabel.hidden = true
MZP.hidden = true
MPP.hidden = true
AHH.hidden = true
planktonSelection.hidden = true
}else{
PSNLabel.hidden = false
MZP.hidden = false
MPP.hidden = false
AHH.hidden = false
planktonSelection.hidden = false
}
}
func gatherAllData(){
var aDictionary = [String : String]()
var bDictionary = [String : String]()
var cDictionary = [String : String]()
var dDictionary = [String : String]()
aDictionary["bsurface_temperature"] = TEMP.text
aDictionary["bseawater_visibility"] = VISIB.text
aDictionary["bseawater_depth"] = DEPTH.text
aDictionary["bseawater_salinity"] = SALIN.text
aDictionary["bplankton_sample"] = planktonSelection.text
aDictionary["bplankton_notes"] = PLANKSPEC.text
aDictionary["bseawater_color"] = colorSelection.text
aDictionary["bmeasurement_time"] = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .ShortStyle)
aDictionary["bmeasurement_date"] = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .NoStyle)
bDictionary["type"] = "biology"
cDictionary["group"] = GroupName
dDictionary["id"] = (sharedData().objectForKey("school_id") as String)
sharedData().setObject(aDictionary, forKey: "data")
sharedData().addEntriesFromDictionary(bDictionary)
sharedData().addEntriesFromDictionary(cDictionary)
sharedData().addEntriesFromDictionary(dDictionary)
//var myNewDictArray: [[String:String]] = []
//myNewDictArray.append(aDictionary)
//sharedData().setObject(myNewDictArray, forKey: "biology")
//bData().setObject(sharedData(), forKey: "group_data")
//cData().setObject(bData(), forKey: "data")
}
@IBAction func saveData(sender: AnyObject) {
gatherAllData()
println(sharedData())
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestVC: SubmitDataViewController = segue.destinationViewController as SubmitDataViewController
DestVC.groupName = GroupName
}
}
| 7c5d55a913d64ef2ca82edab22ad8346 | 30.109635 | 137 | 0.638296 | false | false | false | false |
garynewby/WKWebViewLocal | refs/heads/master | WKWebViewLocal/WKWebViewLocal/ViewController.swift | mit | 1 | //
// ViewController.swift
// WKWebViewLocal
//
// Created by Gary Newby on 2/17/18.
//
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
title = "WKWebView"
webView.navigationDelegate = self
// Add addScriptMessageHandler in javascript: window.webkit.messageHandlers.MyObserver.postMessage()
webView.configuration.userContentController.add(self, name: "MyObserver")
// Choose to load a file or a string
let loadFile = false
if let filePath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "Web_Assets") {
if loadFile {
// load file
let filePathURL = URL.init(fileURLWithPath: filePath)
let fileDirectoryURL = filePathURL.deletingLastPathComponent()
webView.loadFileURL(filePathURL, allowingReadAccessTo: fileDirectoryURL)
} else {
do {
// load html string - baseURL needs to be set for local files to load correctly
let html = try String(contentsOfFile: filePath, encoding: .utf8)
webView.loadHTMLString(html, baseURL: Bundle.main.resourceURL?.appendingPathComponent("Web_Assets"))
} catch {
print("Error loading html")
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func callJavascriptTapped(_ sender: UIButton) {
let script = "testJS()"
webView.evaluateJavaScript(script) { (result: Any?, error: Error?) in
if let error = error {
print("evaluateJavaScript error: \(error.localizedDescription)")
} else {
print("evaluateJavaScript result: \(result ?? "")")
}
}
}
}
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// Callback from javascript: window.webkit.messageHandlers.MyObserver.postMessage(message)
let text = message.body as! String
let alertController = UIAlertController(title: "Javascript said:", message: text, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
print("OK")
}
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
}
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("didFinish navigation:")
}
}
| 54a124a10ab32ab561ad74d5d02637d8 | 35.506494 | 120 | 0.630025 | false | false | false | false |
jbruce2112/cutlines | refs/heads/master | Cutlines/Controllers/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// Cutlines
//
// Created by John on 2/17/17.
// Copyright © 2017 Bruce32. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
@IBOutlet private var versionLabel: UILabel!
@IBOutlet private var iconsLabel: UILabel!
@IBOutlet private var iconsButton: UIButton!
@IBOutlet private var privacyLabel: UILabel!
@IBOutlet private var cellSyncLabel: UILabel!
@IBOutlet private var darkModeLabel: UILabel!
@IBOutlet private var cellSyncSwitch: UISwitch!
@IBOutlet private var darkModeSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Settings"
versionLabel.text = getVersion()
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(iconsLabelTapped))
iconsLabel.addGestureRecognizer(gestureRecognizer)
iconsButton.addTarget(self, action: #selector(openIconsURL), for: .touchUpInside)
// load preferences
cellSyncSwitch.isOn = appGroupDefaults.bool(forKey: PrefKey.cellSync)
darkModeSwitch.isOn = appGroupDefaults.bool(forKey: PrefKey.nightMode)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setTheme()
}
override func setTheme(_ theme: Theme) {
super.setTheme(theme)
var backgroundColor: UIColor!
var foregroundColor: UIColor!
// Styling this view controller is a special case for now
if theme.isNight {
backgroundColor = theme.backgroundColor
foregroundColor = theme.altBackgroundColor
} else {
backgroundColor = theme.altBackgroundColor
foregroundColor = theme.backgroundColor
}
view.backgroundColor = backgroundColor
versionLabel.textColor = theme.textColor
iconsLabel.textColor = theme.textColor
iconsLabel.backgroundColor = foregroundColor
privacyLabel.textColor = theme.textColor
cellSyncLabel.textColor = theme.textColor
darkModeLabel.textColor = theme.textColor
for cell in tableView.visibleCells {
cell.backgroundColor = foregroundColor
}
// force the section headers to refresh
tableView.reloadSections(IndexSet(integer: 0), with: .none)
tableView.reloadSections(IndexSet(integer: 1), with: .none)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier! {
case "showPrivacy":
let vc = segue.destination as! WebViewController
vc.url = Bundle.main.url(forResource: "privacy", withExtension: "html")
default:
break
}
}
@objc func openIconsURL() {
// Open the icons URL in the browser
UIApplication.shared.open(URL(string: "https://icons8.com")!, options: [:], completionHandler: nil)
}
@objc func iconsLabelTapped(recognizer: UITapGestureRecognizer) {
if recognizer.state == UIGestureRecognizer.State.ended {
openIconsURL()
}
}
private func getBuildDate() -> Date {
guard
let infoPath = Bundle.main.path(forResource: "Info.plist", ofType: nil),
let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
let infoDate = infoAttr[.modificationDate] as? Date else {
return Date()
}
return infoDate
}
private func getBuildVersion() -> String {
guard
let infoDict = Bundle.main.infoDictionary,
let version = infoDict["CFBundleShortVersionString"] as? String else {
return "0.0"
}
return version
}
private func getVersion() -> String {
let version = "Version \(getBuildVersion())"
#if DEBUG
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateStyle = .medium
formatter.timeStyle = .medium
let buildDate = formatter.string(from: getBuildDate())
return "\(version) built on \(buildDate)"
#else
return version
#endif
}
// MARK: UI Actions
@IBAction private func toggleCellSync(sender: UISwitch) {
appGroupDefaults.set(sender.isOn, forKey: PrefKey.cellSync)
}
@IBAction private func toggleDarkMode(sender: UISwitch) {
appGroupDefaults.set(sender.isOn, forKey: PrefKey.nightMode)
// Set the theme in the delegate for the root controllers
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.setTheme()
// Force our view to refresh since it's in the foreground
setTheme()
}
}
| 4698f440a57bbff4f05ebc12015d9338 | 24.690476 | 101 | 0.725672 | false | false | false | false |
haawa799/WaniKani-iOS | refs/heads/master | WaniKani/Model/KanjiGraphicInfo.swift | gpl-3.0 | 1 | //
// Kanji.swift
// StrokeDrawingView
//
// Created by Andriy K. on 12/4/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import UIKit
import KanjiBezierPaths
class KanjiGraphicInfo {
let color0 = UIColor(red:0.95, green:0, blue:0.63, alpha:1)
let bezierPathes: [UIBezierPath]
let kanji: String
init(kanji: String) {
self.kanji = kanji
self.bezierPathes = KanjiBezierPathesHelper.pathesForKanji(kanji) ?? [UIBezierPath]()
}
class func kanjiFromString(kanjiChar: String) -> KanjiGraphicInfo? {
let kanji = KanjiGraphicInfo(kanji: kanjiChar)
return (kanji.bezierPathes.count > 0) ? kanji : nil
}
}
extension UIColor {
func lighter(amount : CGFloat = 0.25) -> UIColor {
return hueColorWithBrightnessAmount(1 + amount)
}
func darker(amount : CGFloat = 0.25) -> UIColor {
return hueColorWithBrightnessAmount(1 - amount)
}
private func hueColorWithBrightnessAmount(amount: CGFloat) -> UIColor {
var hue : CGFloat = 0
var saturation : CGFloat = 0
var brightness : CGFloat = 0
var alpha : CGFloat = 0
if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return UIColor( hue: hue,
saturation: saturation,
brightness: brightness * amount,
alpha: alpha )
} else {
return self
}
}
}
| 5f2c7668540d75fa4175d0a0f848e738 | 22.508475 | 89 | 0.648882 | false | false | false | false |
stevethomp/ViDIA-Playgrounds | refs/heads/master | ImportantWorkProject/Carthage/Checkouts/airg-ios-tools/airgiOSTools/Designables.swift | apache-2.0 | 1 | //
// Designables.swift
// airG-iOS-Tools
//
// Created by Steven Thompson on 2016-07-26.
// Copyright © 2016 airg. All rights reserved.
//
import UIKit
//MARK: @IBDesignable
@IBDesignable
public extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
@IBInspectable public var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable public var borderColor: UIColor? {
set {
layer.borderColor = newValue?.cgColor
}
get {
if let layerColor = layer.borderColor {
return UIColor(cgColor: layerColor)
} else {
return nil
}
}
}
@IBInspectable public var shadowColor: UIColor? {
set {
layer.shadowColor = newValue?.cgColor
}
get {
if let shadowColor = layer.shadowColor {
return UIColor(cgColor: shadowColor)
} else {
return nil
}
}
}
@IBInspectable public var shadowRadius: CGFloat? {
set {
layer.shadowRadius = newValue ?? 0
}
get {
return layer.shadowRadius
}
}
}
//MARK:-
extension UIButton {
override open var intrinsicContentSize : CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + titleEdgeInsets.left + titleEdgeInsets.right, height: s.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
}
}
//MARK:-
@IBDesignable
open class ExtraPaddingTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBInspectable open var horizontalPadding: CGFloat = 0 {
didSet {
edgeInsets = UIEdgeInsets(top: 0, left: horizontalPadding, bottom: 0, right: horizontalPadding)
invalidateIntrinsicContentSize()
}
}
fileprivate var edgeInsets: UIEdgeInsets = UIEdgeInsets.zero
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, edgeInsets)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, edgeInsets)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, edgeInsets)
}
override open func rightViewRect(forBounds bounds: CGRect) -> CGRect {
if let rightView = rightView {
return CGRect(x: bounds.size.width - horizontalPadding - rightView.frame.size.width,
y: bounds.size.height/2 - rightView.frame.size.height/2,
width: rightView.frame.size.width,
height: rightView.frame.size.height)
}
return CGRect()
}
}
//MARK:-
@IBDesignable
open class ExtraPaddingLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBInspectable open var extraHorizontalPadding: CGFloat = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
@IBInspectable open var extraVerticalPadding: CGFloat = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
override open var intrinsicContentSize : CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + 2 * extraHorizontalPadding, height: s.height + 2 * extraVerticalPadding)
}
}
//MARK:-
@IBDesignable
open class ExtraPaddingTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBInspectable var horizontalPadding: CGFloat = 0 {
didSet {
textContainerInset = UIEdgeInsets(top: textContainerInset.top, left: horizontalPadding, bottom: textContainerInset.bottom, right: horizontalPadding)
invalidateIntrinsicContentSize()
}
}
@IBInspectable var verticalPadding: CGFloat = 8 {
didSet {
textContainerInset = UIEdgeInsets(top: verticalPadding, left: textContainerInset.left, bottom: verticalPadding, right: textContainerInset.right)
invalidateIntrinsicContentSize()
}
}
override open var intrinsicContentSize : CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + 2 * horizontalPadding, height: s.height + 2 * verticalPadding)
}
}
| 387a810517ec1361aba6cf4c2df69277 | 27.331461 | 160 | 0.618283 | false | false | false | false |
irshadqureshi/IQCacheResources | refs/heads/master | IQCacheResources/Classes/CacheManager.swift | mit | 1 | //
// Cache.swift
// Pods
//
// Created by Irshad on 15/07/17.
//
//
import Foundation
import UIKit
public class CacheManager {
static public let sharedCache = CacheManager()
let imageCache = NSCache<AnyObject, DiscradableImage>()
let dataCache = NSCache<AnyObject, DiscardableData>()
let jsonCache = NSCache<AnyObject, DiscardableJSON>()
public init(cacheCountLimit: Int, cacheSizeLimit: Int) {
imageCache.countLimit = cacheCountLimit
dataCache.countLimit = cacheCountLimit
jsonCache.countLimit = cacheCountLimit
imageCache.totalCostLimit = cacheSizeLimit
dataCache.totalCostLimit = cacheSizeLimit
jsonCache.totalCostLimit = cacheSizeLimit
}
convenience init(){
self.init(cacheCountLimit: 0,cacheSizeLimit: 0)
}
// Mark:- Cache Image
public func archiveImage(image: UIImage?, url: String) {
if image == nil {
imageCache.removeObject(forKey: url as NSString)
return
}
let data = DiscradableImage(image: image!)
imageCache.setObject(data, forKey: url as NSString)
}
// Mark:- Cache Other Data like Json,Xml,etc
public func archiveAnyData(any: AnyObject?, url: String) {
if any == nil {
dataCache.removeObject(forKey: url as NSString)
return
}
let data = DiscardableData(data: any! as! Data)
dataCache.setObject(data, forKey: url as NSString)
}
// Mark:- Retrive Data
public func unarchiveData(url: String?) -> Data? {
if url == nil || url! == "" {
return nil
}
if let cachedData = dataCache.object(forKey: url! as NSString) {
return cachedData.data
}
return nil
}
// Mark:- Retrive Json
public func unarchiveJSON(url: String?) -> [String: AnyObject]? {
if url == nil || url! == "" {
return nil
}
if let cachedJSON = jsonCache.object(forKey: url! as NSString) {
return cachedJSON.json
}
return nil
}
// Mark:- Retrive Image
public func unarchiveImage(url: String?) -> UIImage? {
if url == nil || url! == "" {
return nil
}
if let cachedImage = imageCache.object(forKey: url! as NSString) {
return cachedImage.image
}
return nil
}
// Mark:- Clear Cache
public func clearCache() {
imageCache.removeAllObjects()
dataCache.removeAllObjects()
jsonCache.removeAllObjects()
}
}
| a273a877a4ccd11fd09640df2f39d0ab | 22.385246 | 74 | 0.540834 | false | false | false | false |
spritekitbook/spritekitbook-swift | refs/heads/master | Bonus/SpaceRunner/SpaceRunner/RetryButton.swift | apache-2.0 | 4 | //
// RetryButton.swift
// SpaceRunner
//
// Created by Jeremy Novak on 9/12/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
class RetryButton: SKSpriteNode {
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
let texture = GameTextures.sharedInstance.texture(name: SpriteName.retryButton)
self.init(texture: texture, color: SKColor.white, size: texture.size())
setup()
animate()
}
// MARK: - Setup
private func setup() {
self.position = CGPoint(x: kViewSize.width / 2, y: 0 - kViewSize.height * 0.25)
}
// MARK: - Animations
private func animate() {
let moveIn = SKAction.move(to: CGPoint(x: kViewSize.width / 2, y: kViewSize.height * 0.25), duration: 0.25)
let scaleUp = SKAction.scale(to: 1.1, duration: 0.125)
let scaleDown = SKAction.scale(to: 1.0, duration: 0.125)
self.run(SKAction.sequence([moveIn, scaleUp, scaleDown]))
}
// MARK: - Actions
func tapped() {
self.run(GameAudio.sharedInstance.playClip(type: .button))
}
}
| 3839c18629c4ff617c3171821fa5c86b | 26.2 | 115 | 0.605882 | false | false | false | false |
romankisil/eqMac2 | refs/heads/master | native/shared/Source/EQMClient.swift | mit | 1 | //
// EQMClient.swift
// Driver
//
// Created by Nodeful on 07/09/2021.
// Copyright © 2021 Bitgapp. All rights reserved.
//
import Foundation
import CoreAudio.AudioServerPlugIn
public class EQMClient {
public var clientId: UInt32
public var processId: pid_t
public var bundleId: String?
public init (clientId: UInt32, processId: pid_t, bundleId: String? = nil, volume: Float = 1) {
self.clientId = clientId
self.processId = processId
self.bundleId = bundleId
}
public init (from clientInfo: AudioServerPlugInClientInfo) {
clientId = clientInfo.mClientID
processId = clientInfo.mProcessID
bundleId = clientInfo.mBundleID?.takeUnretainedValue() as String?
}
public var dictionary: [String: Any] {
var dict = [
"clientId": clientId,
"processId": processId,
] as [String : Any]
if bundleId != nil {
dict["bundleId"] = bundleId!
}
return dict
}
public var cfDictionary: CFDictionary {
let dict = NSDictionary(dictionary: dictionary)
return dict as CFDictionary
}
public var isAppClient: Bool {
return bundleId == APP_BUNDLE_ID
}
public static func fromDictionary (_ dict: [String: Any]) -> EQMClient? {
guard
let clientId = dict["clientId"] as? UInt32,
let processId = dict["processId"] as? pid_t,
let volume = dict["volume"] as? Float
else {
return nil
}
let bundleId = dict["bundleId"] as? String
return EQMClient(clientId: clientId, processId: processId, bundleId: bundleId, volume: volume)
}
}
| 3add9d1799a98be94cab33cb2dd0785f | 23.34375 | 98 | 0.668806 | false | false | false | false |
jasonsturges/SwiftLabs | refs/heads/master | SpriteKit2dDrawing/SpriteKit2dDrawing/GameViewController.swift | mit | 2 | //
// GameViewController.swift
// SpriteKit2dDrawing
//
// Created by Jason Sturges on 1/13/17.
// Copyright © 2017 Jason Sturges. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| 9839a1a0a889c1898feff6aa499c50a8 | 24.527273 | 77 | 0.583333 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | refs/heads/master | Food Hygiene Ratings/MapViewController.swift | apache-2.0 | 1 | //
// MapViewController.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 09/02/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate, AppStateChangeObserver {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var loadingLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
@IBAction func refreshClicked(_ sender: UIBarButtonItem) {
let model = MainModel.sharedInstance
if model.canFindEstablishments(){
let mapCentre = mapView.region.center
model.findEstablishments(longitude: mapCentre.longitude, latitude: mapCentre.latitude)
}
}
//Just over a mile radius
let mapRadius : CLLocationDistance = 1000
//UK region, co-ordinates found by trial and error
private let ukregion : MKCoordinateRegion = {
let coords = CLLocationCoordinate2D(latitude: 55.0, longitude: -3.1)
let span = MKCoordinateSpan(latitudeDelta: 12, longitudeDelta: 6)
return MKCoordinateRegion(center: coords, span: span)
}()
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
loadingLabel.isHidden=false
// Do any additional setup after loading the view.
mapView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
let model = MainModel.sharedInstance
modelToView(state: model.state)
model.addObserver("mapView", observer: self)
}
override func viewWillDisappear(_ animated: Bool) {
let model = MainModel.sharedInstance
model.removeObserver("mapView")
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? MapMarker {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView { // 2
dequeuedView.annotation = annotation
view = dequeuedView
} else {
// 3
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
view.pinTintColor = annotation.color
return view
}
return nil
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let annotation = view.annotation as? MapMarker {
showEstablishment(establishment: annotation.establishment)
}
}
fileprivate func showEstablishment(establishment : Establishment){
if let navCtrl = self.navigationController
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let detailsVC = storyboard.instantiateViewController(withIdentifier: "establishmentDetailsScene") as? DetailsViewController{
detailsVC.establishment = establishment
navCtrl.pushViewController(detailsVC, animated: true)
}
}
}
internal func stateChanged(_ newState: AppState) {
OperationQueue.main.addOperation {
self.modelToView(state: newState)
}
}
func modelToView(state : AppState){
switch state {
case .ready:
showActivityIndicator()
case .requestingLocationAuthorization:
break
case .locating:
break
case .foundLocation:
break
case .notAuthorizedForLocating:
break
case .errorLocating:
hideActivityIndicator()
case .loading:
showActivityIndicator()
case .loaded:
hideActivityIndicator()
self.loadedState()
case .error:
hideActivityIndicator()
}
}
func showActivityIndicator(){
activityIndicator.startAnimating()
loadingLabel.isHidden=false
}
func hideActivityIndicator(){
activityIndicator.stopAnimating()
loadingLabel.isHidden=true
}
func loadedState(){
let model = MainModel.sharedInstance
//remove old annotations
self.mapView.removeAnnotations(self.mapView.annotations)
let markers = model.results
.filter(){$0.address.coordinate.isWithinUK()}
.map(){MapMarker(establishment: $0)}
if markers.count==0 {
mapView.setRegion(ukregion, animated: true)
return
}
switch model.searchType {
case .advanced:
self.mapView.showAnnotations(markers, animated: true)
case .map:
self.mapView.showAnnotations(markers, animated: true)
case .local:
self.mapView.addAnnotations(markers)
//show map centred on location in the model
let coords2d = CLLocationCoordinate2D(latitude: model.location.latitude, longitude: model.location.longitude)
let coordinateRegion = MKCoordinateRegion(center: coords2d,latitudinalMeters: mapRadius * 2.0, longitudinalMeters: mapRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
}
}
| 041526351d3061ff363d87e71debbecf | 33.446927 | 143 | 0.633474 | false | false | false | false |
christophhagen/Signal-iOS | refs/heads/master | Signal/src/ViewControllers/ContactsPicker.swift | gpl-3.0 | 1 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
// Originally based on EPContacts
//
// Created by Prabaharan Elangovan on 12/10/15.
// Parts Copyright © 2015 Prabaharan Elangovan. All rights reserved
import UIKit
import Contacts
import SignalServiceKit
@available(iOS 9.0, *)
public protocol ContactsPickerDelegate {
func contactsPicker(_: ContactsPicker, didContactFetchFailed error: NSError)
func contactsPicker(_: ContactsPicker, didCancel error: NSError)
func contactsPicker(_: ContactsPicker, didSelectContact contact: Contact)
func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact])
func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool
}
@available(iOS 9.0, *)
public extension ContactsPickerDelegate {
func contactsPicker(_: ContactsPicker, didContactFetchFailed error: NSError) { }
func contactsPicker(_: ContactsPicker, didCancel error: NSError) { }
func contactsPicker(_: ContactsPicker, didSelectContact contact: Contact) { }
func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact]) { }
func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool { return true }
}
public enum SubtitleCellValue {
case phoneNumber
case email
}
@available(iOS 9.0, *)
open class ContactsPicker: OWSViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
// MARK: - Properties
let TAG = "[ContactsPicker]"
let contactCellReuseIdentifier = "contactCellReuseIdentifier"
let contactsManager: OWSContactsManager
let collation = UILocalizedIndexedCollation.current()
let contactStore = CNContactStore()
// Data Source State
lazy var sections = [[CNContact]]()
lazy var filteredSections = [[CNContact]]()
lazy var selectedContacts = [Contact]()
// Configuration
open var contactsPickerDelegate: ContactsPickerDelegate?
var subtitleCellValue = SubtitleCellValue.phoneNumber
var multiSelectEnabled = false
let allowedContactKeys: [CNKeyDescriptor] = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactThumbnailImageDataKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor
]
// MARK: - Lifecycle Methods
override open func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("INVITE_FRIENDS_PICKER_TITLE", comment: "Navbar title")
searchBar.placeholder = NSLocalizedString("INVITE_FRIENDS_PICKER_SEARCHBAR_PLACEHOLDER", comment: "Search")
// Prevent content form going under the navigation bar
self.edgesForExtendedLayout = []
// Auto size cells for dynamic type
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.allowsMultipleSelection = multiSelectEnabled
registerContactCell()
initializeBarButtons()
reloadContacts()
updateSearchResults(searchText: "")
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangePreferredContentSize), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
}
func didChangePreferredContentSize() {
self.tableView.reloadData()
}
func initializeBarButtons() {
let cancelButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(onTouchCancelButton))
self.navigationItem.leftBarButtonItem = cancelButton
if multiSelectEnabled {
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onTouchDoneButton))
self.navigationItem.rightBarButtonItem = doneButton
}
}
fileprivate func registerContactCell() {
tableView.register(ContactCell.nib, forCellReuseIdentifier: contactCellReuseIdentifier)
}
// MARK: - Initializers
init() {
contactsManager = Environment.current().contactsManager
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
contactsManager = Environment.current().contactsManager
super.init(coder: aDecoder)
}
convenience public init(delegate: ContactsPickerDelegate?) {
self.init(delegate: delegate, multiSelection: false)
}
convenience public init(delegate: ContactsPickerDelegate?, multiSelection: Bool) {
self.init()
multiSelectEnabled = multiSelection
contactsPickerDelegate = delegate
}
convenience public init(delegate: ContactsPickerDelegate?, multiSelection: Bool, subtitleCellType: SubtitleCellValue) {
self.init()
multiSelectEnabled = multiSelection
contactsPickerDelegate = delegate
subtitleCellValue = subtitleCellType
}
// MARK: - Contact Operations
open func reloadContacts() {
getContacts( onError: { error in
Logger.error("\(self.TAG) failed to reload contacts with error:\(error)")
})
}
func getContacts(onError errorHandler: @escaping (_ error: Error) -> Void) {
switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) {
case CNAuthorizationStatus.denied, CNAuthorizationStatus.restricted:
let title = NSLocalizedString("INVITE_FLOW_REQUIRES_CONTACT_ACCESS_TITLE", comment: "Alert title when contacts disabled while trying to invite contacts to signal")
let body = NSLocalizedString("INVITE_FLOW_REQUIRES_CONTACT_ACCESS_BODY", comment: "Alert body when contacts disabled while trying to invite contacts to signal")
let alert = UIAlertController(title: title, message: body, preferredStyle: UIAlertControllerStyle.alert)
let dismissText = CommonStrings.cancelButton
let cancelAction = UIAlertAction(title: dismissText, style: .cancel, handler: { _ in
let error = NSError(domain: "contactsPickerErrorDomain", code: 1, userInfo: [NSLocalizedDescriptionKey: "No Contacts Access"])
self.contactsPickerDelegate?.contactsPicker(self, didContactFetchFailed: error)
errorHandler(error)
self.dismiss(animated: true, completion: nil)
})
alert.addAction(cancelAction)
let settingsText = NSLocalizedString("OPEN_SETTINGS_BUTTON", comment:"Button text which opens the settings app")
let openSettingsAction = UIAlertAction(title: settingsText, style: .default, handler: { (_) in
UIApplication.shared.openSystemSettings()
})
alert.addAction(openSettingsAction)
self.present(alert, animated: true, completion: nil)
case CNAuthorizationStatus.notDetermined:
//This case means the user is prompted for the first time for allowing contacts
contactStore.requestAccess(for: CNEntityType.contacts) { (granted, error) -> Void in
//At this point an alert is provided to the user to provide access to contacts. This will get invoked if a user responds to the alert
if granted {
self.getContacts(onError: errorHandler)
} else {
errorHandler(error!)
}
}
case CNAuthorizationStatus.authorized:
//Authorization granted by user for this app.
var contacts = [CNContact]()
do {
let contactFetchRequest = CNContactFetchRequest(keysToFetch: allowedContactKeys)
try contactStore.enumerateContacts(with: contactFetchRequest) { (contact, _) -> Void in
contacts.append(contact)
}
self.sections = collatedContacts(contacts)
} catch let error as NSError {
Logger.error("\(self.TAG) Failed to fetch contacts with error:\(error)")
}
}
}
func collatedContacts(_ contacts: [CNContact]) -> [[CNContact]] {
let selector: Selector = #selector(getter: CNContact.nameForCollating)
var collated = Array(repeating: [CNContact](), count: collation.sectionTitles.count)
for contact in contacts {
let sectionNumber = collation.section(for: contact, collationStringSelector: selector)
collated[sectionNumber].append(contact)
}
return collated
}
// MARK: - Table View DataSource
open func numberOfSections(in tableView: UITableView) -> Int {
return self.collation.sectionTitles.count
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dataSource = filteredSections
guard section < dataSource.count else {
return 0
}
return dataSource[section].count
}
// MARK: - Table View Delegates
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as! ContactCell
let dataSource = filteredSections
let cnContact = dataSource[indexPath.section][indexPath.row]
let contact = Contact(systemContact: cnContact)
cell.updateContactsinUI(contact, subtitleType: subtitleCellValue, contactsManager: self.contactsManager)
let isSelected = selectedContacts.contains(where: { $0.uniqueId == contact.uniqueId })
cell.isSelected = isSelected
// Make sure we preserve selection across tableView.reloadData which happens when toggling between
// search controller
if (isSelected) {
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
} else {
self.tableView.deselectRow(at: indexPath, animated: false)
}
return cell
}
open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ContactCell
let deselectedContact = cell.contact!
selectedContacts = selectedContacts.filter {
return $0.uniqueId != deselectedContact.uniqueId
}
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ContactCell
let selectedContact = cell.contact!
guard (contactsPickerDelegate == nil || contactsPickerDelegate!.contactsPicker(self, shouldSelectContact: selectedContact)) else {
self.tableView.deselectRow(at: indexPath, animated: false)
return
}
selectedContacts.append(selectedContact)
if !multiSelectEnabled {
//Single selection code
self.dismiss(animated: true) {
self.contactsPickerDelegate?.contactsPicker(self, didSelectContact: selectedContact)
}
}
}
open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return collation.section(forSectionIndexTitle: index)
}
open func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return collation.sectionIndexTitles
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dataSource = filteredSections
guard section < dataSource.count else {
return nil
}
// Don't show empty sections
if dataSource[section].count > 0 {
guard section < collation.sectionTitles.count else {
return nil
}
return collation.sectionTitles[section]
} else {
return nil
}
}
// MARK: - Button Actions
func onTouchCancelButton() {
contactsPickerDelegate?.contactsPicker(self, didCancel: NSError(domain: "contactsPickerErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey: "User Canceled Selection"]))
dismiss(animated: true, completion: nil)
}
func onTouchDoneButton() {
contactsPickerDelegate?.contactsPicker(self, didSelectMultipleContacts: selectedContacts)
dismiss(animated: true, completion: nil)
}
// MARK: - Search Actions
open func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
updateSearchResults(searchText: searchText)
}
open func updateSearchResults(searchText: String) {
let predicate: NSPredicate
if searchText.count == 0 {
filteredSections = sections
} else {
do {
predicate = CNContact.predicateForContacts(matchingName: searchText)
let filteredContacts = try contactStore.unifiedContacts(matching: predicate, keysToFetch: allowedContactKeys)
filteredSections = collatedContacts(filteredContacts)
} catch let error as NSError {
Logger.error("\(self.TAG) updating search results failed with error: \(error)")
}
}
self.tableView.reloadData()
}
}
@available(iOS 9.0, *)
let ContactSortOrder = computeSortOrder()
@available(iOS 9.0, *)
func computeSortOrder() -> CNContactSortOrder {
let comparator = CNContact.comparator(forNameSortOrder: .userDefault)
let contact0 = CNMutableContact()
contact0.givenName = "A"
contact0.familyName = "Z"
let contact1 = CNMutableContact()
contact1.givenName = "Z"
contact1.familyName = "A"
let result = comparator(contact0, contact1)
if result == .orderedAscending {
return .givenName
} else {
return .familyName
}
}
@available(iOS 9.0, *)
fileprivate extension CNContact {
/**
* Sorting Key used by collation
*/
@objc var nameForCollating: String {
get {
if self.familyName.isEmpty && self.givenName.isEmpty {
return self.emailAddresses.first?.value as String? ?? ""
}
let compositeName: String
if ContactSortOrder == .familyName {
compositeName = "\(self.familyName) \(self.givenName)"
} else {
compositeName = "\(self.givenName) \(self.familyName)"
}
return compositeName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
}
| 85a57710fc4cc6a7b34fc6fc1cb0f048 | 37.639687 | 185 | 0.666464 | false | false | false | false |
skyfe79/TIL | refs/heads/master | about.iOS/about.Concurrency/08_DispatchGroup/GCDGroups.playground/Contents.swift | mit | 1 | import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: # GCD Groups
//: It's often useful to get notifications when a set of tasks has been completed—and that's precisely what GCD groups are for
let workerQueue = dispatch_queue_create("com.raywenderlich.worker", DISPATCH_QUEUE_CONCURRENT)
let numberArray = [(0,1), (2,3), (4,5), (6,7), (8,9)]
//: ## Creating a group
let slowSumGroup = dispatch_group_create()
//: ## Dispatching to a group
//: Very much like traditional `dispatch_async()`
for inValue in numberArray {
dispatch_group_async(slowSumGroup, workerQueue) {
let result = slowSum(inValue)
dispatch_group_async(slowSumGroup, dispatch_get_main_queue()) {
print("Result = \(result)")
}
}
}
//: ## Notification of group completion
//: Will be called only when everything in that dispatch group is completed
dispatch_group_notify(slowSumGroup, dispatch_get_main_queue()) {
print("SLOW SUM: Completed all operations")
}
//: ## Waiting for a group to complete
//: __DANGER__ This is synchronous and can block
//: This is a synchronous call on the current queue, so will block it. You cannot have anything in the group that wants to use the current queue otherwise you'll block.
//17라인에서 main-queue를 얻어서 결과를 print하고 있다.
//아래의 문장은 slowSumGroup이 끝나길 기다리는데
//내부에서 main-queue를 사용하므로 main-queue가 끝나길 기다리는 것과 같다
//그러나 main-queue는 끝나지 않고 계속해서 이벤트 등을 처리하므로 끝나는 큐가 아니다.
//그래서 아래의 문장은 main-queue를 블럭 시킨다. DEAD-LOCK
//17라인에서 print출력을 main-queue 없이 하면 블럭되지 않는다.
//dispatch_group_wait(slowSumGroup, DISPATCH_TIME_FOREVER)
//: ## Wrapping an existing Async API
//: All well and good for new APIs, but there are lots of async APIs that don't have group parameters. What can you do with them?
print("\n=== Wrapping an existing Async API ===\n")
let wrappedGroup = dispatch_group_create()
//: Wrap the original function
func asyncSum(input: (Int, Int), completionQueue: dispatch_queue_t, group: dispatch_group_t, completion: (Int)->()) {
dispatch_group_enter(group)
asyncSum(input, completionQueue: completionQueue) {
completion($0)
dispatch_group_leave(group)
}
}
for pair in numberArray {
// TODO: use the new function here to calculate the sums of the array
asyncSum(pair, completionQueue: workerQueue, group: wrappedGroup) {
print("Result : \($0)")
}
}
// TODO: Notify of completion
dispatch_group_notify(wrappedGroup, dispatch_get_main_queue()) {
print("Wrapped API: Completed all operations")
}
| 15f4f5cd13aef242f3425afe6cd27726 | 31.730769 | 168 | 0.710928 | false | false | false | false |
ArthurKK/Cartography | refs/heads/master | Cartography/ViewUtils.swift | mit | 31 | //
// ViewUtils.swift
// Cartography
//
// Created by Garth Snyder on 11/23/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
internal func closestCommonAncestor(a: View, b: View) -> View? {
let (aSuper, bSuper) = (a.superview, b.superview)
if a === b { return a }
if a === bSuper { return a }
if b === aSuper { return b }
if aSuper === bSuper { return aSuper }
var ancestorsOfA = Set(ancestors(a))
for ancestor in ancestors(b) {
if ancestorsOfA.contains(ancestor) {
return ancestor
}
}
return .None
}
private func ancestors(v: View) -> SequenceOf<View> {
return SequenceOf<View> { () -> GeneratorOf<View> in
var view: View? = v
return GeneratorOf {
let current = view
view = view?.superview
return current
}
}
}
| 77f39d76ae4b3466530cb6085e046f6f | 19.130435 | 64 | 0.583153 | false | false | false | false |
KaushalElsewhere/AllHandsOn | refs/heads/master | SwaggerAPiConnect/SwaggerAPiConnect/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwaggerAPiConnect
//
// Created by Kaushal Elsewhere on 15/11/2016.
// Copyright © 2016 Kaushal Elsewhere. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
login()
}
let url = "https://api.stage.totsamour.com/auth/login"
// let headers: HTTPHeaders = [
// "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
// "Accept": "application/json"
// ]
let header: HTTPHeaders = [
"x-socket-api-key" : "7b16afe1aaa3ec502e074ed15c0c020d079a4f9f"
]
func login() {
Alamofire.request(.POST, url).responseJSON { (response) in
print(response)
}
// Alamofire.request(url).responseJSON { response in
// print(response.request) // original URL request
// print(response.response) // HTTP URL response
// print(response.data) // server data
// print(response.result) // result of response serialization
//
// if let JSON = response.result.value {
// print("JSON: \(JSON)")
// }
// }
}
}
| a4c6cceedf5d49dfcfc6a7e8a08c5ecd | 23.576923 | 74 | 0.562598 | false | false | false | false |
danthorpe/TaylorSource | refs/heads/development | Sources/Base/Datasource.swift | mit | 2 | //
// Created by Daniel Thorpe on 16/04/2015.
//
import UIKit
/**
The core protocol of Datasource functionality.
It has an associated type, _FactoryType which in turn is responsible for
associates types for item model, cell class, supplementary view classes,
parent view class and index types.
The factory provides an API to register cells and views, and in
turn it can be used to vend cells and view.
Types which implement DatasourceType (this protocol) should use the
factory in conjuction with a storage medium for data items.
This protocol exists to allow for the definition of different kinds of
datasources. Coupled with DatasourceProviderType, datasources can be
composed and extended with ease. See SegmentedDatasource for example.
*/
public protocol DatasourceType {
associatedtype FactoryType: _FactoryType
/// Access the factory from the datasource, likely should be a stored property.
var factory: FactoryType { get }
/// An identifier which is primarily to ease debugging and logging.
var identifier: String { get }
/// Optional human readable title
var title: String? { get }
/// The number of sections in the data source
var numberOfSections: Int { get }
/**
The number of items in the section.
- parameter section: The section index
- returns: An Int, the number of items.
*/
func numberOfItemsInSection(sectionIndex: Int) -> Int
/**
Access the underlying data item at the indexPath.
- parameter indexPath: A NSIndexPath instance.
- returns: An optional Item
*/
func itemAtIndexPath(indexPath: NSIndexPath) -> FactoryType.ItemType?
/**
Vends a configured cell for the item.
- parameter view: the View which should dequeue the cell.
- parameter indexPath: the NSIndexPath of the item.
- returns: a FactoryType.CellType instance, this should be dequeued and configured.
*/
func cellForItemInView(view: FactoryType.ViewType, atIndexPath indexPath: NSIndexPath) -> FactoryType.CellType
/**
Vends a configured supplementary view of kind.
- parameter view: the View which should dequeue the cell.
- parameter kind: the kind of the supplementary element. See SupplementaryElementKind
- parameter indexPath: the NSIndexPath of the item.
- returns: a Factory.Type.SupplementaryViewType instance, this should be dequeued and configured.
*/
func viewForSupplementaryElementInView(view: FactoryType.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> FactoryType.SupplementaryViewType?
/**
Vends a optional text for the supplementary kind
- parameter view: the View which should dequeue the cell.
- parameter kind: the kind of the supplementary element. See SupplementaryElementKind
- parameter indexPath: the NSIndexPath of the item.
- returns: a TextType?
*/
func textForSupplementaryElementInView(view: FactoryType.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> FactoryType.TextType?
}
public enum EditableDatasourceAction: Int {
case None = 1, Insert, Delete
public var editingStyle: UITableViewCellEditingStyle {
switch self {
case .None: return .None
case .Insert: return .Insert
case .Delete: return .Delete
}
}
public init?(editingStyle: UITableViewCellEditingStyle) {
switch editingStyle {
case .None:
self = .None
case .Insert:
self = .Insert
case .Delete:
self = .Delete
}
}
}
public typealias CanEditItemAtIndexPath = (indexPath: NSIndexPath) -> Bool
public typealias CommitEditActionForItemAtIndexPath = (action: EditableDatasourceAction, indexPath: NSIndexPath) -> Void
public typealias EditActionForItemAtIndexPath = (indexPath: NSIndexPath) -> EditableDatasourceAction
public typealias CanMoveItemAtIndexPath = (indexPath: NSIndexPath) -> Bool
public typealias CommitMoveItemAtIndexPathToIndexPath = (from: NSIndexPath, to: NSIndexPath) -> Void
public protocol DatasourceEditorType {
var canEditItemAtIndexPath: CanEditItemAtIndexPath? { get }
var commitEditActionForItemAtIndexPath: CommitEditActionForItemAtIndexPath? { get }
var editActionForItemAtIndexPath: EditActionForItemAtIndexPath? { get }
var canMoveItemAtIndexPath: CanMoveItemAtIndexPath? { get }
var commitMoveItemAtIndexPathToIndexPath: CommitMoveItemAtIndexPathToIndexPath? { get }
}
/**
Suggested usage is not to use a DatasourceType directly, but instead to create
a bespoke type which implements this protocol, DatasourceProviderType, and vend
a configured datasource. This type could be considered to be like a view model
in MVVM paradigms. But in traditional MVC, such a type is just a model, which
the view controller initalizes and owns.
*/
public protocol DatasourceProviderType {
associatedtype Datasource: DatasourceType
associatedtype Editor: DatasourceEditorType
/// The underlying Datasource.
var datasource: Datasource { get }
/// An datasource editor
var editor: Editor { get }
}
public struct NoEditor: DatasourceEditorType {
public let canEditItemAtIndexPath: CanEditItemAtIndexPath? = .None
public let commitEditActionForItemAtIndexPath: CommitEditActionForItemAtIndexPath? = .None
public let editActionForItemAtIndexPath: EditActionForItemAtIndexPath? = .None
public let canMoveItemAtIndexPath: CanMoveItemAtIndexPath? = .None
public let commitMoveItemAtIndexPathToIndexPath: CommitMoveItemAtIndexPathToIndexPath? = .None
public init() {}
}
public struct Editor: DatasourceEditorType {
public let canEditItemAtIndexPath: CanEditItemAtIndexPath?
public let commitEditActionForItemAtIndexPath: CommitEditActionForItemAtIndexPath?
public let editActionForItemAtIndexPath: EditActionForItemAtIndexPath?
public let canMoveItemAtIndexPath: CanMoveItemAtIndexPath?
public let commitMoveItemAtIndexPathToIndexPath: CommitMoveItemAtIndexPathToIndexPath?
public init(
canEdit: CanEditItemAtIndexPath? = .None,
commitEdit: CommitEditActionForItemAtIndexPath? = .None,
editAction: EditActionForItemAtIndexPath? = .None,
canMove: CanMoveItemAtIndexPath? = .None,
commitMove: CommitMoveItemAtIndexPathToIndexPath? = .None) {
canEditItemAtIndexPath = canEdit
commitEditActionForItemAtIndexPath = commitEdit
editActionForItemAtIndexPath = editAction
canMoveItemAtIndexPath = canMove
commitMoveItemAtIndexPathToIndexPath = commitMove
}
}
public struct ComposedEditor: DatasourceEditorType {
public let canEditItemAtIndexPath: CanEditItemAtIndexPath?
public let commitEditActionForItemAtIndexPath: CommitEditActionForItemAtIndexPath?
public let editActionForItemAtIndexPath: EditActionForItemAtIndexPath?
public let canMoveItemAtIndexPath: CanMoveItemAtIndexPath?
public let commitMoveItemAtIndexPathToIndexPath: CommitMoveItemAtIndexPathToIndexPath?
public init(editor: DatasourceEditorType) {
canEditItemAtIndexPath = editor.canEditItemAtIndexPath
commitEditActionForItemAtIndexPath = editor.commitEditActionForItemAtIndexPath
editActionForItemAtIndexPath = editor.editActionForItemAtIndexPath
canMoveItemAtIndexPath = editor.canMoveItemAtIndexPath
commitMoveItemAtIndexPathToIndexPath = editor.commitMoveItemAtIndexPathToIndexPath
}
}
| 7cdd4a219b3951c565dc079cd605e6ba | 38.166667 | 176 | 0.757979 | false | false | false | false |
LeaderQiu/SwiftWeibo | refs/heads/master | HMWeibo04/HMWeibo04/Classes/UI/Discover/DiscoverViewController.swift | mit | 1 | //
// DiscoverViewController.swift
// HMWeibo04
//
// Created by apple on 15/3/5.
// Copyright (c) 2015年 heima. All rights reserved.
//
import UIKit
class DiscoverViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| e26905f12eb87add01983193ad247fa0 | 33.123711 | 157 | 0.683686 | false | false | false | false |
crewshin/GasLog | refs/heads/master | Davcast-iOS/Pods/Material/Sources/CaptureSession.swift | mit | 2 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import AVFoundation
private var CaptureSessionAdjustingExposureContext: UInt8 = 1
public enum CaptureSessionPreset {
case PresetPhoto
case PresetHigh
case PresetMedium
case PresetLow
case Preset352x288
case Preset640x480
case Preset1280x720
case Preset1920x1080
case Preset3840x2160
case PresetiFrame960x540
case PresetiFrame1280x720
case PresetInputPriority
}
/**
:name: CaptureSessionPresetToString
*/
public func CaptureSessionPresetToString(preset: CaptureSessionPreset) -> String {
switch preset {
case .PresetPhoto:
return AVCaptureSessionPresetPhoto
case .PresetHigh:
return AVCaptureSessionPresetHigh
case .PresetMedium:
return AVCaptureSessionPresetMedium
case .PresetLow:
return AVCaptureSessionPresetLow
case .Preset352x288:
return AVCaptureSessionPreset352x288
case .Preset640x480:
return AVCaptureSessionPreset640x480
case .Preset1280x720:
return AVCaptureSessionPreset1280x720
case .Preset1920x1080:
return AVCaptureSessionPreset1920x1080
case .Preset3840x2160:
if #available(iOS 9.0, *) {
return AVCaptureSessionPreset3840x2160
} else {
return AVCaptureSessionPresetHigh
}
case .PresetiFrame960x540:
return AVCaptureSessionPresetiFrame960x540
case .PresetiFrame1280x720:
return AVCaptureSessionPresetiFrame1280x720
case .PresetInputPriority:
return AVCaptureSessionPresetInputPriority
}
}
@objc(CaptureSessionDelegate)
public protocol CaptureSessionDelegate {
/**
:name: captureSessionFailedWithError
*/
optional func captureSessionFailedWithError(capture: CaptureSession, error: NSError)
/**
:name: captureSessionDidSwitchCameras
*/
optional func captureSessionDidSwitchCameras(capture: CaptureSession, position: AVCaptureDevicePosition)
/**
:name: captureSessionWillSwitchCameras
*/
optional func captureSessionWillSwitchCameras(capture: CaptureSession, position: AVCaptureDevicePosition)
/**
:name: captureStillImageAsynchronously
*/
optional func captureStillImageAsynchronously(capture: CaptureSession, image: UIImage)
/**
:name: captureStillImageAsynchronouslyFailedWithError
*/
optional func captureStillImageAsynchronouslyFailedWithError(capture: CaptureSession, error: NSError)
/**
:name: captureCreateMovieFileFailedWithError
*/
optional func captureCreateMovieFileFailedWithError(capture: CaptureSession, error: NSError)
/**
:name: captureMovieFailedWithError
*/
optional func captureMovieFailedWithError(capture: CaptureSession, error: NSError)
/**
:name: captureDidStartRecordingToOutputFileAtURL
*/
optional func captureDidStartRecordingToOutputFileAtURL(capture: CaptureSession, captureOutput: AVCaptureFileOutput, fileURL: NSURL, fromConnections connections: [AnyObject])
/**
:name: captureDidFinishRecordingToOutputFileAtURL
*/
optional func captureDidFinishRecordingToOutputFileAtURL(capture: CaptureSession, captureOutput: AVCaptureFileOutput, outputFileURL: NSURL, fromConnections connections: [AnyObject], error: NSError!)
}
@objc(CaptureSession)
public class CaptureSession : NSObject, AVCaptureFileOutputRecordingDelegate {
/**
:name: sessionQueue
*/
private lazy var sessionQueue: dispatch_queue_t = dispatch_queue_create("io.material.CaptureSession", DISPATCH_QUEUE_SERIAL)
/**
:name: activeVideoInput
*/
private var activeVideoInput: AVCaptureDeviceInput?
/**
:name: activeAudioInput
*/
private var activeAudioInput: AVCaptureDeviceInput?
/**
:name: imageOutput
*/
private lazy var imageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()
/**
:name: movieOutput
*/
private lazy var movieOutput: AVCaptureMovieFileOutput = AVCaptureMovieFileOutput()
/**
:name: movieOutputURL
*/
private var movieOutputURL: NSURL?
/**
:name: session
*/
internal lazy var session: AVCaptureSession = AVCaptureSession()
/**
:name: isRunning
*/
public private(set) lazy var isRunning: Bool = false
/**
:name: isRecording
*/
public private(set) lazy var isRecording: Bool = false
/**
:name: recordedDuration
*/
public var recordedDuration: CMTime {
return movieOutput.recordedDuration
}
/**
:name: activeCamera
*/
public var activeCamera: AVCaptureDevice? {
return activeVideoInput?.device
}
/**
:name: inactiveCamera
*/
public var inactiveCamera: AVCaptureDevice? {
var device: AVCaptureDevice?
if 1 < cameraCount {
if activeCamera?.position == .Back {
device = cameraWithPosition(.Front)
} else {
device = cameraWithPosition(.Back)
}
}
return device
}
/**
:name: cameraCount
*/
public var cameraCount: Int {
return AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo).count
}
/**
:name: canSwitchCameras
*/
public var canSwitchCameras: Bool {
return 1 < cameraCount
}
/**
:name: caneraSupportsTapToFocus
*/
public var cameraSupportsTapToFocus: Bool {
return nil == activeCamera ? false : activeCamera!.focusPointOfInterestSupported
}
/**
:name: cameraSupportsTapToExpose
*/
public var cameraSupportsTapToExpose: Bool {
return nil == activeCamera ? false : activeCamera!.exposurePointOfInterestSupported
}
/**
:name: cameraHasFlash
*/
public var cameraHasFlash: Bool {
return nil == activeCamera ? false : activeCamera!.hasFlash
}
/**
:name: cameraHasTorch
*/
public var cameraHasTorch: Bool {
return nil == activeCamera ? false : activeCamera!.hasTorch
}
/**
:name: cameraPosition
*/
public var cameraPosition: AVCaptureDevicePosition? {
return activeCamera?.position
}
/**
:name: focusMode
*/
public var focusMode: AVCaptureFocusMode {
get {
return activeCamera!.focusMode
}
set(value) {
var error: NSError?
if isFocusModeSupported(focusMode) {
do {
let device: AVCaptureDevice = activeCamera!
try device.lockForConfiguration()
device.focusMode = value
device.unlockForConfiguration()
} catch let e as NSError {
error = e
}
} else {
var userInfo: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
userInfo[NSLocalizedDescriptionKey] = "[Material Error: Unsupported focusMode.]"
userInfo[NSLocalizedFailureReasonErrorKey] = "[Material Error: Unsupported focusMode.]"
error = NSError(domain: "io.material.CaptureView", code: 0001, userInfo: userInfo)
userInfo[NSUnderlyingErrorKey] = error
}
if let e: NSError = error {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
}
/**
:name: flashMode
*/
public var flashMode: AVCaptureFlashMode {
get {
return activeCamera!.flashMode
}
set(value) {
var error: NSError?
if isFlashModeSupported(flashMode) {
do {
let device: AVCaptureDevice = activeCamera!
try device.lockForConfiguration()
device.flashMode = value
device.unlockForConfiguration()
} catch let e as NSError {
error = e
}
} else {
var userInfo: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
userInfo[NSLocalizedDescriptionKey] = "[Material Error: Unsupported flashMode.]"
userInfo[NSLocalizedFailureReasonErrorKey] = "[Material Error: Unsupported flashMode.]"
error = NSError(domain: "io.material.CaptureView", code: 0002, userInfo: userInfo)
userInfo[NSUnderlyingErrorKey] = error
}
if let e: NSError = error {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
}
/**
:name: torchMode
*/
public var torchMode: AVCaptureTorchMode {
get {
return activeCamera!.torchMode
}
set(value) {
var error: NSError?
if isTorchModeSupported(torchMode) {
do {
let device: AVCaptureDevice = activeCamera!
try device.lockForConfiguration()
device.torchMode = value
device.unlockForConfiguration()
} catch let e as NSError {
error = e
}
} else {
var userInfo: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
userInfo[NSLocalizedDescriptionKey] = "[Material Error: Unsupported torchMode.]"
userInfo[NSLocalizedFailureReasonErrorKey] = "[Material Error: Unsupported torchMode.]"
error = NSError(domain: "io.material.CaptureView", code: 0003, userInfo: userInfo)
userInfo[NSUnderlyingErrorKey] = error
}
if let e: NSError = error {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
}
/**
:name: sessionPreset
*/
public var sessionPreset: CaptureSessionPreset {
didSet {
session.sessionPreset = CaptureSessionPresetToString(sessionPreset)
}
}
/**
:name: sessionPreset
*/
public var currentVideoOrientation: AVCaptureVideoOrientation {
var orientation: AVCaptureVideoOrientation
switch UIDevice.currentDevice().orientation {
case .Portrait:
orientation = .Portrait
case .LandscapeRight:
orientation = .LandscapeLeft
case .PortraitUpsideDown:
orientation = .PortraitUpsideDown
default:
orientation = .LandscapeRight
}
return orientation
}
/**
:name: delegate
*/
public weak var delegate: CaptureSessionDelegate?
/**
:name: init
*/
public override init() {
sessionPreset = .PresetHigh
super.init()
prepareSession()
}
/**
:name: startSession
*/
public func startSession() {
if !isRunning {
dispatch_async(sessionQueue) {
self.session.startRunning()
}
}
}
/**
:name: startSession
*/
public func stopSession() {
if isRunning {
dispatch_async(sessionQueue) {
self.session.stopRunning()
}
}
}
/**
:name: switchCameras
*/
public func switchCameras() {
if canSwitchCameras {
do {
if let v: AVCaptureDevicePosition = self.cameraPosition {
self.delegate?.captureSessionWillSwitchCameras?(self, position: v)
let videoInput: AVCaptureDeviceInput? = try AVCaptureDeviceInput(device: self.inactiveCamera!)
self.session.beginConfiguration()
self.session.removeInput(self.activeVideoInput)
if self.session.canAddInput(videoInput) {
self.session.addInput(videoInput)
self.activeVideoInput = videoInput
} else {
self.session.addInput(self.activeVideoInput)
}
self.session.commitConfiguration()
self.delegate?.captureSessionDidSwitchCameras?(self, position: self.cameraPosition!)
}
} catch let e as NSError {
self.delegate?.captureSessionFailedWithError?(self, error: e)
}
}
}
/**
:name: isFocusModeSupported
*/
public func isFocusModeSupported(focusMode: AVCaptureFocusMode) -> Bool {
return activeCamera!.isFocusModeSupported(focusMode)
}
/**
:name: isExposureModeSupported
*/
public func isExposureModeSupported(exposureMode: AVCaptureExposureMode) -> Bool {
return activeCamera!.isExposureModeSupported(exposureMode)
}
/**
:name: isFlashModeSupported
*/
public func isFlashModeSupported(flashMode: AVCaptureFlashMode) -> Bool {
return activeCamera!.isFlashModeSupported(flashMode)
}
/**
:name: isTorchModeSupported
*/
public func isTorchModeSupported(torchMode: AVCaptureTorchMode) -> Bool {
return activeCamera!.isTorchModeSupported(torchMode)
}
/**
:name: focusAtPoint
*/
public func focusAtPoint(point: CGPoint) {
var error: NSError?
if cameraSupportsTapToFocus && isFocusModeSupported(.AutoFocus) {
do {
let device: AVCaptureDevice = activeCamera!
try device.lockForConfiguration()
device.focusPointOfInterest = point
device.focusMode = .AutoFocus
device.unlockForConfiguration()
} catch let e as NSError {
error = e
}
} else {
var userInfo: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
userInfo[NSLocalizedDescriptionKey] = "[Material Error: Unsupported focusAtPoint.]"
userInfo[NSLocalizedFailureReasonErrorKey] = "[Material Error: Unsupported focusAtPoint.]"
error = NSError(domain: "io.material.CaptureView", code: 0004, userInfo: userInfo)
userInfo[NSUnderlyingErrorKey] = error
}
if let e: NSError = error {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
/**
:name: exposeAtPoint
*/
public func exposeAtPoint(point: CGPoint) {
var error: NSError?
if cameraSupportsTapToExpose && isExposureModeSupported(.ContinuousAutoExposure) {
do {
let device: AVCaptureDevice = activeCamera!
try device.lockForConfiguration()
device.exposurePointOfInterest = point
device.exposureMode = .ContinuousAutoExposure
if device.isExposureModeSupported(.Locked) {
device.addObserver(self, forKeyPath: "adjustingExposure", options: .New, context: &CaptureSessionAdjustingExposureContext)
}
device.unlockForConfiguration()
} catch let e as NSError {
error = e
}
} else {
var userInfo: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
userInfo[NSLocalizedDescriptionKey] = "[Material Error: Unsupported exposeAtPoint.]"
userInfo[NSLocalizedFailureReasonErrorKey] = "[Material Error: Unsupported exposeAtPoint.]"
error = NSError(domain: "io.material.CaptureView", code: 0005, userInfo: userInfo)
userInfo[NSUnderlyingErrorKey] = error
}
if let e: NSError = error {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
/**
:name: observeValueForKeyPath
*/
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &CaptureSessionAdjustingExposureContext {
let device: AVCaptureDevice = object as! AVCaptureDevice
if !device.adjustingExposure && device.isExposureModeSupported(.Locked) {
object!.removeObserver(self, forKeyPath: "adjustingExposure", context: &CaptureSessionAdjustingExposureContext)
dispatch_async(dispatch_get_main_queue()) {
do {
try device.lockForConfiguration()
device.exposureMode = .Locked
device.unlockForConfiguration()
} catch let e as NSError {
self.delegate?.captureSessionFailedWithError?(self, error: e)
}
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
/**
:name: resetFocusAndExposureModes
*/
public func resetFocusAndExposureModes() {
let device: AVCaptureDevice = activeCamera!
let canResetFocus: Bool = device.focusPointOfInterestSupported && device.isFocusModeSupported(.ContinuousAutoFocus)
let canResetExposure: Bool = device.exposurePointOfInterestSupported && device.isExposureModeSupported(.ContinuousAutoExposure)
let centerPoint: CGPoint = CGPointMake(0.5, 0.5)
do {
try device.lockForConfiguration()
if canResetFocus {
device.focusMode = .ContinuousAutoFocus
device.focusPointOfInterest = centerPoint
}
if canResetExposure {
device.exposureMode = .ContinuousAutoExposure
device.exposurePointOfInterest = centerPoint
}
device.unlockForConfiguration()
} catch let e as NSError {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
/**
:name: captureStillImage
*/
public func captureStillImage() {
dispatch_async(sessionQueue) {
if let v: AVCaptureConnection = self.imageOutput.connectionWithMediaType(AVMediaTypeVideo) {
v.videoOrientation = self.currentVideoOrientation
self.imageOutput.captureStillImageAsynchronouslyFromConnection(v) { (sampleBuffer: CMSampleBuffer!, error: NSError!) -> Void in
if nil == error {
let data: NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
self.delegate?.captureStillImageAsynchronously?(self, image: UIImage(data: data)!)
} else {
self.delegate?.captureStillImageAsynchronouslyFailedWithError?(self, error: error!)
}
}
}
}
}
/**
:name: startRecording
*/
public func startRecording() {
if !isRecording {
dispatch_async(sessionQueue) {
if let v: AVCaptureConnection = self.movieOutput.connectionWithMediaType(AVMediaTypeVideo) {
v.videoOrientation = self.currentVideoOrientation
v.preferredVideoStabilizationMode = .Auto
}
if let v: AVCaptureDevice = self.activeCamera {
if v.smoothAutoFocusSupported {
do {
try v.lockForConfiguration()
v.smoothAutoFocusEnabled = true
v.unlockForConfiguration()
} catch let e as NSError {
self.delegate?.captureSessionFailedWithError?(self, error: e)
}
}
self.movieOutputURL = self.uniqueURL()
if let v: NSURL = self.movieOutputURL {
self.movieOutput.startRecordingToOutputFileURL(v, recordingDelegate: self)
}
}
}
}
}
/**
:name: stopRecording
*/
public func stopRecording() {
if isRecording {
movieOutput.stopRecording()
}
}
/**
:name: captureOutput
*/
public func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
isRecording = true
delegate?.captureDidStartRecordingToOutputFileAtURL?(self, captureOutput: captureOutput, fileURL: fileURL, fromConnections: connections)
}
/**
:name: captureOutput
*/
public func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
isRecording = false
delegate?.captureDidFinishRecordingToOutputFileAtURL?(self, captureOutput: captureOutput, outputFileURL: outputFileURL, fromConnections: connections, error: error)
}
/**
:name: prepareSession
*/
private func prepareSession() {
prepareVideoInput()
prepareAudioInput()
prepareImageOutput()
prepareMovieOutput()
}
/**
:name: prepareVideoInput
*/
private func prepareVideoInput() {
do {
activeVideoInput = try AVCaptureDeviceInput(device: AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo))
if session.canAddInput(activeVideoInput) {
session.addInput(activeVideoInput)
}
} catch let e as NSError {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
/**
:name: prepareAudioInput
*/
private func prepareAudioInput() {
do {
activeAudioInput = try AVCaptureDeviceInput(device: AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio))
if session.canAddInput(activeAudioInput) {
session.addInput(activeAudioInput)
}
} catch let e as NSError {
delegate?.captureSessionFailedWithError?(self, error: e)
}
}
/**
:name: prepareImageOutput
*/
private func prepareImageOutput() {
if session.canAddOutput(imageOutput) {
imageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
session.addOutput(imageOutput)
}
}
/**
:name: prepareMovieOutput
*/
private func prepareMovieOutput() {
if session.canAddOutput(movieOutput) {
session.addOutput(movieOutput)
}
}
/**
:name: cameraWithPosition
*/
private func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
let devices: Array<AVCaptureDevice> = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! Array<AVCaptureDevice>
for device in devices {
if device.position == position {
return device
}
}
return nil
}
/**
:name: uniqueURL
*/
private func uniqueURL() -> NSURL? {
do {
let directory: NSURL = try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .FullStyle
dateFormatter.timeStyle = .FullStyle
return directory.URLByAppendingPathComponent(dateFormatter.stringFromDate(NSDate()) + ".mov")
} catch let e as NSError {
delegate?.captureCreateMovieFileFailedWithError?(self, error: e)
}
return nil
}
}
| 521317afe7520444b14c40113012354e | 27.723433 | 199 | 0.741972 | false | false | false | false |
tilltue/TLPhotoPicker | refs/heads/master | Example/TLPhotoPicker/TLPhotosPicker+Extension.swift | mit | 1 | //
// TLPhotosPicker+Extension.swift
// TLPhotoPicker
//
// Created by wade.hawk on 2017. 7. 24..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import Foundation
import TLPhotoPicker
extension TLPhotosPickerViewController {
class func custom(withTLPHAssets: (([TLPHAsset]) -> Void)? = nil, didCancel: (() -> Void)? = nil) -> CustomPhotoPickerViewController {
let picker = CustomPhotoPickerViewController(withTLPHAssets: withTLPHAssets, didCancel:didCancel)
return picker
}
func wrapNavigationControllerWithoutBar() -> UINavigationController {
let navController = UINavigationController(rootViewController: self)
navController.navigationBar.isHidden = true
return navController
}
}
| 331969f7f554b7f360d4096a0e17f236 | 31.956522 | 138 | 0.720317 | false | false | false | false |
revealapp/Revert | refs/heads/master | Shared/Sources/ColourSection.swift | bsd-3-clause | 1 | // Copyright © 2020 Itty Bitty Apps. All rights reserved.
import Foundation
struct ColourSection {
var title: String?
var rows: [ColourItem]
}
extension RevertItems {
static var coloursData: [ColourSection] {
if #available(iOS 13.0, *) {
let labelSection = ColourSection(title: "LABEL", rows: [
ColourItem(name: #keyPath(UIColor.label), color: .label),
ColourItem(name: #keyPath(UIColor.secondaryLabel), color: .secondaryLabel),
ColourItem(name: #keyPath(UIColor.tertiaryLabel), color: .tertiaryLabel),
ColourItem(name: #keyPath(UIColor.quaternaryLabel), color: .quaternaryLabel)
])
let fillSection = ColourSection(title: "FILL", rows: [
ColourItem(name: #keyPath(UIColor.systemFill), color: .systemFill),
ColourItem(name: #keyPath(UIColor.secondarySystemFill), color: .secondarySystemFill),
ColourItem(name: #keyPath(UIColor.tertiarySystemFill), color: .tertiarySystemFill),
ColourItem(name: #keyPath(UIColor.quaternarySystemFill), color: .quaternarySystemFill)
])
let textSection: ColourSection = ColourSection(title: "TEXT", rows: [
ColourItem(name: #keyPath(UIColor.placeholderText), color: .placeholderText)
])
let standardContentBackgroundSection = ColourSection(title: "STANDARD CONTENT BACKGROUND", rows: [
ColourItem(name: #keyPath(UIColor.systemBackground), color: .systemBackground),
ColourItem(name: #keyPath(UIColor.secondarySystemBackground), color: .secondarySystemBackground),
ColourItem(name: #keyPath(UIColor.tertiarySystemBackground), color: .tertiarySystemBackground)
])
let groupedContentBackgroundSection = ColourSection(title: "GROUPED CONTENT BACKGROUND", rows: [
ColourItem(name: #keyPath(UIColor.systemGroupedBackground), color: .systemGroupedBackground),
ColourItem(name: #keyPath(UIColor.secondarySystemGroupedBackground), color: .secondarySystemGroupedBackground),
ColourItem(name: #keyPath(UIColor.tertiarySystemGroupedBackground), color: .tertiarySystemGroupedBackground)
])
let separatorSection: ColourSection = ColourSection(title: "SEPARATOR", rows: [
ColourItem(name: #keyPath(UIColor.separator), color: .separator),
ColourItem(name: #keyPath(UIColor.opaqueSeparator), color: .opaqueSeparator)
])
let linkSection: ColourSection = ColourSection(title: "LINK", rows: [
ColourItem(name: #keyPath(UIColor.link), color: .link)
])
let adaptableSection = ColourSection(title: "ADAPTABLE", rows: [
ColourItem(name: #keyPath(UIColor.systemBlue), color: .systemBlue),
ColourItem(name: #keyPath(UIColor.systemGreen), color: .systemGreen),
ColourItem(name: #keyPath(UIColor.systemIndigo), color: .systemIndigo),
ColourItem(name: #keyPath(UIColor.systemOrange), color: .systemOrange),
ColourItem(name: #keyPath(UIColor.systemPink), color: .systemPink),
ColourItem(name: #keyPath(UIColor.systemPurple), color: .systemPurple),
ColourItem(name: #keyPath(UIColor.systemRed), color: .systemRed),
ColourItem(name: #keyPath(UIColor.systemTeal), color: .systemTeal),
ColourItem(name: #keyPath(UIColor.systemYellow), color: .systemYellow)
])
let adaptableGraySection = ColourSection(title: "ADAPTABLE GRAY", rows: [
ColourItem(name: #keyPath(UIColor.systemGray), color: .systemGray),
ColourItem(name: #keyPath(UIColor.systemGray2), color: .systemGray2),
ColourItem(name: #keyPath(UIColor.systemGray3), color: .systemGray3),
ColourItem(name: #keyPath(UIColor.systemGray4), color: .systemGray4),
ColourItem(name: #keyPath(UIColor.systemGray5), color: .systemGray5),
ColourItem(name: #keyPath(UIColor.systemGray6), color: .systemGray6)
])
let nonAdaptableSection = ColourSection(title: "NONADAPTABLE", rows: [
ColourItem(name: #keyPath(UIColor.darkText), color: .darkText),
ColourItem(name: #keyPath(UIColor.lightText), color: .lightText)
])
let transparentSection = ColourSection(title: "TRANSPARENT", rows: [
ColourItem(name: #keyPath(UIColor.clear), color: .clear)
])
let fixedSection = ColourSection(title: "FIXED", rows: [
ColourItem(name: #keyPath(UIColor.black), color: .black),
ColourItem(name: #keyPath(UIColor.blue), color: .blue),
ColourItem(name: #keyPath(UIColor.brown), color: .brown),
ColourItem(name: #keyPath(UIColor.cyan), color: .cyan),
ColourItem(name: #keyPath(UIColor.darkGray), color: .darkGray),
ColourItem(name: #keyPath(UIColor.gray), color: .gray),
ColourItem(name: #keyPath(UIColor.green), color: .green),
ColourItem(name: #keyPath(UIColor.lightGray), color: .lightGray),
ColourItem(name: #keyPath(UIColor.magenta), color: .magenta),
ColourItem(name: #keyPath(UIColor.orange), color: .orange),
ColourItem(name: #keyPath(UIColor.purple), color: .purple),
ColourItem(name: #keyPath(UIColor.red), color: .red),
ColourItem(name: #keyPath(UIColor.white), color: .white),
ColourItem(name: #keyPath(UIColor.yellow), color: .yellow)
])
return [
labelSection,
fillSection,
textSection,
standardContentBackgroundSection,
groupedContentBackgroundSection,
separatorSection,
linkSection,
adaptableSection,
adaptableGraySection,
nonAdaptableSection,
transparentSection,
fixedSection
]
} else {
return [ColourSection(title: "Dynamic Colours only available in iOS 13 and above", rows: [])]
}
}
}
| d9dceed945f569100037443119e0cbd3 | 47.008403 | 119 | 0.68808 | false | false | false | false |
xuech/OMS-WH | refs/heads/master | OMS-WH/Classes/StockSearch/View/Cell/StockInWHTableViewCell.swift | mit | 1 | //
// StockInWHTableViewCell.swift
// OMS-WH
//
// Created by ___Gwy on 2017/9/18.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class StockInWHTableViewCell: UITableViewCell {
var stockInWhModel:StockInWHModel?{
didSet{
brandLB.text = "品牌产品线:\(stockInWhModel!.medBrandName)(\(stockInWhModel!.medProdLnName))"
medNameLB.text = "物料名称编码:\(stockInWhModel!.medMIName)(\(stockInWhModel!.medMICode))"
medSpecificationLB.text = "规格:\(stockInWhModel!.specification)"
supplyNameLB.text = "供货商:\(stockInWhModel!.pOVDOrgCodeName)"
batchCodeLB.text = "批次/序列号:\(stockInWhModel!.lotSerial)"
countLB.text = "库存:\(stockInWhModel!.inventory)"
}
}
@IBOutlet weak var brandLB: UILabel!
@IBOutlet weak var medNameLB: UILabel!
@IBOutlet weak var medSpecificationLB: UILabel!
@IBOutlet weak var supplyNameLB: UILabel!
@IBOutlet weak var batchCodeLB: UILabel!
@IBOutlet weak var countLB: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 021909ced343105103fef45ad64d9b01 | 30.47619 | 100 | 0.657337 | false | false | false | false |
jkolb/midnightbacon | refs/heads/master | MidnightBacon/Reddit/Thing.swift | mit | 1 | //
// Thing.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public class Thing : Equatable, Hashable, CustomDebugStringConvertible {
public let kind: Kind
public let id: String
public let name: String
public init(kind: Kind, id: String, name: String) {
self.kind = kind
self.id = id
self.name = name
}
public var hashValue: Int {
return kind.hashValue ^ id.hashValue
}
public var debugDescription: String {
return "\(kind.rawValue) \(id)"
}
}
public func ==(lhs: Thing, rhs: Thing) -> Bool {
return lhs.kind == rhs.kind && lhs.id == rhs.id
}
| a30648d01584ff79b4f5ad6b701dc30d | 35.6875 | 80 | 0.704145 | false | false | false | false |
parkera/swift-corelibs-foundation | refs/heads/master | Foundation/Locale.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import CoreFoundation
internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool {
return false // Auto-updating is only on Darwin
}
internal func __NSLocaleCurrent() -> NSLocale {
return CFLocaleCopyCurrent()._nsObject
}
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
internal var _wrapped : NSLocale
internal var _autoupdating : Bool
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false)
}
/// Returns a locale which tracks the user's current preferences.
///
/// If mutated, this Locale will no longer track the user's preferences.
///
/// - note: The autoupdating Locale will only compare equal to another autoupdating Locale.
public static var autoupdatingCurrent : Locale {
// swift-corelibs-foundation does not yet support autoupdating, but we can return the current locale (which will not change).
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: true)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
internal init(reference: NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = _wrapped.object(forKey: .usesMetricSystem) as? Bool {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public var description: String {
return _wrapped.description
}
public var debugDescription : String {
return _wrapped.debugDescription
}
public func hash(into hasher: inout Hasher) {
if _autoupdating {
hasher.combine(1 as Int8)
} else {
hasher.combine(_wrapped)
}
}
public static func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension Locale : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(NSLocale.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension Locale : Codable {
private enum CodingKeys : Int, CodingKey {
case identifier
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifier = try container.decode(String.self, forKey: .identifier)
self.init(identifier: identifier)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.identifier, forKey: .identifier)
}
}
| 674dcf60e2691a2c9ff8eff713ee059b | 38.410309 | 282 | 0.656116 | false | false | false | false |
think-dev/MadridBUS | refs/heads/master | MadridBUS/Source/Data/BusLineBasicInfo.swift | mit | 1 | import Foundation
import ObjectMapper
final class BusLineBasicInfo: Mappable {
var subgroupId: String = ""
var id: String = ""
var name: String = ""
var header: String = ""
var terminus: String = ""
required init?(map: Map) {}
func mapping(map: Map) {
subgroupId <- map["groupNumber"]
id <- map["line"]
name <- map["label"]
header <- map["nameA"]
terminus <- map["nameB"]
}
}
| 780b623fb162f38be3fa463a3bc67363 | 21.95 | 40 | 0.551198 | false | false | false | false |
DigitalCroma/CodPol | refs/heads/master | CodPol/Services/DBService/CoreDataStore.swift | mit | 1 | //
// CoreDataStore.swift
// CodPol
//
// Created by Juan Carlos Samboní Ramírez on 24/02/17.
// Copyright © 2017 DigitalCroma. All rights reserved.
//
import UIKit
import CoreData
class CoreDataStore {
static let sharedInstance = CoreDataStore()
private init() {}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CodPol")
var persistentStoreDescriptions: NSPersistentStoreDescription
let directory = NSPersistentContainer.defaultDirectoryURL()
let storeUrl = [directory.appendingPathComponent("CodPol.sqlite"),
directory.appendingPathComponent("CodPol.sqlite-shm"),
directory.appendingPathComponent("CodPol.sqlite-wal")]
if !FileManager.default.fileExists(atPath: (storeUrl[0].path)) {
let seededDataUrl = [Bundle.main.url(forResource: "db_codpol", withExtension: "sqlite"),
Bundle.main.url(forResource: "db_codpol", withExtension: "sqlite-shm"),
Bundle.main.url(forResource: "db_codpol", withExtension: "sqlite-wal")]
for index in 0 ..< seededDataUrl.count {
do {
try FileManager.default.copyItem(at: seededDataUrl[index]!, to: storeUrl[index])
} catch let error as NSError {
print("Error: \(error.domain)")
}
}
}
let description = NSPersistentStoreDescription()
description.url = storeUrl[0]
container.persistentStoreDescriptions = [description]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
print(container.persistentStoreDescriptions)
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
extension CoreDataStore: DBStoreProtocol {
func fetchPoliceCode(completionHandler: (PoliceCode, Error?) -> Void) {
let managedContext = persistentContainer.viewContext
do {
let fetchRequest: NSFetchRequest<Book> = Book.fetchRequest()
let booksMO = try managedContext.fetch(fetchRequest)
var books:[PoliceCode.Book] = []
for bookInfo: Book in booksMO {
var titles:[PoliceCode.Title] = []
for titleInfo in bookInfo.titles?.array as! [Title] {
var chapters:[PoliceCode.Chapter] = []
for chapterInfo in titleInfo.chapters?.array as! [Chapter] {
var articles:[PoliceCode.Article] = []
for articleInfo in chapterInfo.articles?.array as! [Article] {
let article = PoliceCode.Article(text: articleInfo.text ?? "")
articles.append(article)
}
chapters.append(PoliceCode.Chapter(name: chapterInfo.name ?? "", information: chapterInfo.information ?? "", articles: articles))
}
titles.append(PoliceCode.Title(name: titleInfo.name ?? "", information: titleInfo.information ?? "", chapters: chapters))
}
books.append(PoliceCode.Book(name: bookInfo.name ?? "", information: bookInfo.information ?? "", titles: titles))
}
completionHandler(PoliceCode(books: books), nil)
return
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
completionHandler(PoliceCode(books: []), error)
return
}
}
}
| c35d9d0987b8bd36c8887779db1ba9a9 | 44.748031 | 199 | 0.577453 | false | false | false | false |
arunlj561/AJIBDesignables | refs/heads/master | Example/AJIBDesignables/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// AJIBDesignables
//
// Created by arunlj561 on 03/27/2017.
// Copyright (c) 2017 arunlj561. All rights reserved.
//
import UIKit
import AJIBDesignables
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print(UIFont.fontNames(forFamilyName: "Helvetica Neue"))
AJFontExtension.sharedInstance.larger = "HelveticaNeue-Italic"
AJFontExtension.sharedInstance.normal = "HelveticaNeue-BoldItalic"
AJFontExtension.sharedInstance.title = "HelveticaNeue-Medium"
AJFontExtension.sharedInstance.subtitle = "HelveticaNeue"
AJFontExtension.sharedInstance.descriptive = "HelveticaNeue-Thin"
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 7951b3bc7a080a8dd7468fe5e0d1d0da | 47.301887 | 285 | 0.752344 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureTransaction/Sources/FeatureTransactionDomain/Limits/TransactionLimits.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import MoneyKit
import PlatformKit
/// Use this struct to fill transaction data in `TransactionEngine`s.
public struct TransactionLimits: Equatable {
public let currencyType: CurrencyType
public let minimum: MoneyValue?
public let maximum: MoneyValue?
public let maximumDaily: MoneyValue?
public let maximumAnnual: MoneyValue?
public let effectiveLimit: EffectiveLimit?
public let suggestedUpgrade: SuggestedLimitsUpgrade?
public init(
currencyType: CurrencyType,
minimum: MoneyValue?,
maximum: MoneyValue?,
maximumDaily: MoneyValue?,
maximumAnnual: MoneyValue?,
effectiveLimit: EffectiveLimit?,
suggestedUpgrade: SuggestedLimitsUpgrade?
) {
self.currencyType = currencyType
self.minimum = minimum
self.maximum = maximum
self.maximumDaily = maximumDaily
self.maximumAnnual = maximumAnnual
self.effectiveLimit = effectiveLimit
self.suggestedUpgrade = suggestedUpgrade
}
}
extension TransactionLimits {
public static func zero(for currency: CurrencyType) -> TransactionLimits {
fixedValue(.zero(currency: currency))
}
public static func noLimits(for currency: CurrencyType) -> TransactionLimits {
fixedValue(currencyType: currency)
}
public static func fixedValue(_ value: MoneyValue) -> TransactionLimits {
fixedValue(value, currencyType: value.currencyType)
}
public static func fixedValue(currencyType: CurrencyType) -> TransactionLimits {
fixedValue(nil, currencyType: currencyType)
}
private static func fixedValue(_ value: MoneyValue?, currencyType: CurrencyType) -> TransactionLimits {
if let value = value, value.currencyType != currencyType {
fatalError("The currency type must match the money value's currency type, when present")
}
let effectiveLimit: EffectiveLimit?
if let value = value {
effectiveLimit = .init(timeframe: .single, value: value)
} else {
effectiveLimit = nil
}
return TransactionLimits(
currencyType: currencyType,
minimum: value,
maximum: value,
maximumDaily: value,
maximumAnnual: value,
effectiveLimit: effectiveLimit,
suggestedUpgrade: nil
)
}
}
// MARK: - Currency Conversion
extension TransactionLimits {
public func convert(using exchangeRate: MoneyValue) -> TransactionLimits {
TransactionLimits(
currencyType: exchangeRate.currencyType,
minimum: minimum?.convert(using: exchangeRate),
maximum: maximum?.convert(using: exchangeRate),
maximumDaily: maximumDaily?.convert(using: exchangeRate),
maximumAnnual: maximumAnnual?.convert(using: exchangeRate),
effectiveLimit: effectiveLimit?.convert(using: exchangeRate),
suggestedUpgrade: suggestedUpgrade?.convert(using: exchangeRate)
)
}
}
| e52d2e58840ec7ef297f3a19117abcca | 32.98913 | 107 | 0.673169 | false | false | false | false |
exponent/exponent | refs/heads/master | packages/expo-blur/ios/EXBlur/BlurEffectView.swift | bsd-3-clause | 2 | // Copyright 2015-present 650 Industries. All rights reserved.
import UIKit
/**
This class is based on https://gist.github.com/darrarski/29a2a4515508e385c90b3ffe6f975df7
*/
final class BlurEffectView: UIVisualEffectView {
@Clamping(lowerBound: 0.01, upperBound: 1)
var intensity: Double = 0.5 {
didSet {
setNeedsDisplay()
}
}
@Containing(values: ["default", "light", "dark"])
var tint = "default" {
didSet {
visualEffect = UIBlurEffect(style: blurEffectStyleFrom(tint))
}
}
private var visualEffect: UIVisualEffect = UIBlurEffect(style: blurEffectStyleFrom("default")) {
didSet {
setNeedsDisplay()
}
}
private var animator: UIViewPropertyAnimator?
init() {
super.init(effect: nil)
}
required init?(coder aDecoder: NSCoder) { nil }
deinit {
animator?.stopAnimation(true)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
effect = nil
animator?.stopAnimation(true)
animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [unowned self] in
self.effect = visualEffect
}
animator?.fractionComplete = CGFloat(intensity)
}
}
private func blurEffectStyleFrom(_ tint: String) -> UIBlurEffect.Style {
switch tint {
case "light": return .extraLight
case "dark": return .dark
case "default": return .light
default: return .dark
}
}
/**
Property wrapper clamping the value between an upper and lower bound
*/
@propertyWrapper
struct Clamping<Value: Comparable> {
var wrappedValue: Value
init(wrappedValue: Value, lowerBound: Value, upperBound: Value) {
self.wrappedValue = max(lowerBound, min(upperBound, wrappedValue))
}
}
/**
Property wrapper ensuring that the value is contained in list of valid values
*/
@propertyWrapper
struct Containing<Value: Equatable> {
var wrappedValue: Value
init(wrappedValue: Value, values: [Value]) {
let isValueValid = values.contains(wrappedValue)
self.wrappedValue = isValueValid ? wrappedValue : values.first!
}
}
| c7a190c8935f994838fe247a841f13a9 | 23.325301 | 98 | 0.699851 | false | false | false | false |
zisko/swift | refs/heads/master | test/Sema/typo_correction.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -typo-correction-limit 20
// RUN: not %target-swift-frontend -typecheck -disable-typo-correction %s 2>&1 | %FileCheck %s -check-prefix=DISABLED
// RUN: not %target-swift-frontend -typecheck -typo-correction-limit 0 %s 2>&1 | %FileCheck %s -check-prefix=DISABLED
// RUN: not %target-swift-frontend -typecheck -DIMPORT_FAIL %s 2>&1 | %FileCheck %s -check-prefix=DISABLED
// DISABLED-NOT: did you mean
#if IMPORT_FAIL
import NoSuchModule
#endif
// This is close enough to get typo-correction.
func test_short_and_close() {
let foo = 4 // expected-note {{did you mean 'foo'?}}
let bab = fob + 1 // expected-error {{use of unresolved identifier}}
}
// This is not.
func test_too_different() {
let moo = 4
let bbb = mbb + 1 // expected-error {{use of unresolved identifier}}
}
struct Whatever {}
func *(x: Whatever, y: Whatever) {}
// This works even for single-character identifiers.
func test_very_short() {
// Note that we don't suggest operators.
let x = 0 // expected-note {{did you mean 'x'?}}
let longer = y // expected-error {{use of unresolved identifier 'y'}}
}
// It does not trigger in a variable's own initializer.
func test_own_initializer() {
let x = y // expected-error {{use of unresolved identifier 'y'}}
}
// Report candidates that are the same distance in different ways.
func test_close_matches() {
let match1 = 0 // expected-note {{did you mean 'match1'?}}
let match22 = 0 // expected-note {{did you mean 'match22'?}}
let x = match2 // expected-error {{use of unresolved identifier 'match2'}}
}
// Report not-as-good matches if they're still close enough to the best.
func test_keep_if_not_too_much_worse() {
let longmatch1 = 0 // expected-note {{did you mean 'longmatch1'?}}
let longmatch22 = 0 // expected-note {{did you mean 'longmatch22'?}}
let x = longmatch // expected-error {{use of unresolved identifier 'longmatch'}}
}
// Report not-as-good matches if they're still close enough to the best.
func test_drop_if_too_different() {
let longlongmatch1 = 0 // expected-note {{did you mean 'longlongmatch1'?}}
let longlongmatch2222 = 0
let x = longlongmatch // expected-error {{use of unresolved identifier 'longlongmatch'}}
}
// Candidates are suppressed if we have too many that are the same distance.
func test_too_many_same() {
let match1 = 0
let match2 = 0
let match3 = 0
let match4 = 0
let match5 = 0
let match6 = 0
let x = match // expected-error {{use of unresolved identifier 'match'}}
}
// But if some are better than others, just drop the worse tier.
func test_too_many_but_some_better() {
let mtch1 = 0 // expected-note {{did you mean 'mtch1'?}}
let mtch2 = 0 // expected-note {{did you mean 'mtch2'?}}
let match3 = 0
let match4 = 0
let match5 = 0
let match6 = 0
let x = mtch // expected-error {{use of unresolved identifier 'mtch'}}
}
// rdar://problem/28387684
// Don't crash performing typo correction on bound generic types with
// type variables.
_ = [Any]().withUnsafeBufferPointer { (buf) -> [Any] in
guard let base = buf.baseAddress else { return [] }
return (base ..< base + buf.count).m // expected-error {{value of type 'Range<UnsafePointer<Any>>' has no member 'm'}}
}
// Typo correction with class-bound archetypes.
class SomeClass {
func match1() {}
// expected-note@-1 {{did you mean 'match1'?}}
}
func takesSomeClassArchetype<T : SomeClass>(_ t: T) {
t.match0()
// expected-error@-1 {{value of type 'T' has no member 'match0'}}
}
// Typo correction of unqualified lookup from generic context.
struct Generic<T> {
func match1() {}
// expected-note@-1 {{did you mean 'match1'?}}
class Inner {
func doStuff() {
match0()
// expected-error@-1 {{use of unresolved identifier 'match0'}}
}
}
}
// Typo correction with AnyObject.
func takesAnyObject(_ t: AnyObject) {
_ = t.rawPointer
// expected-error@-1 {{value of type 'AnyObject' has no member 'rawPointer'}}
}
func takesAnyObjectArchetype<T : AnyObject>(_ t: T) {
_ = t.rawPointer
// expected-error@-1 {{value of type 'T' has no member 'rawPointer'}}
}
// Typo correction with an UnresolvedDotExpr.
enum Foo {
// note: the fixit is actually for the line with the error below, but
// -verify mode is not smart enough for that yet.
case flashing // expected-note {{did you mean 'flashing'?}}{{8-15=flashing}}
}
func foo(_ a: Foo) {
}
func bar() {
foo(.flashin) // expected-error {{type 'Foo' has no member 'flashin'}}
}
| ceebe77087631156e2c3880e5046fd93 | 31.766423 | 120 | 0.678548 | false | true | false | false |
OctMon/OMExtension | refs/heads/master | OMExtension/OMExtension/Source/Foundation/OMData.swift | mit | 1 | //
// OMData.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public extension Data {
struct OM {
public static func JSONString(from json: Any?) -> String? {
guard let json = json else {
return nil
}
var string: String? = nil
if let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted), let dataString = String(data: data, encoding: .utf8) {
string = dataString
}
return string
}
}
func omToJson() -> String? {
var string: String? = nil
if let json = try? JSONSerialization.jsonObject(with: self, options: []), let dataString = Data.OM.JSONString(from: json) {
string = dataString
} else if let dataString = String(data: self, encoding: .utf8) {
string = dataString
}
return string
}
}
| a83fcc828a13c11350dc866510877c12 | 32.818182 | 156 | 0.614247 | false | false | false | false |
avaidyam/Parrot | refs/heads/master | MochaUI/PreviewController.swift | mpl-2.0 | 1 | import AppKit
import Mocha
import Quartz
/* TODO: NSPopover.title/addTitlebar(animated: ...)? */
/* TODO: Use NSPressGestureRecognizer if no haptic support. */
/* TODO: Maybe support tear-off popover-windows? */
//let preview = PreviewController(for: self.view, with: .file(URL(fileURLWithPath: pathToFile), nil))
//preview.delegate = self // not required
/// Provides content for a `PreviewController` dynamically.
public protocol PreviewControllerDelegate: class {
/// Return the content for the previewing controller, depending on where
/// the user began the previewing within the `parentView`. If `nil` is
/// returned from this method, previewing is disabled.
func previewController(_: PreviewController, contentAtPoint: CGPoint) -> PreviewController.ContentType?
}
/// The `PreviewController` handles user interactions with previewing indications.
/// The functionality is similar to dictionary or Safari link force touch lookup.
public class PreviewController: NSObject, NSPopoverDelegate, NSGestureRecognizerDelegate {
/// Describes the content to be previewed by the controller for a given interaction.
public enum ContentType {
///
case view(NSViewController)
/// The content is a `file://` URL, optionally with a preview size.
/// If no size is specified (`nil`), `PreviewController.defaultSize` is used.
case file(URL, CGSize?)
}
/// If no size is provided for a `ContentType.file(_, _)`, this value is used.
public static var defaultSize = CGSize(width: 512, height: 512)
/// Create a `QLPreviewView`-containing `NSViewController` to support files.
private static func previewer(for item: QLPreviewItem, size: CGSize?) -> NSViewController {
let vc = NSViewController()
let rect = NSRect(origin: .zero, size: size ?? PreviewController.defaultSize)
let ql = QLPreviewView(frame: rect, style: .normal)!
ql.previewItem = item
vc.view = ql
return vc
}
/// If the `delegate` is not set, the `content` set will be used for previewing,
/// applicable to the whole `bounds` of the `parentView`.
///
/// If both `delegate` and `content` are `nil`, previewing is disabled.
public var content: ContentType? = nil
/// Provides content for previewing controller dynamically.
///
/// If both `delegate` and `content` are `nil`, previewing is disabled.
public weak var delegate: PreviewControllerDelegate? = nil
/// The view that should be registered for previewing; this is not the view
/// that is contained within the preview itself.
public weak var parentView: NSView? = nil {
willSet {
self.parentView?.removeGestureRecognizer(self.gesture)
}
didSet {
self.parentView?.addGestureRecognizer(self.gesture)
}
}
/// Whether the user is currently interacting the preview; that is, the user
/// is engaged in a force touch interaction to display the preview.
public private(set) var interacting: Bool = false
/// Whether the preview is visible; setting this property manually bypasses
/// the user interaction to display the preview regardless.
///
/// When setting `isVisible = true`, the `delegate` is not consulted. Use
/// `content` to specify the preview content.
///
/// Setting `isVisible` while the user is currently interacting is a no-op.
public var isVisible: Bool {
get { return self.popover.isShown }
set {
switch newValue {
case false:
guard self.popover.isShown, !self.interacting else { return }
self.popover.performClose(nil)
case true:
guard !self.popover.isShown, !self.interacting else { return }
guard let view = self.parentView else {
fatalError("PreviewController.parentView was not set, isVisible=true failed.")
}
guard let content = self.content else { return }
// Set the contentView here to maintain only a short-term reference.
switch content {
case .view(let vc):
self.popover.contentViewController = vc
case .file(let url, let size):
self.popover.contentViewController = PreviewController.previewer(for: url as NSURL, size: size)
}
self.popover.show(relativeTo: view.bounds, of: view, preferredEdge: .minY)
}
}
}
/// The popover used to contain and animate the preview content.
private lazy var popover: NSPopover = {
let popover = NSPopover()
popover.behavior = .semitransient
popover.delegate = self
//popover.positioningOptions = .keepTopStable
return popover
}()
/// The gesture recognizer used to handle user interaction for previewing.
private lazy var gesture: PressureGestureRecognizer = {
let gesture = PressureGestureRecognizer(target: self, action: #selector(self.gesture(_:)))
gesture.delegate = self
//gesture.behavior = .primaryAccelerator
return gesture
}()
/// Create a `PreviewController` with a provided `parentView` and `content`.
public init(for view: NSView? = nil, with content: ContentType? = nil) {
super.init()
self.commonInit(view, content) // rebound to call property observers
}
private func commonInit(_ view: NSView? = nil, _ content: ContentType? = nil) {
self.parentView = view
self.content = content
}
@objc dynamic private func gesture(_ sender: PressureGestureRecognizer) {
switch sender.state {
case .possible: break // ignore
case .began:
guard !self.popover.isShown, !self.interacting else { return }
// Begin interaction animation:
self.interacting = true
let point = sender.location(in: self.parentView)
self.popover._private._beginPredeepAnimationAgainstPoint(point, inView: self.parentView)
case .changed:
guard self.popover.isShown, self.interacting else { return }
// Update interaction animation, unless stage 2 (deep press):
guard sender.stage != 2 else { fallthrough }
self.popover._private._doPredeepAnimation(withProgress: Double(sender.stage == 2 ? 1.0 : sender.pressure))
case .ended:
guard self.popover.isShown, self.interacting else { return }
// Complete interaction animation, only if stage 2 (deep press):
guard sender.stage == 2 else { fallthrough }
self.interacting = false
self.popover._private._completeDeepAnimation()
case .failed, .cancelled:
guard self.popover.isShown, self.interacting else { return }
// Cancel interaction animation:
self.interacting = false
self.popover._private._cancelPredeepAnimation()
}
}
public func popoverDidClose(_ notification: Notification) {
self.interacting = false
// Clear the contentView here to maintain only a short-term reference.
self.popover.contentViewController = nil
}
public func gestureRecognizerShouldBegin(_ sender: NSGestureRecognizer) -> Bool {
/// If there exists a `delegate`, request its dynamic content.
/// Otherwise, possibly use the static `content` property.
func effectiveContent(_ point: CGPoint) -> ContentType? {
guard let delegate = self.delegate else {
return self.content
}
return delegate.previewController(self, contentAtPoint: point)
}
// Because `self.popover.behavior = .semitransient`, if the preview is
// currently visible, allow the click to passthrough to the `parentView`.
// This allows the "second click" to be the actual commit action.
guard !self.popover.isShown else { return false }
let content = effectiveContent(sender.location(in: self.parentView))
guard content != nil else { return false }
// Set the contentView here to maintain only a short-term reference.
switch content! {
case .view(let vc):
self.popover.contentViewController = vc
case .file(let url, let size):
self.popover.contentViewController = PreviewController.previewer(for: url as NSURL, size: size)
}
return true
}
// TODO:
/*
public func gestureRecognizer(_ sender: NSGestureRecognizer, shouldAttemptToRecognizeWith event: NSEvent) -> Bool {
if sender is NSPressGestureRecognizer {
return !event.associatedEventsMask.contains(.pressure)
} else if sender is PressureGestureRecognizer {
return event.associatedEventsMask.contains(.pressure)
}
return false
}
*/
}
| a5ce13f719c59aeb7be79c170fe8266c | 42.070423 | 119 | 0.63462 | false | false | false | false |
ntwf/TheTaleClient | refs/heads/1.2/stable | TheTale/Stores/PlayerInformation/AccountInformation/Hero/Quest/Actor.swift | mit | 1 | //
// Actor.swift
// the-tale
//
// Created by Mikhail Vospennikov on 25/06/2017.
// Copyright © 2017 Mikhail Vospennikov. All rights reserved.
//
import Foundation
class Actor: NSObject {
var nameActors: String
var typeActors: Int
var gender: Int?
var actorsID: Int?
var name: String?
var personalityCosmetic: Int?
var personalityPractical: Int?
var place: Int?
var profession: Int?
var race: String?
var info: String?
var goal: String?
required init?(arrayObject: NSArray) {
guard let nameActors = arrayObject[0] as? String,
let typeActors = arrayObject[1] as? Int,
let actorJSON = arrayObject[2] as? JSON else {
return nil
}
let race = String(describing: actorJSON["race"] as? Int)
let personality = actorJSON["personality"] as? JSON
self.nameActors = nameActors
self.typeActors = typeActors
self.gender = actorJSON["gender"] as? Int
self.actorsID = actorJSON["id"] as? Int
self.name = actorJSON["name"] as? String
self.personalityCosmetic = personality?["cosmetic"] as? Int
self.personalityPractical = personality?["practical"] as? Int
self.place = actorJSON["place"] as? Int
self.profession = actorJSON["profession"] as? Int
self.race = String(describing: Types.shared.common?.race[race])
self.info = actorJSON["description"] as? String
self.goal = actorJSON["goal"] as? String
}
}
extension Actor {
var nameActorsRepresentation: String {
return "\(nameActors.capitalizeFirstLetter):"
}
}
| 86288c4b8e7e6c148944a4e5bab46f1c | 28.736842 | 83 | 0.615929 | false | false | false | false |
IngmarStein/swift | refs/heads/master | stdlib/public/core/StringUTF8.swift | apache-2.0 | 4 | //===--- StringUTF8.swift - A UTF8 view of _StringCore --------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// _StringCore currently has three representations: Native ASCII,
// Native UTF-16, and Opaque Cocoa. Expose each of these as UTF-8 in a
// way that will hopefully be efficient to traverse
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#72 : The UTF-8 string view should conform to
// `BidirectionalCollection`.
// FIXME(ABI)#73 : The UTF-8 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension _StringCore {
/// An integral type that holds a sequence of UTF-8 code units, starting in
/// its low byte.
internal typealias _UTF8Chunk = UInt64
/// Encode text starting at `i` as UTF-8. Returns a pair whose first
/// element is the index of the text following whatever got encoded,
/// and the second element contains the encoded UTF-8 starting in its
/// low byte. Any unused high bytes in the result will be set to
/// 0xFF.
func _encodeSomeUTF8(from i: Int) -> (Int, _UTF8Chunk) {
_sanityCheck(i <= count)
if let asciiBuffer = self.asciiBuffer {
// How many UTF-16 code units might we use before we've filled up
// our _UTF8Chunk with UTF-8 code units?
let utf16Count =
Swift.min(MemoryLayout<_UTF8Chunk>.size, asciiBuffer.count - i)
var result: _UTF8Chunk = ~0 // Start with all bits set
_memcpy(
dest: UnsafeMutableRawPointer(Builtin.addressof(&result)),
src: asciiBuffer.baseAddress! + i,
size: numericCast(utf16Count))
// Convert the _UTF8Chunk into host endianness.
return (i + utf16Count, _UTF8Chunk(littleEndian: result))
} else if _fastPath(_baseAddress != nil) {
// Transcoding should return a _UTF8Chunk in host endianness.
return _encodeSomeContiguousUTF16AsUTF8(from: i)
} else {
#if _runtime(_ObjC)
return _encodeSomeNonContiguousUTF16AsUTF8(from: i)
#else
_sanityCheckFailure("_encodeSomeUTF8: Unexpected cocoa string")
#endif
}
}
/// Helper for `_encodeSomeUTF8`, above. Handles the case where the
/// storage is contiguous UTF-16.
func _encodeSomeContiguousUTF16AsUTF8(from i: Int) -> (Int, _UTF8Chunk) {
_sanityCheck(elementWidth == 2)
_sanityCheck(_baseAddress != nil)
let storage = UnsafeBufferPointer(start: startUTF16, count: self.count)
return _transcodeSomeUTF16AsUTF8(storage, i)
}
#if _runtime(_ObjC)
/// Helper for `_encodeSomeUTF8`, above. Handles the case where the
/// storage is non-contiguous UTF-16.
func _encodeSomeNonContiguousUTF16AsUTF8(from i: Int) -> (Int, _UTF8Chunk) {
_sanityCheck(elementWidth == 2)
_sanityCheck(_baseAddress == nil)
let storage = _CollectionOf<Int, UInt16>(
_startIndex: 0, endIndex: self.count
) {
(i: Int) -> UInt16 in
return _cocoaStringSubscript(self, i)
}
return _transcodeSomeUTF16AsUTF8(storage, i)
}
#endif
}
extension String {
/// A view of a string's contents as a collection of UTF-8 code units.
///
/// You can access a string's view of UTF-8 code units by using its `utf8`
/// property. A string's UTF-8 view encodes the string's Unicode scalar
/// values as 8-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf8 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 240
/// // 159
/// // 146
/// // 144
///
/// A string's Unicode scalar values can be up to 21 bits in length. To
/// represent those scalar values using 8-bit integers, more than one UTF-8
/// code unit is often required.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf8 {
/// print(v)
/// }
/// // 240
/// // 159
/// // 146
/// // 144
///
/// In the encoded representation of a Unicode scalar value, each UTF-8 code
/// unit after the first is called a *continuation byte*.
///
/// UTF8View Elements Match Encoded C Strings
/// =========================================
///
/// Swift streamlines interoperation with C string APIs by letting you pass a
/// `String` instance to a function as an `Int8` or `UInt8` pointer. When you
/// call a C function using a `String`, Swift automatically creates a buffer
/// of UTF-8 code units and passes a pointer to that buffer. The code units
/// of that buffer match the code units in the string's `utf8` view.
///
/// The following example uses the C `strncmp` function to compare the
/// beginning of two Swift strings. The `strncmp` function takes two
/// `const char*` pointers and an integer specifying the number of characters
/// to compare. Because the strings are identical up to the 14th character,
/// comparing only those characters results in a return value of `0`.
///
/// let s1 = "They call me 'Bell'"
/// let s2 = "They call me 'Stacey'"
///
/// print(strncmp(s1, s2, 14))
/// // Prints "0"
/// print(String(s1.utf8.prefix(14)))
/// // Prints "They call me '"
///
/// Extending the compared character count to 15 includes the differing
/// characters, so a nonzero result is returned.
///
/// print(strncmp(s1, s2, 15))
/// // Prints "-17"
/// print(String(s1.utf8.prefix(15)))
/// // Prints "They call me 'B"
public struct UTF8View
: Collection,
CustomStringConvertible,
CustomDebugStringConvertible {
internal let _core: _StringCore
internal let _startIndex: Index
internal let _endIndex: Index
init(_ _core: _StringCore) {
self._core = _core
self._endIndex = Index(_coreIndex: _core.endIndex, Index._emptyBuffer)
if _fastPath(_core.count != 0) {
let (_, buffer) = _core._encodeSomeUTF8(from: 0)
self._startIndex = Index(_coreIndex: 0, buffer)
} else {
self._startIndex = self._endIndex
}
}
init(_ _core: _StringCore, _ s: Index, _ e: Index) {
self._core = _core
self._startIndex = s
self._endIndex = e
}
/// A position in a string's `UTF8View` instance.
///
/// You can convert between indices of the different string views by using
/// conversion initializers and the `samePosition(in:)` method overloads.
/// For example, the following code sample finds the index of the first
/// space in the string's character view and then converts that to the same
/// position in the UTF-8 view.
///
/// let hearts = "Hearts <3 ♥︎ 💘"
/// if let i = hearts.characters.index(of: " ") {
/// let j = i.samePosition(in: hearts.utf8)
/// print(Array(hearts.utf8.prefix(upTo: j)))
/// print(hearts.utf8.prefix(upTo: j))
/// }
/// // Prints "[72, 101, 97, 114, 116, 115]"
/// // Prints "Hearts"
public struct Index {
internal typealias Buffer = _StringCore._UTF8Chunk
init(_coreIndex: Int, _ _buffer: Buffer) {
self._coreIndex = _coreIndex
self._buffer = _buffer
}
/// True iff the index is at the end of its view or if the next
/// byte begins a new UnicodeScalar.
internal func _isOnUnicodeScalarBoundary(in core: _StringCore) -> Bool {
let buffer = UInt32(truncatingBitPattern: _buffer)
let (codePoint, _) = UTF8._decodeOne(buffer)
return codePoint != nil || _isEndIndex(of: core)
}
/// True iff the index is at the end of its view
internal func _isEndIndex(of core: _StringCore) -> Bool {
return _buffer == Index._emptyBuffer
&& _coreIndex == core.endIndex
}
/// The number of UTF-8 code units remaining in the buffer before the
/// next unicode scalar value is reached. This simulates calling
/// `index(after: i)` until `i._coreIndex` is incremented, but doesn't
/// need a `_core` reference.
internal var _utf8ContinuationBytesUntilNextUnicodeScalar: Int {
var buffer = _buffer
var count = 0
while true {
let currentUnit = UTF8.CodeUnit(truncatingBitPattern: buffer)
if currentUnit & 0b1100_0000 != 0b1000_0000 {
break
}
count += 1
buffer = Index._nextBuffer(after: buffer)
}
return count
}
/// The value of the buffer when it is empty
internal static var _emptyBuffer: Buffer {
return ~0
}
/// A Buffer value with the high byte set
internal static var _bufferHiByte: Buffer {
return 0xFF << numericCast((MemoryLayout<Buffer>.size &- 1) &* 8)
}
/// Consume a byte of the given buffer: shift out the low byte
/// and put FF in the high byte
internal static func _nextBuffer(after thisBuffer: Buffer) -> Buffer {
return (thisBuffer >> 8) | _bufferHiByte
}
/// The position of `self`, rounded up to the nearest unicode
/// scalar boundary, in the underlying UTF-16.
internal let _coreIndex: Int
/// If `self` is at the end of its `_core`, has the value `_emptyBuffer`.
/// Otherwise, the low byte contains the value of the UTF-8 code unit
/// at this position.
internal let _buffer: Buffer
}
public typealias IndexDistance = Int
/// The position of the first code unit if the UTF-8 view is
/// nonempty.
///
/// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Index {
return self._startIndex
}
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In an empty UTF-8 view, `endIndex` is equal to `startIndex`.
public var endIndex: Index {
return self._endIndex
}
/// Returns the next consecutive position after `i`.
///
/// - Precondition: The next position is representable.
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check i?
let currentUnit = UTF8.CodeUnit(truncatingBitPattern: i._buffer)
let hiNibble = currentUnit >> 4
// Amounts to increment the UTF-16 index based on the high nibble of a
// UTF-8 code unit. If the high nibble is:
//
// - 0b0000-0b0111: U+0000...U+007F: increment the UTF-16 pointer by 1
// - 0b1000-0b1011: UTF-8 continuation byte, do not increment
// the UTF-16 pointer
// - 0b1100-0b1110: U+0080...U+FFFF: increment the UTF-16 pointer by 1
// - 0b1111: U+10000...U+1FFFFF: increment the UTF-16 pointer by 2
let u16Increments = Int(bitPattern:
// 1111 1110 1101 1100 1011 1010 1001 1000 0111 0110 0101 0100 0011 0010 0001 0000
0b10___01___01___01___00___00___00___00___01___01___01___01___01___01___01___01)
// Map the high nibble of the current code unit into the
// amount by which to increment the UTF-16 index.
let increment = (u16Increments >> numericCast(hiNibble << 1)) & 0x3
let nextCoreIndex = i._coreIndex &+ increment
let nextBuffer = Index._nextBuffer(after: i._buffer)
// If the nextBuffer is nonempty, we have all we need
if _fastPath(nextBuffer != Index._emptyBuffer) {
return Index(_coreIndex: nextCoreIndex, nextBuffer)
}
// If the underlying UTF16 isn't exhausted, fill a new buffer
else if _fastPath(nextCoreIndex < _core.endIndex) {
let (_, freshBuffer) = _core._encodeSomeUTF8(from: nextCoreIndex)
return Index(_coreIndex: nextCoreIndex, freshBuffer)
}
else {
// Produce the endIndex
_precondition(
nextCoreIndex == _core.endIndex,
"Can't increment past endIndex of String.UTF8View")
return Index(_coreIndex: nextCoreIndex, nextBuffer)
}
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-8 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf8.startIndex
/// print("First character's UTF-8 code unit: \(greeting.utf8[i])")
/// // Prints "First character's UTF-8 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position`
/// must be less than the view's end index.
public subscript(position: Index) -> UTF8.CodeUnit {
let result = UTF8.CodeUnit(truncatingBitPattern: position._buffer & 0xFF)
_precondition(result != 0xFF, "cannot subscript using endIndex")
return result
}
/// Accesses the contiguous subrange of elements enclosed by the specified
/// range.
///
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
public subscript(bounds: Range<Index>) -> UTF8View {
return UTF8View(_core, bounds.lowerBound, bounds.upperBound)
}
public var description: String {
return String._fromCodeUnitSequenceWithRepair(UTF8.self, input: self).0
}
public var debugDescription: String {
return "UTF8View(\(self.description.debugDescription))"
}
}
/// A UTF-8 encoding of `self`.
public var utf8: UTF8View {
get {
return UTF8View(self._core)
}
set {
self = String(describing: newValue)
}
}
/// A contiguously stored null-terminated UTF-8 representation of the string.
///
/// To access the underlying memory, invoke `withUnsafeBufferPointer` on the
/// array.
///
/// let s = "Hello!"
/// let bytes = s.utf8CString
/// print(bytes)
/// // Prints "[72, 101, 108, 108, 111, 33, 0]"
///
/// bytes.withUnsafeBufferPointer { ptr in
/// print(strlen(ptr.baseAddress!))
/// }
/// // Prints "6"
public var utf8CString: ContiguousArray<CChar> {
var result = ContiguousArray<CChar>()
result.reserveCapacity(utf8.count + 1)
for c in utf8 {
result.append(CChar(bitPattern: c))
}
result.append(0)
return result
}
internal func _withUnsafeBufferPointerToUTF8<R>(
_ body: (UnsafeBufferPointer<UTF8.CodeUnit>) throws -> R
) rethrows -> R {
if let asciiBuffer = self._core.asciiBuffer {
return try body(UnsafeBufferPointer(
start: asciiBuffer.baseAddress,
count: asciiBuffer.count))
}
var nullTerminatedUTF8 = ContiguousArray<UTF8.CodeUnit>()
nullTerminatedUTF8.reserveCapacity(utf8.count + 1)
nullTerminatedUTF8 += utf8
nullTerminatedUTF8.append(0)
return try nullTerminatedUTF8.withUnsafeBufferPointer(body)
}
/// Creates a string corresponding to the given sequence of UTF-8 code units.
///
/// If `utf8` is an ill-formed UTF-8 code sequence, the result is `nil`.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `utf8` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.utf8.index(of: 32) {
/// let adjective = String(picnicGuest.utf8.prefix(upTo: i))
/// print(adjective)
/// }
/// // Prints "Optional(Deserving)"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.utf8` view.
///
/// - Parameter utf8: A UTF-8 code sequence.
public init?(_ utf8: UTF8View) {
let wholeString = String(utf8._core)
if let start = utf8.startIndex.samePosition(in: wholeString),
let end = utf8.endIndex.samePosition(in: wholeString) {
self = wholeString[start..<end]
return
}
return nil
}
/// The index type for subscripting a string's `utf8` view.
public typealias UTF8Index = UTF8View.Index
}
extension String.UTF8View.Index : Comparable {
// FIXME: swift-3-indexing-model: add complete set of forwards for Comparable
// assuming String.UTF8View.Index continues to exist
public static func == (
lhs: String.UTF8View.Index,
rhs: String.UTF8View.Index
) -> Bool {
// If the underlying UTF16 index differs, they're unequal
if lhs._coreIndex != rhs._coreIndex {
return false
}
// Match up bytes in the buffer
var buffer = (lhs._buffer, rhs._buffer)
var isContinuation: Bool
while true {
let unit = (
UTF8.CodeUnit(truncatingBitPattern: buffer.0),
UTF8.CodeUnit(truncatingBitPattern: buffer.1))
isContinuation = UTF8.isContinuation(unit.0)
if !isContinuation {
// We don't check for unit equality in this case because one of
// the units might be an 0xFF read from the end of the buffer.
return !UTF8.isContinuation(unit.1)
}
// Continuation bytes must match exactly
else if unit.0 != unit.1 {
return false
}
// Move the buffers along.
buffer = (
String.UTF8Index._nextBuffer(after: buffer.0),
String.UTF8Index._nextBuffer(after: buffer.1))
}
}
public static func < (
lhs: String.UTF8View.Index,
rhs: String.UTF8View.Index
) -> Bool {
if lhs._coreIndex == rhs._coreIndex && lhs._buffer != rhs._buffer {
// The index with more continuation bytes remaining before the next
return lhs._utf8ContinuationBytesUntilNextUnicodeScalar >
rhs._utf8ContinuationBytesUntilNextUnicodeScalar
}
return lhs._coreIndex < rhs._coreIndex
}
}
// Index conversions
extension String.UTF8View.Index {
internal init(_ core: _StringCore, _utf16Offset: Int) {
let (_, buffer) = core._encodeSomeUTF8(from: _utf16Offset)
self.init(_coreIndex: _utf16Offset, buffer)
}
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `utf8` view.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.index(of: 32)!
/// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)!
///
/// print(Array(cafe.utf8.prefix(upTo: utf8Index)))
/// // Prints "[67, 97, 102, 195, 169]"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `utf8`, the result of the initializer is
/// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code
/// points differently, an attempt to convert the position of the trailing
/// surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `utf8`, but the
/// index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.UTF8View.Index(emojiLow, within: cafe.utf8))
/// // Prints "nil"
///
/// - Parameters:
/// - utf16Index: A position in a `UTF16View` instance. `utf16Index` must
/// be an element in `String(utf8).utf16.indices`.
/// - utf8: The `UTF8View` in which to find the new position.
public init?(_ utf16Index: String.UTF16Index, within utf8: String.UTF8View) {
let utf16 = String.UTF16View(utf8._core)
if utf16Index != utf16.startIndex
&& utf16Index != utf16.endIndex {
_precondition(
utf16Index >= utf16.startIndex
&& utf16Index <= utf16.endIndex,
"Invalid String.UTF16Index for this UTF-8 view")
// Detect positions that have no corresponding index. Note that
// we have to check before and after, because an unpaired
// surrogate will be decoded as a single replacement character,
// thus making the corresponding position valid in UTF8.
if UTF16.isTrailSurrogate(utf16[utf16Index])
&& UTF16.isLeadSurrogate(utf16[utf16.index(before: utf16Index)]) {
return nil
}
}
self.init(utf8._core, _utf16Offset: utf16Index._offset)
}
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified `UnicodeScalarView` position.
///
/// The following example converts the position of the Unicode scalar `"e"`
/// into its corresponding position in the string's `utf8` view.
///
/// let cafe = "Cafe\u{0301}"
/// let scalarsIndex = cafe.unicodeScalars.index(of: "e")!
/// let utf8Index = String.UTF8View.Index(scalarsIndex, within: cafe.utf8)
///
/// print(Array(cafe.utf8.prefix(through: utf8Index)))
/// // Prints "[67, 97, 102, 101]"
///
/// - Parameters:
/// - unicodeScalarIndex: A position in a `UnicodeScalarView` instance.
/// `unicodeScalarIndex` must be an element of
/// `String(utf8).unicodeScalars.indices`.
/// - utf8: The `UTF8View` in which to find the new position.
public init(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within utf8: String.UTF8View
) {
self.init(utf8._core, _utf16Offset: unicodeScalarIndex._position)
}
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified string position.
///
/// The following example converts the position of the teacup emoji (`"🍵"`)
/// into its corresponding position in the string's `utf8` view.
///
/// let cafe = "Café 🍵"
/// let characterIndex = cafe.characters.index(of: "🍵")!
/// let utf8Index = String.UTF8View.Index(characterIndex, within: cafe.utf8)
///
/// print(Array(cafe.utf8.suffix(from: utf8Index)))
/// // Prints "[240, 159, 141, 181]"
///
/// - Parameters:
/// - characterIndex: A position in a `CharacterView` instance.
/// `characterIndex` must be an element of
/// `String(utf8).characters.indices`.
/// - utf8: The `UTF8View` in which to find the new position.
public init(_ characterIndex: String.Index, within utf8: String.UTF8View) {
self.init(utf8._core, _utf16Offset: characterIndex._base._position)
}
/// Returns the position in the given UTF-16 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf16).utf8`.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method to find the same
/// position in the string's `utf16` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf8.index(of: 32)!
/// let j = i.samePosition(in: cafe.utf16)!
/// print(cafe.utf16.prefix(upTo: j))
/// // Prints "Café"
///
/// - Parameter utf16: The view to use for the index conversion.
/// - Returns: The position in `utf16` that corresponds exactly to this
/// index. If this index does not have an exact corresponding position in
/// `utf16`, this method returns `nil`. For example, an attempt to convert
/// the position of a UTF-8 continuation byte returns `nil`.
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index? {
return String.UTF16View.Index(self, within: utf16)
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// This index must be a valid index of `String(unicodeScalars).utf8`.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method to find the same position
/// in the string's `unicodeScalars` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf8.index(of: 32)!
/// let j = i.samePosition(in: cafe.unicodeScalars)!
/// print(cafe.unicodeScalars.prefix(upTo: j))
/// // Prints "Café"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `unicodeScalars`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-8 continuation byte
/// returns `nil`.
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarIndex? {
return String.UnicodeScalarIndex(self, within: unicodeScalars)
}
/// Returns the position in the given string that corresponds exactly to this
/// index.
///
/// This index must be a valid index of `characters.utf8`.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method find the same position
/// in the string.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf8.index(of: 32)!
/// let j = i.samePosition(in: cafe)!
/// print(cafe[cafe.startIndex ..< j])
/// // Prints "Café"
///
/// - Parameter characters: The string to use for the index conversion.
/// - Returns: The position in `characters` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `characters`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-8 continuation byte
/// returns `nil`.
public func samePosition(
in characters: String
) -> String.Index? {
return String.Index(self, within: characters)
}
}
// Reflection
extension String.UTF8View : CustomReflectable {
/// Returns a mirror that reflects the UTF-8 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UTF8View : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
extension String {
@available(*, unavailable, message: "Please use String.utf8CString instead.")
public var nulTerminatedUTF8: ContiguousArray<UTF8.CodeUnit> {
Builtin.unreachable()
}
}
| 7e523b357b2113decbb1f658c2939240 | 36.4875 | 89 | 0.631507 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | refs/heads/master | InfiniteScroll/InfiniteScrollUITests/InfiniteScrollUITests.swift | apache-2.0 | 1 | //
// InfiniteScrollUITests.swift
// InfiniteScrollUITests
//
// Created by Anirudh Das on 7/8/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import XCTest
@testable import InfiniteScroll
class InfiniteScrollUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testAlertOnInvalidInput() {
let app = XCUIApplication()
let nametxtfldTextField = app/*@START_MENU_TOKEN@*/.textFields["NameTxtFld"]/*[[".textFields[\"Full Name\"]",".textFields[\"NameTxtFld\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/
nametxtfldTextField.tap()
app/*@START_MENU_TOKEN@*/.buttons["StartBtn"]/*[[".buttons[\"Start\"]",".buttons[\"StartBtn\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.alerts["Invalid Entry!"].buttons["OK"].tap()
XCTAssertEqual(nametxtfldTextField.label, "")
}
func testImageRenderingOnValidInput() {
let app = XCUIApplication()
let nametxtfldTextField = app/*@START_MENU_TOKEN@*/.textFields["NameTxtFld"]/*[[".textFields[\"Full Name\"]",".textFields[\"NameTxtFld\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/
nametxtfldTextField.tap()
nametxtfldTextField.typeText("Anirudh")
app/*@START_MENU_TOKEN@*/.buttons["StartBtn"]/*[[".buttons[\"Start\"]",".buttons[\"StartBtn\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
let collectionView = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .collectionView).element
collectionView.swipeUp()
collectionView.swipeUp()
collectionView.swipeUp()
collectionView.swipeDown()
let name = app.staticTexts["NameLbl"]
XCTAssertEqual(name.label, "Anirudh")
XCTAssertTrue(!name.label.isEmpty)
let time = app.staticTexts["TimeLbl"]
XCTAssertTrue(!time.label.isEmpty)
XCTAssertEqual(time.label.count, "Sun, 8 Jul 2018 09:56:10:45 AM".count)
}
func testTapOnImage() {
let app = XCUIApplication()
let nametxtfldTextField = app/*@START_MENU_TOKEN@*/.textFields["NameTxtFld"]/*[[".textFields[\"Full Name\"]",".textFields[\"NameTxtFld\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/
nametxtfldTextField.tap()
nametxtfldTextField.typeText("Anirudh")
app/*@START_MENU_TOKEN@*/.buttons["StartBtn"]/*[[".buttons[\"Start\"]",".buttons[\"StartBtn\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.collectionViews.children(matching: .cell).element(boundBy: 0).otherElements.containing(.image, identifier:"PixlrImgView").element.tap()
app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).children(matching: .other).element.children(matching: .scrollView).element.tap()
}
}
| 4abb26790a84eabd0202f3d9637b8b8c | 48.472973 | 188 | 0.636711 | false | true | false | false |
duliodenis/blocstagram2 | refs/heads/master | Blocstagram/Blocstagram/Model/Post.swift | mit | 1 | //
// Post.swift
// Blocstagram
//
// Created by ddenis on 1/16/17.
// Copyright © 2017 ddApps. All rights reserved.
//
import Foundation
import FirebaseAuth
class Post {
var caption: String?
var photoURL: String?
var uid: String?
var id: String?
var likeCount: Int?
var likes: Dictionary<String, Any>?
var isLiked: Bool?
}
extension Post {
static func transformPost(postDictionary: [String: Any], key: String) -> Post {
let post = Post()
post.id = key
post.caption = postDictionary["caption"] as? String
post.photoURL = postDictionary["photoURL"] as? String
post.uid = postDictionary["uid"] as? String
post.likeCount = postDictionary["likesCount"] as? Int
post.likes = postDictionary["likes"] as? Dictionary<String, Any>
if let currentUserID = FIRAuth.auth()?.currentUser?.uid {
if post.likes != nil {
post.isLiked = post.likes![currentUserID] != nil
}
}
return post
}
}
| 2d0a345864e5e1ca7753d8ce76d63288 | 23.386364 | 83 | 0.589935 | false | false | false | false |
rajeejones/SavingPennies | refs/heads/master | Saving Pennies/PopupView.swift | gpl-3.0 | 1 | //
// PopupView.swift
// Saving Pennies
//
// Created by Rajee Jones on 2/28/17.
// Copyright © 2017 Rajee Jones. All rights reserved.
//
import UIKit
protocol BillPaymentDelegate: class {
func payBill(forAmount: Int)
func advanceLevel()
}
enum PopupViewType {
case expenses, assets, goals, unknown
}
class PopupView: UIView {
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var bottomButton: UIButton!
@IBOutlet weak var mainHeader: UIView!
@IBOutlet weak var mainHeaderLabel: UILabel!
@IBOutlet weak var mainHeaderSubLabel: UILabel!
@IBOutlet weak var mainTableView: UITableView!
var popupType = PopupViewType.unknown {
didSet {
configurePopupView()
}
}
weak var billPaymentDelegate:BillPaymentDelegate?
override func awakeFromNib() {
setup()
}
func setup() {
mainTableView.register(UINib(nibName: "ExpenseTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
mainTableView.delegate = self
mainTableView.dataSource = self
}
@IBAction func closePopupButtonPressed(_ sender: AnyObject) {
if let superView = self.superview as? PopupContainer {
(superView ).close()
}
}
func configurePopupView() {
switch popupType {
case .assets:
break
case .expenses:
mainHeader.backgroundColor = UIColor().brandRed()
mainHeaderLabel.text = "Expenses"
mainHeaderSubLabel.text = "select item to purchase"
break
case .goals:
break
case .unknown:
break
}
}
}
extension PopupView: UITableViewDataSource, UITableViewDelegate, PayButtonDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch(self.popupType) {
case .expenses:
return level.expenses.count
default:
return 0
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
switch(self.popupType) {
case .expenses:
cell = setupExpensesTableViewCell(tableView, indexPath: indexPath)
break
default:
break
}
return cell
}
func setupExpensesTableViewCell(_ tableView:UITableView,indexPath:IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ExpenseTableViewCell
cell.itemLabel.text = level.expenses[indexPath.row].description
cell.itemLabel.textColor = UIColor().brandRed()
cell.paid = level.expenses[indexPath.row].paid
cell.payButtonDelegate = self
cell.paymentAmount = level.expenses[indexPath.row].amount
if cell.paid {
cell.payBtn.alpha = 0
cell.paidCheckmarkImage.alpha = 1
}
else if !cell.canBePaid() {
cell.payBtn.borderColor = UIColor.clear
cell.payBtn.setTitle(formatter.string(from: NSNumber(value: level.expenses[indexPath.row].amount)), for: UIControlState.normal)
cell.payBtn.tintColor = UIColor().brandRed()
cell.payBtn.setTitleColor(UIColor().brandRed(), for: UIControlState.normal)
} else {
cell.payBtn.borderColor = UIColor().brandGreen()
cell.payBtn.setTitle("Pay!", for: UIControlState.normal)
cell.payBtn.tintColor = UIColor().brandGreen()
cell.payBtn.setTitleColor(UIColor().brandGreen(), for: UIControlState.normal)
}
return cell
}
//PayButtonDelegate
func payButtonPressed(amount: Int, cell: UITableViewCell) {
// check if paid, then set the variable to paid, and change the image
guard let expenseCell = cell as? ExpenseTableViewCell else {
return
}
guard let cellIndex = mainTableView.indexPath(for: expenseCell)?.row else {
return
}
if expenseCell.canBePaid() {
expenseCell.paid = true
level.expenses[cellIndex].paid = true
expenseCell.animateItemPaid()
mainTableView.reloadData()
}
billPaymentDelegate?.payBill(forAmount: amount)
var advance = false
for expense in level.expenses {
if expense.paid {
advance = true
} else {
advance = false
break
}
}
if advance {
if let superView = self.superview as? PopupContainer {
(superView ).close()
}
billPaymentDelegate?.advanceLevel()
}
}
}
| 19ef696865abac61f965d5ed03533fe2 | 27.917127 | 139 | 0.589989 | false | false | false | false |
carabina/DDMathParser | refs/heads/master | MathParser/TokenResolver.swift | mit | 2 | //
// TokenResolver.swift
// DDMathParser
//
// Created by Dave DeLong on 8/8/15.
//
//
import Foundation
public struct TokenResolverOptions: OptionSetType {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let None = TokenResolverOptions(rawValue: 0)
public static let AllowArgumentlessFunctions = TokenResolverOptions(rawValue: 1 << 0)
public static let AllowImplicitMultiplication = TokenResolverOptions(rawValue: 1 << 1)
public static let UseHighPrecedenceImplicitMultiplication = TokenResolverOptions(rawValue: 1 << 2)
public static let defaultOptions: TokenResolverOptions = [.AllowArgumentlessFunctions, .AllowImplicitMultiplication, .UseHighPrecedenceImplicitMultiplication]
}
public struct TokenResolver {
private let tokenizer: Tokenizer
private let options: TokenResolverOptions
private let locale: NSLocale?
private let numberFormatters: Array<NSNumberFormatter>
internal var operatorSet: OperatorSet { return tokenizer.operatorSet }
private static func formattersForLocale(locale: NSLocale?) -> Array<NSNumberFormatter> {
guard let locale = locale else { return [] }
let decimal = NSNumberFormatter()
decimal.locale = locale
decimal.numberStyle = .DecimalStyle
return [decimal]
}
public init(tokenizer: Tokenizer, options: TokenResolverOptions = TokenResolverOptions.defaultOptions) {
self.tokenizer = tokenizer
self.options = options
self.locale = tokenizer.locale
self.numberFormatters = TokenResolver.formattersForLocale(tokenizer.locale)
}
public init(string: String, operatorSet: OperatorSet = OperatorSet.defaultOperatorSet, options: TokenResolverOptions = TokenResolverOptions.defaultOptions, locale: NSLocale? = nil) {
self.tokenizer = Tokenizer(string: string, operatorSet: operatorSet, locale: locale)
self.options = options
self.locale = locale
self.numberFormatters = TokenResolver.formattersForLocale(locale)
}
public func resolve() throws -> Array<ResolvedToken> {
let rawTokens = try tokenizer.tokenize()
var resolvedTokens = Array<ResolvedToken>()
for rawToken in rawTokens {
let resolved = try resolveToken(rawToken, previous: resolvedTokens.last)
resolvedTokens.appendContentsOf(resolved)
}
let finalResolved = try resolveToken(nil, previous: resolvedTokens.last)
resolvedTokens.appendContentsOf(finalResolved)
return resolvedTokens
}
}
extension TokenResolver {
private func resolveToken(raw: RawToken?, previous: ResolvedToken?) throws -> Array<ResolvedToken> {
guard let raw = raw else {
// this is the case where the we check for argumentless stuff
// after the last token
if options.contains(.AllowArgumentlessFunctions) {
return extraTokensForArgumentlessFunction(nil, previous: previous)
} else {
return []
}
}
let resolvedTokens = try resolveRawToken(raw, previous: previous)
guard let firstResolved = resolvedTokens.first else {
fatalError("Implementation flaw! A token cannot resolve to nothing")
}
var final = Array<ResolvedToken>()
// check for argumentless functions
if options.contains(.AllowArgumentlessFunctions) {
let extras = extraTokensForArgumentlessFunction(firstResolved, previous: previous)
final.appendContentsOf(extras)
}
// check for implicit multiplication
if options.contains(.AllowImplicitMultiplication) {
let last = final.last ?? previous
let extras = extraTokensForImplicitMultiplication(firstResolved, previous: last)
final.appendContentsOf(extras)
}
final.appendContentsOf(resolvedTokens)
return final
}
private func resolveRawToken(rawToken: RawToken, previous: ResolvedToken?) throws -> Array<ResolvedToken> {
var resolvedTokens = Array<ResolvedToken>()
switch rawToken.kind {
case .HexNumber:
if let number = UInt(rawToken.string, radix: 16) {
resolvedTokens.append(ResolvedToken(kind: .Number(Double(number)), string: rawToken.string, range: rawToken.range))
} else {
throw TokenResolverError(kind: .CannotParseHexNumber, rawToken: rawToken)
}
case .Number:
resolvedTokens.append(resolveNumber(rawToken))
case .LocalizedNumber:
resolvedTokens.append(try resolveLocalizedNumber(rawToken))
case .Exponent:
resolvedTokens.appendContentsOf(try resolveExponent(rawToken))
case .Variable:
resolvedTokens.append(ResolvedToken(kind: .Variable(rawToken.string), string: rawToken.string, range: rawToken.range))
case .Identifier:
resolvedTokens.append(ResolvedToken(kind: .Identifier(rawToken.string), string: rawToken.string, range: rawToken.range))
case .Operator:
resolvedTokens.append(try resolveOperator(rawToken, previous: previous))
}
return resolvedTokens
}
private func resolveNumber(raw: RawToken) -> ResolvedToken {
// first, see if it's a special number
if let character = raw.string.characters.first, let value = SpecialNumberExtractor.specialNumbers[character] {
return ResolvedToken(kind: .Number(value), string: raw.string, range: raw.range)
}
let cleaned = raw.string.stringByReplacingOccurrencesOfString("−", withString: "-")
let number = NSDecimalNumber(string: cleaned)
return ResolvedToken(kind: .Number(number.doubleValue), string: raw.string, range: raw.range)
}
private func resolveLocalizedNumber(raw: RawToken) throws -> ResolvedToken {
for formatter in numberFormatters {
if let number = formatter.numberFromString(raw.string) {
return ResolvedToken(kind: .Number(number.doubleValue), string: raw.string, range: raw.range)
}
}
throw TokenResolverError(kind: .CannotParseLocalizedNumber, rawToken: raw)
}
private func resolveExponent(raw: RawToken) throws -> Array<ResolvedToken> {
var resolved = Array<ResolvedToken>()
let powerOperator = operatorSet.powerOperator
let power = ResolvedToken(kind: .Operator(powerOperator), string: "**", range: raw.range.startIndex ..< raw.range.startIndex)
let openParen = ResolvedToken(kind: .Operator(Operator(builtInOperator: .ParenthesisOpen)), string: "(", range: raw.range.startIndex ..< raw.range.startIndex)
resolved += [power, openParen]
let exponentTokenizer = Tokenizer(string: raw.string, operatorSet: operatorSet, locale: locale)
let exponentResolver = TokenResolver(tokenizer: exponentTokenizer, options: options)
let exponentTokens = try exponentResolver.resolve()
var distanceSoFar = 0
for exponentToken in exponentTokens {
let tokenStart = raw.range.startIndex.advancedBy(distanceSoFar)
let tokenLength = exponentToken.range.startIndex.distanceTo(exponentToken.range.endIndex)
let tokenEnd = tokenStart.advancedBy(tokenLength)
distanceSoFar += tokenLength
resolved.append(ResolvedToken(kind: exponentToken.kind, string: exponentToken.string, range: tokenStart ..< tokenEnd))
}
let closeParen = ResolvedToken(kind: .Operator(Operator(builtInOperator: .ParenthesisClose)), string: ")", range: raw.range.endIndex ..< raw.range.endIndex)
resolved.append(closeParen)
return resolved
}
private func resolveOperator(raw: RawToken, previous: ResolvedToken?) throws -> ResolvedToken {
let matches = operatorSet.operatorForToken(raw.string)
if matches.isEmpty {
throw TokenResolverError(kind: .UnknownOperator, rawToken: raw)
}
if matches.count == 1 {
let op = matches[0]
return ResolvedToken(kind: .Operator(op), string: raw.string, range: raw.range)
}
// more than one operator has this token
var resolvedOperator: Operator? = nil
if let previous = previous {
switch previous.kind {
case .Operator(let o):
resolvedOperator = resolveOperator(raw, previousOperator: o)
default:
// a number/variable can be followed by:
// a left-assoc unary operator,
// a binary operator,
// or a right-assoc unary operator (assuming implicit multiplication)
// we'll prefer them from left-to-right:
// left-assoc unary, binary, right-assoc unary
// TODO: is this correct?? should we be looking at precedence instead?
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Left).first
if resolvedOperator == nil {
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Binary).first
}
if resolvedOperator == nil {
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Right).first
}
}
} else {
// no previous token, so this must be a right-assoc unary operator
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Right).first
}
if let resolved = resolvedOperator {
return ResolvedToken(kind: .Operator(resolved), string: raw.string, range: raw.range)
} else {
throw TokenResolverError(kind: .AmbiguousOperator, rawToken: raw)
}
}
private func resolveOperator(raw: RawToken, previousOperator o: Operator) -> Operator? {
var resolvedOperator: Operator?
switch (o.arity, o.associativity) {
case (.Unary, .Left):
// a left-assoc unary operator can be followed by either:
// another left-assoc unary operator
// or a binary operator
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Left).first
if resolvedOperator == nil {
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Binary).first
}
default:
// either a binary operator or a right-assoc unary operator
// a binary operator can only be followed by a right-assoc unary operator
//a right-assoc operator can only be followed by a right-assoc unary operator
resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Right).first
}
return resolvedOperator
}
private func extraTokensForArgumentlessFunction(next: ResolvedToken?, previous: ResolvedToken?) -> Array<ResolvedToken> {
guard let previous = previous else { return [] }
// we only insert tokens here if the previous token was an identifier
guard let _ = previous.kind.identifier else { return [] }
let nextOperator = next?.kind.resolvedOperator
if nextOperator == nil || nextOperator?.builtInOperator != .ParenthesisOpen {
let range = previous.range.endIndex ..< previous.range.endIndex
let openParenOp = Operator(builtInOperator: .ParenthesisOpen)
let openParen = ResolvedToken(kind: .Operator(openParenOp), string: "(", range: range)
let closeParenOp = Operator(builtInOperator: .ParenthesisClose)
let closeParen = ResolvedToken(kind: .Operator(closeParenOp), string: ")", range: range)
return [openParen, closeParen]
}
return []
}
private func extraTokensForImplicitMultiplication(next: ResolvedToken, previous: ResolvedToken?) -> Array<ResolvedToken> {
guard let previousKind = previous?.kind else { return [] }
let nextKind = next.kind
let previousMatches = previousKind.isNumber || previousKind.isVariable || (previousKind.resolvedOperator?.arity == .Unary && previousKind.resolvedOperator?.associativity == .Left)
let nextMatches = nextKind.isOperator == false || (nextKind.resolvedOperator?.arity == .Unary && nextKind.resolvedOperator?.associativity == .Right)
guard previousMatches && nextMatches else { return [] }
let multiplyOperator: Operator
if options.contains(.UseHighPrecedenceImplicitMultiplication) {
multiplyOperator = operatorSet.implicitMultiplyOperator
} else {
multiplyOperator = operatorSet.multiplyOperator
}
return [ResolvedToken(kind: .Operator(multiplyOperator), string: "*", range: next.range.startIndex ..< next.range.startIndex)]
}
}
| 73a90e9d510a4b5906169298d3681474 | 42.609375 | 187 | 0.624006 | false | false | false | false |
QuarkX/Quark | refs/heads/master | Tests/QuarkTests/Core/JSON/JSONTests.swift | mit | 1 | import XCTest
@testable import Quark
class JSONTests : XCTestCase {
func testJSON() throws {
let parser = JSONMapParser()
let serializer = JSONMapSerializer(ordering: true)
let data = Data("{\"array\":[true,-4.2,-1969,null,\"hey! 😊\"],\"boolean\":false,\"dictionaryOfEmptyStuff\":{\"emptyArray\":[],\"emptyDictionary\":{},\"emptyString\":\"\"},\"double\":4.2,\"integer\":1969,\"null\":null,\"string\":\"yoo! 😎\"}")
let map: Map = [
"array": [
true,
-4.2,
-1969,
nil,
"hey! 😊",
],
"boolean": false,
"dictionaryOfEmptyStuff": [
"emptyArray": [],
"emptyDictionary": [:],
"emptyString": ""
],
"double": 4.2,
"integer": 1969,
"null": nil,
"string": "yoo! 😎",
]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
let serialized = try serializer.serialize(map)
XCTAssertEqual(serialized, data)
}
func testNumberWithExponent() throws {
let parser = JSONMapParser()
let data = Data("[1E3]")
let map: Map = [1_000]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
}
func testNumberWithNegativeExponent() throws {
let parser = JSONMapParser()
let data = Data("[1E-3]")
let map: Map = [1E-3]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
}
func testWhitespaces() throws {
let parser = JSONMapParser()
let data = Data("[ \n\t\r1 \n\t\r]")
let map: Map = [1]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
}
func testNumberStartingWithZero() throws {
let parser = JSONMapParser()
let data = Data("[0001000]")
let map: Map = [1000]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
}
func testEscapedSlash() throws {
let parser = JSONMapParser()
let serializer = JSONMapSerializer()
let data = Data("{\"foo\":\"\\\"\"}")
let map: Map = [
"foo": "\""
]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
let serialized = try serializer.serialize(map)
XCTAssertEqual(serialized, data)
}
func testSmallDictionary() throws {
let parser = JSONMapParser()
let serializer = JSONMapSerializer()
let data = Data("{\"foo\":\"bar\",\"fuu\":\"baz\"}")
let map: Map = [
"foo": "bar",
"fuu": "baz",
]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
let serialized = try serializer.serialize(map)
XCTAssert(serialized == data || serialized == Data("{\"fuu\":\"baz\",\"foo\":\"bar\"}"))
}
func testInvalidMap() throws {
let serializer = JSONMapSerializer()
let map: Map = [
"foo": .data(Data("yo!"))
]
var called = false
do {
_ = try serializer.serialize(map)
XCTFail("Should've throwed error")
} catch {
called = true
}
XCTAssert(called)
}
func testEscapedEmoji() throws {
let parser = JSONMapParser()
let serializer = JSONMapSerializer()
let data = Data("[\"\\ud83d\\ude0e\"]")
let map: Map = ["😎"]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
let serialized = try serializer.serialize(map)
XCTAssertEqual(serialized, Data("[\"😎\"]"))
}
func testEscapedSymbol() throws {
let parser = JSONMapParser()
let serializer = JSONMapSerializer()
let data = Data("[\"\\u221e\"]")
let map: Map = ["∞"]
let parsed = try parser.parse(data)
XCTAssertEqual(parsed, map)
let serialized = try serializer.serialize(map)
XCTAssertEqual(serialized, Data("[\"∞\"]"))
}
func testFailures() throws {
let parser = JSONMapParser()
var data: Data
data = Data("")
XCTAssertThrowsError(try parser.parse(data))
data = Data("nudes")
XCTAssertThrowsError(try parser.parse(data))
data = Data("bar")
XCTAssertThrowsError(try parser.parse(data))
data = Data("{}foo")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\u")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud8")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\u")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\ud")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\ude")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\ude0")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\ude0e")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\ud83d\\u0000")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\u0000\\u0000")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\u0000\\ude0e")
XCTAssertThrowsError(try parser.parse(data))
data = Data("\"\\uGGGG\\uGGGG")
XCTAssertThrowsError(try parser.parse(data))
data = Data("0F")
XCTAssertThrowsError(try parser.parse(data))
data = Data("-0F")
XCTAssertThrowsError(try parser.parse(data))
data = Data("-09F")
XCTAssertThrowsError(try parser.parse(data))
data = Data("999999999999999998")
XCTAssertThrowsError(try parser.parse(data))
data = Data("999999999999999999")
XCTAssertThrowsError(try parser.parse(data))
data = Data("9999999999999999990")
XCTAssertThrowsError(try parser.parse(data))
data = Data("9999999999999999999")
XCTAssertThrowsError(try parser.parse(data))
data = Data("9.")
XCTAssertThrowsError(try parser.parse(data))
data = Data("0E")
XCTAssertThrowsError(try parser.parse(data))
data = Data("{\"foo\"}")
XCTAssertThrowsError(try parser.parse(data))
data = Data("{\"foo\":\"bar\"\"fuu\"}")
XCTAssertThrowsError(try parser.parse(data))
data = Data("{1969}")
XCTAssertThrowsError(try parser.parse(data))
data = Data("[\"foo\"\"bar\"]")
XCTAssertThrowsError(try parser.parse(data))
}
func testDescription() throws {
XCTAssertEqual(String(describing: JSONMapParseError.unexpectedTokenError(reason: "foo", lineNumber: 0, columnNumber: 0)), "UnexpectedTokenError[Line: 0, Column: 0]: foo")
XCTAssertEqual(String(describing: JSONMapParseError.insufficientTokenError(reason: "foo", lineNumber: 0, columnNumber: 0)), "InsufficientTokenError[Line: 0, Column: 0]: foo")
XCTAssertEqual(String(describing: JSONMapParseError.extraTokenError(reason: "foo", lineNumber: 0, columnNumber: 0)), "ExtraTokenError[Line: 0, Column: 0]: foo")
XCTAssertEqual(String(describing: JSONMapParseError.nonStringKeyError(reason: "foo", lineNumber: 0, columnNumber: 0)), "NonStringKeyError[Line: 0, Column: 0]: foo")
XCTAssertEqual(String(describing: JSONMapParseError.invalidStringError(reason: "foo", lineNumber: 0, columnNumber: 0)), "InvalidStringError[Line: 0, Column: 0]: foo")
XCTAssertEqual(String(describing: JSONMapParseError.invalidNumberError(reason: "foo", lineNumber: 0, columnNumber: 0)), "InvalidNumberError[Line: 0, Column: 0]: foo")
}
}
extension JSONTests {
static var allTests: [(String, (JSONTests) -> () throws -> Void)] {
return [
("testJSON", testJSON),
("testNumberWithExponent", testNumberWithExponent),
("testNumberWithNegativeExponent", testNumberWithNegativeExponent),
("testWhitespaces", testWhitespaces),
("testNumberStartingWithZero", testNumberStartingWithZero),
("testEscapedSlash", testEscapedSlash),
("testSmallDictionary", testSmallDictionary),
("testInvalidMap", testInvalidMap),
("testEscapedEmoji", testEscapedEmoji),
("testEscapedSymbol", testEscapedSymbol),
("testFailures", testFailures),
("testDescription", testDescription),
]
}
}
| b400ef77fd87d616c45f5eb8d2eecd72 | 34.972332 | 249 | 0.582024 | false | true | false | false |
PREAlbert/rulerSwift | refs/heads/master | rulerSwift-Demo/rulerSwift/rulerSwift/FSRulerScrollView.swift | mit | 2 | //
// FSRulerScrollView.swift
// rulerSwift
//
// Created by Albert on 16/6/4.
// Copyright © 2016年 Albert. All rights reserved.
//
import UIKit
class FSRulerScrollView: UIScrollView {
override init(frame: CGRect) {
super.init(frame: frame);
// self.rulerScrollView?.rulerWidth = CGFloat
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!;
fatalError("init(coder:) has not been implemented")
}
let DISTANCELEFTANDRIGHT :CGFloat = 8 //标尺左右距离
let DISTANCEVALUE: CGFloat = 8 //刻度实际长度
let DISTANCETOPANDBOTTOM: CGFloat = 20 //标尺上下距离
var rulerCount: NSInteger?
var rulerAverage: NSNumber?
var rulerHeight: NSInteger?
var rulerWidth: NSInteger?
var rulerValue: Float?
var mode: Bool?
func drawRuler() {
let pathRef1 = CGMutablePath()
let pathRef2 = CGMutablePath()
let shapeLayer1 = CAShapeLayer.init()
shapeLayer1.strokeColor = UIColor.lightGray().cgColor
shapeLayer1.fillColor = UIColor.clear().cgColor
shapeLayer1.lineWidth = 1
shapeLayer1.lineCap = kCALineCapButt
let shapeLayer2 = CAShapeLayer.init()
shapeLayer2.strokeColor = UIColor.lightGray().cgColor
shapeLayer2.fillColor = UIColor.clear().cgColor
shapeLayer2.lineWidth = 1
shapeLayer2.lineCap = kCALineCapButt
for index in 0...NSInteger(self.rulerCount!) {
let rule: UILabel = UILabel.init()
rule.textColor = UIColor.black()
rule.text = String(format: "%.0f",Float(index) * self.rulerAverage!.floatValue)
let ruleTextString: NSString = rule.text! as NSString
let textSize = ruleTextString.size(attributes: [NSFontAttributeName: rule.font])
if index % 10 == 0 {
pathRef2.moveTo(nil, x:DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index) , y: DISTANCETOPANDBOTTOM)
pathRef2.addLineTo(nil, x:DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index) , y: CGFloat(self.rulerHeight!) - DISTANCETOPANDBOTTOM - CGFloat(textSize.height))
rule.frame = CGRect.init(x: DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index) - textSize.width / 2, y: CGFloat(self.rulerHeight!) - DISTANCETOPANDBOTTOM - textSize.height, width: 0, height: 0)
rule.sizeToFit()
self.addSubview(rule)
}
else if index % 5 == 0 {
pathRef1.moveTo(nil, x: DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index), y: DISTANCETOPANDBOTTOM + 10)
pathRef1.addLineTo(nil, x:DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index) , y: CGFloat(self.rulerHeight!) - DISTANCETOPANDBOTTOM - CGFloat(textSize.height) - 10)
}
else {
pathRef1.moveTo(nil, x: DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index), y: DISTANCETOPANDBOTTOM + 20)
pathRef1.addLineTo(nil, x:DISTANCELEFTANDRIGHT + DISTANCEVALUE * CGFloat(index) , y: CGFloat(self.rulerHeight!) - DISTANCETOPANDBOTTOM - CGFloat(textSize.height) - 20)
}
}
shapeLayer1.path = pathRef1
shapeLayer2.path = pathRef2
self.layer.addSublayer(shapeLayer1)
self.layer.addSublayer(shapeLayer2)
self.frame = CGRect.init(x: 0, y: 0, width: self.rulerWidth!, height: self.rulerHeight!)
//开启最小模式
if self.mode! {
let edge: UIEdgeInsets = UIEdgeInsetsMake(0, CGFloat(self.rulerWidth! / 2) - DISTANCELEFTANDRIGHT, 0, CGFloat(self.rulerWidth! / 2) - DISTANCELEFTANDRIGHT)
self.contentInset = edge
self.contentOffset = CGPoint.init(x: DISTANCEVALUE * (CGFloat(self.rulerValue!) / CGFloat(self.rulerAverage!) - CGFloat(self.rulerWidth!) + CGFloat(self.rulerWidth! / 2) + DISTANCELEFTANDRIGHT), y: 0)
}
else {
let edge: UIEdgeInsets = UIEdgeInsetsMake(0, CGFloat(self.rulerWidth! / 2) - DISTANCELEFTANDRIGHT, 0, CGFloat(self.rulerWidth! / 2) - DISTANCELEFTANDRIGHT)
self.contentInset = edge
self.contentOffset = CGPoint.init(x: DISTANCEVALUE * (CGFloat(self.rulerValue!) / CGFloat(self.rulerAverage!) - CGFloat(self.rulerWidth! / 2) + DISTANCELEFTANDRIGHT), y: 0)
}
self.contentSize = CGSize.init(width: CGFloat(self.rulerCount!) * DISTANCEVALUE + DISTANCELEFTANDRIGHT * 2, height: CGFloat(self.rulerHeight!))
}
}
| 82e90f4c9667592b7138b73b71cbab92 | 43.572816 | 212 | 0.631888 | false | false | false | false |
barabashd/WeatherApp | refs/heads/master | WeatherApp/WeatherGetter.swift | mit | 1 | //
// WeatherGetter.swift
// WeatherApp
//
// Created by Dmytro on 2/11/17.
// Copyright © 2017 Dmytro. All rights reserved.
//
import Foundation
import MapKit
class WeatherGetter {
lazy var values = Symbol()
var curreentImage: UIImage!
}
extension WeatherGetter {
func getWeather(_ lat: Double, lon: Double, completion: @escaping (Bool) -> ()) {
let stringURL = "\(Strings.URL.openWeatherMapBaseURL)lat=\(lat)&lon=\(lon)&appid=\(Strings.URL.openWeatherMapAPIKey)"
searchInfo(weatherRequestURL: URL(string: stringURL)!, completion: { isFinished in
completion(isFinished)
})
}
func searchInfo(weatherRequestURL: URL, completion: @escaping (Bool) -> ()) {
let dataTask = URLSession.shared.dataTask(with: weatherRequestURL) {
(data, response, error) -> Void in
guard error == nil else {
print(ErrorHandler.wrongGetCall.rawValue)
print(error!)
completion(false)
return
}
guard let responseData = data else {
print(ErrorHandler.noData.rawValue)
completion(false)
return
}
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
print(ErrorHandler.convertData.rawValue)
completion(false)
return
}
guard let cityInfo = todo[Keys.name] as? String else {
print(ErrorHandler.cityInfoJSON.rawValue)
completion(false)
return
}
guard let sysInfo = todo[Keys.sys] as? [String: Any], let countryInfo = sysInfo[Keys.country] else {
print(ErrorHandler.countryInfoJSON.rawValue)
completion(false)
return
}
guard let windInfo = todo[Keys.wind] as? [String: Double], let speedInfo = windInfo[Keys.speed] else {
print(ErrorHandler.speedInfoJSON.rawValue)
completion(false)
return
}
let mainInfo = todo[Keys.main] as! [String: Double]
let temp = mainInfo[Keys.temp]
let pressure = mainInfo[Keys.pressure]
let humidity = mainInfo[Keys.humidity]
let seaLevel = mainInfo[Keys.sea_level]
guard let weather = todo[Keys.weather] as? [[String: AnyObject]], let sky = weather[0][Keys.description], let clouds = weather[0][Keys.main], let icon = weather[0][Keys.icon] as? String else {
print(ErrorHandler.weatherInfoJSON.rawValue)
completion(false)
return
}
self.values.city = cityInfo
self.values.country = countryInfo as! String
self.values.temp = temp
self.values.pressure = pressure
self.values.humidity = humidity
self.values.sea_level = seaLevel
self.values.skyDescription = sky as! String
self.values.windSpeedMps = speedInfo
self.values.clouds = clouds as! String
let stringURL = "\(Strings.URL.iconURL)\(icon).png"
if let url = URL(string: stringURL) {
DispatchQueue.global().async {
self.image(from: url, completion: { (image) in
if let img = image {
self.curreentImage = img
completion(true)
}
})
}
}
} catch {
print(ErrorHandler.noData.rawValue)
completion(false)
return
}
}
dataTask.resume()
}
}
| b5ea53b7583f006363ab4b99911d3689 | 37.351852 | 208 | 0.499517 | false | false | false | false |
jameslinjl/SHPJavaGrader | refs/heads/master | Sources/App/Models/Assignment.swift | mit | 1 | import Vapor
import Fluent
final class Assignment: Model {
var id: Node?
var username: String
var labNumber: Int
var content: String
var exists: Bool = false
init(username: String, labNumber: Int, content: String) {
self.username = username
self.labNumber = labNumber
self.content = content
}
init(node: Node, in context: Context) throws {
id = try node.extract("_id")
username = try node.extract("username")
labNumber = try node.extract("lab_number")
content = try node.extract("content")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"_id": id,
"username": username,
"lab_number": labNumber,
"content": content
])
}
func merge(patch: Node?) {
content = patch?["content"]?.string ?? content
}
static func prepare(_ database: Database) throws {}
static func revert(_ database: Database) throws {}
}
| 2b7ffd5d4c156a97fd4e26731aeda18f | 21.075 | 58 | 0.679502 | false | false | false | false |
1457792186/JWSwift | refs/heads/master | SwiftLearn/SwiftLearning/SwiftLearning/Learning/函数和闭包/结构体/CaculatorClass.swift | apache-2.0 | 1 | //
// CaculatorClass.swift
// JSwiftLearnMore
//
// Created by apple on 17/3/8.
// Copyright © 2017年 BP. All rights reserved.
//
import UIKit
// MARK: - 结构体
struct Caculator {
func sum(a:Int,b:Int) -> Int {
return a + b
}
@discardableResult
func func1(a:Int,b:Int) ->Int {
return a - b + 1
}
}
func showCaculator() {
let ca = Caculator()
ca.sum(a: 1, b: 2) // 此处会警告,因为方法有返回值但是没有接收
let _ = ca.sum(a: 1, b: 2) // 使用"_"接收无用返回值
ca.func1(a: 1, b: 2) // 由于func1添加了@discardableResult声明,即使不接收返回值也不会警告
}
class CaculatorClass: NSObject {
}
/*
结构体和类是构造复杂数据类型时常用的构造体,在其他高级语言中结构体相比于类要简单的多(在结构体内部仅仅能定义一些简单成员),但是在Swift中结构体和类的关系要紧密的多,这也是为什么将结构体放到后面来说的原因。Swift中的结构体可以定义属性、方法、下标脚本、构造方法,支持扩展,可以实现协议等等,很多类可以实现的功能结构体都能实现,但是结构体和类有着本质区别:类是引用类型,结构体是值类型。
*/
struct Man {
var firstName:String
var lastName:String
var fullName:String{
return firstName + " " + lastName
}
var age:Int=0
//构造函数,如果定义了构造方法则不会再自动生成默认构造函数
// init(firstName:String,lastName:String){
// self.firstName=firstName
// self.lastName=lastName
// }
func showMessage(){
print("firstName=\(firstName),lastName=\(lastName),age=\(age)")
}
//注意对于类中声明类型方法使用关键字class修饰,但结构体里使用static修饰
static func showStructName(){
print("Struct name is \"Person\"")
}
}
/*
默认情况下如果不自定义构造函数那么将自动生成一个无参构造函数和一个全员的逐一构造函数;
由于结构体是值类型,所以它虽然有构造函数但是没有析构函数,内存释放系统自动管理不需要开发人员过多关注;
类的类型方法使用class修饰(以便子类可以重写),而结构体、枚举的类型方法使用static修饰(补充:类方法也可以使用static修饰,但是不是类型方法而是静态方法;另外类的存储属性如果是类型属性使用static修饰,而类中的计算属性如果是类型属性使用class修饰以便可以被子类重写;换句话说class作为“类型范围作用域”来理解时只有在类中定义类型方法或者类型计算属性时使用,其他情况使用static修饰[包括结构体、枚举、协议和类型存储属性]);
*/
| 11dbdacb804eaf66dd0c8ed42b6ea450 | 23.366197 | 228 | 0.677457 | false | false | false | false |
davejlong/ResponseDetective | refs/heads/develop | ResponseDetective Tests/Source Files/JSONInterceptorSpec.swift | mit | 1 | //
// JSONInterceptorSpec.swift
//
// Copyright (c) 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import Nimble
import ResponseDetective
import Quick
class JSONInterceptorSpec: QuickSpec {
override func spec() {
describe("JSONInterceptor") {
var stream: BufferOutputStream!
var sut: JSONInterceptor!
let uglyFixtureString = "{\"foo\":\"bar\"\n,\"baz\":true }"
let uglyFixtureData = uglyFixtureString.dataUsingEncoding(NSUTF8StringEncoding)!
let prettyFixtureString = "{\n \"foo\" : \"bar\",\n \"baz\" : true\n}"
let fixtureRequest = RequestRepresentation( {
let mutableRequest = NSMutableURLRequest()
mutableRequest.URL = NSURL(string: "https://httpbin.org/post")!
mutableRequest.HTTPMethod = "POST"
mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = uglyFixtureData
return mutableRequest
}())!
let fixtureResponse = ResponseRepresentation(NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/post")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: [
"Content-Type": "application/json"
]
)!, uglyFixtureData)!
beforeEach {
stream = BufferOutputStream()
sut = JSONInterceptor(outputStream: stream)
}
it("should be able to intercept application/json requests") {
expect(sut.canInterceptRequest(fixtureRequest)).to(beTrue())
}
it("should be able to intercept application/json responses") {
expect(sut.canInterceptResponse(fixtureResponse)).to(beTrue())
}
it("should output a correct string when intercepting a application/json request") {
sut.interceptRequest(fixtureRequest)
expect(stream.buffer).toEventually(contain(prettyFixtureString), timeout: 2, pollInterval: 0.5)
}
it("should output a correct string when intercepting a application/json response") {
sut.interceptResponse(fixtureResponse)
expect(stream.buffer).toEventually(contain(prettyFixtureString), timeout: 2, pollInterval: 0.5)
}
}
}
}
| 79e0304f431c11e013673e61e14da74a | 28.371429 | 99 | 0.713035 | false | false | false | false |
huonw/swift | refs/heads/master | test/stdlib/TestDecimal.swift | apache-2.0 | 2 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %empty-directory(%t)
//
// RUN: %target-clang %S/Inputs/FoundationBridge/FoundationBridge.m -c -o %t/FoundationBridgeObjC.o -g
// RUN: %target-build-swift %s -I %S/Inputs/FoundationBridge/ -Xlinker %t/FoundationBridgeObjC.o -o %t/TestDecimal
// RUN: %target-run %t/TestDecimal > %t.txt
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import FoundationBridgeObjC
#if FOUNDATION_XCTEST
import XCTest
class TestDecimalSuper : XCTestCase { }
#else
import StdlibUnittest
class TestDecimalSuper { }
#endif
class TestDecimal : TestDecimalSuper {
func test_AdditionWithNormalization() {
let biggie = Decimal(65536)
let smallee = Decimal(65536)
let answer = biggie/smallee
expectEqual(Decimal(1),answer)
var one = Decimal(1)
var addend = Decimal(1)
var expected = Decimal()
var result = Decimal()
expected._isNegative = 0;
expected._isCompact = 0;
// 2 digits -- certain to work
addend._exponent = -1;
expectEqual(.noError, NSDecimalAdd(&result, &one, &addend, .plain), "1 + 0.1")
expected._exponent = -1;
expected._length = 1;
expected._mantissa.0 = 11;
expectEqual(.orderedSame, NSDecimalCompare(&expected, &result), "1.1 == 1 + 0.1")
// 38 digits -- guaranteed by NSDecimal to work
addend._exponent = -37;
expectEqual(.noError, NSDecimalAdd(&result, &one, &addend, .plain), "1 + 1e-37")
expected._exponent = -37;
expected._length = 8;
expected._mantissa.0 = 0x0001;
expected._mantissa.1 = 0x0000;
expected._mantissa.2 = 0x36a0;
expected._mantissa.3 = 0x00f4;
expected._mantissa.4 = 0x46d9;
expected._mantissa.5 = 0xd5da;
expected._mantissa.6 = 0xee10;
expected._mantissa.7 = 0x0785;
expectEqual(.orderedSame, NSDecimalCompare(&expected, &result), "1 + 1e-37")
// 39 digits -- not guaranteed to work but it happens to, so we make the test work either way
addend._exponent = -38;
let error = NSDecimalAdd(&result, &one, &addend, .plain)
expectTrue(error == .noError || error == .lossOfPrecision, "1 + 1e-38")
if error == .noError {
expected._exponent = -38;
expected._length = 8;
expected._mantissa.0 = 0x0001;
expected._mantissa.1 = 0x0000;
expected._mantissa.2 = 0x2240;
expected._mantissa.3 = 0x098a;
expected._mantissa.4 = 0xc47a;
expected._mantissa.5 = 0x5a86;
expected._mantissa.6 = 0x4ca8;
expected._mantissa.7 = 0x4b3b;
expectEqual(.orderedSame, NSDecimalCompare(&expected, &result), "1 + 1e-38")
} else {
expectEqual(.orderedSame, NSDecimalCompare(&one, &result), "1 + 1e-38")
}
// 40 digits -- doesn't work; need to make sure it's rounding for us
addend._exponent = -39;
expectEqual(.lossOfPrecision, NSDecimalAdd(&result, &one, &addend, .plain), "1 + 1e-39")
expectEqual("1", result.description)
expectEqual(.orderedSame, NSDecimalCompare(&one, &result), "1 + 1e-39")
}
func test_BasicConstruction() {
let zero = Decimal()
expectEqual(20, MemoryLayout<Decimal>.size)
expectEqual(0, zero._exponent)
expectEqual(0, zero._length)
expectEqual(0, zero._isNegative)
expectEqual(0, zero._isCompact)
expectEqual(0, zero._reserved)
let (m0, m1, m2, m3, m4, m5, m6, m7) = zero._mantissa
expectEqual(0, m0)
expectEqual(0, m1)
expectEqual(0, m2)
expectEqual(0, m3)
expectEqual(0, m4)
expectEqual(0, m5)
expectEqual(0, m6)
expectEqual(0, m7)
expectEqual(8, NSDecimalMaxSize)
expectEqual(32767, NSDecimalNoScale)
expectFalse(zero.isNormal)
expectTrue(zero.isFinite)
expectTrue(zero.isZero)
expectFalse(zero.isSubnormal)
expectFalse(zero.isInfinite)
expectFalse(zero.isNaN)
expectFalse(zero.isSignaling)
}
func test_Constants() {
expectEqual(8, NSDecimalMaxSize)
expectEqual(32767, NSDecimalNoScale)
let smallest = Decimal(_exponent: 127, _length: 8, _isNegative: 1, _isCompact: 1, _reserved: 0, _mantissa: (UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max))
expectEqual(smallest, Decimal.leastFiniteMagnitude)
let biggest = Decimal(_exponent: 127, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max))
expectEqual(biggest, Decimal.greatestFiniteMagnitude)
let leastNormal = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (1, 0, 0, 0, 0, 0, 0, 0))
expectEqual(leastNormal, Decimal.leastNormalMagnitude)
let leastNonzero = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (1, 0, 0, 0, 0, 0, 0, 0))
expectEqual(leastNonzero, Decimal.leastNonzeroMagnitude)
let pi = Decimal(_exponent: -38, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58))
expectEqual(pi, Decimal.pi)
expectEqual(10, Decimal.radix)
expectTrue(Decimal().isCanonical)
expectFalse(Decimal().isSignalingNaN)
expectFalse(Decimal.nan.isSignalingNaN)
expectTrue(Decimal.nan.isNaN)
expectEqual(.quietNaN, Decimal.nan.floatingPointClass)
expectEqual(.positiveZero, Decimal().floatingPointClass)
expectEqual(.negativeNormal, smallest.floatingPointClass)
expectEqual(.positiveNormal, biggest.floatingPointClass)
expectFalse(Double.nan.isFinite)
expectFalse(Double.nan.isInfinite)
}
func test_Description() {
expectEqual("0", Decimal().description)
expectEqual("0", Decimal(0).description)
expectEqual("10", Decimal(_exponent: 1, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (1, 0, 0, 0, 0, 0, 0, 0)).description)
expectEqual("10", Decimal(10).description)
expectEqual("123.458", Decimal(_exponent: -3, _length: 2, _isNegative: 0, _isCompact:1, _reserved: 0, _mantissa: (57922, 1, 0, 0, 0, 0, 0, 0)).description)
expectEqual("123.458", Decimal(123.458).description)
expectEqual("123", Decimal(UInt8(123)).description)
expectEqual("45", Decimal(Int8(45)).description)
expectEqual("3.14159265358979323846264338327950288419", Decimal.pi.description)
expectEqual("-30000000000", Decimal(sign: .minus, exponent: 10, significand: Decimal(3)).description)
expectEqual("300000", Decimal(sign: .plus, exponent: 5, significand: Decimal(3)).description)
expectEqual("5", Decimal(signOf: Decimal(3), magnitudeOf: Decimal(5)).description)
expectEqual("-5", Decimal(signOf: Decimal(-3), magnitudeOf: Decimal(5)).description)
expectEqual("5", Decimal(signOf: Decimal(3), magnitudeOf: Decimal(-5)).description)
expectEqual("-5", Decimal(signOf: Decimal(-3), magnitudeOf: Decimal(-5)).description)
}
func test_ExplicitConstruction() {
var explicit = Decimal(
_exponent: 0x17f,
_length: 0xff,
_isNegative: 3,
_isCompact: 4,
_reserved: UInt32(1<<18 + 1<<17 + 1),
_mantissa: (6, 7, 8, 9, 10, 11, 12, 13)
)
expectEqual(0x7f, explicit._exponent)
expectEqual(0x7f, explicit.exponent)
expectEqual(0x0f, explicit._length)
expectEqual(1, explicit._isNegative)
expectEqual(FloatingPointSign.minus, explicit.sign)
expectTrue(explicit.isSignMinus)
expectEqual(0, explicit._isCompact)
expectEqual(UInt32(1<<17 + 1), explicit._reserved)
let (m0, m1, m2, m3, m4, m5, m6, m7) = explicit._mantissa
expectEqual(6, m0)
expectEqual(7, m1)
expectEqual(8, m2)
expectEqual(9, m3)
expectEqual(10, m4)
expectEqual(11, m5)
expectEqual(12, m6)
expectEqual(13, m7)
explicit._isCompact = 5
explicit._isNegative = 6
expectEqual(0, explicit._isNegative)
expectEqual(1, explicit._isCompact)
expectEqual(FloatingPointSign.plus, explicit.sign)
expectFalse(explicit.isSignMinus)
expectTrue(explicit.isNormal)
let significand = explicit.significand
expectEqual(0, significand._exponent)
expectEqual(0, significand.exponent)
expectEqual(0x0f, significand._length)
expectEqual(0, significand._isNegative)
expectEqual(1, significand._isCompact)
expectEqual(0, significand._reserved)
let (sm0, sm1, sm2, sm3, sm4, sm5, sm6, sm7) = significand._mantissa
expectEqual(6, sm0)
expectEqual(7, sm1)
expectEqual(8, sm2)
expectEqual(9, sm3)
expectEqual(10, sm4)
expectEqual(11, sm5)
expectEqual(12, sm6)
expectEqual(13, sm7)
let ulp = explicit.ulp
expectEqual(0x7f, ulp.exponent)
expectEqual(8, ulp._length)
expectEqual(0, ulp._isNegative)
expectEqual(1, ulp._isCompact)
expectEqual(0, ulp._reserved)
expectEqual(1, ulp._mantissa.0)
expectEqual(0, ulp._mantissa.1)
expectEqual(0, ulp._mantissa.2)
expectEqual(0, ulp._mantissa.3)
expectEqual(0, ulp._mantissa.4)
expectEqual(0, ulp._mantissa.5)
expectEqual(0, ulp._mantissa.6)
expectEqual(0, ulp._mantissa.7)
}
func test_Maths() {
for i in -2...10 {
for j in 0...5 {
expectEqual(Decimal(i*j), Decimal(i) * Decimal(j), "\(Decimal(i*j)) == \(i) * \(j)")
expectEqual(Decimal(i+j), Decimal(i) + Decimal(j), "\(Decimal(i+j)) == \(i)+\(j)")
expectEqual(Decimal(i-j), Decimal(i) - Decimal(j), "\(Decimal(i-j)) == \(i)-\(j)")
if j != 0 {
let approximation = Decimal(Double(i)/Double(j))
let answer = Decimal(i) / Decimal(j)
let answerDescription = answer.description
let approximationDescription = approximation.description
var failed: Bool = false
var count = 0
let SIG_FIG = 14
for (a, b) in zip(answerDescription.characters, approximationDescription.characters) {
if a != b {
failed = true
break
}
if count == 0 && (a == "-" || a == "0" || a == ".") {
continue // don't count these as significant figures
}
if count >= SIG_FIG {
break
}
count += 1
}
expectFalse(failed, "\(Decimal(i/j)) == \(i)/\(j)")
}
}
}
}
func test_Misc() {
expectEqual(.minus, Decimal(-5.2).sign)
expectEqual(.plus, Decimal(5.2).sign)
var d = Decimal(5.2)
expectEqual(.plus, d.sign)
d.negate()
expectEqual(.minus, d.sign)
d.negate()
expectEqual(.plus, d.sign)
var e = Decimal(0)
e.negate()
expectEqual(e, 0)
expectTrue(Decimal(3.5).isEqual(to: Decimal(3.5)))
expectTrue(Decimal.nan.isEqual(to: Decimal.nan))
expectTrue(Decimal(1.28).isLess(than: Decimal(2.24)))
expectFalse(Decimal(2.28).isLess(than: Decimal(2.24)))
expectTrue(Decimal(1.28).isTotallyOrdered(belowOrEqualTo: Decimal(2.24)))
expectFalse(Decimal(2.28).isTotallyOrdered(belowOrEqualTo: Decimal(2.24)))
expectTrue(Decimal(1.2).isTotallyOrdered(belowOrEqualTo: Decimal(1.2)))
expectTrue(Decimal.nan.isEqual(to: Decimal.nan))
expectTrue(Decimal.nan.isLess(than: Decimal(0)))
expectFalse(Decimal.nan.isLess(than: Decimal.nan))
expectTrue(Decimal.nan.isLessThanOrEqualTo(Decimal(0)))
expectTrue(Decimal.nan.isLessThanOrEqualTo(Decimal.nan))
expectFalse(Decimal.nan.isTotallyOrdered(belowOrEqualTo: Decimal.nan))
expectFalse(Decimal.nan.isTotallyOrdered(belowOrEqualTo: Decimal(2.3)))
expectTrue(Decimal(2) < Decimal(3))
expectTrue(Decimal(3) > Decimal(2))
expectEqual(Decimal(-9), Decimal(1) - Decimal(10))
expectEqual(Decimal(3), Decimal(2).nextUp)
expectEqual(Decimal(2), Decimal(3).nextDown)
expectEqual(Decimal(-476), Decimal(1024).distance(to: Decimal(1500)))
expectEqual(Decimal(68040), Decimal(386).advanced(by: Decimal(67654)))
expectEqual(Decimal(1.234), abs(Decimal(1.234)))
expectEqual(Decimal(1.234), abs(Decimal(-1.234)))
var a = Decimal(1234)
expectEqual(.noError, NSDecimalMultiplyByPowerOf10(&a, &a, 1, .plain))
expectEqual(Decimal(12340), a)
a = Decimal(1234)
expectEqual(.noError, NSDecimalMultiplyByPowerOf10(&a, &a, 2, .plain))
expectEqual(Decimal(123400), a)
expectEqual(.overflow, NSDecimalMultiplyByPowerOf10(&a, &a, 128, .plain))
expectTrue(a.isNaN)
a = Decimal(1234)
expectEqual(.noError, NSDecimalMultiplyByPowerOf10(&a, &a, -2, .plain))
expectEqual(Decimal(12.34), a)
expectEqual(.underflow, NSDecimalMultiplyByPowerOf10(&a, &a, -128, .plain))
expectTrue(a.isNaN)
a = Decimal(1234)
expectEqual(.noError, NSDecimalPower(&a, &a, 0, .plain))
expectEqual(Decimal(1), a)
a = Decimal(8)
expectEqual(.noError, NSDecimalPower(&a, &a, 2, .plain))
expectEqual(Decimal(64), a)
a = Decimal(-2)
expectEqual(.noError, NSDecimalPower(&a, &a, 3, .plain))
expectEqual(Decimal(-8), a)
for i in -2...10 {
for j in 0...5 {
var actual = Decimal(i)
expectEqual(.noError, NSDecimalPower(&actual, &actual, j, .plain))
let expected = Decimal(pow(Double(i), Double(j)))
expectEqual(expected, actual, "\(actual) == \(i)^\(j)")
}
}
}
func test_MultiplicationOverflow() {
var multiplicand = Decimal(_exponent: 0, _length: 8, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: ( 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff ))
var result = Decimal()
var multiplier = Decimal(1)
multiplier._mantissa.0 = 2
expectEqual(.noError, NSDecimalMultiply(&result, &multiplicand, &multiplier, .plain), "2 * max mantissa")
expectEqual(.noError, NSDecimalMultiply(&result, &multiplier, &multiplicand, .plain), "max mantissa * 2")
multiplier._exponent = 0x7f
expectEqual(.overflow, NSDecimalMultiply(&result, &multiplicand, &multiplier, .plain), "2e127 * max mantissa")
expectEqual(.overflow, NSDecimalMultiply(&result, &multiplier, &multiplicand, .plain), "max mantissa * 2e127")
}
func test_NaNInput() {
var NaN = Decimal.nan
var one = Decimal(1)
var result = Decimal()
expectNotEqual(.noError, NSDecimalAdd(&result, &NaN, &one, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN + 1")
expectNotEqual(.noError, NSDecimalAdd(&result, &one, &NaN, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "1 + NaN")
expectNotEqual(.noError, NSDecimalSubtract(&result, &NaN, &one, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN - 1")
expectNotEqual(.noError, NSDecimalSubtract(&result, &one, &NaN, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "1 - NaN")
expectNotEqual(.noError, NSDecimalMultiply(&result, &NaN, &one, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN * 1")
expectNotEqual(.noError, NSDecimalMultiply(&result, &one, &NaN, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "1 * NaN")
expectNotEqual(.noError, NSDecimalDivide(&result, &NaN, &one, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN / 1")
expectNotEqual(.noError, NSDecimalDivide(&result, &one, &NaN, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "1 / NaN")
expectNotEqual(.noError, NSDecimalPower(&result, &NaN, 0, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN ^ 0")
expectNotEqual(.noError, NSDecimalPower(&result, &NaN, 4, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN ^ 4")
expectNotEqual(.noError, NSDecimalPower(&result, &NaN, 5, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN ^ 5")
expectNotEqual(.noError, NSDecimalMultiplyByPowerOf10(&result, &NaN, 0, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN e0")
expectNotEqual(.noError, NSDecimalMultiplyByPowerOf10(&result, &NaN, 4, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN e4")
expectNotEqual(.noError, NSDecimalMultiplyByPowerOf10(&result, &NaN, 5, .plain))
expectTrue(NSDecimalIsNotANumber(&result), "NaN e5")
}
func test_NegativeAndZeroMultiplication() {
var one = Decimal(1)
var zero = Decimal(0)
var negativeOne = Decimal(-1)
var result = Decimal()
expectEqual(.noError, NSDecimalMultiply(&result, &one, &one, .plain), "1 * 1")
expectEqual(.orderedSame, NSDecimalCompare(&one, &result), "1 * 1")
expectEqual(.noError, NSDecimalMultiply(&result, &one, &negativeOne, .plain), "1 * -1")
expectEqual(.orderedSame, NSDecimalCompare(&negativeOne, &result), "1 * -1")
expectEqual(.noError, NSDecimalMultiply(&result, &negativeOne, &one, .plain), "-1 * 1")
expectEqual(.orderedSame, NSDecimalCompare(&negativeOne, &result), "-1 * 1")
expectEqual(.noError, NSDecimalMultiply(&result, &negativeOne, &negativeOne, .plain), "-1 * -1")
expectEqual(.orderedSame, NSDecimalCompare(&one, &result), "-1 * -1")
expectEqual(.noError, NSDecimalMultiply(&result, &one, &zero, .plain), "1 * 0")
expectEqual(.orderedSame, NSDecimalCompare(&zero, &result), "1 * 0")
expectEqual(0, result._isNegative, "1 * 0")
expectEqual(.noError, NSDecimalMultiply(&result, &zero, &one, .plain), "0 * 1")
expectEqual(.orderedSame, NSDecimalCompare(&zero, &result), "0 * 1")
expectEqual(0, result._isNegative, "0 * 1")
expectEqual(.noError, NSDecimalMultiply(&result, &negativeOne, &zero, .plain), "-1 * 0")
expectEqual(.orderedSame, NSDecimalCompare(&zero, &result), "-1 * 0")
expectEqual(0, result._isNegative, "-1 * 0")
expectEqual(.noError, NSDecimalMultiply(&result, &zero, &negativeOne, .plain), "0 * -1")
expectEqual(.orderedSame, NSDecimalCompare(&zero, &result), "0 * -1")
expectEqual(0, result._isNegative, "0 * -1")
}
func test_Normalize() {
var one = Decimal(1)
var ten = Decimal(-10)
expectEqual(.noError, NSDecimalNormalize(&one, &ten, .plain))
expectEqual(Decimal(1), one)
expectEqual(Decimal(-10), ten)
expectEqual(1, one._length)
expectEqual(1, ten._length)
one = Decimal(1)
ten = Decimal(10)
expectEqual(.noError, NSDecimalNormalize(&one, &ten, .plain))
expectEqual(Decimal(1), one)
expectEqual(Decimal(10), ten)
expectEqual(1, one._length)
expectEqual(1, ten._length)
}
func test_NSDecimal() {
var nan = Decimal.nan
expectTrue(NSDecimalIsNotANumber(&nan))
var zero = Decimal()
expectFalse(NSDecimalIsNotANumber(&zero))
var three = Decimal(3)
var guess = Decimal()
NSDecimalCopy(&guess, &three)
expectEqual(three, guess)
var f = Decimal(_exponent: 0, _length: 2, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
let before = f.description
expectEqual(0, f._isCompact)
NSDecimalCompact(&f)
expectEqual(1, f._isCompact)
let after = f.description
expectEqual(before, after)
}
func test_RepeatingDivision() {
let repeatingNumerator = Decimal(16)
let repeatingDenominator = Decimal(9)
let repeating = repeatingNumerator / repeatingDenominator
let numerator = Decimal(1010)
var result = numerator / repeating
var expected = Decimal()
expected._exponent = -35;
expected._length = 8;
expected._isNegative = 0;
expected._isCompact = 1;
expected._reserved = 0;
expected._mantissa.0 = 51946;
expected._mantissa.1 = 3;
expected._mantissa.2 = 15549;
expected._mantissa.3 = 55864;
expected._mantissa.4 = 57984;
expected._mantissa.5 = 55436;
expected._mantissa.6 = 45186;
expected._mantissa.7 = 10941;
expectEqual(.orderedSame, NSDecimalCompare(&expected, &result), "568.12500000000000000000000000000248554: \(expected.description) != \(result.description)");
}
func test_Round() {
let testCases = [
// expected, start, scale, round
( 0, 0.5, 0, Decimal.RoundingMode.down ),
( 1, 0.5, 0, Decimal.RoundingMode.up ),
( 2, 2.5, 0, Decimal.RoundingMode.bankers ),
( 4, 3.5, 0, Decimal.RoundingMode.bankers ),
( 5, 5.2, 0, Decimal.RoundingMode.plain ),
( 4.5, 4.5, 1, Decimal.RoundingMode.down ),
( 5.5, 5.5, 1, Decimal.RoundingMode.up ),
( 6.5, 6.5, 1, Decimal.RoundingMode.plain ),
( 7.5, 7.5, 1, Decimal.RoundingMode.bankers ),
( -1, -0.5, 0, Decimal.RoundingMode.down ),
( -2, -2.5, 0, Decimal.RoundingMode.up ),
( -3, -2.5, 0, Decimal.RoundingMode.bankers ),
( -4, -3.5, 0, Decimal.RoundingMode.bankers ),
( -5, -5.2, 0, Decimal.RoundingMode.plain ),
( -4.5, -4.5, 1, Decimal.RoundingMode.down ),
( -5.5, -5.5, 1, Decimal.RoundingMode.up ),
( -6.5, -6.5, 1, Decimal.RoundingMode.plain ),
( -7.5, -7.5, 1, Decimal.RoundingMode.bankers ),
]
for testCase in testCases {
let (expected, start, scale, mode) = testCase
var num = Decimal(start)
NSDecimalRound(&num, &num, scale, mode)
expectEqual(Decimal(expected), num)
let numnum = NSDecimalNumber(decimal:Decimal(start))
let behavior = NSDecimalNumberHandler(roundingMode: mode, scale: Int16(scale), raiseOnExactness: false, raiseOnOverflow: true, raiseOnUnderflow: true, raiseOnDivideByZero: true)
let result = numnum.rounding(accordingToBehavior:behavior)
expectEqual(Double(expected), result.doubleValue)
}
}
func test_ScanDecimal() {
let testCases = [
// expected, value
( 123.456e78, "123.456e78" ),
( -123.456e78, "-123.456e78" ),
( 123.456, " 123.456 " ),
( 3.14159, " 3.14159e0" ),
( 3.14159, " 3.14159e-0" ),
( 0.314159, " 3.14159e-1" ),
( 3.14159, " 3.14159e+0" ),
( 31.4159, " 3.14159e+1" ),
( 12.34, " 01234e-02"),
]
for testCase in testCases {
let (expected, string) = testCase
let decimal = Decimal(string:string)!
let aboutOne = Decimal(expected) / decimal
let approximatelyRight = aboutOne >= Decimal(0.99999) && aboutOne <= Decimal(1.00001)
expectTrue(approximatelyRight, "\(expected) ~= \(decimal) : \(aboutOne) \(aboutOne >= Decimal(0.99999)) \(aboutOne <= Decimal(1.00001))" )
}
guard let ones = Decimal(string:"111111111111111111111111111111111111111") else {
expectUnreachable("Unable to parse Decimal(string:'111111111111111111111111111111111111111')")
return
}
let num = ones / Decimal(9)
guard let answer = Decimal(string:"12345679012345679012345679012345679012.3") else {
expectUnreachable("Unable to parse Decimal(string:'12345679012345679012345679012345679012.3')")
return
}
expectEqual(answer,num,"\(ones) / 9 = \(answer) \(num)")
}
func test_SimpleMultiplication() {
var multiplicand = Decimal()
multiplicand._isNegative = 0
multiplicand._isCompact = 0
multiplicand._length = 1
multiplicand._exponent = 1
var multiplier = multiplicand
multiplier._exponent = 2
var expected = multiplicand
expected._isNegative = 0
expected._isCompact = 0
expected._exponent = 3
expected._length = 1
var result = Decimal()
for i in 1..<UInt8.max {
multiplicand._mantissa.0 = UInt16(i)
for j in 1..<UInt8.max {
multiplier._mantissa.0 = UInt16(j)
expected._mantissa.0 = UInt16(i) * UInt16(j)
expectEqual(.noError, NSDecimalMultiply(&result, &multiplicand, &multiplier, .plain), "\(i) * \(j)")
expectEqual(.orderedSame, NSDecimalCompare(&expected, &result), "\(expected._mantissa.0) == \(i) * \(j)");
}
}
}
func test_unconditionallyBridgeFromObjectiveC() {
expectEqual(Decimal(), Decimal._unconditionallyBridgeFromObjectiveC(nil))
}
}
#if !FOUNDATION_XCTEST
var DecimalTests = TestSuite("TestDecimal")
DecimalTests.test("test_AdditionWithNormalization") { TestDecimal().test_AdditionWithNormalization() }
DecimalTests.test("test_BasicConstruction") { TestDecimal().test_BasicConstruction() }
DecimalTests.test("test_Constants") { TestDecimal().test_Constants() }
DecimalTests.test("test_Description") { TestDecimal().test_Description() }
DecimalTests.test("test_ExplicitConstruction") { TestDecimal().test_ExplicitConstruction() }
DecimalTests.test("test_Maths") { TestDecimal().test_Maths() }
DecimalTests.test("test_Misc") { TestDecimal().test_Misc() }
DecimalTests.test("test_MultiplicationOverflow") { TestDecimal().test_MultiplicationOverflow() }
DecimalTests.test("test_NaNInput") { TestDecimal().test_NaNInput() }
DecimalTests.test("test_NegativeAndZeroMultiplication") { TestDecimal().test_NegativeAndZeroMultiplication() }
DecimalTests.test("test_Normalize") { TestDecimal().test_Normalize() }
DecimalTests.test("test_NSDecimal") { TestDecimal().test_NSDecimal() }
DecimalTests.test("test_RepeatingDivision") { TestDecimal().test_RepeatingDivision() }
DecimalTests.test("test_Round") { TestDecimal().test_Round() }
DecimalTests.test("test_ScanDecimal") { TestDecimal().test_ScanDecimal() }
DecimalTests.test("test_SimpleMultiplication") { TestDecimal().test_SimpleMultiplication() }
DecimalTests.test("test_unconditionallyBridgeFromObjectiveC") { TestDecimal().test_unconditionallyBridgeFromObjectiveC() }
runAllTests()
#endif
| 4aa1cbb26d229d9ae5fc778f01e111ef | 44.957447 | 212 | 0.603526 | false | true | false | false |
thiagotmb/BEPiD-Challenges-2016 | refs/heads/master | 2016-02-16-SimpleTable/SimpleTable/SimpleTable WatchKit Extension/Country+Request.swift | mit | 2 | //
// Country+Request.swift
// SimpleTable
//
// Created by Thiago-Bernardes on 2/16/16.
// Copyright © 2016 TMB. All rights reserved.
//
import WatchKit
let countryURL = "https://api.myjson.com/bins/2jo7n";
extension Country{
private class func parseJSON(data: NSData) -> NSDictionary{
var jsonResult: NSDictionary = NSDictionary()
do{
jsonResult = try (NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary)!
// print("AsSynchronous\(jsonResult)")
}catch{
print(error)
}
return jsonResult
}
private class func getJSON() -> NSDictionary{
let jsonData = NSData(contentsOfURL: NSURL(string: countryURL)!)!
return parseJSON(jsonData)
}
private class func getObjects() -> NSArray{
let objects = getJSON()["postalcodes"] as? NSArray
return objects!
}
class func getCountries() -> Array<Country>{
let countriesDictArray = getObjects()
var countriesObjectsArray : Array<Country> = []
for countryDict in countriesDictArray{
let countryName = countryDict["placeName"] as! String
let countryCode = countryDict["countryCode"] as! String
let countryImage = UIImage(named: "\(arc4random_uniform(2 - 1) + 1)")
let countryLatitude = (countryDict["lat"] as! NSNumber).stringValue
let countryLongitude = (countryDict["lng"] as! NSNumber).stringValue
let countryPostalCode = countryDict["postalcode"] as! String
let countryObject = Country(countryName: countryName, countryCode: countryCode, countryImage: countryImage!, countryLatitude: countryLatitude, countryLongitude: countryLongitude, countryPostalCode: countryPostalCode)
countriesObjectsArray.append(countryObject)
}
return countriesObjectsArray
}
}
| e01eb8403632a09f5b5fc93582f88e17 | 28.901408 | 228 | 0.589732 | false | false | false | false |
edwinbosire/YAWA | refs/heads/master | YAWA-Weather/Model/City.swift | gpl-2.0 | 1 | //
// City.swift
// YAWA-Weather
//
// Created by edwin bosire on 15/06/2015.
// Copyright (c) 2015 Edwin Bosire. All rights reserved.
//
import Foundation
import CoreData
@objc(City)
class City: NSManagedObject {
@NSManaged var index: NSNumber
@NSManaged var weather: Forecast
@NSManaged var location: Location
class func createNewCity() -> City {
let city = NSEntityDescription.insertNewObjectForEntityForName("City", inManagedObjectContext: StoreManager.sharedInstance.managedObjectContext!) as! City
return city
}
class func fetchCities() -> [City] {
let cities = StoreManager.sharedInstance.executeRequestWithPredicate(nil, entityName: "City") as! [City]
return cities
}
class func fetchCityWithLocation(location: Location) ->City {
let predicate = NSPredicate(format: "location.locality == %@ AND location.country == %@ ", location.locality, location.country)
let cities = StoreManager.sharedInstance.executeRequestWithPredicate(predicate, entityName: "City") as! [City]
if let aCity = cities.first {
return aCity
}else {
let newCity = City.createNewCity()
newCity.index = cities.count + 1
return newCity
}
}
}
| 831bb12d26c5175bd2a87d3d16d1d3d2 | 27.142857 | 156 | 0.728426 | false | false | false | false |
CocoaheadsSaar/Treffen | refs/heads/master | Treffen1/UI_Erstellung_ohne_Storyboard/AutolayoutTests/AutolayoutTests/MainStackButtonsViewController.swift | gpl-2.0 | 1 | //
// MainStackButtonsViewController.swift
// AutolayoutTests
//
// Created by Markus Schmitt on 13.01.16.
// Copyright © 2016 Insecom - Markus Schmitt. All rights reserved.
//
import UIKit
import Foundation
class MainStackButtonsViewController: UIViewController {
var mainStackView: MainStackButtonsView {
return view as! MainStackButtonsView
}
override func viewDidLoad() {
super.viewDidLoad()
for newButton in mainStackView.buttonArray {
newButton.addTarget(self, action: Selector("evaluateButton:"), forControlEvents: .TouchDown)
}
mainStackView.switchButton.addTarget(self, action: Selector("switchButtonAlignment:"), forControlEvents: .TouchDown)
}
override func loadView() {
let contentView = MainStackButtonsView(frame: .zero)
view = contentView
}
override func viewWillLayoutSubviews() {
let topLayoutGuide = self.topLayoutGuide
let bottomLayoutGuide = self.bottomLayoutGuide
let views = ["topLayoutGuide": topLayoutGuide, "buttonStackView" : mainStackView.buttonStackView, "bottomLayoutGuide" : bottomLayoutGuide, "switchButton" : mainStackView.switchButton] as [String:AnyObject]
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-[buttonStackView]-[switchButton(40)]-[bottomLayoutGuide]", options: [], metrics: nil, views: views))
}
func evaluateButton(sender: UIButton) {
print("Button : \(sender.tag)")
}
func switchButtonAlignment(sender: UIButton) {
let newOrientation: UILayoutConstraintAxis = (mainStackView.buttonStackView.axis == .Horizontal) ? .Vertical : .Horizontal
mainStackView.buttonStackView.axis = newOrientation
}
}
| 8cfd412861949b9f6d82d4f9e9788618 | 32.321429 | 214 | 0.689711 | false | false | false | false |
pisces/OrangeRealm | refs/heads/master | OrangeRealm/Classes/AbstractRealmManager.swift | mit | 1 | //
// AbstractRealmManager.swift
// OrangeRealm
//
// Created by Steve Kim on 23/4/17.
//
import Realm
import RealmSwift
open class AbstractRealmManager {
// MARK: - Constants
public static let queue = DispatchQueue(label: Const.name)
public let notificationManager = RealmNotificationManager()
private struct Const {
static let name = "pisces.orange.RealmManager"
}
// MARK: - Properties
private var isUseSerialQueue: Bool = true
public var realm: Realm {
var realm: Realm!
perform {
do {
realm = try Realm(configuration: self.createConfiguration())
} catch {
do {
try FileManager.default.removeItem(at: self.fileURL)
} catch {
print("AbstractRealmManager remove realm error \(error.localizedDescription)")
}
realm = try! Realm(configuration: self.createConfiguration())
self.clear()
self.recover()
}
}
return realm
}
// MARK: - Con(De)structor
public init(isUseSerialQueue: Bool = true) {
self.isUseSerialQueue = isUseSerialQueue
configure()
}
// MARK: - Abstract
open var schemaVersion: UInt64 {
fatalError("schemaVersion has not been implemented")
}
open var fileURL: URL {
fatalError("fileURL has not been implemented")
}
open var objectTypes: [Object.Type]? {
fatalError("fileURL has not been implemented")
}
open func deleteAll(_ realm: Realm) {
fatalError("deleteAll() has not been implemented")
}
open func process(forMigration migration: Migration, oldSchemaVersion: UInt64) {
fatalError("process(forMigration:oldSchemaVersion:) has not been implemented")
}
open func recover() {
fatalError("recover has not been implemented")
}
// MARK: - Public methods
open class var shared: AbstractRealmManager {
struct Static {
static let instance = AbstractRealmManager()
}
return Static.instance
}
public func array<T: Object>(forResults results: Results<T>, unlink: Bool = false) -> [T] {
return results.map({return unlink ? T(value: $0, schema: RLMSchema()) : $0})
}
public func clear() {
notificationManager.removeAll()
try? transaction { (realm) in
self.deleteAll(realm)
}
}
public func initialize() {
}
public func objects<T: Object>(_ where: String? = nil, sortProperty: Any? = nil, ascending: Bool = true, limit: Int = -1, max: Int = -1, unlink: Bool = false, filter: ((T) -> Bool)? = nil) -> [T] {
return query(`where`, sortProperty: sortProperty, ascending: ascending, limit: limit, max: max, unlink: unlink, filter: filter).objects
}
public func perform(execution: @escaping () -> ()) {
if !isUseSerialQueue || DispatchQueue.isCurrentQueue(queue: AbstractRealmManager.queue) {
execution()
} else {
AbstractRealmManager.queue.sync {
execution()
}
}
}
public func query<T: Object>(_ where: String? = nil, sortProperty: Any? = nil, ascending: Bool = true, limit: Int = -1, max: Int = -1, unlink: Bool = false, filter: ((T) -> Bool)? = nil) -> RealmQueryResult<T> {
var results: Results<T>!
var objects: [T] = []
perform {
results = self.results(`where`, sortProperty: sortProperty, ascending: ascending)
let elements = self.array(forResults: results, unlink: unlink)
if let filter = filter {
for element in elements {
if filter(element) {
objects.append(element)
}
}
} else {
objects = elements
}
if limit > -1 {
objects = objects.count > limit ? Array(objects[0..<limit]) : objects
}
}
return RealmQueryResult(notificationManager: notificationManager, objects: objects, results: results, max: max)
}
public func results<T: Object>(_ where: String? = nil, sortProperty: Any? = nil, ascending: Bool = true) -> Results<T> {
var results: Results<T>!
perform {
results = self.realm.objects(T.self)
if let `where` = `where` {
results = results.filter(`where`)
}
if let properties = sortProperty as? [String] {
for property in properties {
results = results.sorted(byKeyPath: property, ascending: ascending)
}
} else if let sortProperty = sortProperty as? String {
results = results.sorted(byKeyPath: sortProperty, ascending: ascending)
}
}
return results
}
public func transaction(_ realm: Realm? = nil, execution: @escaping (Realm) -> ()) throws {
var _error: Error?
perform {
let realm = realm == nil ? self.realm : realm!
if realm.isInWriteTransaction {
execution(realm)
} else {
do {
realm.beginWrite()
execution(realm)
try realm.commitWrite()
} catch {
realm.cancelWrite()
_error = error
}
}
}
if let error = _error {
throw error
}
}
// MARK: - Internal methods
internal func configure() {
}
internal func createConfiguration() -> Realm.Configuration {
return Realm.Configuration(
fileURL: fileURL,
schemaVersion: schemaVersion,
migrationBlock: { (migration, oldSchemaVersion) in
if oldSchemaVersion < self.schemaVersion {
self.process(forMigration: migration, oldSchemaVersion: oldSchemaVersion)
}
},
objectTypes: objectTypes
)
}
}
extension List where Element: Object {
subscript() -> [Element] {
get {
return Array(self)
}
}
}
extension DispatchQueue {
public class func isCurrentQueue(queue: DispatchQueue) -> Bool {
return queue.label == String(validatingUTF8: __dispatch_queue_get_label(nil))!
}
}
| 03ba43fee14c90061a4672bcc3c75ed3 | 29.775229 | 215 | 0.536593 | false | false | false | false |
cwwise/Keyboard-swift | refs/heads/master | Sources/Emoticon/Emoticon.swift | mit | 1 | //
// Emoticon.swift
// Keyboard
//
// Created by chenwei on 2017/3/26.
// Copyright © 2017年 cwwise. All rights reserved.
//
import UIKit
public enum EmoticonFormat {
case image // png jpg
case gif
}
public enum EmoticonType: Int {
case normal
case big
}
public class Emoticon: NSObject {
/// 唯一id
var id: String
///
var type: EmoticonType
/// 表情格式
var format: EmoticonFormat = .image
/// 标题
var title: String?
///
var size: CGSize = CGSize.zero
// 原图(本地路径 或者 网络路径)
var originalUrl: URL?
// 小图
var thumbUrl: URL?
//
convenience init(id: String, title: String, path: URL) {
self.init(id: id, title: title, originalUrl: path, type: .normal)
}
private init(id: String,
title: String? = nil,
originalUrl: URL? = nil,
type: EmoticonType) {
self.id = id
self.originalUrl = originalUrl
self.title = title
self.type = type
}
public override var description: String {
return self.title ?? "无title"
}
}
| ea0061baa1c1fec8f2b9b9a08ec8bb76 | 17.241935 | 73 | 0.555261 | false | false | false | false |
whong7/swift-knowledge | refs/heads/master | 思维导图/4-3:网易新闻/网易新闻/NetworkTools.swift | mit | 1 | //
// NetworkTools.swift
// 网易新闻
//
// Created by 吴鸿 on 2017/3/4.
// Copyright © 2017年 吴鸿. All rights reserved.
//
import UIKit
import Alamofire
enum methodType {
case get
case post
}
class NetworkTools {
//类方法
class func requestData(URLString : String,type : methodType,parameters:[String : Any]? = nil,finishedCallback: @escaping(_ result : Any)->()){
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
//1.校验是否有结果
guard let result = response.result.value else{
return
}
//2.将结果回调出去
finishedCallback(result)
}
}
}
| 70b0e41708e2c11c42b32ab3d9fe0941 | 20.297297 | 146 | 0.577411 | false | false | false | false |
kingslay/KSSwiftExtension | refs/heads/master | Core/Source/Extension/Color.swift | mit | 1 | //
// KSColor.swift
// PolyGe
//
// Created by king on 15/4/16.
// Copyright (c) 2015年 king. All rights reserved.
//
import UIKit
extension Swifty where Base: UIColor {
static public func colorFrom(colorString: String) -> UIColor {
let leftParenCharset: NSCharacterSet = NSCharacterSet(charactersInString: "( ")
let commaCharset: NSCharacterSet = NSCharacterSet(charactersInString: ", ")
let colorString = colorString.lowercaseString
if colorString.hasPrefix("#")
{
var argb: [UInt] = [255, 0, 0, 0]
let colorString = colorString.unicodeScalars
var length = colorString.count
var index = colorString.startIndex
let endIndex = colorString.endIndex
index = index.advancedBy(1)
length = length - 1
if length == 3 || length == 6 || length == 8
{
var i = length == 8 ? 0 : 1
while index < endIndex
{
var c = colorString[index]
index = index.advancedBy(1)
var val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30
argb[i] = UInt(val) * 16
if length == 3
{
argb[i] = argb[i] + UInt(val)
}
else
{
c = colorString[index]
index = index.advancedBy(1)
val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30
argb[i] = argb[i] + UInt(val)
}
i += 1
}
}
return UIColor(red: CGFloat(argb[1]) / 255.0, green: CGFloat(argb[2]) / 255.0, blue: CGFloat(argb[3]) / 255.0, alpha: CGFloat(argb[0]) / 255.0)
}
else if colorString.hasPrefix("rgba")
{
var a: Float = 1.0
var r: Int32 = 0
var g: Int32 = 0
var b: Int32 = 0
let scanner: NSScanner = NSScanner(string: colorString)
scanner.scanString("rgba", intoString: nil)
scanner.scanCharactersFromSet(leftParenCharset, intoString: nil)
scanner.scanInt(&r)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&g)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&b)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanFloat(&a)
return UIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: CGFloat(a)
)
}
else if colorString.hasPrefix("argb")
{
var a: Float = 1.0
var r: Int32 = 0
var g: Int32 = 0
var b: Int32 = 0
let scanner: NSScanner = NSScanner(string: colorString)
scanner.scanString("argb", intoString: nil)
scanner.scanCharactersFromSet(leftParenCharset, intoString: nil)
scanner.scanFloat(&a)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&r)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&g)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&b)
return UIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: CGFloat(a)
)
}
else if colorString.hasPrefix("rgb")
{
var r: Int32 = 0
var g: Int32 = 0
var b: Int32 = 0
let scanner: NSScanner = NSScanner(string: colorString)
scanner.scanString("rgb", intoString: nil)
scanner.scanCharactersFromSet(leftParenCharset, intoString: nil)
scanner.scanInt(&r)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&g)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&b)
return UIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: 1.0
)
}
return UIColor.clearColor()
}
public func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
self.base.getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
public static func createImage(color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 5d113b6029aad9ac2ea10872de5afe25 | 35.675676 | 155 | 0.519528 | false | false | false | false |
augusteo/techfugee | refs/heads/master | Askari/CustomTabBarController.swift | mit | 1 | //
// CustomTabBarController.swift
// Askari
//
// Created by Pk Heng on 16/04/2016.
// Copyright © 2016 Pk Heng. All rights reserved.
//
import UIKit
import Onboard
class CustomTabBarController: UITabBarController {
let hasBeenOnboarded = NSUserDefaults.standardUserDefaults().boolForKey("hasBeenOnboarded")
let onboardVC = OnboardingViewController()
let isLoggedIn = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !hasBeenOnboarded {
showOnboarding()
} else {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "hasBeenOnboarded")
}
if !isLoggedIn {
// showSignUpModal()
}
}
func showOnboarding() {
let onboardImage = UIImage(named: "onboard")
let onboardVC = OnboardingViewController(backgroundImage: onboardImage, contents: generatePages())
onboardVC.shouldBlurBackground = true
onboardVC.shouldFadeTransitions = true
presentViewController(onboardVC, animated: true, completion: nil)
}
func generatePages() -> [OnboardingContentViewController] {
let page1 = OnboardingContentViewController(title: "Welcome to Askari", body: "Where mentee and mentors connect to help each others", image: nil, buttonText: nil, action: nil)
let page2 = OnboardingContentViewController(title: "Your own profile", body: "Register with your bio, industry, and what are you looking for", image: nil, buttonText: nil, action: nil)
let page3 = OnboardingContentViewController(title: "Connect", body: "Find mentors or mentee and connect with them personally", image: nil, buttonText: "Get Started", action: {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "hasBeenOnboarded")
self.dismissViewControllerAnimated(true, completion: nil)
})
return [page1, page2, page3]
}
func showSignUpModal() {
self.performSegueWithIdentifier("showSignUp", sender: nil)
}
}
| a605a5e4177f57dfeadf8e46136359f9 | 23.309524 | 188 | 0.712537 | false | false | false | false |
tilltue/TLPhotoPicker | refs/heads/master | Example/TLPhotoPicker/CustomCell_Instagram.swift | mit | 1 | //
// CustomCell_Instagram.swift
// TLPhotoPicker
//
// Created by wade.hawk on 2017. 5. 15..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import Foundation
import TLPhotoPicker
import PhotosUI
class CustomCell_Instagram: TLPhotoCollectionViewCell {
@IBOutlet var sizeRequiredLabel: UILabel!
@IBOutlet var sizeRequiredOverlayView: UIView!
let selectedColor = UIColor(red: 88/255, green: 144/255, blue: 255/255, alpha: 1.0)
override var duration: TimeInterval? {
didSet {
self.durationLabel?.isHidden = self.duration == nil ? true : false
guard let duration = self.duration else { return }
self.durationLabel?.text = timeFormatted(timeInterval: duration)
}
}
override var isCameraCell: Bool {
didSet {
self.orderLabel?.isHidden = self.isCameraCell
}
}
override public var selectedAsset: Bool {
willSet(newValue) {
self.orderLabel?.layer.borderColor = newValue ? self.selectedColor.cgColor : UIColor.white.cgColor
self.orderLabel?.backgroundColor = newValue ? self.selectedColor : UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)
}
}
override func update(with phAsset: PHAsset) {
super.update(with: phAsset)
self.sizeRequiredOverlayView?.isHidden = (phAsset.pixelWidth == 300 && phAsset.pixelHeight == 300)
self.sizeRequiredLabel?.text = "\(phAsset.pixelWidth)\nx\n\(phAsset.pixelHeight)"
}
override func awakeFromNib() {
super.awakeFromNib()
self.sizeRequiredOverlayView?.isHidden = true
self.durationView?.backgroundColor = UIColor.clear
self.orderLabel?.clipsToBounds = true
self.orderLabel?.layer.cornerRadius = 10
self.orderLabel?.layer.borderWidth = 1
self.orderLabel?.layer.borderColor = UIColor.white.cgColor
}
override open func prepareForReuse() {
super.prepareForReuse()
self.durationView?.backgroundColor = UIColor.clear
}
}
| 4a88704cb017c67608ac22db36ca9736 | 32.868852 | 125 | 0.655857 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/SILOptimizer/specialize_unconditional_checked_cast.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -Xllvm -sil-disable-pass="Function Signature Optimization" -emit-sil -o - -O %s | FileCheck %s
//////////////////
// Declarations //
//////////////////
public class C {}
public class D : C {}
public class E {}
var b : UInt8 = 0
var c = C()
var d = D()
var e = E()
var f : UInt64 = 0
var o : AnyObject = c
////////////////////////////
// Archetype To Archetype //
////////////////////////////
@inline(never)
public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 {
return t as! T2
}
ArchetypeToArchetype(t: b, t2: b)
ArchetypeToArchetype(t: c, t2: c)
ArchetypeToArchetype(t: b, t2: c)
ArchetypeToArchetype(t: c, t2: b)
ArchetypeToArchetype(t: c, t2: d)
ArchetypeToArchetype(t: d, t2: c)
ArchetypeToArchetype(t: c, t2: e)
ArchetypeToArchetype(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_S____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, UInt8) -> UInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_S0____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast_addr
// y -> x where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_Vs5UInt8___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1D___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $C
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK: unconditional_checked_cast_addr take_always C in [[STACK]] : $*C to D in
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D_CS_1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: upcast {{%[0-9]+}} : $D to $C
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1E___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated non classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_Vs6UInt64___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, UInt64) -> UInt64 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
///////////////////////////
// Archetype To Concrete //
///////////////////////////
@inline(never)
public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> UInt8 {
return t as! UInt8
}
ArchetypeToConcreteConvertUInt8(t: b)
ArchetypeToConcreteConvertUInt8(t: c)
ArchetypeToConcreteConvertUInt8(t: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{.*}} : $@convention(thin) (UInt8) -> UInt8 {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where y is a class but x is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@owned C) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are classes and x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@owned D) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: [[UC:%[0-9]+]] = upcast %0
// CHECK-NEXT: return [[UC]]
// x -> y where x,y are classes, but x is unrelated to y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ArchetypeToConcreteConvertC<T>(t t: T) -> C {
return t as! C
}
ArchetypeToConcreteConvertC(t: c)
ArchetypeToConcreteConvertC(t: b)
ArchetypeToConcreteConvertC(t: d)
ArchetypeToConcreteConvertC(t: e)
@inline(never)
public func ArchetypeToConcreteConvertD<T>(t t: T) -> D {
return t as! D
}
ArchetypeToConcreteConvertD(t: c)
// x -> y where x,y are classes and x is a sub class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{.*}} : $@convention(thin) (@owned C) -> @owned D {
// CHECK: bb0(%0 : $C):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func ArchetypeToConcreteConvertE<T>(t t: T) -> E {
return t as! E
}
ArchetypeToConcreteConvertE(t: c)
// x -> y where x,y are classes, but y is unrelated to x. The idea is
// to make sure that the fact that y is concrete does not affect the
// result.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
///////////////////////////
// Concrete to Archetype //
///////////////////////////
@inline(never)
public func ConcreteToArchetypeConvertUInt8<T>(t t: UInt8, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertUInt8(t: b, t2: b)
ConcreteToArchetypeConvertUInt8(t: b, t2: c)
ConcreteToArchetypeConvertUInt8(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, UInt8) -> UInt8 {
// CHECK: bb0(%0 : $UInt8, %1 : $UInt8):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where x is not a class but y is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, @owned C) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are different non class types.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, UInt64) -> UInt64 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertC(t: c, t2: c)
ConcreteToArchetypeConvertC(t: c, t2: b)
ConcreteToArchetypeConvertC(t: c, t2: d)
ConcreteToArchetypeConvertC(t: c, t2: e)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0(%0 : $C, %1 : $D):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: strong_release %1
// CHECK-DAG: strong_release %0
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK: bb0(%0 : $C, %1 : $E):
// CHECK-NEXT: builtin "int_trap"
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertD(t: d, t2: c)
// x -> y where x is a subclass of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK: bb0(%0 : $D, %1 : $C):
// CHECK-DAG: [[UC:%[0-9]+]] = upcast %0
// CHECK-DAG: strong_release %1
// CHECK: return [[UC]]
////////////////////////
// Super To Archetype //
////////////////////////
@inline(never)
public func SuperToArchetypeC<T>(c c : C, t : T) -> T {
return c as! T
}
SuperToArchetypeC(c: c, t: c)
SuperToArchetypeC(c: c, t: d)
SuperToArchetypeC(c: c, t: b)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0
// CHECK: unconditional_checked_cast_addr take_always C in
// x -> y where x is a class and y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func SuperToArchetypeD<T>(d d : D, t : T) -> T {
return d as! T
}
SuperToArchetypeD(d: d, t: c)
SuperToArchetypeD(d: d, t: d)
// *NOTE* The frontend is smart enough to turn this into an upcast. When this
// test is converted to SIL, this should be fixed appropriately.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK: upcast
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@owned D, @owned D) -> @owned D {
// CHECK: bb0(%0 : $D, %1 : $D):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
@inline(never)
public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T {
return o as! T
}
// AnyObject -> Class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, @owned C) -> @owned C {
// CHECK: unconditional_checked_cast_addr take_always AnyObject in {{%.*}} : $*AnyObject to C
// AnyObject -> Non Class (should always fail)
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, UInt8) -> UInt8 {
// CHECK: builtin "int_trap"()
// CHECK: unreachable
// CHECK-NEXT: }
// AnyObject -> AnyObject
// CHECK-LABEL: sil shared [noinline] @_TTSg5Ps9AnyObject____TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, @owned AnyObject) -> @owned AnyObject {
// CHECK: bb0(%0 : $AnyObject, %1 : $AnyObject):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
ExistentialToArchetype(o: o, t: c)
ExistentialToArchetype(o: o, t: b)
ExistentialToArchetype(o: o, t: o)
// Ensure that a downcast from an Optional source is not promoted to a
// value cast. We could do the promotion, but the optimizer would need
// to insert the Optional unwrapping logic before the cast.
//
// CHECK-LABEL: sil shared [noinline] @_TTSg5GSqC37specialize_unconditional_checked_cast1C__CS_1D___TF37specialize_unconditional_checked_cast15genericDownCastu0_rFTxMq__q_ : $@convention(thin) (@owned Optional<C>, @thick D.Type) -> @owned D {
// CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type):
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C>
// CHECK-DAG: store %0 to [[STACK_C]]
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always Optional<C> in [[STACK_C]] : $*Optional<C> to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func genericDownCast<T, U>(_ a: T, _ : U.Type) -> U {
return a as! U
}
public func callGenericDownCast(_ c: C?) -> D {
return genericDownCast(c, D.self)
}
| 307f68d6dbb3ee9aa75551bc007ca2dd | 42.850394 | 242 | 0.694799 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Kickstarter-iOS/Features/ProjectPage/Controller/ProjectDescriptionViewController.swift | apache-2.0 | 1 | import Foundation
import KsApi
import Library
import Prelude
import SafariServices
import UIKit
import WebKit
internal final class ProjectDescriptionViewController: WebViewController {
private let loadingIndicator = UIActivityIndicatorView()
private let viewModel: ProjectDescriptionViewModelType = ProjectDescriptionViewModel()
internal static func configuredWith(data: ProjectPamphletMainCellData) -> ProjectDescriptionViewController {
let vc = ProjectDescriptionViewController()
vc.viewModel.inputs.configureWith(value: data)
return vc
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.loadingIndicator)
NSLayoutConstraint.activate(
[
self.loadingIndicator.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.loadingIndicator.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
]
)
self.viewModel.inputs.viewDidLoad()
}
internal override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self
|> self.projectDescriptionViewControllerStyle
_ = self.loadingIndicator
|> baseActivityIndicatorStyle
}
private let projectDescriptionViewControllerStyle: (WebViewController) -> WebViewController = { vc in
vc
|> baseControllerStyle()
|> WebViewController.lens.title %~ { _ in Strings.project_menu_buttons_campaign() }
|> (WebViewController.lens.webView.scrollView .. UIScrollView.lens.delaysContentTouches) .~ false
|> (WebViewController.lens.webView.scrollView .. UIScrollView.lens.canCancelContentTouches) .~ true
}
// MARK: - View model
override func bindViewModel() {
super.bindViewModel()
self.loadingIndicator.rac.animating = self.viewModel.outputs.isLoading
self.viewModel.outputs.goToMessageDialog
.observeForControllerAction()
.observeValues { [weak self] in self?.goToMessageDialog(subject: $0, context: $1) }
self.viewModel.outputs.goBackToProject
.observeForControllerAction()
.observeValues { [weak self] _ in
_ = self?.navigationController?.popViewController(animated: true)
}
self.viewModel.outputs.goToSafariBrowser
.observeForControllerAction()
.observeValues { [weak self] in
self?.goTo(url: $0)
}
self.viewModel.outputs.loadWebViewRequest
.observeForControllerAction()
.observeValues { [weak self] in
_ = self?.webView.load($0)
}
self.viewModel.outputs.showErrorAlert
.observeForControllerAction()
.observeValues { [weak self] in
self?.present(
UIAlertController.genericError($0.localizedDescription),
animated: true,
completion: nil
)
}
}
// MARK: - WKNavigationDelegate
internal func webView(
_: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
self.viewModel.inputs.decidePolicyFor(navigationAction: .init(navigationAction: navigationAction))
decisionHandler(self.viewModel.outputs.decidedPolicyForNavigationAction)
}
internal func webView(_: WKWebView, didStartProvisionalNavigation _: WKNavigation!) {
self.viewModel.inputs.webViewDidStartProvisionalNavigation()
}
internal func webView(_: WKWebView, didFinish _: WKNavigation!) {
self.viewModel.inputs.webViewDidFinishNavigation()
}
internal func webView(
_: WKWebView,
didFailProvisionalNavigation _: WKNavigation!,
withError error: Error
) {
self.viewModel.inputs.webViewDidFailProvisionalNavigation(withError: error)
}
// MARK: - Navigation
fileprivate func goToMessageDialog(subject: MessageSubject, context: KSRAnalytics.MessageDialogContext) {
let vc = MessageDialogViewController.configuredWith(messageSubject: subject, context: context)
vc.delegate = self
self.present(
UINavigationController(rootViewController: vc),
animated: true,
completion: nil
)
}
}
// MARK: - MessageDialogViewControllerDelegate
extension ProjectDescriptionViewController: MessageDialogViewControllerDelegate {
internal func messageDialogWantsDismissal(_ dialog: MessageDialogViewController) {
dialog.dismiss(animated: true, completion: nil)
}
internal func messageDialog(_: MessageDialogViewController, postedMessage _: Message) {}
}
| c2d74ad103cc5d1607d18cc2cb76e002 | 30.322148 | 110 | 0.734519 | false | false | false | false |
openHPI/xikolo-ios | refs/heads/dev | iOS/Layouts/CardListLayout.swift | gpl-3.0 | 1 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import UIKit
protocol CardListLayoutDelegate: AnyObject {
var topInset: CGFloat { get }
var heightForSectionHeader: CGFloat { get }
var kindForGlobalHeader: String? { get }
var heightForGlobalHeader: CGFloat { get }
}
extension CardListLayoutDelegate {
var topInset: CGFloat {
return 0
}
var heightForSectionHeader: CGFloat {
return 0
}
var kindForGlobalHeader: String? {
return nil
}
var heightForGlobalHeader: CGFloat {
return 0
}
}
class CardListLayout: TopAlignedCollectionViewFlowLayout {
weak var delegate: CardListLayoutDelegate?
private var topInset: CGFloat { self.delegate?.topInset ?? 0 }
private var heightForSectionHeader: CGFloat { self.delegate?.heightForSectionHeader ?? 0 }
private var kindForGlobalHeader: String? { self.delegate?.kindForGlobalHeader }
private var heightForGlobalHeader: CGFloat { self.delegate?.heightForGlobalHeader ?? 0 }
override var collectionViewContentSize: CGSize {
let numberOfSections = self.collectionView?.numberOfSections ?? 0
let heightForHeaders = CGFloat(numberOfSections) * self.heightForSectionHeader
var contentSize = super.collectionViewContentSize
contentSize.height += self.topInset + self.heightForGlobalHeader + heightForHeaders
return contentSize
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let newRect = rect.offsetBy(dx: 0, dy: (self.topInset + self.heightForGlobalHeader) * -1)
let originalLayoutAttributes = super.layoutAttributesForElements(in: newRect)
var layoutAttributes: [UICollectionViewLayoutAttributes] = []
let sectionsToAdd = NSMutableIndexSet()
originalLayoutAttributes?.forEach { originalLayoutAttribute in
sectionsToAdd.add(originalLayoutAttribute.indexPath.section)
if originalLayoutAttribute.representedElementCategory == .cell {
// swiftlint:disable:next force_cast
let layoutAttribute = originalLayoutAttribute.copy() as! UICollectionViewLayoutAttributes
layoutAttribute.frame = layoutAttribute.frame.offsetBy(
dx: 0,
dy: CGFloat(layoutAttribute.indexPath.section + 1) * (self.heightForSectionHeader) + self.topInset + self.heightForGlobalHeader
)
layoutAttributes.append(layoutAttribute)
}
}
if let headerHeight = self.delegate?.heightForSectionHeader, headerHeight > 0 {
for section in sectionsToAdd {
let indexPath = IndexPath(item: 0, section: section)
let attributes = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath)
if let sectionAttributes = attributes, sectionAttributes.frame.intersects(rect) {
layoutAttributes.append(sectionAttributes)
}
}
}
if let globalHeaderKind = self.kindForGlobalHeader, self.heightForGlobalHeader > 0 {
if let headerLayoutAttributes = self.layoutAttributesForSupplementaryView(ofKind: globalHeaderKind, at: IndexPath(item: 0, section: 0)) {
layoutAttributes.append(headerLayoutAttributes)
}
}
return layoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let originalLayoutAttributes = super.layoutAttributesForItem(at: indexPath) else { return nil }
if originalLayoutAttributes.representedElementCategory == .cell {
// swiftlint:disable:next force_cast
let layoutAttributes = originalLayoutAttributes.copy() as! UICollectionViewLayoutAttributes
layoutAttributes.frame = layoutAttributes.frame.offsetBy(
dx: 0,
dy: CGFloat(indexPath.section + 1) * self.heightForSectionHeader + self.topInset + self.heightForGlobalHeader
)
return layoutAttributes
} else {
return originalLayoutAttributes
}
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String,
at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if elementKind == UICollectionView.elementKindSectionHeader {
guard self.heightForSectionHeader > 0 else { return nil }
guard let boundaries = self.boundaries(forSection: indexPath.section) else { return nil }
guard let collectionView = collectionView else { return nil }
let contentOffsetY = collectionView.contentOffset.y + collectionView.safeAreaInsets.top
var offsetY: CGFloat
if contentOffsetY < boundaries.minimum {
// normal position
offsetY = boundaries.minimum
} else if contentOffsetY > boundaries.maximum - self.heightForSectionHeader {
// position when moving out of the screen
offsetY = boundaries.maximum - self.heightForSectionHeader
} else {
// sticky position
offsetY = contentOffsetY
}
let frame = CGRect(x: 0, y: offsetY, width: collectionView.bounds.width, height: self.heightForSectionHeader)
let layoutAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: indexPath)
layoutAttributes.frame = frame
layoutAttributes.isHidden = false
layoutAttributes.zIndex = 1
return layoutAttributes
} else {
guard let collectionView = collectionView else { return nil }
let height = self.delegate?.heightForGlobalHeader ?? 0
let frame = CGRect(x: 0, y: 0, width: collectionView.bounds.width, height: height)
let layoutAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath)
layoutAttributes.frame = frame
return layoutAttributes
}
}
func boundaries(forSection section: Int) -> (minimum: CGFloat, maximum: CGFloat)? {
var result = (minimum: CGFloat(0.0), maximum: CGFloat(0.0))
guard let collectionView = collectionView else { return result }
let numberOfItems = collectionView.numberOfItems(inSection: section)
guard numberOfItems > 0 else { return result }
let layoutAttributes = (0..<numberOfItems).compactMap { self.layoutAttributesForItem(at: IndexPath(item: $0, section: section)) }
result.minimum = layoutAttributes.map(\.frame.minY).min() ?? 0
result.maximum = layoutAttributes.map(\.frame.maxY).max() ?? 0
result.minimum -= self.delegate?.heightForSectionHeader ?? 0
result.minimum = max(result.minimum, 0)
return result
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override class var invalidationContextClass: AnyClass {
return StickyHeaderInvalidationContext.self
}
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
// swiftlint:disable:next force_cast
let context = super.invalidationContext(forBoundsChange: newBounds) as! StickyHeaderInvalidationContext
guard self.collectionView?.bounds.width == newBounds.width else { return context }
// Invalidate only section headers
context.onlyHeaders = true
let numberOfSections = self.collectionView?.numberOfSections ?? 0
let sectionIndices = (0..<numberOfSections).map { IndexPath(item: 0, section: $0) }
context.invalidateSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader, at: sectionIndices)
return context
}
}
class StickyHeaderInvalidationContext: UICollectionViewFlowLayoutInvalidationContext {
var onlyHeaders = false
override var invalidateEverything: Bool { return !onlyHeaders }
override var invalidateDataSourceCounts: Bool { return false }
}
| 7d6416ec11719103245429ba93bcef72 | 42.273196 | 155 | 0.68112 | false | false | false | false |
BrandonMA/SwifterUI | refs/heads/master | Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift | gpl-3.0 | 4 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2019 Wei Wang <[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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension KingfisherWrapper where Base: ImageView {
// MARK: Setting Image
/// Sets an image to the image view with a `Source`.
///
/// - Parameters:
/// - source: The `Source` object defines data information from network or a data provider.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
/// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
///
/// ```
/// // Set image from a network source.
/// let url = URL(string: "https://example.com/image.png")!
/// imageView.kf.setImage(with: .network(url))
///
/// // Or set image from a data provider.
/// let provider = LocalFileImageDataProvider(fileURL: fileURL)
/// imageView.kf.setImage(with: .provider(provider))
/// ```
///
/// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
/// above is equivalent to:
///
/// ```
/// imageView.kf.setImage(with: url)
/// imageView.kf.setImage(with: provider)
/// ```
///
/// Internally, this method will use `KingfisherManager` to get the source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
mutatingSelf.placeholder = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet {
// Always set placeholder while there is no image/placeholder yet.
mutatingSelf.placeholder = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if base.shouldPreloadAllAnimation() {
options.preloadAllAnimationData = true
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
progressBlock: { receivedSize, totalSize in
guard issuedIdentifier == self.taskIdentifier else { return }
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
maybeIndicator?.stopAnimatingView()
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
switch result {
case .success(let value):
guard self.needsTransition(options: options, cacheType: value.cacheType) else {
mutatingSelf.placeholder = nil
self.base.image = value.image
completionHandler?(result)
return
}
self.makeTransition(image: value.image, transition: options.transition) {
completionHandler?(result)
}
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
})
mutatingSelf.imageTask = task
return task
}
/// Sets an image to the image view with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
/// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
///
/// ```
/// let url = URL(string: "https://example.com/image.png")!
/// imageView.kf.setImage(with: url)
/// ```
///
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource.map { .network($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
/// Sets an image to the image view with a data provider.
///
/// - Parameters:
/// - provider: The `ImageDataProvider` object contains information about the data.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// Internally, this method will use `KingfisherManager` to get the image data, from either cache
/// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with provider: ImageDataProvider?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: provider.map { .provider($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the image view if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelDownloadTask() {
imageTask?.cancel()
}
private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
switch options.transition {
case .none:
return false
#if !os(macOS)
default:
if options.forceTransition { return true }
if cacheType == .none { return true }
return false
#endif
}
}
private func makeTransition(image: Image, transition: ImageTransition, done: @escaping () -> Void) {
#if !os(macOS)
// Force hiding the indicator without transition first.
UIView.transition(
with: self.base,
duration: 0.0,
options: [],
animations: { self.indicator?.stopAnimatingView() },
completion: { _ in
var mutatingSelf = self
mutatingSelf.placeholder = nil
UIView.transition(
with: self.base,
duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: { transition.animations?(self.base, image) },
completion: { finished in
transition.completion?(finished)
done()
}
)
}
)
#else
done()
#endif
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var placeholderKey: Void?
private var imageTaskKey: Void?
extension KingfisherWrapper where Base: ImageView {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
/// Holds which indicator type is going to be used.
/// Default is `.none`, means no indicator will be shown while downloading.
public var indicatorType: IndicatorType {
get {
return getAssociatedObject(base, &indicatorTypeKey) ?? .none
}
set {
switch newValue {
case .none: indicator = nil
case .activity: indicator = ActivityIndicator()
case .image(let data): indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator): indicator = anIndicator
}
setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public private(set) var indicator: Indicator? {
get {
let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
return box?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if let newIndicator = newValue {
// Set default indicator layout
let view = newIndicator.view
base.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.centerXAnchor.constraint(
equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
view.centerYAnchor.constraint(
equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
newIndicator.view.isHidden = true
}
// Save in associated object
// Wrap newValue with Box to workaround an issue that Swift does not recognize
// and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
/// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
/// it is downloading an image.
public private(set) var placeholder: Placeholder? {
get { return getAssociatedObject(base, &placeholderKey) }
set {
if let previousPlaceholder = placeholder {
previousPlaceholder.remove(from: base)
}
if let newPlaceholder = newValue {
newPlaceholder.add(to: base)
} else {
base.image = nil
}
setRetainedAssociatedObject(base, &placeholderKey, newValue)
}
}
}
@objc extension ImageView {
func shouldPreloadAllAnimation() -> Bool { return true }
}
extension KingfisherWrapper where Base: ImageView {
/// Gets the image URL bound to this image view.
@available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
public private(set) var webURL: URL? {
get { return nil }
set { }
}
}
| 652b928a3fd5dca9813f29115fd0736d | 40.799492 | 120 | 0.610298 | false | false | false | false |
abertelrud/swift-package-manager | refs/heads/main | Sources/PackageLoading/ContextModel.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import Foundation
struct ContextModel {
let packageDirectory : String
init(packageDirectory : String) {
self.packageDirectory = packageDirectory
}
var environment : [String : String] {
ProcessInfo.processInfo.environment
}
}
extension ContextModel : Codable {
private enum CodingKeys: CodingKey {
case packageDirectory
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.packageDirectory = try container.decode(String.self, forKey: .packageDirectory)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(packageDirectory, forKey: .packageDirectory)
}
func encode() throws -> String {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)!
}
static func decode() throws -> ContextModel {
var args = Array(ProcessInfo.processInfo.arguments[1...]).makeIterator()
while let arg = args.next() {
if arg == "-context", let json = args.next() {
let decoder = JSONDecoder()
guard let data = json.data(using: .utf8) else {
throw StringError(description: "Failed decoding context json as UTF8")
}
return try decoder.decode(ContextModel.self, from: data)
}
}
throw StringError(description: "Could not decode ContextModel parameter.")
}
struct StringError: Error, CustomStringConvertible {
let description: String
}
}
| c72da205589f7a1dcbd96a43c5a9d8b2 | 33.4 | 92 | 0.602415 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/attr/attr_objc_swift4.swift | apache-2.0 | 30 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 4 -enable-source-import -I %S/Inputs
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
class ObjCSubclass : NSObject {
func foo() { } // expected-note{{add '@objc' to expose this instance method to Objective-C}}
}
class DynamicMembers {
@objc dynamic func foo() { }
@objc dynamic var bar: NSObject? = nil
}
func test(sc: ObjCSubclass, dm: DynamicMembers) {
_ = #selector(sc.foo) // expected-error{{argument of '#selector' refers to instance method 'foo()' that is not exposed to Objective-C}}
_ = #selector(getter: dm.bar)
_ = #keyPath(DynamicMembers.bar)
}
struct PlainStruct { }
class BadInSwift4 {
@IBInspectable var badIBInspectable: PlainStruct?
// expected-error@-1{{property cannot be marked @IBInspectable because its type cannot be represented in Objective-C}}
@GKInspectable var badGKInspectable: PlainStruct?
// expected-error@-1{{property cannot be marked @GKInspectable because its type cannot be represented in Objective-C}}
}
// CHECK-LABEL: class InitsInheritObjCAttrBase
class InitsInheritObjCAttrBase: NSObject {
override init() {}
// CHECK: {{^}} @objc convenience init(foo: Int)
@objc convenience init(foo: Int) { self.init() }
} // CHECK: {{^[}]$}}
// CHECK-LABEL: extension InitsInheritObjCAttrBase
extension InitsInheritObjCAttrBase {
// CHECK: {{^}} @objc convenience dynamic init(bar: Int)
@objc convenience init(bar: Int) { self.init() }
} // CHECK: {{^[}]$}}
// CHECK-LABEL: class ConvenienceInitsInheritObjCAttrSub
class ConvenienceInitsInheritObjCAttrSub: InitsInheritObjCAttrBase {
init(somethingElse: ()) { super.init() }
// CHECK: {{^}} @objc convenience init(foo: Int)
convenience init(foo: Int) { self.init(somethingElse: ()) }
// FIXME: The '@objc' is relied upon, but the 'dynamic' probably shouldn't be!
// CHECK: {{^}} @objc convenience dynamic init(bar: Int)
convenience init(bar: Int) { self.init(somethingElse: ()) }
// CHECK: {{^}} convenience init(unrelated: Int)
convenience init(unrelated: Int) { self.init(somethingElse: ()) }
} // CHECK: {{^[}]$}}
// CHECK-LABEL: class DesignatedInitsInheritObjCAttrSub
class DesignatedInitsInheritObjCAttrSub: InitsInheritObjCAttrBase {
// CHECK: {{^}} @objc init(foo: Int)
init(foo: Int) { super.init() }
// FIXME: The '@objc' is relied upon, but the 'dynamic' probably shouldn't be!
// CHECK: {{^}} @objc dynamic init(bar: Int)
init(bar: Int) { super.init() }
// CHECK: {{^}} init(unrelated: Int)
init(unrelated: Int) { super.init() }
} // CHECK: {{^[}]$}}
| cae55d76e2ed414b9b14531f89e3bf7a | 40.169014 | 293 | 0.702703 | false | false | false | false |
V3ronique/TailBook | refs/heads/master | TailBook/TailBook/NewsFeedPageContentTableViewCell.swift | mit | 1 | //
// NewsFeedPageContentTableViewCell.swift
// TailBook
//
// Created by Roni Beberoni on 2/4/16.
// Copyright © 2016 Veronica. All rights reserved.
//
import UIKit
class NewsFeedPageContentTableViewCell: UITableViewCell {
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var actionLabel: UILabel!
@IBOutlet weak var objectLabel: UILabel!
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var likesLabel: UILabel!
var manager = UpdateDataSource()
var updates = []
@IBOutlet weak var likeBtn: UIButton!
@IBAction func like(sender: UIButton) {
var count = Int(self.likesLabel.text!)
count = count!+1
self.likesLabel.text = String(count)
self.likeBtn.enabled = false
}
}
| 0deba1cda910b75a456c25e3701d6ac9 | 24.322581 | 57 | 0.66879 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/SILGen/optional_lvalue.swift | apache-2.0 | 10 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// CHECK-LABEL: sil hidden @_TF15optional_lvalue22assign_optional_lvalueFTRGSqSi_Si_T_
// CHECK: [[PRECOND:%.*]] = function_ref @_TFs30_diagnoseUnexpectedNilOptional
// CHECK: apply [[PRECOND]](
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr %0 : $*Optional<Int>, #Optional.some!enumelt.1
// CHECK: assign {{%.*}} to [[PAYLOAD]]
func assign_optional_lvalue(_ x: inout Int?, _ y: Int) {
x! = y
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue17assign_iuo_lvalueFTRGSQSi_Si_T_
// CHECK: [[PRECOND:%.*]] = function_ref @_TFs30_diagnoseUnexpectedNilOptional
// CHECK: apply [[PRECOND]](
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr %0 : $*Optional<Int>, #Optional.some!enumelt.1
// CHECK: assign {{%.*}} to [[PAYLOAD]]
func assign_iuo_lvalue(_ x: inout Int!, _ y: Int) {
x! = y
}
struct S {
var x: Int
var computed: Int {
get {}
set {}
}
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue26assign_iuo_lvalue_implicitFTRGSQVS_1S_Si_T_
// CHECK: [[SOME:%.*]] = unchecked_take_enum_data_addr %0
// CHECK: [[X:%.*]] = struct_element_addr [[SOME]]
func assign_iuo_lvalue_implicit(_ s: inout S!, _ y: Int) {
s.x = y
}
struct Struct<T> {
var value: T?
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue35assign_optional_lvalue_reabstractedFTRGVS_6StructFSiSi_FSiSi_T_
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK: [[REABSTRACTED:%.*]] = partial_apply [[REABSTRACT]]
// CHECK: assign [[REABSTRACTED]] to {{%.*}} : $*@callee_owned (@in Int) -> @out Int
func assign_optional_lvalue_reabstracted(_ x: inout Struct<(Int) -> Int>,
_ y: @escaping (Int) -> Int) {
x.value! = y
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue31assign_optional_lvalue_computedFTRGSqVS_1S_Si_Si
// CHECK: function_ref @_TFV15optional_lvalue1Ss8computedSi
// CHECK: function_ref @_TFV15optional_lvalue1Sg8computedSi
func assign_optional_lvalue_computed(_ x: inout S?, _ y: Int) -> Int {
x!.computed = y
return x!.computed
}
func generate_int() -> Int { return 0 }
// CHECK-LABEL: sil hidden @_TF15optional_lvalue28assign_bound_optional_lvalueFRGSqSi_T_
// CHECK: select_enum_addr
// CHECK: cond_br {{%.*}}, [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]]
// CHECK: [[SOME]]:
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr
// CHECK: [[FN:%.*]] = function_ref
// CHECK: [[T0:%.*]] = apply [[FN]]()
// CHECK: assign [[T0]] to [[PAYLOAD]]
func assign_bound_optional_lvalue(_ x: inout Int?) {
x? = generate_int()
}
| 9a6f01a1a89a820da3897f5700786a94 | 38.357143 | 113 | 0.601815 | false | false | false | false |
mbeloded/discountsPublic | refs/heads/master | discounts/Classes/DAO/DataObjects/CompanyObject/CompanyObject.swift | gpl-3.0 | 1 | //
// CompanyObject.swift
// discounts
//
// Created by Michael Bielodied on 9/10/14.
// Copyright (c) 2014 Michael Bielodied. All rights reserved.
//
import Foundation
struct CompanyObject {
var companyId:Int = 0
var categoryId:Int = 0
var companyName:String = ""
var discount:String = ""
var imageName:String = ""
var discountCode:String = ""
init() {
companyId = 0
categoryId = 0
companyName = ""
discount = ""
imageName = ""
discountCode = ""
}
}
| f33652e89a980d5c9691f21036b1a3b5 | 17.931034 | 62 | 0.57377 | false | false | false | false |
alexanderedge/Toolbelt | refs/heads/master | Toolbelt/Toolbelt/AVCaptureDevice+Hardware.swift | mit | 1 | //
// AVCaptureDevice+Hardware.swift
// Company
//
// Created by Alexander G Edge on 21/07/2015.
// Copyright (c) 2015 Company. All rights reserved.
//
import AVFoundation
extension AVCaptureDevice {
public class func hasFrontAndBackCamera() -> Bool {
return (self.backCamera() != nil) && (self.frontCamera() != nil)
}
public class func backCamera() -> AVCaptureDevice? {
return self.cameraWithPosition(.back)
}
public class func frontCamera() -> AVCaptureDevice? {
return self.cameraWithPosition(.front)
}
public class func cameraWithPosition(_ position : AVCaptureDevicePosition) -> AVCaptureDevice? {
guard let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] else { return nil }
return devices.filter({ $0.position == position }).first
}
public class func microphone() -> AVCaptureDevice? {
return AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio).first as? AVCaptureDevice
}
}
| fa6f1e6b981f290a410274e1c0de8ef4 | 29.970588 | 126 | 0.674264 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/Categories/UIViewController+alternative.swift | apache-2.0 | 5 | extension UIViewController {
func alternativeSizeClass<T>(iPhone: @autoclosure () -> T, iPad: @autoclosure () -> T) -> T {
if traitCollection.verticalSizeClass == .regular && traitCollection.horizontalSizeClass == .regular {
return iPad()
}
return iPhone()
}
func alternativeSizeClass(iPhone: () -> Void, iPad: () -> Void) {
if traitCollection.verticalSizeClass == .regular && traitCollection.horizontalSizeClass == .regular {
iPad()
} else {
iPhone()
}
}
}
| 218e74f2c157bc8c8cf1479ea7a590f3 | 30.8125 | 105 | 0.642436 | false | false | false | false |
project-chip/connectedhomeip | refs/heads/master | examples/tv-casting-app/darwin/TvCasting/TvCasting/StartFromCacheViewModel.swift | apache-2.0 | 1 | /**
*
* Copyright (c) 2020-2022 Project CHIP Authors
*
* 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 os.log
class StartFromCacheViewModel: ObservableObject {
let Log = Logger(subsystem: "com.matter.casting",
category: "StartFromCacheViewModel")
@Published var videoPlayers: [VideoPlayer] = []
func readFromCache() {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
castingServerBridge.readCachedVideoPlayers(DispatchQueue.main, readCachedVideoPlayersHandler: { (cachedVideoPlayers: NSMutableArray?) -> () in
if(cachedVideoPlayers != nil)
{
self.videoPlayers = cachedVideoPlayers! as! [VideoPlayer]
}
})
}
}
}
| 329361e0390c3469f6f862e28eb88d12 | 35.078947 | 154 | 0.652079 | false | false | false | false |
argon/WordPress-iOS | refs/heads/develop | WordPress/Classes/Services/PushAuthenticationService.swift | gpl-2.0 | 1 | import Foundation
/**
* @class PushAuthenticationService
* @brief The purpose of this service is to encapsulate the Restful API that performs Mobile 2FA
* Code Verification.
*/
@objc public class PushAuthenticationService : NSObject, LocalCoreDataService
{
var authenticationServiceRemote:PushAuthenticationServiceRemote?
/**
* @details Designated Initializer
* @param managedObjectContext A Reference to the MOC that should be used to interact with
* the Core Data Persistent Store.
*/
public required init(managedObjectContext: NSManagedObjectContext) {
super.init()
self.managedObjectContext = managedObjectContext
self.authenticationServiceRemote = PushAuthenticationServiceRemote(remoteApi: apiForRequest())
}
/**
* @details Authorizes a WordPress.com Login Attempt (2FA Protected Accounts)
* @param token The Token sent over by the backend, via Push Notifications.
* @param completion The completion block to be executed when the remote call finishes.
*/
public func authorizeLogin(token: String, completion: ((Bool) -> ())) {
if self.authenticationServiceRemote == nil {
return
}
self.authenticationServiceRemote!.authorizeLogin(token,
success: {
completion(true)
},
failure: {
completion(false)
})
}
/**
* @details Helper method to get the WordPress.com REST Api, if any
* @returns WordPressComApi instance, if applicable, or nil.
*/
private func apiForRequest() -> WordPressComApi? {
let accountService = AccountService(managedObjectContext: managedObjectContext)
if let unwrappedRestApi = accountService.defaultWordPressComAccount()?.restApi {
if unwrappedRestApi.hasCredentials() {
return unwrappedRestApi
}
}
return nil
}
// MARK: - Private Internal Properties
private var managedObjectContext : NSManagedObjectContext!
}
| acd3f45a56450bec209cf4fde00fce4e | 34.873016 | 106 | 0.613274 | false | false | false | false |
brightdigit/speculid | refs/heads/master | frameworks/speculid/Models/CwlSysctl.swift | mit | 1 | import Foundation
// swiftlint:disable all
/// A "static"-only namespace around a series of functions that operate on buffers returned from the `Darwin.sysctl` function
public struct Sysctl {
/// Possible errors.
public enum Error: Swift.Error {
case unknown
case malformedUTF8
case invalidSize
case posixError(POSIXErrorCode)
}
/// Access the raw data for an array of sysctl identifiers.
public static func dataForKeys(_ keys: [Int32]) throws -> [Int8] {
try keys.withUnsafeBufferPointer { keysPointer throws -> [Int8] in
// Preflight the request to get the required data size
var requiredSize = 0
let preFlightResult = Darwin.sysctl(UnsafeMutablePointer<Int32>(mutating: keysPointer.baseAddress), UInt32(keys.count), nil, &requiredSize, nil, 0)
if preFlightResult != 0 {
throw POSIXErrorCode(rawValue: errno).map {
print($0.rawValue)
return Error.posixError($0)
} ?? Error.unknown
}
// Run the actual request with an appropriately sized array buffer
let data = [Int8](repeating: 0, count: requiredSize)
let result = data.withUnsafeBufferPointer { dataBuffer -> Int32 in
Darwin.sysctl(UnsafeMutablePointer<Int32>(mutating: keysPointer.baseAddress), UInt32(keys.count), UnsafeMutableRawPointer(mutating: dataBuffer.baseAddress), &requiredSize, nil, 0)
}
if result != 0 {
throw POSIXErrorCode(rawValue: errno).map { Error.posixError($0) } ?? Error.unknown
}
return data
}
}
/// Convert a sysctl name string like "hw.memsize" to the array of `sysctl` identifiers (e.g. [CTL_HW, HW_MEMSIZE])
public static func keysForName(_ name: String) throws -> [Int32] {
var keysBufferSize = Int(CTL_MAXNAME)
var keysBuffer = [Int32](repeating: 0, count: keysBufferSize)
try keysBuffer.withUnsafeMutableBufferPointer { (lbp: inout UnsafeMutableBufferPointer<Int32>) throws in
try name.withCString { (nbp: UnsafePointer<Int8>) throws in
guard sysctlnametomib(nbp, lbp.baseAddress, &keysBufferSize) == 0 else {
throw POSIXErrorCode(rawValue: errno).map { Error.posixError($0) } ?? Error.unknown
}
}
}
if keysBuffer.count > keysBufferSize {
keysBuffer.removeSubrange(keysBufferSize ..< keysBuffer.count)
}
return keysBuffer
}
/// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`.
public static func valueOfType<T>(_: T.Type, forKeys keys: [Int32]) throws -> T {
let buffer = try dataForKeys(keys)
if buffer.count != MemoryLayout<T>.size {
throw Error.invalidSize
}
return try buffer.withUnsafeBufferPointer { bufferPtr throws -> T in
guard let baseAddress = bufferPtr.baseAddress else { throw Error.unknown }
return baseAddress.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee }
}
}
/// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`.
public static func valueOfType<T>(_ type: T.Type, forKeys keys: Int32...) throws -> T {
try valueOfType(type, forKeys: keys)
}
/// Invoke `sysctl` with the specified name, interpreting the returned buffer as the specified type. This function will throw `Error.invalidSize` if the size of buffer returned from `sysctl` fails to match the size of `T`.
public static func valueOfType<T>(_ type: T.Type, forName name: String) throws -> T {
try valueOfType(type, forKeys: keysForName(name))
}
/// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer.
public static func stringForKeys(_ keys: [Int32]) throws -> String {
let optionalString = try dataForKeys(keys).withUnsafeBufferPointer { dataPointer -> String? in
dataPointer.baseAddress.flatMap { String(validatingUTF8: $0) }
}
guard let s = optionalString else {
throw Error.malformedUTF8
}
return s
}
/// Invoke `sysctl` with an array of identifers, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer.
public static func stringForKeys(_ keys: Int32...) throws -> String {
try stringForKeys(keys)
}
/// Invoke `sysctl` with the specified name, interpreting the returned buffer as a `String`. This function will throw `Error.malformedUTF8` if the buffer returned from `sysctl` cannot be interpreted as a UTF8 buffer.
public static func stringForName(_ name: String) throws -> String {
try stringForKeys(keysForName(name))
}
/// e.g. "MyComputer.local" (from System Preferences -> Sharing -> Computer Name) or
/// "My-Name-iPhone" (from Settings -> General -> About -> Name)
public static var hostName: String { try! Sysctl.stringForKeys([CTL_KERN, KERN_HOSTNAME]) }
/// e.g. "x86_64" or "N71mAP"
/// NOTE: this is *corrected* on iOS devices to fetch hw.model
public static var machine: String {
#if os(iOS) && !arch(x86_64) && !arch(i386)
return try! Sysctl.stringForKeys([CTL_HW, HW_MODEL])
#else
return try! Sysctl.stringForKeys([CTL_HW, HW_MACHINE])
#endif
}
/// e.g. "MacPro4,1" or "iPhone8,1"
/// NOTE: this is *corrected* on iOS devices to fetch hw.machine
public static var model: String {
#if os(iOS) && !arch(x86_64) && !arch(i386)
return try! Sysctl.stringForKeys([CTL_HW, HW_MACHINE])
#else
return try! Sysctl.stringForKeys([CTL_HW, HW_MODEL])
#endif
}
/// e.g. "8" or "2"
public static var activeCPUs: Int32 { try! Sysctl.valueOfType(Int32.self, forKeys: [CTL_HW, HW_AVAILCPU]) }
/// e.g. "15.3.0" or "15.0.0"
public static var osRelease: String { try! Sysctl.stringForKeys([CTL_KERN, KERN_OSRELEASE]) }
/// e.g. "Darwin" or "Darwin"
public static var osType: String { try! Sysctl.stringForKeys([CTL_KERN, KERN_OSTYPE]) }
/// e.g. "15D21" or "13D20"
public static var osVersion: String { try! Sysctl.stringForKeys([CTL_KERN, KERN_OSVERSION]) }
/// e.g. "Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64" or
/// "Darwin Kernel Version 15.0.0: Wed Dec 9 22:19:38 PST 2015; root:xnu-3248.31.3~2/RELEASE_ARM64_S8000"
public static var version: String { try! Sysctl.stringForKeys([CTL_KERN, KERN_VERSION]) }
#if os(macOS)
/// e.g. 199506 (not available on iOS)
public static var osRev: Int32 { try! Sysctl.valueOfType(Int32.self, forKeys: [CTL_KERN, KERN_OSREV]) }
/// e.g. 2659000000 (not available on iOS)
public static var cpuFreq: Int64 { try! Sysctl.valueOfType(Int64.self, forName: "hw.cpufrequency") }
/// e.g. 25769803776 (not available on iOS)
public static var memSize: UInt64 { try! Sysctl.valueOfType(UInt64.self, forKeys: [CTL_HW, HW_MEMSIZE]) }
#endif
}
// swiftlint:enable all
| 9741d1d89793db767fd101b1e2fcdb0e | 46.405229 | 228 | 0.694196 | false | false | false | false |
dpricha89/DrApp | refs/heads/master | Pods/Eureka/Source/Core/Core.swift | apache-2.0 | 2 | // Core.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: Row
internal class RowDefaults {
static var cellUpdate = [String: (BaseCell, BaseRow) -> Void]()
static var cellSetup = [String: (BaseCell, BaseRow) -> Void]()
static var onCellHighlightChanged = [String: (BaseCell, BaseRow) -> Void]()
static var rowInitialization = [String: (BaseRow) -> Void]()
static var onRowValidationChanged = [String: (BaseCell, BaseRow) -> Void]()
static var rawCellUpdate = [String: Any]()
static var rawCellSetup = [String: Any]()
static var rawOnCellHighlightChanged = [String: Any]()
static var rawRowInitialization = [String: Any]()
static var rawOnRowValidationChanged = [String: Any]()
}
// MARK: FormCells
public struct CellProvider<Cell: BaseCell> where Cell: CellType {
/// Nibname of the cell that will be created.
public private (set) var nibName: String?
/// Bundle from which to get the nib file.
public private (set) var bundle: Bundle!
public init() {}
public init(nibName: String, bundle: Bundle? = nil) {
self.nibName = nibName
self.bundle = bundle ?? Bundle(for: Cell.self)
}
/**
Creates the cell with the specified style.
- parameter cellStyle: The style with which the cell will be created.
- returns: the cell
*/
func makeCell(style: UITableViewCellStyle) -> Cell {
if let nibName = self.nibName {
return bundle.loadNibNamed(nibName, owner: nil, options: nil)!.first as! Cell
}
return Cell.init(style: style, reuseIdentifier: nil)
}
}
/**
Enumeration that defines how a controller should be created.
- Callback->VCType: Creates the controller inside the specified block
- NibFile: Loads a controller from a nib file in some bundle
- StoryBoard: Loads the controller from a Storyboard by its storyboard id
*/
public enum ControllerProvider<VCType: UIViewController> {
/**
* Creates the controller inside the specified block
*/
case callback(builder: (() -> VCType))
/**
* Loads a controller from a nib file in some bundle
*/
case nibFile(name: String, bundle: Bundle?)
/**
* Loads the controller from a Storyboard by its storyboard id
*/
case storyBoard(storyboardId: String, storyboardName: String, bundle: Bundle?)
func makeController() -> VCType {
switch self {
case .callback(let builder):
return builder()
case .nibFile(let nibName, let bundle):
return VCType.init(nibName: nibName, bundle:bundle ?? Bundle(for: VCType.self))
case .storyBoard(let storyboardId, let storyboardName, let bundle):
let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? Bundle(for: VCType.self))
return sb.instantiateViewController(withIdentifier: storyboardId) as! VCType
}
}
}
/**
Defines how a controller should be presented.
- Show?: Shows the controller with `showViewController(...)`.
- PresentModally?: Presents the controller modally.
- SegueName?: Performs the segue with the specified identifier (name).
- SegueClass?: Performs a segue from a segue class.
*/
public enum PresentationMode<VCType: UIViewController> {
/**
* Shows the controller, created by the specified provider, with `showViewController(...)`.
*/
case show(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?)
/**
* Presents the controller, created by the specified provider, modally.
*/
case presentModally(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?)
/**
* Performs the segue with the specified identifier (name).
*/
case segueName(segueName: String, onDismiss: ((UIViewController) -> Void)?)
/**
* Performs a segue from a segue class.
*/
case segueClass(segueClass: UIStoryboardSegue.Type, onDismiss: ((UIViewController) -> Void)?)
case popover(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?)
public var onDismissCallback: ((UIViewController) -> Void)? {
switch self {
case .show(_, let completion):
return completion
case .presentModally(_, let completion):
return completion
case .segueName(_, let completion):
return completion
case .segueClass(_, let completion):
return completion
case .popover(_, let completion):
return completion
}
}
/**
Present the view controller provided by PresentationMode. Should only be used from custom row implementation.
- parameter viewController: viewController to present if it makes sense (normally provided by makeController method)
- parameter row: associated row
- parameter presentingViewController: form view controller
*/
public func present(_ viewController: VCType!, row: BaseRow, presentingController: FormViewController) {
switch self {
case .show(_, _):
presentingController.show(viewController, sender: row)
case .presentModally(_, _):
presentingController.present(viewController, animated: true)
case .segueName(let segueName, _):
presentingController.performSegue(withIdentifier: segueName, sender: row)
case .segueClass(let segueClass, _):
let segue = segueClass.init(identifier: row.tag, source: presentingController, destination: viewController)
presentingController.prepare(for: segue, sender: row)
segue.perform()
case .popover(_, _):
guard let porpoverController = viewController.popoverPresentationController else {
fatalError()
}
porpoverController.sourceView = porpoverController.sourceView ?? presentingController.tableView
presentingController.present(viewController, animated: true)
}
}
/**
Creates the view controller specified by presentation mode. Should only be used from custom row implementation.
- returns: the created view controller or nil depending on the PresentationMode type.
*/
public func makeController() -> VCType? {
switch self {
case .show(let controllerProvider, let completionCallback):
let controller = controllerProvider.makeController()
let completionController = controller as? RowControllerType
if let callback = completionCallback {
completionController?.onDismissCallback = callback
}
return controller
case .presentModally(let controllerProvider, let completionCallback):
let controller = controllerProvider.makeController()
let completionController = controller as? RowControllerType
if let callback = completionCallback {
completionController?.onDismissCallback = callback
}
return controller
case .popover(let controllerProvider, let completionCallback):
let controller = controllerProvider.makeController()
controller.modalPresentationStyle = .popover
let completionController = controller as? RowControllerType
if let callback = completionCallback {
completionController?.onDismissCallback = callback
}
return controller
default:
return nil
}
}
}
/**
* Protocol to be implemented by custom formatters.
*/
public protocol FormatterProtocol {
func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition
}
// MARK: Predicate Machine
enum ConditionType {
case hidden, disabled
}
/**
Enumeration that are used to specify the disbaled and hidden conditions of rows
- Function: A function that calculates the result
- Predicate: A predicate that returns the result
*/
public enum Condition {
/**
* Calculate the condition inside a block
*
* @param Array of tags of the rows this function depends on
* @param Form->Bool The block that calculates the result
*
* @return If the condition is true or false
*/
case function([String], (Form)->Bool)
/**
* Calculate the condition using a NSPredicate
*
* @param NSPredicate The predicate that will be evaluated
*
* @return If the condition is true or false
*/
case predicate(NSPredicate)
}
extension Condition : ExpressibleByBooleanLiteral {
/**
Initialize a condition to return afixed boolean value always
*/
public init(booleanLiteral value: Bool) {
self = Condition.function([]) { _ in return value }
}
}
extension Condition : ExpressibleByStringLiteral {
/**
Initialize a Condition with a string that will be converted to a NSPredicate
*/
public init(stringLiteral value: String) {
self = .predicate(NSPredicate(format: value))
}
/**
Initialize a Condition with a string that will be converted to a NSPredicate
*/
public init(unicodeScalarLiteral value: String) {
self = .predicate(NSPredicate(format: value))
}
/**
Initialize a Condition with a string that will be converted to a NSPredicate
*/
public init(extendedGraphemeClusterLiteral value: String) {
self = .predicate(NSPredicate(format: value))
}
}
// MARK: Errors
/**
Errors thrown by Eureka
- DuplicatedTag: When a section or row is inserted whose tag dows already exist
*/
public enum EurekaError: Error {
case duplicatedTag(tag: String)
}
//Mark: FormViewController
/**
* A protocol implemented by FormViewController
*/
public protocol FormViewControllerProtocol {
var tableView: UITableView! { get }
func beginEditing<T>(of: Cell<T>)
func endEditing<T>(of: Cell<T>)
func insertAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation
func deleteAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation
func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation
func insertAnimation(forSections sections: [Section]) -> UITableViewRowAnimation
func deleteAnimation(forSections sections: [Section]) -> UITableViewRowAnimation
func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation
}
/**
* Navigation options for a form view controller.
*/
public struct RowNavigationOptions: OptionSet {
private enum NavigationOptions: Int {
case disabled = 0, enabled = 1, stopDisabledRow = 2, skipCanNotBecomeFirstResponderRow = 4
}
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue}
private init(_ options: NavigationOptions ) { self.rawValue = options.rawValue }
/// No navigation.
public static let Disabled = RowNavigationOptions(.disabled)
/// Full navigation.
public static let Enabled = RowNavigationOptions(.enabled)
/// Break navigation when next row is disabled.
public static let StopDisabledRow = RowNavigationOptions(.stopDisabledRow)
/// Break navigation when next row cannot become first responder.
public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.skipCanNotBecomeFirstResponderRow)
}
/**
* Defines the configuration for the keyboardType of FieldRows.
*/
public struct KeyboardReturnTypeConfiguration {
/// Used when the next row is available.
public var nextKeyboardType = UIReturnKeyType.next
/// Used if next row is not available.
public var defaultKeyboardType = UIReturnKeyType.default
public init() {}
public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType) {
self.nextKeyboardType = nextKeyboardType
self.defaultKeyboardType = defaultKeyboardType
}
}
/**
* Options that define when an inline row should collapse.
*/
public struct InlineRowHideOptions: OptionSet {
private enum _InlineRowHideOptions: Int {
case never = 0, anotherInlineRowIsShown = 1, firstResponderChanges = 2
}
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue}
private init(_ options: _InlineRowHideOptions ) { self.rawValue = options.rawValue }
/// Never collapse automatically. Only when user taps inline row.
public static let Never = InlineRowHideOptions(.never)
/// Collapse qhen another inline row expands. Just one inline row will be expanded at a time.
public static let AnotherInlineRowIsShown = InlineRowHideOptions(.anotherInlineRowIsShown)
/// Collapse when first responder changes.
public static let FirstResponderChanges = InlineRowHideOptions(.firstResponderChanges)
}
/// View controller that shows a form.
open class FormViewController: UIViewController, FormViewControllerProtocol, FormDelegate {
@IBOutlet public var tableView: UITableView!
private lazy var _form: Form = { [weak self] in
let form = Form()
form.delegate = self
return form
}()
public var form: Form {
get { return _form }
set {
guard form !== newValue else { return }
_form.delegate = nil
tableView?.endEditing(false)
_form = newValue
_form.delegate = self
if isViewLoaded {
tableView?.reloadData()
}
}
}
/// Extra space to leave between between the row in focus and the keyboard
open var rowKeyboardSpacing: CGFloat = 0
/// Enables animated scrolling on row navigation
open var animateScroll = false
/// Accessory view that is responsible for the navigation between rows
open var navigationAccessoryView: NavigationAccessoryView!
/// Defines the behaviour of the navigation between rows
public var navigationOptions: RowNavigationOptions?
private var tableViewStyle: UITableViewStyle = .grouped
public init(style: UITableViewStyle) {
super.init(nibName: nil, bundle: nil)
tableViewStyle = style
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func viewDidLoad() {
super.viewDidLoad()
navigationAccessoryView = NavigationAccessoryView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44.0))
navigationAccessoryView.autoresizingMask = .flexibleWidth
if tableView == nil {
tableView = UITableView(frame: view.bounds, style: tableViewStyle)
tableView.autoresizingMask = UIViewAutoresizing.flexibleWidth.union(.flexibleHeight)
if #available(iOS 9.0, *) {
tableView.cellLayoutMarginsFollowReadableWidth = false
}
}
if tableView.superview == nil {
view.addSubview(tableView)
}
if tableView.delegate == nil {
tableView.delegate = self
}
if tableView.dataSource == nil {
tableView.dataSource = self
}
tableView.estimatedRowHeight = BaseRow.estimatedRowHeight
tableView.setEditing(true, animated: false)
tableView.allowsSelectionDuringEditing = true
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
animateTableView = true
let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? []
if !selectedIndexPaths.isEmpty {
tableView.reloadRows(at: selectedIndexPaths, with: .none)
}
selectedIndexPaths.forEach {
tableView.selectRow(at: $0, animated: false, scrollPosition: .none)
}
let deselectionAnimation = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in
selectedIndexPaths.forEach {
self?.tableView.deselectRow(at: $0, animated: context.isAnimated)
}
}
let reselection = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in
if context.isCancelled {
selectedIndexPaths.forEach {
self?.tableView.selectRow(at: $0, animated: false, scrollPosition: .none)
}
}
}
if let coordinator = transitionCoordinator {
coordinator.animate(alongsideTransition: deselectionAnimation, completion: reselection)
} else {
selectedIndexPaths.forEach {
tableView.deselectRow(at: $0, animated: false)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil)
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let baseRow = sender as? BaseRow
baseRow?.prepare(for: segue)
}
/**
Returns the navigation accessory view if it is enabled. Returns nil otherwise.
*/
open func inputAccessoryView(for row: BaseRow) -> UIView? {
let options = navigationOptions ?? Form.defaultNavigationOptions
guard options.contains(.Enabled) else { return nil }
guard row.baseCell.cellCanBecomeFirstResponder() else { return nil}
navigationAccessoryView.previousButton.isEnabled = nextRow(for: row, withDirection: .up) != nil
navigationAccessoryView.doneButton.target = self
navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:))
navigationAccessoryView.previousButton.target = self
navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:))
navigationAccessoryView.nextButton.target = self
navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:))
navigationAccessoryView.nextButton.isEnabled = nextRow(for: row, withDirection: .down) != nil
return navigationAccessoryView
}
// MARK: FormViewControllerProtocol
/**
Called when a cell becomes first responder
*/
public final func beginEditing<T>(of cell: Cell<T>) {
cell.row.isHighlighted = true
cell.row.updateCell()
RowDefaults.onCellHighlightChanged["\(type(of: cell.row!))"]?(cell, cell.row)
cell.row.callbackOnCellHighlightChanged?()
guard let _ = tableView, (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return }
let row = cell.baseRow
let inlineRow = row?._inlineRow
for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) {
if let inlineRow = row as? BaseInlineRowType {
inlineRow.collapseInlineRow()
}
}
}
/**
Called when a cell resigns first responder
*/
public final func endEditing<T>(of cell: Cell<T>) {
cell.row.isHighlighted = false
cell.row.wasBlurred = true
RowDefaults.onCellHighlightChanged["\(type(of: self))"]?(cell, cell.row)
cell.row.callbackOnCellHighlightChanged?()
if cell.row.validationOptions.contains(.validatesOnBlur) || (cell.row.wasChanged && cell.row.validationOptions.contains(.validatesOnChangeAfterBlurred)) {
cell.row.validate()
}
cell.row.updateCell()
}
/**
Returns the animation for the insertion of the given rows.
*/
open func insertAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation {
return .fade
}
/**
Returns the animation for the deletion of the given rows.
*/
open func deleteAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation {
return .fade
}
/**
Returns the animation for the reloading of the given rows.
*/
open func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation {
return .automatic
}
/**
Returns the animation for the insertion of the given sections.
*/
open func insertAnimation(forSections sections: [Section]) -> UITableViewRowAnimation {
return .automatic
}
/**
Returns the animation for the deletion of the given sections.
*/
open func deleteAnimation(forSections sections: [Section]) -> UITableViewRowAnimation {
return .automatic
}
/**
Returns the animation for the reloading of the given sections.
*/
open func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation {
return .automatic
}
// MARK: TextField and TextView Delegate
open func textInputShouldBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
return true
}
open func textInputDidBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) {
if let row = cell.row as? KeyboardReturnHandler {
let next = nextRow(for: cell.row, withDirection: .down)
if let textField = textInput as? UITextField {
textField.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ??
(form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) :
(row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ??
Form.defaultKeyboardReturnType.defaultKeyboardType))
} else if let textView = textInput as? UITextView {
textView.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ??
(form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) :
(row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ??
Form.defaultKeyboardReturnType.defaultKeyboardType))
}
}
}
open func textInputShouldEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
return true
}
open func textInputDidEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) {
}
open func textInput<T>(_ textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool {
return true
}
open func textInputShouldClear<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
return true
}
open func textInputShouldReturn<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool {
if let nextRow = nextRow(for: cell.row, withDirection: .down) {
if nextRow.baseCell.cellCanBecomeFirstResponder() {
nextRow.baseCell.cellBecomeFirstResponder()
return true
}
}
tableView?.endEditing(true)
return true
}
// MARK: FormDelegate
open func valueHasBeenChanged(for: BaseRow, oldValue: Any?, newValue: Any?) {}
// MARK: UITableViewDelegate
@objc open func tableView(_ tableView: UITableView, willBeginReorderingRowAtIndexPath indexPath: IndexPath) {
// end editing if inline cell is first responder
let row = form[indexPath]
if let inlineRow = row as? BaseInlineRowType, row._inlineRow != nil {
inlineRow.collapseInlineRow()
}
}
// MARK: FormDelegate
open func sectionsHaveBeenAdded(_ sections: [Section], at indexes: IndexSet) {
guard animateTableView else { return }
tableView?.beginUpdates()
tableView?.insertSections(indexes, with: insertAnimation(forSections: sections))
tableView?.endUpdates()
}
open func sectionsHaveBeenRemoved(_ sections: [Section], at indexes: IndexSet) {
guard animateTableView else { return }
tableView?.beginUpdates()
tableView?.deleteSections(indexes, with: deleteAnimation(forSections: sections))
tableView?.endUpdates()
}
open func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at indexes: IndexSet) {
guard animateTableView else { return }
tableView?.beginUpdates()
tableView?.reloadSections(indexes, with: reloadAnimation(oldSections: oldSections, newSections: newSections))
tableView?.endUpdates()
}
open func rowsHaveBeenAdded(_ rows: [BaseRow], at indexes: [IndexPath]) {
guard animateTableView else { return }
tableView?.beginUpdates()
tableView?.insertRows(at: indexes, with: insertAnimation(forRows: rows))
tableView?.endUpdates()
}
open func rowsHaveBeenRemoved(_ rows: [BaseRow], at indexes: [IndexPath]) {
guard animateTableView else { return }
tableView?.beginUpdates()
tableView?.deleteRows(at: indexes, with: deleteAnimation(forRows: rows))
tableView?.endUpdates()
}
open func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at indexes: [IndexPath]) {
guard animateTableView else { return }
tableView?.beginUpdates()
tableView?.reloadRows(at: indexes, with: reloadAnimation(oldRows: oldRows, newRows: newRows))
tableView?.endUpdates()
}
// MARK: Private
var oldBottomInset: CGFloat?
var animateTableView = false
}
extension FormViewController : UITableViewDelegate {
// MARK: UITableViewDelegate
open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return indexPath
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard tableView == self.tableView else { return }
let row = form[indexPath]
// row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds.
if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() {
self.tableView?.endEditing(true)
}
row.didSelect()
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard tableView == self.tableView else { return tableView.rowHeight }
let row = form[indexPath.section][indexPath.row]
return row.baseCell.height?() ?? tableView.rowHeight
}
open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
guard tableView == self.tableView else { return tableView.rowHeight }
let row = form[indexPath.section][indexPath.row]
return row.baseCell.height?() ?? tableView.estimatedRowHeight
}
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return form[section].header?.viewForSection(form[section], type: .header)
}
open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return form[section].footer?.viewForSection(form[section], type:.footer)
}
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let height = form[section].header?.height {
return height()
}
guard let view = form[section].header?.viewForSection(form[section], type: .header) else {
return UITableViewAutomaticDimension
}
guard view.bounds.height != 0 else {
return UITableViewAutomaticDimension
}
return view.bounds.height
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if let height = form[section].footer?.height {
return height()
}
guard let view = form[section].footer?.viewForSection(form[section], type: .footer) else {
return UITableViewAutomaticDimension
}
guard view.bounds.height != 0 else {
return UITableViewAutomaticDimension
}
return view.bounds.height
}
open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
guard let section = form[indexPath.section] as? MultivaluedSection else { return false }
let row = form[indexPath]
guard !row.isDisabled else { return false }
guard !(indexPath.row == section.count - 1 && section.multivaluedOptions.contains(.Insert) && section.showInsertIconInAddButton) else {
return true
}
if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil {
return false
}
return true
}
open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let row = form[indexPath]
let section = row.section!
if let _ = row.baseCell.findFirstResponder() {
tableView.endEditing(true)
}
section.remove(at: indexPath.row)
DispatchQueue.main.async {
tableView.isEditing = !tableView.isEditing
tableView.isEditing = !tableView.isEditing
}
} else if editingStyle == .insert {
guard var section = form[indexPath.section] as? MultivaluedSection else { return }
guard let multivaluedRowToInsertAt = section.multivaluedRowToInsertAt else {
fatalError("Multivalued section multivaluedRowToInsertAt property must be set up")
}
let newRow = multivaluedRowToInsertAt(max(0, section.count - 1))
section.insert(newRow, at: section.count - 1)
DispatchQueue.main.async {
tableView.isEditing = !tableView.isEditing
tableView.isEditing = !tableView.isEditing
}
tableView.scrollToRow(at: IndexPath(row: section.count - 1, section: indexPath.section), at: .bottom, animated: true)
if newRow.baseCell.cellCanBecomeFirstResponder() {
newRow.baseCell.cellBecomeFirstResponder()
} else if let inlineRow = newRow as? BaseInlineRowType {
inlineRow.expandInlineRow()
}
}
}
open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
guard let section = form[indexPath.section] as? MultivaluedSection, section.multivaluedOptions.contains(.Reorder) && section.count > 1 else {
return false
}
if section.multivaluedOptions.contains(.Insert) && (section.count <= 2 || indexPath.row == (section.count - 1)) {
return false
}
if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil {
return false
}
return true
}
open func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard let section = form[sourceIndexPath.section] as? MultivaluedSection else { return sourceIndexPath }
guard sourceIndexPath.section == proposedDestinationIndexPath.section else { return sourceIndexPath }
let destRow = form[proposedDestinationIndexPath]
if destRow is BaseInlineRowType && destRow._inlineRow != nil {
return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section)
}
if proposedDestinationIndexPath.row > 0 {
let previousRow = form[IndexPath(row: proposedDestinationIndexPath.row - 1, section: proposedDestinationIndexPath.section)]
if previousRow is BaseInlineRowType && previousRow._inlineRow != nil {
return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section)
}
}
if section.multivaluedOptions.contains(.Insert) && proposedDestinationIndexPath.row == section.count - 1 {
return IndexPath(row: section.count - 2, section: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard var section = form[sourceIndexPath.section] as? MultivaluedSection else { return }
if sourceIndexPath.row < section.count && destinationIndexPath.row < section.count && sourceIndexPath.row != destinationIndexPath.row {
let sourceRow = form[sourceIndexPath]
animateTableView = false
section.remove(at: sourceIndexPath.row)
section.insert(sourceRow, at: destinationIndexPath.row)
animateTableView = true
// update the accessory view
let _ = inputAccessoryView(for: sourceRow)
}
}
open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
guard let section = form[indexPath.section] as? MultivaluedSection else {
return .none
}
if section.multivaluedOptions.contains(.Insert) && indexPath.row == section.count - 1 {
return .insert
}
if section.multivaluedOptions.contains(.Delete) {
return .delete
}
return .none
}
open func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return self.tableView(tableView, editingStyleForRowAt: indexPath) != .none
}
}
extension FormViewController : UITableViewDataSource {
// MARK: UITableViewDataSource
open func numberOfSections(in tableView: UITableView) -> Int {
return form.count
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return form[section].count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
form[indexPath].updateCell()
return form[indexPath].baseCell
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return form[section].header?.title
}
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return form[section].footer?.title
}
}
extension FormViewController : UIScrollViewDelegate {
// MARK: UIScrollViewDelegate
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
guard let tableView = tableView, scrollView === tableView else { return }
tableView.endEditing(true)
}
}
extension FormViewController {
// MARK: KeyBoard Notifications
/**
Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary.
*/
@objc open func keyboardWillShow(_ notification: Notification) {
guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return }
let keyBoardInfo = notification.userInfo!
let endFrame = keyBoardInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
let keyBoardFrame = table.window!.convert(endFrame.cgRectValue, to: table.superview)
let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y + rowKeyboardSpacing
var tableInsets = table.contentInset
var scrollIndicatorInsets = table.scrollIndicatorInsets
oldBottomInset = oldBottomInset ?? tableInsets.bottom
if newBottomInset > oldBottomInset! {
tableInsets.bottom = newBottomInset
scrollIndicatorInsets.bottom = tableInsets.bottom
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double))
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int))!)
table.contentInset = tableInsets
table.scrollIndicatorInsets = scrollIndicatorInsets
if let selectedRow = table.indexPath(for: cell) {
table.scrollToRow(at: selectedRow, at: .none, animated: animateScroll)
}
UIView.commitAnimations()
}
}
/**
Called when the keyboard will disappear. Adjusts insets of the tableView.
*/
@objc open func keyboardWillHide(_ notification: Notification) {
guard let table = tableView, let oldBottom = oldBottomInset else { return }
let keyBoardInfo = notification.userInfo!
var tableInsets = table.contentInset
var scrollIndicatorInsets = table.scrollIndicatorInsets
tableInsets.bottom = oldBottom
scrollIndicatorInsets.bottom = tableInsets.bottom
oldBottomInset = nil
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double))
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int))!)
table.contentInset = tableInsets
table.scrollIndicatorInsets = scrollIndicatorInsets
UIView.commitAnimations()
}
}
public enum Direction { case up, down }
extension FormViewController {
// MARK: Navigation Methods
@objc func navigationDone(_ sender: UIBarButtonItem) {
tableView?.endEditing(true)
}
@objc func navigationAction(_ sender: UIBarButtonItem) {
navigateTo(direction: sender == navigationAccessoryView.previousButton ? .up : .down)
}
public func navigateTo(direction: Direction) {
guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return }
guard let currentIndexPath = tableView?.indexPath(for: currentCell) else { assertionFailure(); return }
guard let nextRow = nextRow(for: form[currentIndexPath], withDirection: direction) else { return }
if nextRow.baseCell.cellCanBecomeFirstResponder() {
tableView?.scrollToRow(at: nextRow.indexPath!, at: .none, animated: animateScroll)
nextRow.baseCell.cellBecomeFirstResponder(withDirection: direction)
}
}
func nextRow(for currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? {
let options = navigationOptions ?? Form.defaultNavigationOptions
guard options.contains(.Enabled) else { return nil }
guard let next = direction == .down ? form.nextRow(for: currentRow) : form.previousRow(for: currentRow) else { return nil }
if next.isDisabled && options.contains(.StopDisabledRow) {
return nil
}
if !next.baseCell.cellCanBecomeFirstResponder() && !next.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow) {
return nil
}
if !next.isDisabled && next.baseCell.cellCanBecomeFirstResponder() {
return next
}
return nextRow(for: next, withDirection:direction)
}
}
extension FormViewControllerProtocol {
// MARK: Helpers
func makeRowVisible(_ row: BaseRow) {
guard let cell = row.baseCell, let indexPath = row.indexPath, let tableView = tableView else { return }
if cell.window == nil || (tableView.contentOffset.y + tableView.frame.size.height <= cell.frame.origin.y + cell.frame.size.height) {
tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
}
}
| dd1e2322851a60776b71fc6b5308e321 | 39.47318 | 185 | 0.669735 | false | false | false | false |
ParsifalC/CPCollectionViewKit | refs/heads/master | Demos/CPCollectionViewTimeMachineLayoutDemo/CPCollectionViewTimeMachineLayoutDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// CPCollectionViewTimeMachineLayoutDemo
//
// Created by Parsifal on 2017/2/15.
// Copyright © 2017年 Parsifal. All rights reserved.
//
import UIKit
import CPCollectionViewKit
class ViewController: UIViewController {
let cellIdentifier = "CPCollectionViewCell"
@IBOutlet weak var collectionView: UICollectionView!
var timeMachineLayout: CollectionViewTimeMachineLayout!
var layoutConfiguration: TimeMachineLayoutConfiguration!
var colorsArray = [UIColor]()
@IBOutlet weak var spacingXSlider: UISlider!
@IBOutlet weak var spacingYSlider: UISlider!
@IBOutlet weak var reversedSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
for _ in 0...19 {
colorsArray.append(randomColor())
}
timeMachineLayout = collectionView.collectionViewLayout as! CollectionViewTimeMachineLayout
layoutConfiguration = timeMachineLayout.configuration
layoutConfiguration.cellSize = CGSize(width: 250, height: 250)
layoutConfiguration.visibleCount = 6
layoutConfiguration.scaleFactor = 0.8
layoutConfiguration.spacingX = CGFloat(spacingXSlider.value)
layoutConfiguration.spacingY = CGFloat(spacingYSlider.value)
layoutConfiguration.reversed = reversedSwitch.isOn
}
func randomColor() -> UIColor {
return UIColor.init(_colorLiteralRed: Float(arc4random_uniform(256))/255.0, green: Float(arc4random_uniform(256))/255.0, blue: Float(arc4random_uniform(256))/255.0, alpha: 1)
}
func updateLayout(closure:() -> Void) {
timeMachineLayout.invalidateLayout()
closure()
collectionView.reloadData()
}
@IBAction func reversedValueChanged(_ sender: UISwitch) {
updateLayout {
layoutConfiguration.reversed = sender.isOn
}
}
@IBAction func spacingXValueChanged(_ sender: UISlider) {
updateLayout {
layoutConfiguration.spacingX = CGFloat(sender.value)
}
}
@IBAction func spacingYValueChanged(_ sender: UISlider) {
updateLayout {
layoutConfiguration.spacingY = CGFloat(sender.value)
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colorsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CPCollectionViewCell
cell.label.text = "\(indexPath.item)"
cell.backgroundColor = colorsArray[indexPath.item]
return cell
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let contentOffset = timeMachineLayout.contentOffsetFor(indexPath: indexPath)
collectionView.setContentOffset(contentOffset, animated: true)
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("current index:\(timeMachineLayout.currentIndex)")
}
}
| 39b46ca90a4fa8fe16ed98dd751ee548 | 32.89899 | 182 | 0.701132 | false | true | false | false |
aotian16/SwiftGCD | refs/heads/master | SwiftGCD/SwiftGCD/gcd.swift | mit | 1 | //
// gcd.swift
// TestGCD
//
// Created by 童进 on 16/5/7.
// Copyright © 2016年 qefee. All rights reserved.
//
import Foundation
public class gcd {
public static var sharedMain = gcd.main()
public static var sharedGlobalHigh = gcd.globalHigh()
public static var sharedGlobalDefault = gcd.globalDefault()
public static var sharedGlobalLow = gcd.globalLow()
public static var sharedGlobalBackground = gcd.globalBackground()
/**
main queue
- returns: main queue
*/
public class func main() -> GCDQueue {
let main = dispatch_get_main_queue()
let queue = GCDQueue(queue: main)
return queue
}
/**
global queue
- parameter priority: priority(default = GCDPriority.DEFAULT)
- returns: global queue
*/
public class func global(priority: GCDPriority = GCDPriority.DEFAULT) -> GCDQueue {
var identifier: dispatch_queue_priority_t!
switch priority {
case GCDPriority.HIGH:
identifier = DISPATCH_QUEUE_PRIORITY_HIGH
case GCDPriority.DEFAULT:
identifier = DISPATCH_QUEUE_PRIORITY_DEFAULT
case GCDPriority.LOW:
identifier = DISPATCH_QUEUE_PRIORITY_LOW
default:
identifier = DISPATCH_QUEUE_PRIORITY_BACKGROUND
}
let global = dispatch_get_global_queue(identifier, 0)
let queue = GCDQueue(queue: global)
return queue
}
/**
global high priority queue
- returns: global high priority queue
*/
public class func globalHigh() -> GCDQueue {
return global(GCDPriority.HIGH)
}
/**
global default priority queue
- returns: global default priority queue
*/
public class func globalDefault() -> GCDQueue {
return global(GCDPriority.DEFAULT)
}
/**
global low priority queue
- returns: global low priority queue
*/
public class func globalLow() -> GCDQueue {
return global(GCDPriority.LOW)
}
/**
global background priority queue
- returns: global background priority queue
*/
public class func globalBackground() -> GCDQueue {
return global(GCDPriority.BACKGROUND)
}
/**
custom queue
- parameter label: label
- parameter type: type (1. serial 2. concurrent)
- returns: custom queue
*/
public class func custom(label: String, type: GCDQueueType = GCDQueueType.CONCURRENT) -> GCDQueue {
var attr: dispatch_queue_attr_t!
switch type {
case GCDQueueType.SERIAL:
attr = DISPATCH_QUEUE_SERIAL
default:
attr = DISPATCH_QUEUE_CONCURRENT
}
let create = dispatch_queue_create(label, attr)
let queue = GCDQueue(queue: create)
return queue
}
/**
group
- returns: group
*/
public class func group() -> GCDGroup {
let group = dispatch_group_create()
return GCDGroup(group: group)
}
} | b4140f952f54d2c3fbc3e8e6b02a9edb | 24.304 | 103 | 0.586654 | false | false | false | false |
kildevaeld/FASlideView | refs/heads/master | Example/Pods/Nimble/Nimble/Wrappers/ObjCMatcher.swift | mit | 1 | import Foundation
struct ObjCMatcherWrapper : Matcher {
let matcher: NMBMatcher
let to: String
let toNot: String
func matches(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
failureMessage.to = to
return matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location)
}
func doesNotMatch(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
failureMessage.to = toNot
return matcher.doesNotMatch(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location)
}
}
// Equivalent to Expectation, but simplified for ObjC objects only
public class NMBExpectation : NSObject {
let _actualBlock: () -> NSObject!
var _negative: Bool
let _file: String
let _line: UInt
var _timeout: NSTimeInterval = 1.0
public init(actualBlock: () -> NSObject!, negative: Bool, file: String, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
public var withTimeout: (NSTimeInterval) -> NMBExpectation {
return ({ timeout in self._timeout = timeout
return self
})
}
public var to: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(self._file, line: self._line){ self._actualBlock() as NSObject? }.to(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not")
)
})
}
public var toNot: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(self._file, line: self._line){ self._actualBlock() as NSObject? }.toNot(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not")
)
})
}
public var notTo: (matcher: NMBMatcher) -> Void { return toNot }
public var toEventually: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventually(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"),
timeout: self._timeout
)
})
}
public var toEventuallyNot: (matcher: NMBMatcher) -> Void {
return ({ matcher in
expect(self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"),
timeout: self._timeout
)
})
}
}
typealias MatcherBlock = (actualExpression: Expression<NSObject>, failureMessage: FailureMessage, location: SourceLocation) -> Bool
typealias FullMatcherBlock = (actualExpression: Expression<NSObject>, failureMessage: FailureMessage, location: SourceLocation, shouldNotMatch: Bool) -> Bool
public class NMBObjCMatcher : NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
init(canMatchNil: Bool, matcher: MatcherBlock, notMatcher: MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
convenience init(matcher: MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
convenience init(canMatchNil: Bool, matcher: MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage, location in
return !matcher(actualExpression: actualExpression, failureMessage: failureMessage, location: location)
}))
}
convenience init(matcher: FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
convenience init(canMatchNil: Bool, matcher: FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage, location in
return matcher(actualExpression: actualExpression, failureMessage: failureMessage, location: location, shouldNotMatch: false)
}), notMatcher: ({ actualExpression, failureMessage, location in
return matcher(actualExpression: actualExpression, failureMessage: failureMessage, location: location, shouldNotMatch: true)
}))
}
private func canMatch(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
if !canMatchNil && actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
return true
}
public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: SourceLocation())
let result = _match(
actualExpression: expr,
failureMessage: failureMessage,
location: location)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: SourceLocation())
let result = _doesNotMatch(
actualExpression: expr,
failureMessage: failureMessage,
location: location)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
| 3202a9c5683b87cecf80d3f4af57d40e | 38.493151 | 157 | 0.650017 | false | false | false | false |
eigengo/lift | refs/heads/master | ios/Lift/LiveSessionController.swift | apache-2.0 | 3 | import Foundation
import UIKit
@objc
protocol MultiDeviceSessionSettable {
func multiDeviceSessionEncoding(session: MultiDeviceSession)
func mutliDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedBetween start: CFAbsoluteTime, and end: CFAbsoluteTime)
}
class LiveSessionController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, ExerciseSessionSettable,
DeviceSessionDelegate, DeviceDelegate, MultiDeviceSessionDelegate {
private var multi: MultiDeviceSession?
private var timer: NSTimer?
private var startTime: NSDate?
private var exerciseSession: ExerciseSession?
private var pageViewControllers: [UIViewController] = []
private var pageControl: UIPageControl!
@IBOutlet var stopSessionButton: UIBarButtonItem!
// MARK: main
override func viewWillDisappear(animated: Bool) {
if let x = timer { x.invalidate() }
navigationItem.prompt = nil
pageControl.removeFromSuperview()
pageControl = nil
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction
func stopSession() {
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Really?".localized()
stopSessionButton.tag = 3
} else {
end()
}
}
func end() {
if let x = exerciseSession {
x.end(const(()))
self.exerciseSession = nil
} else {
NSLog("[WARN] LiveSessionController.end() with sessionId == nil")
}
multi?.stop()
UIApplication.sharedApplication().idleTimerDisabled = false
if let x = navigationController {
x.popToRootViewControllerAnimated(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let pagesStoryboard = UIStoryboard(name: "LiveSession", bundle: nil)
pageViewControllers = ["classification", "devices", "sensorDataGroup"].map { pagesStoryboard.instantiateViewControllerWithIdentifier($0) as UIViewController }
setViewControllers([pageViewControllers.first!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
if let nc = navigationController {
let navBarSize = nc.navigationBar.bounds.size
let origin = CGPoint(x: navBarSize.width / 2, y: navBarSize.height / 2 + navBarSize.height / 4)
pageControl = UIPageControl(frame: CGRect(x: origin.x, y: origin.y, width: 0, height: 0))
pageControl.numberOfPages = 3
nc.navigationBar.addSubview(pageControl)
}
multiDeviceSessionEncoding(multi)
// propagate to children
if let session = exerciseSession {
pageViewControllers.foreach { e in
if let s = e as? ExerciseSessionSettable {
s.setExerciseSession(session)
}
}
}
startTime = NSDate()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
func tick() {
let elapsed = Int(NSDate().timeIntervalSinceDate(startTime!))
let minutes: Int = elapsed / 60
let seconds: Int = elapsed - minutes * 60
navigationItem.prompt = "LiveSessionController.elapsed".localized(minutes, seconds)
stopSessionButton.tag -= 1
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Stop".localized()
}
}
// MARK: ExerciseSessionSettable
func setExerciseSession(session: ExerciseSession) {
self.exerciseSession = session
multi = MultiDeviceSession(delegate: self, deviceDelegate: self, deviceSessionDelegate: self)
multi!.start()
UIApplication.sharedApplication().idleTimerDisabled = true
}
private func multiDeviceSessionEncoding(session: MultiDeviceSession?) {
if let x = session {
viewControllers.foreach { e in
if let s = e as? MultiDeviceSessionSettable {
s.multiDeviceSessionEncoding(x)
}
}
}
}
private func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedBetween start: CFAbsoluteTime, and end: CFAbsoluteTime) {
viewControllers.foreach { e in
if let s = e as? MultiDeviceSessionSettable {
s.mutliDeviceSession(session, continuousSensorDataEncodedBetween: start, and: end)
}
}
}
// MARK: UIPageViewControllerDataSource
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
if let x = (pageViewControllers.indexOf { $0 === viewController }) {
if x < pageViewControllers.count - 1 { return pageViewControllers[x + 1] }
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if let x = (pageViewControllers.indexOf { $0 === viewController }) {
if x > 0 { return pageViewControllers[x - 1] }
}
return nil
}
// MARK: UIPageViewControllerDelegate
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) {
if let x = (pageViewControllers.indexOf { $0 === pageViewController.viewControllers.first! }) {
pageControl.currentPage = x
}
}
// MARK: MultiDeviceSessionDelegate
func multiDeviceSession(session: MultiDeviceSession, encodingSensorDataGroup group: SensorDataGroup) {
multiDeviceSessionEncoding(multi)
}
func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedRange range: TimeRange) {
multiDeviceSession(session, continuousSensorDataEncodedBetween: range.start, and: range.end)
}
// MARK: DeviceSessionDelegate
func deviceSession(session: DeviceSession, endedFrom deviceId: DeviceId) {
end()
}
func deviceSession(session: DeviceSession, sensorDataNotReceivedFrom deviceId: DeviceId) {
// ???
}
func deviceSession(session: DeviceSession, sensorDataReceivedFrom deviceId: DeviceId, atDeviceTime: CFAbsoluteTime, data: NSData) {
if let x = exerciseSession {
x.submitData(data, f: const(()))
if UIApplication.sharedApplication().applicationState != UIApplicationState.Background {
multiDeviceSessionEncoding(multi)
}
} else {
RKDropdownAlert.title("Internal inconsistency", message: "AD received, but no sessionId.", backgroundColor: UIColor.orangeColor(), textColor: UIColor.blackColor(), time: 3)
}
}
// MARK: DeviceDelegate
func deviceGotDeviceInfo(deviceId: DeviceId, deviceInfo: DeviceInfo) {
multiDeviceSessionEncoding(multi)
}
func deviceGotDeviceInfoDetail(deviceId: DeviceId, detail: DeviceInfo.Detail) {
multiDeviceSessionEncoding(multi)
}
func deviceAppLaunched(deviceId: DeviceId) {
//
}
func deviceAppLaunchFailed(deviceId: DeviceId, error: NSError) {
//
}
func deviceDidNotConnect(error: NSError) {
multiDeviceSessionEncoding(multi)
}
func deviceDisconnected(deviceId: DeviceId) {
multiDeviceSessionEncoding(multi)
}
}
| 4b43f583a67b2e3a1ac943878a95474e | 36.932039 | 184 | 0.658178 | false | false | false | false |
crossroadlabs/Twist | refs/heads/master | Sources/Twist/Observable.swift | apache-2.0 | 1 | //===--- Observable.swift ----------------------------------------------===//
//Copyright (c) 2016 Crossroad Labs s.r.o.
//
//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 ExecutionContext
import Event
public protocol AccessableProtocol {
associatedtype Payload
func async(_ f:@escaping (Payload)->Void)
}
public enum ObservableWillChangeEvent<T> : Event {
public typealias Payload = T
case event
}
public enum ObservableDidChangeEvent<T> : Event {
public typealias Payload = T
case event
}
public struct ObservableEventGroup<T, E : Event> {
fileprivate let event:E
private init(_ event:E) {
self.event = event
}
public static var willChange:ObservableEventGroup<T, ObservableWillChangeEvent<T>> {
return ObservableEventGroup<T, ObservableWillChangeEvent<T>>(.event)
}
public static var didChange:ObservableEventGroup<T, ObservableDidChangeEvent<T>> {
return ObservableEventGroup<T, ObservableDidChangeEvent<T>>(.event)
}
}
public protocol ObservableProtocol : EventEmitter, SignalStreamProtocol {
associatedtype Payload
typealias ChangePayload = (Payload, Payload)
func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableWillChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload>
func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableDidChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload>
}
public extension ObservableProtocol {
public var stream:SignalStream<Payload> {
get {
return self.on(.didChange).map {(_, value) in value}
}
}
}
public extension ObservableProtocol where Self : AccessableProtocol {
var stream:SignalStream<Payload> {
get {
let node = SignalNode<Payload>(context: context)
let sig:Set<Int> = [self.signature]
//TODO: WTF?
let off = self.on(.didChange).map {(_, value) in value}.pour(to: node)
async { value in
node.signal(signature: sig, payload: value)
}
return node
}
}
}
public extension ObservableProtocol {
public func chain(_ f: @escaping Chainer) -> Off {
return self.on(.didChange).map {(_, value) in value}.chain(f)
}
}
public extension ObservableProtocol where Self : AccessableProtocol {
internal func chainNoInitial(_ f: @escaping Chainer) -> Off {
return self.on(.didChange).map {(_, value) in value}.chain(f)
}
public func chain(_ f: @escaping Chainer) -> Off {
let sig:Set<Int> = [self.signature]
let off = self.on(.didChange).map {(_, value) in value}.chain(f)
async { payload in
f((sig, payload))
}
return off
}
}
public extension SignalNodeProtocol where Self : ObservableProtocol, Self : AccessableProtocol {
public func bind<SN : SignalNodeProtocol>(to node: SN) -> Off where SN.Payload == Payload {
let forth = chainNoInitial(node.signal)
let back = subscribe(to: node)
return {
forth()
back()
}
}
}
public protocol MutableObservableProtocol : ObservableProtocol, AccessableProtocol, SignalNodeProtocol {
//function passed for mutation
typealias Mutator = (Signal<Payload>) -> Void
//current, mutator
func async(_ f:@escaping (Payload, Mutator)->Void)
func sync(_ f:@escaping (Payload, Mutator)->Void) -> Payload
}
public extension MutableObservableProtocol {
public func mutate(_ f:@escaping (Payload, (Payload)->Void)->Void) {
async { payload, mutator in
f(payload) { new in
mutator(([], new))
}
}
}
}
public extension MutableObservableProtocol {
func sync() -> Payload {
return sync {_,_ in}
}
}
public extension AccessableProtocol where Self : MutableObservableProtocol {
public func async(_ f:@escaping (Payload)->Void) {
self.async { value, _ in
f(value)
}
}
}
public protocol ParametrizableObservableProtocol : ObservableProtocol {
typealias Subscriber = (Bool) -> SignalStream<ChangePayload>
init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber)
}
public protocol ParametrizableMutableObservableProtocol : ParametrizableObservableProtocol, MutableObservableProtocol {
typealias Accessor = () -> Payload
typealias Mutator = (Signal<Payload>) -> Void
init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber, accessor:@escaping Accessor, mutator:@escaping Mutator)
}
public class ReadonlyObservable<T> : ParametrizableObservableProtocol {
public typealias Payload = T
public typealias ChangePayload = (Payload, Payload)
//early if true, late otherwise
public typealias Subscriber = (Bool) -> SignalStream<ChangePayload>
public let dispatcher:EventDispatcher = EventDispatcher()
public let context: ExecutionContextProtocol
private let _subscriber:Subscriber
public required init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber) {
self.context = context
self._subscriber = subscriber
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableWillChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return _subscriber(true)
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableDidChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return _subscriber(false)
}
}
public class MutableObservable<T> : ReadonlyObservable<T>, ParametrizableMutableObservableProtocol {
public typealias ChangePayload = (Payload, Payload)
public typealias Accessor = () -> Payload
public typealias Mutator = (Signal<Payload>) -> Void
private let _accessor:Accessor
private let _mutator:Mutator
public required init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber, accessor:@escaping Accessor, mutator:@escaping Mutator) {
self._accessor = accessor
self._mutator = mutator
super.init(context: context, subscriber: subscriber)
}
public required init(context: ExecutionContextProtocol, subscriber: @escaping Subscriber) {
fatalError("init(context:subscriber:) has not been implemented")
}
public func async(_ f: @escaping (T, Mutator) -> Void) {
context.immediateIfCurrent {
f(self._accessor(), self._mutator)
}
}
public func sync(_ f:@escaping (Payload, Mutator)->Void) -> T {
return context.sync {
f(self._accessor(), self._mutator)
return self._accessor()
}
}
}
//TODO: combine latest
public class ObservableValue<T> : MutableObservableProtocol {
public typealias Payload = T
//old, new
public typealias ChangePayload = (Payload, Payload)
//function passed for mutation
public typealias Mutator = (Signal<Payload>) -> Void
public let dispatcher:EventDispatcher = EventDispatcher()
public let context: ExecutionContextProtocol
private var _var:T
public init(_ value:T, context:ExecutionContextProtocol = ExecutionContext.current) {
_var = value
self.context = context
}
private func _mutate(signature:Set<Int>, value:T) {
let old = _var
self.emit(.willChange, payload: (old, value), signature: signature)
_var = value
self.emit(.didChange, payload: (old, value), signature: signature)
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableWillChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return self.on(groupedEvent.event)
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableDidChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return self.on(groupedEvent.event)
}
public func async(_ f:@escaping (Payload)->Void) {
context.immediateIfCurrent {
f(self._var)
}
}
//current, mutator
public func async(_ f:@escaping (Payload, Mutator)->Void) {
context.immediateIfCurrent {
f(self._var, self._mutate)
}
}
public func sync(_ f:@escaping (Payload, Mutator)->Void = {_,_ in}) -> T {
return context.sync {
f(self._var, self._mutate)
return self._var
}
}
}
extension MutableObservableProtocol {
fileprivate func emit<E : Event>(_ groupedEvent: ObservableEventGroup<ChangePayload, E>, payload:E.Payload, signature:Set<Int>) {
self.emit(groupedEvent.event, payload: payload, signature:signature)
}
}
extension MutableObservableProtocol {
public func signal(signature:Set<Int>, payload: Payload) {
async { _, mutator in
mutator((signature, payload))
}
}
}
| fd6ffe6a3da7040dee3e9a1e891b21dd | 32.249135 | 149 | 0.65959 | false | false | false | false |
huonw/swift | refs/heads/master | test/Compatibility/tuple_arguments_4.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift -swift-version 4
// See test/Compatibility/tuple_arguments_3.swift for the Swift 3 behavior.
func concrete(_ x: Int) {}
func concreteLabeled(x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
do {
concrete(3)
concrete((3))
concreteLabeled(x: 3)
concreteLabeled(x: (3))
concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}}
concreteTwo(3, 4)
concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
do {
generic(3)
generic(3, 4) // expected-error {{extra argument in call}}
generic((3))
generic((3, 4))
genericLabeled(x: 3)
genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
genericLabeled(x: (3))
genericLabeled(x: (3, 4))
genericTwo(3, 4)
genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
var function: (Int) -> ()
var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> ()
do {
function(3)
function((3))
functionTwo(3, 4)
functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
struct Concrete {}
extension Concrete {
func concrete(_ x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
}
do {
let s = Concrete()
s.concrete(3)
s.concrete((3))
s.concreteTwo(3, 4)
s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
extension Concrete {
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
}
do {
let s = Concrete()
s.generic(3)
s.generic(3, 4) // expected-error {{extra argument in call}}
s.generic((3))
s.generic((3, 4))
s.genericLabeled(x: 3)
s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.genericLabeled(x: (3))
s.genericLabeled(x: (3, 4))
s.genericTwo(3, 4)
s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
extension Concrete {
mutating func mutatingConcrete(_ x: Int) {}
mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}}
mutating func mutatingConcreteTuple(_ x: (Int, Int)) {}
}
do {
var s = Concrete()
s.mutatingConcrete(3)
s.mutatingConcrete((3))
s.mutatingConcreteTwo(3, 4)
s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
extension Concrete {
mutating func mutatingGeneric<T>(_ x: T) {}
mutating func mutatingGenericLabeled<T>(x: T) {}
mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {}
}
do {
var s = Concrete()
s.mutatingGeneric(3)
s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}}
s.mutatingGeneric((3))
s.mutatingGeneric((3, 4))
s.mutatingGenericLabeled(x: 3)
s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericLabeled(x: (3))
s.mutatingGenericLabeled(x: (3, 4))
s.mutatingGenericTwo(3, 4)
s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
extension Concrete {
var function: (Int) -> () { return concrete }
var functionTwo: (Int, Int) -> () { return concreteTwo }
var functionTuple: ((Int, Int)) -> () { return concreteTuple }
}
do {
let s = Concrete()
s.function(3)
s.function((3))
s.functionTwo(3, 4)
s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(3, 4) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
struct InitTwo {
init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init' declared here}}
}
struct InitTuple {
init(_ x: (Int, Int)) {}
}
struct InitLabeledTuple {
init(x: (Int, Int)) {}
}
do {
_ = InitTwo(3, 4)
_ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((3, 4))
_ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = InitLabeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
struct SubscriptTwo {
subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript' declared here}}
}
struct SubscriptTuple {
subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } }
}
struct SubscriptLabeledTuple {
subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } }
}
do {
let s1 = SubscriptTwo()
_ = s1[3, 4]
_ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}}
let s2 = SubscriptTuple()
_ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(3, 4)]
}
do {
let a = 3
let b = 4
let d = (a, b)
let s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s1[d] // expected-error {{missing argument for parameter #2 in call}}
let s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
let s3 = SubscriptLabeledTuple()
_ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}}
_ = s3[x: (3, 4)]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s1[d] // expected-error {{missing argument for parameter #2 in call}}
var s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
}
enum Enum {
case two(Int, Int) // expected-note 6 {{'two' declared here}}
case tuple((Int, Int))
case labeledTuple(x: (Int, Int))
}
do {
_ = Enum.two(3, 4)
_ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((3, 4))
_ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum element 'labeledTuple' expects a single parameter of type '(Int, Int)'}}
_ = Enum.labeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
struct Generic<T> {}
extension Generic {
func generic(_ x: T) {}
func genericLabeled(x: T) {}
func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}}
func genericTuple(_ x: (T, T)) {}
}
do {
let s = Generic<Double>()
s.generic(3.0)
s.generic((3.0))
s.genericLabeled(x: 3.0)
s.genericLabeled(x: (3.0))
s.genericTwo(3.0, 4.0)
s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}}
s.genericTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}}
sTwo.generic((3.0, 4.0))
sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.genericLabeled(x: (3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
extension Generic {
mutating func mutatingGeneric(_ x: T) {}
mutating func mutatingGenericLabeled(x: T) {}
mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple(_ x: (T, T)) {}
}
do {
var s = Generic<Double>()
s.mutatingGeneric(3.0)
s.mutatingGeneric((3.0))
s.mutatingGenericLabeled(x: 3.0)
s.mutatingGenericLabeled(x: (3.0))
s.mutatingGenericTwo(3.0, 4.0)
s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.mutatingGenericTuple((3.0, 4.0))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.mutatingGeneric((3.0, 4.0))
sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.mutatingGenericLabeled(x: (3.0, 4.0))
}
do {
var s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
extension Generic {
var genericFunction: (T) -> () { return generic }
var genericFunctionTwo: (T, T) -> () { return genericTwo }
var genericFunctionTuple: ((T, T)) -> () { return genericTuple }
}
do {
let s = Generic<Double>()
s.genericFunction(3.0)
s.genericFunction((3.0))
s.genericFunctionTwo(3.0, 4.0)
s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{34-34=)}}
s.genericFunctionTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{32-32=)}}
sTwo.genericFunction((3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
struct GenericInit<T> {
init(_ x: T) {}
}
struct GenericInitLabeled<T> {
init(x: T) {}
}
struct GenericInitTwo<T> {
init(_ x: T, _ y: T) {} // expected-note 10 {{'init' declared here}}
}
struct GenericInitTuple<T> {
init(_ x: (T, T)) {}
}
struct GenericInitLabeledTuple<T> {
init(x: (T, T)) {}
}
do {
_ = GenericInit(3, 4) // expected-error {{extra argument in call}}
_ = GenericInit((3, 4))
_ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled(x: (3, 4))
_ = GenericInitTwo(3, 4)
_ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((3, 4))
_ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}}
_ = GenericInitLabeledTuple(x: (3, 4))
}
do {
_ = GenericInit<(Int, Int)>(3, 4) // expected-error {{extra argument in call}}
_ = GenericInit<(Int, Int)>((3, 4))
_ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled<(Int, Int)>(x: (3, 4))
_ = GenericInitTwo<Int>(3, 4)
_ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((3, 4))
_ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}}
_ = GenericInitLabeledTuple<Int>(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{extra argument in call}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{extra argument in call}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
struct GenericSubscript<T> {
subscript(_ x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeled<T> {
subscript(x x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTwo<T> {
subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript' declared here}}
}
struct GenericSubscriptLabeledTuple<T> {
subscript(x x: (T, T)) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTuple<T> {
subscript(_ x: (T, T)) -> Int { get { return 0 } set { } }
}
do {
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[3.0, 4.0] // expected-error {{extra argument in call}}
_ = s1[(3.0, 4.0)]
let s1a = GenericSubscriptLabeled<(Double, Double)>()
_ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}}
_ = s1a [x: (3.0, 4.0)]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[3.0, 4.0]
_ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{18-18=)}}
_ = s3[(3.0, 4.0)]
let s3a = GenericSubscriptLabeledTuple<Double>()
_ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}}
_ = s3a[x: (3.0, 4.0)]
}
do {
let a = 3.0
let b = 4.0
let d = (a, b)
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{extra argument in call}}
_ = s1[(a, b)]
_ = s1[d]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s2[d] // expected-error {{missing argument for parameter #2 in call}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{extra argument in call}}
_ = s1[(a, b)]
_ = s1[d]
var s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s2[d] // expected-error {{missing argument for parameter #2 in call}}
var s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
enum GenericEnum<T> {
case one(T)
case labeled(x: T)
case two(T, T) // expected-note 10 {{'two' declared here}}
case tuple((T, T))
}
do {
_ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.one((3, 4))
_ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled(x: (3, 4))
_ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum.two(3, 4)
_ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((3, 4))
}
do {
_ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum element 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((3, 4))
_ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum element 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled(x: (3, 4))
_ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum element 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum<Int>.two(3, 4)
_ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum element 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum element 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum element 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
protocol Protocol {
associatedtype Element
}
extension Protocol {
func requirement(_ x: Element) {}
func requirementLabeled(x: Element) {}
func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}}
func requirementTuple(_ x: (Element, Element)) {}
}
struct GenericConforms<T> : Protocol {
typealias Element = T
}
do {
let s = GenericConforms<Double>()
s.requirement(3.0)
s.requirement((3.0))
s.requirementLabeled(x: 3.0)
s.requirementLabeled(x: (3.0))
s.requirementTwo(3.0, 4.0)
s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{30-30=)}}
s.requirementTuple((3.0, 4.0))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{28-28=)}}
sTwo.requirement((3.0, 4.0))
sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.requirementLabeled(x: (3.0, 4.0))
}
do {
let s = GenericConforms<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
do {
var s = GenericConforms<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
var sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
extension Protocol {
func takesClosure(_ fn: (Element) -> ()) {}
func takesClosureTwo(_ fn: (Element, Element) -> ()) {}
func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {}
}
do {
let s = GenericConforms<Double>()
s.takesClosure({ _ = $0 })
s.takesClosure({ x in })
s.takesClosure({ (x: Double) in })
s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ _ = $0; _ = $1 })
s.takesClosureTwo({ (x, y) in })
s.takesClosureTwo({ (x: Double, y:Double) in })
s.takesClosureTuple({ _ = $0 })
s.takesClosureTuple({ x in })
s.takesClosureTuple({ (x: (Double, Double)) in })
s.takesClosureTuple({ _ = $0; _ = $1 })
s.takesClosureTuple({ (x, y) in })
s.takesClosureTuple({ (x: Double, y:Double) in })
let sTwo = GenericConforms<(Double, Double)>()
sTwo.takesClosure({ _ = $0 })
sTwo.takesClosure({ x in })
sTwo.takesClosure({ (x: (Double, Double)) in })
sTwo.takesClosure({ _ = $0; _ = $1 })
sTwo.takesClosure({ (x, y) in })
sTwo.takesClosure({ (x: Double, y: Double) in })
}
do {
let _: ((Int, Int)) -> () = { _ = $0 }
let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) }
let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) }
let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}}
let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }}
let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0, $1) }
let _: (Int, Int) -> () = { t, u in _ = (t, u) }
}
// rdar://problem/28952837 - argument labels ignored when calling function
// with single 'Any' parameter
func takesAny(_: Any) {}
enum HasAnyCase {
case any(_: Any)
}
do {
let fn: (Any) -> () = { _ in }
fn(123)
fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
takesAny(123)
takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
_ = HasAnyCase.any(123)
_ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
}
// rdar://problem/29739905 - protocol extension methods on Array had
// ParenType sugar stripped off the element type
func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()],
f2: [(Bool, Bool) -> ()],
c: Bool) {
let p = (c, c)
f1.forEach { block in
block(p)
block((c, c))
block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}}
}
f2.forEach { block in
// expected-note@-1 2{{'block' declared here}}
block(p) // expected-error {{missing argument for parameter #2 in call}}
block((c, c)) // expected-error {{missing argument for parameter #2 in call}}
block(c, c)
}
f2.forEach { (block: ((Bool, Bool)) -> ()) in
// expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> ()' to expected argument type '((Bool, Bool) -> ()) -> Void}}
block(p)
block((c, c))
block(c, c)
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 2{{'block' declared here}}
block(p) // expected-error {{missing argument for parameter #2 in call}}
block((c, c)) // expected-error {{missing argument for parameter #2 in call}}
block(c, c)
}
}
// expected-error@+1 {{cannot create a single-element tuple with an element label}}
func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) {
// TODO: Error could be improved.
// expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}}
completion((didAdjust: true))
}
// SR-4378
final public class MutableProperty<Value> {
public init(_ initialValue: Value) {}
}
enum DataSourcePage<T> {
case notLoaded
}
let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: .notLoaded,
totalCount: 0
))
let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage.notLoaded,
totalCount: 0
))
let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage<Int>.notLoaded,
totalCount: 0
))
// SR-4745
let sr4745 = [1, 2]
let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" }
// SR-4738
let sr4738 = (1, (2, 3))
[sr4738].map { (x, (y, z)) -> Int in x + y + z } // expected-error {{use of undeclared type 'y'}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }}
// rdar://problem/31892961
let r31892961_1 = [1: 1, 2: 2]
r31892961_1.forEach { (k, v) in print(k + v) }
let r31892961_2 = [1, 2, 3]
let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }}
// expected-error@-2 {{use of undeclared type 'index'}}
val + 1
}
let r31892961_3 = (x: 1, y: 42)
_ = [r31892961_3].map { (x: Int, y: Int) in x + y }
_ = [r31892961_3].map { (x, y: Int) in x + y }
let r31892961_4 = (1, 2)
_ = [r31892961_4].map { x, y in x + y }
let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4)))
[r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y }
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }}
let r31892961_6 = (x: 1, (y: 2, z: 4))
[r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y }
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }}
// rdar://problem/32214649 -- these regressed in Swift 4 mode
// with SE-0110 because of a problem in associated type inference
func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] {
return a.map(f)
}
func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] {
return a.filter(f)
}
func r32214649_3<X>(_ a: [X]) -> [X] {
return a.filter { _ in return true }
}
// rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters
func rdar32301091_1(_ :((Int, Int) -> ())!) {}
rdar32301091_1 { _ in }
// expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '((Int, Int) -> ())?'}}
func rdar32301091_2(_ :(Int, Int) -> ()) {}
rdar32301091_2 { _ in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }}
rdar32301091_2 { x in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }}
func rdar32875953() {
let myDictionary = ["hi":1]
myDictionary.forEach {
print("\($0) -> \($1)")
}
myDictionary.forEach { key, value in
print("\(key) -> \(value)")
}
myDictionary.forEach { (key, value) in
print("\(key) -> \(value)")
}
let array1 = [1]
let array2 = [2]
_ = zip(array1, array2).map(+)
}
struct SR_5199 {}
extension Sequence where Iterator.Element == (key: String, value: String?) {
func f() -> [SR_5199] {
return self.map { (key, value) in
SR_5199() // Ok
}
}
}
func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] {
let x: [Int] = records.map { _ in
let i = 1
return i
}
let y: [Int] = other.map { _ in
let i = 1
return i
}
return x + y
}
func itsFalse(_: Int) -> Bool? {
return false
}
func rdar33159366(s: AnySequence<Int>) {
_ = s.compactMap(itsFalse)
let a = Array(s)
_ = a.compactMap(itsFalse)
}
func sr5429<T>(t: T) {
_ = AnySequence([t]).first(where: { (t: T) in true })
}
extension Concrete {
typealias T = (Int, Int)
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
extension Generic {
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
func rdar33239714() {
Concrete().opt1 { x, y in }
Concrete().opt1 { (x, y) in }
Concrete().opt2 { x, y in }
Concrete().opt2 { (x, y) in }
Concrete().opt3 { x, y in }
Concrete().opt3 { (x, y) in }
Concrete().optAliasT { x, y in }
Concrete().optAliasT { (x, y) in }
Concrete().optAliasF { x, y in }
Concrete().optAliasF { (x, y) in }
Generic<(Int, Int)>().opt1 { x, y in }
Generic<(Int, Int)>().opt1 { (x, y) in }
Generic<(Int, Int)>().opt2 { x, y in }
Generic<(Int, Int)>().opt2 { (x, y) in }
Generic<(Int, Int)>().opt3 { x, y in }
Generic<(Int, Int)>().opt3 { (x, y) in }
Generic<(Int, Int)>().optAliasT { x, y in }
Generic<(Int, Int)>().optAliasT { (x, y) in }
Generic<(Int, Int)>().optAliasF { x, y in }
Generic<(Int, Int)>().optAliasF { (x, y) in }
}
// rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above"
do {
func foo(_: (() -> Void)?) {}
func bar() -> ((()) -> Void)? { return nil }
foo(bar()) // Allow ((()) -> Void)? to be passed in place of (() -> Void)? for -swift-version 4 but not later.
}
// https://bugs.swift.org/browse/SR-6509
public extension Optional {
public func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? {
return self.flatMap { value in
transform.map { $0(value) }
}
}
public func apply<Value, Result>(_ value: Value?) -> Result?
where Wrapped == (Value) -> Result {
return value.apply(self)
}
}
// https://bugs.swift.org/browse/SR-6837
do {
func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {}
func takePair(_ pair: (Int, Int?)) {}
takeFn(fn: takePair) // Allow for -swift-version 4, but not later
takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// https://bugs.swift.org/browse/SR-6796
do {
func f(a: (() -> Void)? = nil) {}
func log<T>() -> ((T) -> Void)? { return nil }
f(a: log() as ((()) -> Void)?) // Allow ((()) -> Void)? to be passed in place of (() -> Void)? for -swift-version 4 but not later.
func logNoOptional<T>() -> (T) -> Void { }
f(a: logNoOptional() as ((()) -> Void)) // Also allow the optional-injected form.
func g() {}
g(()) // expected-error {{argument passed to call that takes no arguments}}
func h(_: ()) {} // expected-note {{'h' declared here}}
h() // expected-error {{missing argument for parameter #1 in call}}
}
// https://bugs.swift.org/browse/SR-7191
class Mappable<T> {
init(_: T) { }
func map<U>(_ body: (T) -> U) -> U { fatalError() }
}
let x = Mappable(())
_ = x.map { (_: Void) in return () }
| 682f662c18efa3d767e35d243bafee5d | 30.58799 | 187 | 0.618321 | false | false | false | false |
MillmanY/MMLocalization | refs/heads/master | Example/MMLocalization/ChooseLanguageTableViewController.swift | mit | 1 | //
// ChooseLanguageTableViewController.swift
// LocalLizeDemo
//
// Created by MILLMAN on 2016/7/8.
// Copyright © 2016年 MILLMAN. All rights reserved.
//
import UIKit
import MMLocalization
class ChooseLanguageTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
var string = ""
switch (indexPath as NSIndexPath).row {
case 0:
string = "ILocalizable_CH"
case 1:
string = "ILocalizable_EN"
case 2:
string = "ILocalizable_ID"
default: break
}
MMLocalization.set(type: .custom(tableName: string))
self.navigationController?.popViewController(animated: true)
}
// MARK: - Table view data source
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 683c63a47e63fbc947dd149f3367bfb6 | 32.711538 | 157 | 0.669424 | false | false | false | false |
yuzawa-san/ico-saver | refs/heads/master | Polyhedra/DefaultsManager.swift | mit | 1 | import ScreenSaver
class DefaultsManager {
private var defaults: UserDefaults
init() {
let identifier = Bundle(for: DefaultsManager.self).bundleIdentifier
defaults = ScreenSaverDefaults(forModuleWithName: identifier!)!
}
func synchronize() {
defaults.synchronize()
}
var polyhedronName: String {
get {
return defaults.string(forKey: "polyhedron_name") ?? PolyhedraRegistry.defaultName
}
set(value) {
defaults.setValue(value, forKey: "polyhedron_name")
}
}
var useColorOverride: Bool {
get {
return defaults.bool(forKey: "use_color_override")
}
set(value) {
defaults.setValue(value, forKey: "use_color_override")
}
}
var showPolyhedronName: Bool {
get {
return defaults.bool(forKey: "show_polyhedron_name")
}
set(value) {
defaults.setValue(value, forKey: "show_polyhedron_name")
}
}
var colorOverride: NSColor {
get {
guard
let storedData = defaults.data(forKey: "color_override"),
let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: storedData),
let color = unarchivedData as NSColor?
else {
return NSColor.red
}
return color
}
set(color) {
if let data = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) {
defaults.set(data, forKey: "color_override")
}
}
}
}
| 74b1ee550a399e1ef2456d73bb776295 | 27.305085 | 118 | 0.567066 | false | false | false | false |
CoderFeiSu/FFCategoryHUD | refs/heads/master | FFCategoryHUD/FFKeyboardLayout.swift | mit | 1 | //
// FFCategoryKeyboardLayout.swift
// FFCategoryHUDExample
//
// Created by Freedom on 2017/4/23.
// Copyright © 2017年 Freedom. All rights reserved.
//
import UIKit
public class FFCategoryKeyboardLayout: UICollectionViewLayout {
public var sectionInset: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
public var rowMargin: CGFloat = 10
public var colMargin: CGFloat = 10
public var rows: Int = 3
public var cols: Int = 7
fileprivate lazy var totalPages = 0
fileprivate lazy var attributes: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
fileprivate lazy var attrsWH: (CGFloat, CGFloat) = {
let attrsW = ((self.collectionView?.bounds.width)! - self.sectionInset.left - self.sectionInset.right - CGFloat(self.cols - 1) * self.colMargin) / CGFloat(self.cols)
let attrsH: CGFloat = ((self.collectionView?.bounds.height)! - self.sectionInset.top - self.sectionInset.bottom - CGFloat(self.rows - 1) * self.rowMargin) / CGFloat(self.rows)
return (attrsW, attrsH)
}()
}
extension FFCategoryKeyboardLayout {
override public func prepare() {
super.prepare()
guard let collectionView = collectionView else {return}
let sections = collectionView.numberOfSections
var previousTotalPages = 0
for section in 0..<sections {
let items = collectionView.numberOfItems(inSection: section)
for item in 0..<items {
let indexPath = IndexPath(item: item, section: section)
let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
let currentPage = item / (rows * cols)
let currentIndex = item % (rows * cols)
let attrsX = CGFloat(previousTotalPages + currentPage) * collectionView.bounds.width + sectionInset.left + CGFloat(currentIndex % cols) * (colMargin + attrsWH.0)
let attrsY = sectionInset.top + CGFloat(currentIndex / cols) * (rowMargin + attrsWH.1)
attrs.frame = CGRect(x: attrsX, y: attrsY, width: attrsWH.0, height: attrsWH.1)
attributes.append(attrs)
}
previousTotalPages += ((items - 1) / (rows * cols) + 1)
}
totalPages = previousTotalPages
}
}
extension FFCategoryKeyboardLayout {
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
super.layoutAttributesForElements(in: rect)
return attributes
}
}
extension FFCategoryKeyboardLayout {
override public var collectionViewContentSize: CGSize {
return CGSize(width: CGFloat(totalPages) * (collectionView?.bounds.width ?? 1), height: 0)
}
}
| 36791f106671286250c2cbdd51ad481d | 37.164384 | 184 | 0.662599 | false | false | false | false |
yuzumikan15/SmileDetector | refs/heads/master | SmileDetector/ViewController.swift | mit | 1 | //
// ViewController.swift
// SmileDetector
//
// Created by Yuki Ishii on 2015/07/19.
// Copyright (c) 2015年 Yuki Ishii. All rights reserved.
//
import UIKit
import AVFoundation
import SpriteKit
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
// for animation (SpriteKit)
lazy var skView = SKView()
lazy var smileView = SmileView(size: CGSizeMake(0, 0))
// for face detection (CIFaceFeature)
lazy var session = AVCaptureSession()
// lazy var device = AVCaptureDevice()
lazy var output = AVCaptureVideoDataOutput()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupSKView()
setupSmileView()
if initCamera() {
session.startRunning()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupSKView () {
skView = SKView(frame: self.view.frame)
self.view.addSubview(skView)
skView.multipleTouchEnabled = false
}
func setupSmileView () {
let size = skView.bounds.size
smileView = SmileView(size: size)
smileView.scaleMode = SKSceneScaleMode.AspectFill
skView.presentScene(smileView)
}
func initCamera () -> Bool {
session.sessionPreset = AVCaptureSessionPresetMedium
if let device = initDevice(),
input = AVCaptureDeviceInput.deviceInputWithDevice(device, error: nil) as? AVCaptureDeviceInput {
// set session input
if !session.canAddInput(input) {
return false
}
session.addInput(input)
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey : kCVPixelFormatType_32BGRA]
// set FPS
if !setupFPS(device) {
return false
}
// set delegate
let queue : dispatch_queue_t = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)
output.setSampleBufferDelegate(self, queue: queue)
output.alwaysDiscardsLateVideoFrames = true
// set session output
if !session.canAddOutput(output) {
return false
}
session.addOutput(output)
// set camera orientation
setupCameraOrientation()
return true
}
else {
return false
}
}
func initDevice () -> AVCaptureDevice? {
let devices = AVCaptureDevice.devices()
for d in devices {
if d.position == AVCaptureDevicePosition.Front {
return d as? AVCaptureDevice
}
}
return nil
}
func setupFPS (device : AVCaptureDevice) -> Bool {
var lockError : NSError?
if device.lockForConfiguration(&lockError) {
if let error = lockError {
return false
}
device.activeVideoMinFrameDuration = CMTimeMake(1, 15)
device.unlockForConfiguration()
return true
}
else {
return false
}
}
func setupCameraOrientation () {
for c in output.connections {
if let connection = c as? AVCaptureConnection {
if connection.supportsVideoOrientation {
connection.videoOrientation = AVCaptureVideoOrientation.Portrait
}
}
}
}
func detectFace (srcImage : CIImage) {
let options = [CIDetectorSmile:true]
let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
let features = detector.featuresInImage(srcImage, options: options)
for f in features {
if let feature = f as? CIFaceFeature {
if feature.hasMouthPosition {
if isSmile(feature) {
println("good smile!")
smileView.showSmile()
NSThread.sleepForTimeInterval(1.5)
smileView.showYokokumesi()
NSThread.sleepForTimeInterval(2.0)
smileView.showMesi()
}
}
}
}
}
func isSmile (feature : CIFaceFeature) -> Bool {
return feature.hasSmile
}
}
extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
let srcImage = imageFromSampleBuffer(sampleBuffer)
detectFace(srcImage)
}
func imageFromSampleBuffer(sampleBuffer: CMSampleBufferRef) -> CIImage {
let imageBuffer: CVImageBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)
CVPixelBufferLockBaseAddress(imageBuffer, 0)
let baseAddress : UnsafeMutablePointer<Void> = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()
let bitsPerCompornent = 8
let bitmapInfo = CGBitmapInfo((CGBitmapInfo.ByteOrder32Little.rawValue | CGImageAlphaInfo.PremultipliedFirst.rawValue) as UInt32)
let newContext: CGContextRef = CGBitmapContextCreate(baseAddress, width, height, bitsPerCompornent, bytesPerRow, colorSpace, bitmapInfo) as CGContextRef
let imageRef : CGImageRef = CGBitmapContextCreateImage(newContext)
var resultImage = CIImage(CGImage : imageRef)
return resultImage
}
}
| f5c661b4648e865fe72932a5da22c594 | 26.155914 | 156 | 0.730152 | false | false | false | false |
coderQuanjun/PigTV | refs/heads/master | GYJTV/GYJTV/Classes/Live/View/GiftAnimation/GiftContentView.swift | mit | 1 | //
// GiftContentView.swift
// GiftAnimation
//
// Created by zcm_iOS on 2017/6/7.
// Copyright © 2017年 com.zcmlc.zcmlc. All rights reserved.
//
import UIKit
private let kChannelCount = 2
private let kChannelViewH : CGFloat = 40
private let kChannelMargin : CGFloat = 10
class GiftContentView: UIView {
//MARK: 私有属性
fileprivate lazy var giftChannelArr : [GiftChannelView] = [GiftChannelView]()
fileprivate lazy var cacheGiftModels : [GiftAnimationModel] = [GiftAnimationModel]()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: 界面处理
extension GiftContentView{
fileprivate func setupViews(){
// 根据当前的渠道数,创建HYGiftChannelView
for i in 0..<kChannelCount {
let channelView = GiftChannelView.loadFromNib()
channelView.frame = CGRect(x: 0, y: (kChannelViewH + kChannelMargin) * CGFloat(i), width: frame.width, height: kChannelViewH)
channelView.alpha = 0
addSubview(channelView)
giftChannelArr.append(channelView)
channelView.complectionCallback = {channelView in
//1.取出缓存中的模型
guard self.cacheGiftModels.count != 0 else {
return
}
//2.取出缓存中的第一个模型
let firstmodel = self.cacheGiftModels.first
//3.清除第一个模型
self.cacheGiftModels.removeFirst()
//4.让闲置的channelView执行动画
channelView.giftModel = firstmodel
//5.将数组中剩余有和firstGiftModel相同的模型放入到ChanelView缓存中
for i in (0..<self.cacheGiftModels.count).reversed() {
let giftModel = self.cacheGiftModels[i]
if giftModel.isEqual(firstmodel) {
channelView.addOnceToCache()
self.cacheGiftModels.remove(at: i)
}
}
}
}
}
}
//MARK:
extension GiftContentView{
func showGiftModel(_ giftModel : GiftAnimationModel) {
// 1.判断正在忙的ChanelView和赠送的新礼物的(username/giftname)
if let channelView = chackUsingChannelView(giftModel){
channelView.addOnceToCache()
return
}
// 2.判断有没有闲置的ChanelView
if let channelView = chackIdelChannelView(){
channelView.giftModel = giftModel
return
}
// 3.将数据放入缓存中
cacheGiftModels.append(giftModel)
}
//判断有没有正在使用的,并且和赠送礼物相同的
private func chackUsingChannelView(_ giftModel : GiftAnimationModel) -> GiftChannelView?{
for channelView in giftChannelArr {
if giftModel.isEqual(channelView.giftModel) && channelView.giftState != .endAnimating {
return channelView
}
}
return nil
}
//判断有没有闲置的channelView
private func chackIdelChannelView() -> GiftChannelView? {
for channelView in giftChannelArr {
if channelView.giftState == .idle {
return channelView
}
}
return nil
}
}
| 7b08a0862943f57c452453c8c6a7b918 | 29.272727 | 137 | 0.572673 | false | false | false | false |
soapyigu/Swift30Projects | refs/heads/master | Project 07 - PokedexGo/PokedexGo/DetailViewController.swift | apache-2.0 | 1 | //
// DetailViewController.swift
// PokedexGo
//
// Created by Yi Gu on 7/13/16.
// Copyright © 2016 yigu. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var nameIDLabel: UILabel!
@IBOutlet weak var pokeImageView: UIImageView!
@IBOutlet weak var pokeInfoLabel: UILabel!
var pokemon: Pokemon! {
didSet (newPokemon) {
self.refreshUI()
}
}
override func viewDidLoad() {
refreshUI()
super.viewDidLoad()
}
func refreshUI() {
nameIDLabel?.text = pokemon.name + (pokemon.id < 10 ? " #00\(pokemon.id)" : pokemon.id < 100 ? " #0\(pokemon.id)" : " #\(pokemon.id)")
pokeImageView?.image = LibraryAPI.sharedInstance.downloadImg(pokemon.pokeImgUrl)
pokeInfoLabel?.text = pokemon.detailInfo
self.title = pokemon.name
}
}
extension DetailViewController: PokemonSelectionDelegate {
func pokemonSelected(_ newPokemon: Pokemon) {
pokemon = newPokemon
}
}
| ef68d9b2da30999140ebef16198ee7d5 | 22.857143 | 138 | 0.674651 | false | false | false | false |
mpurland/ReactiveBind | refs/heads/master | ReactiveBind/ViewBinding.swift | bsd-3-clause | 1 | import UIKit
import ReactiveCocoa
import Result
extension UIView {
public var rac_alpha: MutableProperty<CGFloat> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.AlphaProperty, { self.alpha = $0 }, { self.alpha })
}
public var rac_hidden: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.HiddenProperty, { self.hidden = $0 }, { self.hidden })
}
public var rac_backgroundColor: MutableProperty<UIColor?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.BackgroundColorProperty, { self.backgroundColor = $0 }, { self.backgroundColor })
}
}
extension UIBarItem {
public var rac_enabled: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.EnabledProperty, { self.enabled = $0 }, { self.enabled })
}
}
extension UIButton {
public var rac_normalTitle: MutableProperty<String?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.NormalTitleProperty, { self.setTitle($0, forState: .Normal) }, { self.titleForState(.Normal) })
}
public var rac_highlightedTitle: MutableProperty<String?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.HighlightedTitleProperty, { self.setTitle($0, forState: .Highlighted) }, { self.titleForState(.Highlighted) })
}
public var rac_selectedTitle: MutableProperty<String?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.SelectedTitleProperty, { self.setTitle($0, forState: .Selected) }, { self.titleForState(.Selected) })
}
public var rac_disabledTitle: MutableProperty<String?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.DisabledTitleProperty, { self.setTitle($0, forState: .Disabled) }, { self.titleForState(.Disabled) })
}
}
extension UIControl {
public var rac_enabled: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.EnabledProperty, { self.enabled = $0 }, { self.enabled })
}
public var rac_highlighted: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.HighlightedProperty, { self.highlighted = $0 }, { self.highlighted })
}
public var rac_selected: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.SelectedProperty, { self.selected = $0 }, { self.selected })
}
}
extension UILabel {
public var rac_text: MutableProperty<String?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.TextProperty, { self.text = $0 }, { self.text })
}
public var rac_attributedText: MutableProperty<NSAttributedString?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.AttributedTextProperty, { self.attributedText = $0 }, { self.attributedText })
}
public var rac_textColor: MutableProperty<UIColor?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.TextColorProperty, { self.textColor = $0 }, { self.textColor })
}
}
extension UITextField {
public var rac_text: MutableProperty<String> {
return lazyAssociatedProperty(self, &ReactiveBindAssocationKeys.TextProperty) {
self.rac_signalForControlEvents(UIControlEvents.EditingChanged).toSignalProducer().startWithNext { _ in
let value = self.text ?? ""
self.rac_text.value = value
}
let property = MutableProperty<String>(self.text ?? "")
property.producer.startWithNext { newValue in
self.text = newValue
}
return property
}
}
public var rac_attributedText: MutableProperty<NSAttributedString?> {
return lazyAssociatedProperty(self, &ReactiveBindAssocationKeys.AttributedTextProperty) {
self.rac_signalForControlEvents(UIControlEvents.EditingChanged).toSignalProducer().startWithNext { _ in
let value = self.attributedText
self.rac_attributedText.value = value
}
let property = MutableProperty<NSAttributedString?>(self.attributedText)
property.producer.startWithNext { newValue in
self.attributedText = newValue
}
return property
}
}
public var rac_textColor: MutableProperty<UIColor?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.TextColorProperty, { self.textColor = $0 }, { self.textColor })
}
/// A property that represents the active status of whether the text field is being edited (active) or not being edited (not active)
public var rac_active: SignalProducer<Bool, NoError> {
let property = MutableProperty<Bool>(false)
rac_signalForControlEvents(UIControlEvents.EditingDidBegin).toSignalProducer().startWithNext { _ in
print("text field: \(self) active")
property.value = true
}
rac_signalForControlEvents(UIControlEvents.EditingDidEnd).toSignalProducer().startWithNext { _ in
print("text field: \(self) inactive")
property.value = false
}
return property.producer.skip(1).skipRepeats()
}
}
extension UIImageView {
public var rac_image: MutableProperty<UIImage?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.ImageProperty, { self.image = $0 }, { self.image })
}
}
extension UITableViewCell {
public var rac_highlighted: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.HighlightedProperty, { self.highlighted = $0 }, { self.highlighted })
}
public var rac_selected: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.SelectedProperty, { self.selected = $0 }, { self.selected })
}
}
extension UICollectionViewCell {
public var rac_highlighted: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.HighlightedProperty, { self.highlighted = $0 }, { self.highlighted })
}
public var rac_selected: MutableProperty<Bool> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.SelectedProperty, { self.selected = $0 }, { self.selected })
}
}
extension UIViewController {
public var rac_title: MutableProperty<String?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.TitleProperty, { self.title = $0 }, { self.title })
}
public var rac_titleView: MutableProperty<UIView?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.TitleViewProperty, { self.navigationItem.titleView = $0 }, { self.navigationItem.titleView })
}
public var rac_leftBarButtonItem: MutableProperty<UIBarButtonItem?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.LeftBarButtonItemProperty, { self.navigationItem.leftBarButtonItem = $0 }, { self.navigationItem.leftBarButtonItem })
}
public var rac_leftBarButtonItems: MutableProperty<[UIBarButtonItem]?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.LeftBarButtonItemsProperty, { self.navigationItem.leftBarButtonItems = $0 }, { self.navigationItem.leftBarButtonItems })
}
public var rac_rightBarButtonItem: MutableProperty<UIBarButtonItem?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.RightBarButtonItemProperty, { self.navigationItem.rightBarButtonItem = $0 }, { self.navigationItem.rightBarButtonItem })
}
public var rac_rightBarButtonItems: MutableProperty<[UIBarButtonItem]?> {
return lazyMutableProperty(self, &ReactiveBindAssocationKeys.RightBarButtonItemsProperty, { self.navigationItem.rightBarButtonItems = $0 }, { self.navigationItem.rightBarButtonItems })
}
} | 90d03fa4cc5aba1c5e8a7a666285cca4 | 43.966292 | 192 | 0.696614 | false | false | false | false |
SandcastleApps/partyup | refs/heads/master | PartyUP/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2015-09-13.
// Copyright © 2015 Sandcastle Application Development. All rights reserved.
//
import UIKit
import AWSCore
import AWSS3
import AWSCognito
import Flurry_iOS_SDK
import FBSDKCoreKit
struct PartyUpPreferences
{
static let VideoQuality = "VideoQuality"
static let ListingRadius = "ListRadius"
static let SampleRadius = "SampleRadius"
static let VenueCategories = "VenueCategories"
static let StaleSampleInterval = "StaleSampleInterval"
static let CameraJump = "CameraJump"
static let StickyTowns = "StickyTowns"
static let PlayTutorial = "Tutorial"
static let TutorialViewed = "TutorialViewed"
static let AgreedToTerms = "Terms"
static let RemindersInterface = "RemindersInterface"
static let RemindersInterval = "RemindersInterval"
static let SampleSuppressionThreshold = "SampleSuppressionThreshold"
static let FeedNavigationArrows = "FeedNavigationArrows"
static let SeedFacebookVideo = "SeedFacebookVideo"
static let SeedFacebookBroadcast = "SeedFacebookBroadcast"
static let SeedFacebookTimeline = "SeedFacebookTimeline"
static let SeedStaleInterval = "SeedStaleInterval"
static let PromptAuthentication = "PromptAuthentication"
static let AllowAuthenticationPutoff = "AllowAuthenticationPutoff"
}
struct PartyUpConstants
{
static let FavoriteLocationNotification = "FavoriteLocationNotification"
static let RecordVideoNotification = "RecordVideoNotification"
static let DefaultStoragePrefix = "media"
static let TitleLogo: ()->UIImageView = {
let logoView = UIImageView(image: UIImage(named: "Logo"))
logoView.contentMode = .ScaleAspectFit
logoView.bounds = CGRect(x: 0, y: 0, width: 24, height: 40)
return logoView
}
}
struct FacebookConstants
{
static let GraphApiHost = NSURL(scheme: "https", host: "graph.facebook.com/v2.7", path: "/")!
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private struct AwsConstants
{
static let BackgroundSession = "com.sandcastleapps.partyup.session"
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSSetUncaughtExceptionHandler({
(error) in Flurry.logError("Uncaught_Exception", message: "Uh oh", exception: error)
})
Flurry.setUserID(UIDevice.currentDevice().identifierForVendor?.UUIDString)
Flurry.startSession(PartyUpKeys.FlurryIdentifier)
let tint = UIColor(r: 247, g: 126, b: 86, alpha: 255)
window?.tintColor = tint
UINavigationBar.appearance().backgroundColor = UIColor.whiteColor()
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "Back")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "Back")
UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().tintColor = tint
UIToolbar.appearance().tintColor = tint
UITextView.appearance().tintColor = tint
UIButton.appearance().tintColor = tint
let defaults = NSUserDefaults.standardUserDefaults()
if let defaultsUrl = NSBundle.mainBundle().URLForResource("PartyDefaults", withExtension: "plist") {
if let defaultsDictionary = NSDictionary(contentsOfURL: defaultsUrl) as? [String:AnyObject] {
defaults.registerDefaults(defaultsDictionary)
}
}
observeSettingsChange()
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert], categories: nil))
let manager = NSFileManager.defaultManager()
let mediaTemp = NSTemporaryDirectory() + PartyUpConstants.DefaultStoragePrefix
if !manager.fileExistsAtPath(mediaTemp) {
try! NSFileManager.defaultManager().createDirectoryAtPath(mediaTemp, withIntermediateDirectories: true, attributes: nil)
}
#if DEBUG
AWSLogger.defaultLogger().logLevel = .Warn
#else
AWSLogger.defaultLogger().logLevel = .Error
#endif
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.observeSettingsChange), name: NSUserDefaultsDidChangeNotification, object: nil)
Sample.InitializeStamps()
return AuthenticationManager.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func observeSettingsChange() {
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(PartyUpPreferences.PlayTutorial) {
defaults.setBool(false, forKey: PartyUpPreferences.PlayTutorial)
defaults.setObject([], forKey: PartyUpPreferences.TutorialViewed)
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
application.cancelAllLocalNotifications()
if notificationSettings.types != .None {
scheduleReminders()
if let notifyUrl = NSBundle.mainBundle().URLForResource("PartyNotify", withExtension: "plist") {
scheduleNotificationsFromUrl(notifyUrl, inApplication: application, withNotificationSettings: notificationSettings)
}
}
}
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: AwsConstants.BackgroundSession, completionHandler: completionHandler)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return AuthenticationManager.shared.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func scheduleNotificationsFromUrl(url: NSURL, inApplication application: UIApplication, withNotificationSettings notificationSettings: UIUserNotificationSettings) {
if let notifications = NSArray(contentsOfURL: url) as? [[String:AnyObject]] {
for notify in notifications {
scheduleNotificationFromDictionary(notify, inApplication: application, withNotificationSettings: notificationSettings)
}
}
}
func scheduleNotificationFromDictionary(notify: [String : AnyObject], inApplication application: UIApplication, withNotificationSettings notificationSettings: UIUserNotificationSettings) {
if let whens = notify["whens"] as? [[String:Int]],
what = notify["messages"] as? [String],
action = notify["action"] as? String,
tag = notify["tag"] as? Int where what.count > 0 {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
for when in whens {
let relative = NSDateComponents()
relative.calendar = calendar
relative.hour = when["hour"] ?? NSDateComponentUndefined
relative.minute = when["minute"] ?? NSDateComponentUndefined
relative.weekday = when["weekday"] ?? NSDateComponentUndefined
let range = when["range"] ?? 0
let prebook = notify["prebook"] as? Int ?? 0
let iterations = prebook < 0 ? 1 : prebook
let randomize = notify["randomize"] as? Bool ?? false
var date = NSDate().dateByAddingTimeInterval(NSTimeInterval(range/2)*60)
for i in 0..<iterations {
if let futureDate = calendar?.nextDateAfterDate(date, matchingComponents: relative, options: .MatchNextTime) {
let localNote = UILocalNotification()
localNote.alertAction = action
localNote.alertBody = what[randomize ? Int(arc4random_uniform(UInt32(what.count))) : i % what.count]
localNote.userInfo = ["tag" : tag]
localNote.soundName = "drink.caf"
let offset = (NSTimeInterval(arc4random_uniform(UInt32(range))) - (NSTimeInterval(range/2))) * 60
localNote.fireDate = futureDate.dateByAddingTimeInterval(offset)
localNote.timeZone = NSTimeZone.defaultTimeZone()
if prebook < 0 {
localNote.repeatInterval = .WeekOfYear
localNote.repeatCalendar = calendar
}
application.scheduleLocalNotification(localNote)
date = futureDate
}
}
}
}
}
func scheduleReminders() {
let application = UIApplication.sharedApplication()
let interval = NSUserDefaults.standardUserDefaults().integerForKey(PartyUpPreferences.RemindersInterval)
if let notes = application.scheduledLocalNotifications {
for note in notes {
if note.userInfo?["reminder"] != nil {
application.cancelLocalNotification(note)
}
}
}
if NSUserDefaults.standardUserDefaults().boolForKey(PartyUpPreferences.RemindersInterface) {
var minutes = [Int]()
if interval > 0 { minutes.append(0) }
if interval == 30 { minutes.append(30) }
let now = NSDate()
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let relative = NSDateComponents()
relative.calendar = calendar
relative.timeZone = NSTimeZone.defaultTimeZone()
for minute in minutes {
relative.minute = minute
let future = calendar.nextDateAfterDate(now, matchingComponents: relative, options: .MatchNextTime)
let localNote = UILocalNotification()
localNote.alertAction = NSLocalizedString("submit a video", comment: "Reminders alert action")
localNote.alertBody = NSLocalizedString("Time to record a party video!", comment: "Reminders alert body")
localNote.userInfo = ["reminder" : interval]
localNote.soundName = "drink.caf"
localNote.fireDate = future
localNote.repeatInterval = .Hour
localNote.repeatCalendar = calendar
localNote.timeZone = NSTimeZone.defaultTimeZone()
application.scheduleLocalNotification(localNote)
}
}
}
}
| 0b8a65f5af900e76dee66fbaf621c5ff | 42.033613 | 192 | 0.710115 | false | false | false | false |
nhdang103/HDNotificationView | refs/heads/master | HDNotificationView/Source/HDNotificationData.swift | mit | 1 | //
// HDNotificationData.swift
// HDNotificationView
//
// Created by nhdang103 on 10/6/18.
// Copyright © 2018 AnG Studio. All rights reserved.
//
import Foundation
public class HDNotificationData: NSObject {
public var iconImage: UIImage?
public var appTitle: String?
public var title: String?
public var message: String?
public var time: String?
public init(iconImage: UIImage?, appTitle: String?, title: String?, message: String?, time: String?) {
self.iconImage = iconImage
self.appTitle = appTitle
self.title = title
self.message = message
self.time = time
super.init()
}
}
| 439eb4d660e6aa8657b9c9f1afdce551 | 23.37931 | 106 | 0.61669 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.