repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ksco/swift-algorithm-club-cn | Counting Sort/CountingSort.playground/Contents.swift | 1 | 1037 | //: Playground - noun: a place where people can play
enum CountingSortError: ErrorType {
case ArrayEmpty
}
func countingSort(array: [Int]) throws -> [Int] {
guard array.count > 0 else {
throw CountingSortError.ArrayEmpty
}
// Step 1
// Create an array to store the count of each element
let maxElement = array.maxElement() ?? 0
var countArray = [Int](count: Int(maxElement + 1), repeatedValue: 0)
for element in array {
countArray[element] += 1
}
// Step 2
// Set each value to be the sum of the previous two values
for index in 1 ..< countArray.count {
let sum = countArray[index] + countArray[index - 1]
countArray[index] = sum
}
print(countArray)
// Step 3
// Place the element in the final array as per the number of elements before it
var sortedArray = [Int](count: array.count, repeatedValue: 0)
for element in array {
countArray[element] -= 1
sortedArray[countArray[element]] = element
}
return sortedArray
}
try countingSort([10, 9, 8, 7, 1, 2, 7, 3])
| mit | 46f0cfbbffd7dcf0e77903ec6d4180c6 | 24.292683 | 81 | 0.670203 | 3.716846 | false | false | false | false |
ozgur/TestApp | TestApp/Models/Campaign.swift | 1 | 890 | //
// Campaign.swift
// TestApp
//
// Created by Ozgur on 20/02/2017.
// Copyright © 2017 Ozgur. All rights reserved.
//
import ObjectMapper
class Campaign: Mappable {
var startsAt: Date!
var endsAt: Date!
var message: String!
var text: String?
var link: URL?
var isActive: Bool = false
required init?(map: Map) {}
func mapping(map: Map) {
isActive <- map["active"]
startsAt <- (map["starts_at"], ISO8601DateTransform())
endsAt <- (map["ends_at"], ISO8601DateTransform())
message <- map["message"]
text <- map["text"]
}
}
// MARK: Equatable
extension Campaign: Equatable {}
func ==(lhs: Campaign, rhs: Campaign) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
// MARK: CustomStringConvertible
extension Campaign: CustomStringConvertible {
var description: String {
return "Campaign <\(message)>"
}
}
| gpl-3.0 | e30484cb7ef07c90646685655c7b2b78 | 18.326087 | 58 | 0.652418 | 3.782979 | false | false | false | false |
mamouneyya/TheSkillsProof | SouqTask/Modules/Prices/Helpers/PricesManager.swift | 1 | 4244 | //
// PricesManager.swift
// SouqTask
//
// Created by Ma'moun Diraneyya on 3/5/16.
// Copyright © 2016 Mamouneyya. All rights reserved.
//
import UIKit
class PricesManager {
// MARK: - Public Vars
/// Singleton's class shared instance
static let sharedInstance = PricesManager()
/// Type alias for actions that need to return single Price object.
typealias ActionHandler = (object: Price?, error: ErrorType?) -> ()
/// Type alias for actions that need to return array of Price objects.
typealias ArrayActionHandler = (objects: [Price]?, error: ErrorType?) -> ()
// MARK: - Private Vars
/// SwiftyDB database object.
private let database = SwiftyDB(databaseName: DBNames.TrackedPrices)
// MARK: - Lifecycle
private init() {}
// MARK: - CRUD Operations
/**
Get all prices for product asynchronously from DB.
- Parameter productId: Product Id to get tracked prices for.
- Parameter action: Action to fire when fetch completes.
- NOTE: If you need to update views, make sure to run your code in the main thread (e.g. thorugh GCD)
*/
class func getAllPricesForProduct(productId: String) -> [Price]? {
let result = sharedInstance.database.objectsForType(Price.self, matchingFilter: ["productId": productId])
if let objects = result.value {
return objects
}
return nil
}
/**
Get all prices for product asynchronously from DB.
- Parameter productId: Product Id to get tracked prices for.
- Parameter action: Action to fire when fetch completes.
- NOTE: If you need to update views, make sure to run your code in the main thread (e.g. thorugh GCD)
*/
class func asyncGetAllPricesForProduct(productId: String, action: ArrayActionHandler) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
let result = sharedInstance.database.objectsForType(Price.self, matchingFilter: ["productId": productId])
if let objects = result.value {
action(objects: objects, error: nil)
return
}
action(objects: nil, error: result.error)
}
}
/**
Add a new price for product asynchronously.
- Parameter price: Price to add.
- Parameter action: Action to fire when insertion completes.
*/
class func asyncAddPriceForProduct(price: Price, action: ActionHandler? = nil) {
sharedInstance.database.asyncAddObject(price, update: false) { (result) -> Void in
if let error = result.error {
// TODO Handle error
#if DEBUG
print(error)
#endif
action?(object: nil, error: error)
} else {
action?(object: price, error: nil)
}
}
}
/**
Remove all prices for specific product asynchronously. This can be used to clean DB when untrack a product.
- Parameter product: Product to remove.
- Parameter action: Action to fire when deletion completes.
*/
class func asyncRemoveAllPricesForProduct(productId: String, action: ActionHandler? = nil) {
sharedInstance.database.asyncDeleteObjectsForType(Price.self, matchingFilter: ["productId": productId]) { (result) -> Void in
if let error = result.error {
// TODO Handle error
#if DEBUG
print(error)
#endif
action?(object: nil, error: error)
} else {
action?(object: nil, error: nil)
}
}
}
// MARK: - Helpers
/**
Look for the last tracked price in DB for a product.
- Parameter productId: Product id to look for.
- Returns: Last tracked price if exists, or nil.
*/
class func lastTrackedPriceForProduct(productId: String) -> Int? {
if let prices = getAllPricesForProduct(productId) where prices.count > 0 {
return prices.last?.value
}
return nil
}
} | mit | 8a60cb574c434affdbb324c0ed0d6f2c | 32.68254 | 133 | 0.597455 | 4.719689 | false | false | false | false |
magfurulabeer/CalcuLayout | CalcuLayout/NSLayoutConstraint+CalcuLayout.swift | 1 | 1320 | //
// NSLayoutConstraint+CalcuLayout.swift
// CalcuLayout
//
// Created by Magfurul Abeer on 9/9/16.
// Copyright © 2016 Magfurul Abeer. All rights reserved.
//
import Foundation
/// This extension allows for all the attached LayoutModifiers to affect the NSLayoutConstraint.
public extension NSLayoutConstraint {
/// All the attached LayoutModifiers will affect the NSLayoutConstraint.
internal func runAttachedOperations(_ operations: [ConstraintFunction]) -> NSLayoutConstraint {
var modifiedConstraint = NSLayoutConstraint()
for function in operations {
switch function {
case .addConstant(let constant):
modifiedConstraint = self + constant^
break
case .subtractConstant(let constant):
modifiedConstraint = self - constant^
break
case .multiplyConstant(let constant):
modifiedConstraint = self * constant^
break
case .divideConstant(let constant):
modifiedConstraint = self / constant^
break
case .activateConstraint(let isActive):
self.isActive = isActive
break
}
}
return modifiedConstraint
}
}
| mit | f1786165eda8641e3d84bde3e524f9cc | 31.975 | 99 | 0.605762 | 5.709957 | false | false | false | false |
gottesmm/swift | test/SILGen/witnesses.swift | 2 | 30191 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
infix operator <~> {}
func archetype_method<T: X>(x: T, y: T) -> T {
var x = x
var y = y
return x.selfTypes(x: y)
}
// CHECK-LABEL: sil hidden @_T09witnesses16archetype_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : X> (@in T, @in T) -> @out T {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: }
func archetype_generic_method<T: X>(x: T, y: Loadable) -> Loadable {
var x = x
return x.generic(x: y)
}
// CHECK-LABEL: sil hidden @_T09witnesses24archetype_generic_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: }
// CHECK-LABEL: sil hidden @_T09witnesses32archetype_associated_type_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : WithAssoc> (@in T, @in T.AssocType) -> @out T
// CHECK: apply %{{[0-9]+}}<T>
func archetype_associated_type_method<T: WithAssoc>(x: T, y: T.AssocType) -> T {
return x.useAssocType(x: y)
}
protocol StaticMethod { static func staticMethod() }
// CHECK-LABEL: sil hidden @_T09witnesses23archetype_static_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : StaticMethod> (@in T) -> ()
func archetype_static_method<T: StaticMethod>(x: T) {
// CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> ()
// CHECK: apply [[METHOD]]<T>
T.staticMethod()
}
protocol Existentiable {
func foo() -> Loadable
func generic<T>() -> T
}
func protocol_method(x: Existentiable) -> Loadable {
return x.foo()
}
// CHECK-LABEL: sil hidden @_T09witnesses15protocol_methodAA8LoadableVAA13Existentiable_p1x_tF : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1
// CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}})
// CHECK: }
func protocol_generic_method(x: Existentiable) -> Loadable {
return x.generic()
}
// CHECK-LABEL: sil hidden @_T09witnesses23protocol_generic_methodAA8LoadableVAA13Existentiable_p1x_tF : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1
// CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
// CHECK: }
@objc protocol ObjCAble {
func foo()
}
// CHECK-LABEL: sil hidden @_T09witnesses20protocol_objc_methodyAA8ObjCAble_p1x_tF : $@convention(thin) (@owned ObjCAble) -> ()
// CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign
func protocol_objc_method(x: ObjCAble) {
x.foo()
}
struct Loadable {}
protocol AddrOnly {}
protocol Classes : class {}
protocol X {
mutating
func selfTypes(x: Self) -> Self
mutating
func loadable(x: Loadable) -> Loadable
mutating
func addrOnly(x: AddrOnly) -> AddrOnly
mutating
func generic<A>(x: A) -> A
mutating
func classes<A2: Classes>(x: A2) -> A2
static func <~>(_ x: Self, y: Self) -> Self
}
protocol Y {}
protocol WithAssoc {
associatedtype AssocType
func useAssocType(x: AssocType) -> Self
}
protocol ClassBounded : class {
func selfTypes(x: Self) -> Self
}
struct ConformingStruct : X {
mutating
func selfTypes(x: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XAaaDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformingStruct, @inout ConformingStruct) -> @out ConformingStruct {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct):
// CHECK-NEXT: %3 = load [trivial] %1 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @_T09witnesses16ConformingStructV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %5 to [trivial] %0 : $*ConformingStruct
// CHECK-NEXT: %7 = tuple ()
// CHECK-NEXT: return %7 : $()
// CHECK-NEXT: }
mutating
func loadable(x: Loadable) -> Loadable { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XAaaDP8loadable{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable {
// CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_T09witnesses16ConformingStructV8loadable{{[_0-9a-zA-Z]*}}F : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: return %3 : $Loadable
// CHECK-NEXT: }
mutating
func addrOnly(x: AddrOnly) -> AddrOnly { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XAaaDP8addrOnly{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_T09witnesses16ConformingStructV8addrOnly{{[_0-9a-zA-Z]*}}F : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func generic<C>(x: C) -> C { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0 {
// CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_T09witnesses16ConformingStructV7generic{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<τ_0_0>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func classes<C2: Classes>(x: C2) -> C2 { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XAaaDP7classes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0 {
// CHECK: bb0(%0 : $τ_0_0, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_T09witnesses16ConformingStructV7classes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: %3 = apply %2<τ_0_0>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: return %3 : $τ_0_0
// CHECK-NEXT: }
}
func <~>(_ x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> @out ConformingStruct {
// CHECK: bb0([[ARG1:%.*]] : $*ConformingStruct, [[ARG2:%.*]] : $*ConformingStruct, [[ARG3:%.*]] : $*ConformingStruct, [[ARG4:%.*]] : $@thick ConformingStruct.Type):
// CHECK-NEXT: [[LOADED_ARG2:%.*]] = load [trivial] [[ARG2]] : $*ConformingStruct
// CHECK-NEXT: [[LOADED_ARG3:%.*]] = load [trivial] [[ARG3]] : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FUNC:%.*]] = function_ref @_T09witnesses3ltgoiAA16ConformingStructVAD_ADtF : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[LOADED_ARG2]], [[LOADED_ARG3]]) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store [[FUNC_RESULT]] to [trivial] [[ARG1]] : $*ConformingStruct
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
final class ConformingClass : X {
func selfTypes(x: ConformingClass) -> ConformingClass { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses15ConformingClassCAA1XAaaDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformingClass, @inout ConformingClass) -> @out ConformingClass {
// CHECK: bb0([[ARG1:%.*]] : $*ConformingClass, [[ARG2:%.*]] : $*ConformingClass, [[ARG3:%.*]] : $*ConformingClass):
// -- load and copy_value 'self' from inout witness 'self' parameter
// CHECK: [[ARG3_LOADED:%.*]] = load [copy] [[ARG3]] : $*ConformingClass
// CHECK: [[ARG2_LOADED:%.*]] = load [take] [[ARG2]] : $*ConformingClass
// CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses15ConformingClassC9selfTypes{{[_0-9a-zA-Z]*}}F
// CHECK: [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[ARG2_LOADED]], [[ARG3_LOADED]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK: store [[FUNC_RESULT]] to [init] [[ARG1]] : $*ConformingClass
// CHECK: destroy_value [[ARG3_LOADED]]
// CHECK: } // end sil function '_T09witnesses15ConformingClassCAA1XAaaDP9selfTypes{{[_0-9a-zA-Z]*}}FTW'
func loadable(x: Loadable) -> Loadable { return x }
func addrOnly(x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x: D) -> D { return x }
func classes<D2: Classes>(x: D2) -> D2 { return x }
}
func <~>(_ x: ConformingClass, y: ConformingClass) -> ConformingClass { return x }
extension ConformingClass : ClassBounded { }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses15ConformingClassCAA0C7BoundedAaaDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass {
// CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass):
// CHECK-NEXT: [[C1_COPY:%.*]] = copy_value [[C1]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_T09witnesses15ConformingClassC9selfTypes{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1_COPY]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: destroy_value [[C1_COPY]]
// CHECK-NEXT: return [[RESULT]] : $ConformingClass
// CHECK-NEXT: }
struct ConformingAOStruct : X {
var makeMeAO : AddrOnly
mutating
func selfTypes(x: ConformingAOStruct) -> ConformingAOStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18ConformingAOStructVAA1XAaaDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct {
// CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_T09witnesses18ConformingAOStructV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
func loadable(x: Loadable) -> Loadable { return x }
func addrOnly(x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x: D) -> D { return x }
func classes<D2: Classes>(x: D2) -> D2 { return x }
}
func <~>(_ x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x }
struct ConformsWithMoreGeneric : X, Y {
mutating
func selfTypes<E>(x: E) -> E { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XAaaDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> @out ConformsWithMoreGeneric {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_T09witnesses23ConformsWithMoreGenericV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func loadable<F>(x: F) -> F { return x }
mutating
func addrOnly<G>(x: G) -> G { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XAaaDP8addrOnly{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in AddrOnly, @inout ConformsWithMoreGeneric) -> @out AddrOnly {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_T09witnesses23ConformsWithMoreGenericV8addrOnly{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func generic<H>(x: H) -> H { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XAaaDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 {
// CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_T09witnesses23ConformsWithMoreGenericV7generic{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<τ_0_0>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func classes<I>(x: I) -> I { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XAaaDP7classes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformsWithMoreGeneric) -> @owned τ_0_0 {
// CHECK: bb0(%0 : $τ_0_0, %1 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: store %0 to [init] [[SELF_BOX]] : $*τ_0_0
// CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_T09witnesses23ConformsWithMoreGenericV7classes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<τ_0_0>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = load [take] [[RESULT_BOX]] : $*τ_0_0
// CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*τ_0_0
// CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*τ_0_0
// CHECK-NEXT: return [[RESULT]] : $τ_0_0
// CHECK-NEXT: }
}
func <~> <J: Y, K: Y>(_ x: J, y: K) -> K { return y }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XAaaDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> @out ConformsWithMoreGeneric {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_T09witnesses3ltgoi{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
protocol LabeledRequirement {
func method(x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16UnlabeledWitnessVAA18LabeledRequirementAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> ()
func method(x _: Loadable) {}
}
protocol LabeledSelfRequirement {
func method(x: Self)
}
struct UnlabeledSelfWitness : LabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses20UnlabeledSelfWitnessVAA07LabeledC11RequirementAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> ()
func method(x _: UnlabeledSelfWitness) {}
}
protocol UnlabeledRequirement {
func method(x _: Loadable)
}
struct LabeledWitness : UnlabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses14LabeledWitnessVAA20UnlabeledRequirementAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> ()
func method(x: Loadable) {}
}
protocol UnlabeledSelfRequirement {
func method(_: Self)
}
struct LabeledSelfWitness : UnlabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18LabeledSelfWitnessVAA09UnlabeledC11RequirementAaaDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> ()
func method(_ x: LabeledSelfWitness) {}
}
protocol ReadOnlyRequirement {
var prop: String { get }
static var prop: String { get }
}
struct ImmutableModel: ReadOnlyRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses14ImmutableModelVAA19ReadOnlyRequirementAaaDP4propSSfgTW : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String
let prop: String = "a"
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses14ImmutableModelVAA19ReadOnlyRequirementAaaDP4propSSfgZTW : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String
static let prop: String = "b"
}
protocol FailableRequirement {
init?(foo: Int)
}
protocol NonFailableRefinement: FailableRequirement {
init(foo: Int)
}
protocol IUOFailableRequirement {
init!(foo: Int)
}
struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16NonFailableModelVAA0C11Requirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16NonFailableModelVAA0bC10Refinement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out NonFailableModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16NonFailableModelVAA22IUOFailableRequirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel>
init(foo: Int) {}
}
struct FailableModel: FailableRequirement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses13FailableModelVAA0B11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses13FailableModelVAA22IUOFailableRequirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: bb0([[SELF:%[0-9]+]] : $*Optional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type):
// CHECK: [[FN:%.*]] = function_ref @_T09witnesses13FailableModelV{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INNER:%.*]] = apply [[FN]](
// CHECK: store [[INNER]] to [trivial] [[SELF]]
// CHECK: return
init?(foo: Int) {}
}
struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16IUOFailableModelVAA21NonFailableRefinement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type):
// CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type
// CHECK: [[INIT:%[0-9]+]] = function_ref @_T09witnesses16IUOFailableModelV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thin IUOFailableModel.Type) -> Optional<IUOFailableModel>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(method) (Int, @thin IUOFailableModel.Type) -> Optional<IUOFailableModel>
// CHECK: [[RESULT:%[0-9]+]] = unchecked_enum_data [[IUO_RESULT]]
// CHECK: store [[RESULT]] to [trivial] [[SELF]] : $*IUOFailableModel
// CHECK: return
init!(foo: Int) { return nil }
}
protocol FailableClassRequirement: class {
init?(foo: Int)
}
protocol NonFailableClassRefinement: FailableClassRequirement {
init(foo: Int)
}
protocol IUOFailableClassRequirement: class {
init!(foo: Int)
}
final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21NonFailableClassModelCAA0cD11Requirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21NonFailableClassModelCAA0bcD10Refinement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21NonFailableClassModelCAA011IUOFailableD11Requirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel>
init(foo: Int) {}
}
final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18FailableClassModelCAA0bC11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18FailableClassModelCAA011IUOFailableC11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses18FailableClassModelC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: return [[INNER]] : $Optional<FailableClassModel>
init?(foo: Int) {}
}
final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA011NonFailableC10Refinement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: unchecked_enum_data
// CHECK: return [[RESULT:%[0-9]+]] : $IUOFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA0bC11Requirement{{[_0-9a-zA-Z]*}}fCTW
init!(foo: Int) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA08FailableC11Requirement{{[_0-9a-zA-Z]*}}fCTW
// CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses21IUOFailableClassModelC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: return [[INNER]] : $Optional<IUOFailableClassModel>
}
protocol HasAssoc {
associatedtype Assoc
}
protocol GenericParameterNameCollisionProtocol {
func foo<T>(_ x: T)
associatedtype Assoc2
func bar<T>(_ x: (T) -> Assoc2)
}
struct GenericParameterNameCollision<T: HasAssoc> :
GenericParameterNameCollisionProtocol {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolAaA8HasAssocRzlAaDP3fooyqd__lFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@in τ_1_0, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () {
// CHECK: bb0(%0 : $*τ_1_0, %1 : $*GenericParameterNameCollision<τ_0_0>):
// CHECK: apply {{%.*}}<τ_0_0, τ_1_0>
func foo<U>(_ x: U) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolAaA8HasAssocRzlAaDP3bary6Assoc2Qzqd__clFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@owned @callee_owned (@in τ_1_0) -> @out τ_0_0.Assoc, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () {
// CHECK: bb0(%0 : $@callee_owned (@in τ_1_0) -> @out τ_0_0.Assoc, %1 : $*GenericParameterNameCollision<τ_0_0>):
// CHECK: apply {{%.*}}<τ_0_0, τ_1_0>
func bar<V>(_ x: (V) -> T.Assoc) {}
}
protocol PropertyRequirement {
var width: Int { get set }
static var height: Int { get set }
var depth: Int { get set }
}
class PropertyRequirementBase {
var width: Int = 12
static var height: Int = 13
}
class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement {
var depth: Int = 14
// Make sure the contravariant return type in materializeForSet works correctly
// If the witness is in a base class of the conforming class, make sure we have a bit_cast in there:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses34PropertyRequirementWitnessFromBaseCAA0bC0AaaDP5widthSifmTW : {{.*}} {
// CHECK: upcast
// CHECK-NEXT: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CADR]] : {{.*}})
// CHECK-NEXT: destroy_value
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses34PropertyRequirementWitnessFromBaseCAA0bC0AaaDP6heightSifmZTW : {{.*}} {
// CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type
// CHECK: [[METH:%.*]] = function_ref @_T09witnesses23PropertyRequirementBaseC6heightSifmZ
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CADR]] : {{.*}})
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses34PropertyRequirementWitnessFromBaseCAA0bC0AaaDP5depthSifmTW
// CHECK: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: [[RES:%.*]] = tuple
// CHECK-NEXT: destroy_value
// CHECK-NEXT: return [[RES]]
}
protocol Crashable {
func crash()
}
class CrashableBase {
func crash() {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16GenericCrashableCyxGAA0C0AAlAaDP5crashyyFTW : $@convention(witness_method) <τ_0_0> (@in_guaranteed GenericCrashable<τ_0_0>) -> ()
// CHECK: bb0(%0 : $*GenericCrashable<τ_0_0>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_stack $GenericCrashable<τ_0_0>
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] : $*GenericCrashable<τ_0_0>
// CHECK-NEXT: [[SELF:%.*]] = load [take] [[BOX]] : $*GenericCrashable<τ_0_0>
// CHECK-NEXT: [[BASE:%.*]] = upcast [[SELF]] : $GenericCrashable<τ_0_0> to $CrashableBase
// CHECK-NEXT: [[FN:%.*]] = class_method [[BASE]] : $CrashableBase, #CrashableBase.crash!1 : (CrashableBase) -> () -> () , $@convention(method) (@guaranteed CrashableBase) -> ()
// CHECK-NEXT: apply [[FN]]([[BASE]]) : $@convention(method) (@guaranteed CrashableBase) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: destroy_value [[SELF]] : $GenericCrashable<τ_0_0>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*GenericCrashable<τ_0_0>
// CHECK-NEXT: return [[RESULT]] : $()
class GenericCrashable<T> : CrashableBase, Crashable {}
| apache-2.0 | 0f8e888f9e5c8d27c4d267a762a9d573 | 58.866534 | 343 | 0.664093 | 3.201896 | false | false | false | false |
hyperoslo/Brick | Sources/Shared/Extensions.swift | 1 | 1502 | import Tailor
// MARK: - Array
public extension Array where Element : Indexable {
mutating func refreshIndexes() {
enumerated().forEach {
self[$0.offset].index = $0.offset
}
}
}
// MARK: - Dictionary
/**
A dictionary extension to work with custom Key type
*/
extension Dictionary where Key: ExpressibleByStringLiteral {
/**
- parameter name: The name of the property that you want to map
- returns: A generic type if casting succeeds, otherwise it returns nil
*/
func property<T>(_ name: Item.Key) -> T? {
return property(name.string)
}
/**
Access the value associated with the given key.
- parameter key: The key associated with the value you want to get
- returns: The value associated with the given key
*/
subscript(key: Item.Key) -> Value? {
set(value) {
guard let key = key.string as? Key else { return }
self[key] = value
}
get {
guard let key = key.string as? Key else { return nil }
return self[key]
}
}
}
// MARK: - Mappable
extension Mappable {
/**
- returns: A key-value dictionary.
*/
var metaProperties: [String : Any] {
var properties = [String : Any]()
for tuple in Mirror(reflecting: self).children {
guard let key = tuple.label else { continue }
if let value = Mirror(reflecting: tuple.value).descendant("Some") {
properties[key] = value
} else {
properties[key] = tuple.value
}
}
return properties
}
}
| mit | 170f6d766d586a62cf4efa10bed76ec3 | 20.15493 | 74 | 0.627164 | 4.016043 | false | false | false | false |
cyhuang1230/CYHPOPImageButton | Example/CYHPOPImageButton/ViewController.swift | 1 | 1322 | //
// ViewController.swift
// CYHPOPImageButton
//
// Created by cyhuang1230 on 08/11/2015.
// Copyright (c) 2015 cyhuang1230. All rights reserved.
//
import UIKit
import CYHPOPImageButton
class ViewController: UIViewController {
var buttonPlace: CYHPOPImageButton!
var buttonAdd: CYHPOPImageButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
buttonPlace = CYHPOPImageButton(image: UIImage(named: "ic_location_on_48pt")!);
buttonPlace.frame.origin = CGPointMake(view.frame.width/2 - 98, 50);
buttonPlace.addTarget(self, action: "changeColor:", forControlEvents: .TouchUpInside);
view.addSubview(buttonPlace);
buttonAdd = CYHPOPImageButton(image: UIImage(named: "ic_add_circle_48pt")!);
buttonAdd.frame.origin = CGPointMake(view.frame.width/2 + 50, 50);
buttonAdd.addTarget(self, action: "changeColor:", forControlEvents: .TouchUpInside);
view.addSubview(buttonAdd);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func changeColor(sender: CYHPOPImageButton) {
let viewTintColor = self.view.tintColor;
sender.tintColor = sender.tintColor == viewTintColor ? UIColor.redColor() : viewTintColor;
}
}
| mit | 51d220426b16ac39822421ff53fa248e | 28.377778 | 92 | 0.74357 | 3.651934 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Modules/Schedule/View/UIKit/ScheduleSearchTableViewController.swift | 1 | 2460 | import UIKit
class ScheduleSearchTableViewController: UITableViewController {
// MARK: Search Convenience Collab
private var numberOfItemsPerSection: [Int] = []
private var binder: ScheduleSceneBinder?
var onDidSelectSearchResultAtIndexPath: ((IndexPath) -> Void)?
func updateSearchResults(numberOfItemsPerSection: [Int], binder: ScheduleSceneBinder) {
self.numberOfItemsPerSection = numberOfItemsPerSection
self.binder = binder
tableView.reloadData()
}
func deselectSearchResult(at indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerConventionBrandedHeader()
tableView.register(EventTableViewCell.self)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
tableView.setEditing(false, animated: false)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return numberOfItemsPerSection.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfItemsPerSection[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(EventTableViewCell.self)
binder?.bind(cell, forEventAt: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueConventionBrandedHeader()
binder?.bind(header, forGroupAt: section)
return header
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onDidSelectSearchResultAtIndexPath?(indexPath)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
guard let action = binder?.eventActionForComponent(at: indexPath) else { return nil }
let rowAction: UITableViewRowAction = UITableViewRowAction(style: .normal, title: action.title, handler: { (_, _) in
action.run()
})
rowAction.backgroundColor = .pantone330U
return [rowAction]
}
}
| mit | 9b3e14ae5e5641507491062b7064a2c1 | 34.142857 | 124 | 0.70813 | 5.324675 | false | false | false | false |
qRoC/Loobee | Sources/Loobee/Library/AssertionConcern/Assertion/LessOrEqualThanAssertions.swift | 1 | 2102 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
/// The default message in notifications from `lessOrEqualThan` assertions.
@usableFromInline internal let kLessOrEqualThanDefaultMessage: StaticString = """
The value is not less or equal than max value.
"""
/// Determines if the `value` is less or equal than given limit value.
@inlinable
public func assert<T: Comparable>(
_ value: T,
lessOrEqualThan maxValue: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value > maxValue) {
return .create(
message: message() ?? kLessOrEqualThanDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is less or equal than given limit value.
@inlinable
public func assert<T1: BinaryInteger, T2: BinaryInteger>(
_ value: T1,
lessOrEqualThan maxValue: T2,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value > maxValue) {
return .create(
message: message() ?? kLessOrEqualThanDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is less or equal than given limit value.
///
/// - Note: This is ambiguity breaker.
@inlinable
public func assert<T: BinaryInteger>(
_ value: T,
lessOrEqualThan maxValue: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value > maxValue) {
return .create(
message: message() ?? kLessOrEqualThanDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
| mit | 1197afc0a62ec9a67688dfb9e7b83cae | 27.794521 | 81 | 0.646051 | 4.162376 | false | false | false | false |
SoneeJohn/WWDC | WWDC/SearchFiltersViewController.swift | 1 | 9032 | //
// SearchFiltersViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 25/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
protocol SearchFiltersViewControllerDelegate: class {
func searchFiltersViewController(_ controller: SearchFiltersViewController, didChangeFilters filters: [FilterType])
}
enum FilterSegment: Int {
case favorite
case downloaded
case unwatched
init?(_ id: FilterIdentifier) {
switch id {
case .isFavorite:
self = .favorite
case .isDownloaded:
self = .downloaded
case .isUnwatched:
self = .unwatched
default:
return nil
}
}
}
extension NSSegmentedControl {
func isSelected(for segment: FilterSegment) -> Bool {
return isSelected(forSegment: segment.rawValue)
}
}
final class SearchFiltersViewController: NSViewController {
static func loadFromStoryboard() -> SearchFiltersViewController {
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "SearchFiltersViewController")) as! SearchFiltersViewController
}
@IBOutlet weak var eventsPopUp: NSPopUpButton!
@IBOutlet weak var focusesPopUp: NSPopUpButton!
@IBOutlet weak var tracksPopUp: NSPopUpButton!
@IBOutlet weak var bottomSegmentedControl: NSSegmentedControl!
@IBOutlet weak var filterButton: NSButton!
@IBOutlet weak var searchField: NSSearchField!
var filters: [FilterType] {
set {
effectiveFilters = newValue
updateUI()
}
get {
return effectiveFilters
}
}
private var effectiveFilters: [FilterType] = []
weak var delegate: SearchFiltersViewControllerDelegate?
@IBAction func eventsPopUpAction(_ sender: Any) {
guard let filterIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.event.rawValue }) else { return }
updateMultipleChoiceFilter(at: filterIndex, with: eventsPopUp)
}
@IBAction func focusesPopUpAction(_ sender: Any) {
guard let filterIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.focus.rawValue }) else { return }
updateMultipleChoiceFilter(at: filterIndex, with: focusesPopUp)
}
@IBAction func tracksPopUpAction(_ sender: Any) {
guard let filterIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.track.rawValue }) else { return }
updateMultipleChoiceFilter(at: filterIndex, with: tracksPopUp)
}
private var favoriteSegmentSelected = false
private var downloadedSegmentSelected = false
private var unwatchedSegmentSelected = false
@IBAction func bottomSegmentedControlAction(_ sender: Any) {
if favoriteSegmentSelected != bottomSegmentedControl.isSelected(for: .favorite) {
if let favoriteIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.isFavorite.rawValue }) {
updateToggleFilter(at: favoriteIndex, with: bottomSegmentedControl.isSelected(for: .favorite))
}
}
if downloadedSegmentSelected != bottomSegmentedControl.isSelected(for: .downloaded) {
if let downloadedIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.isDownloaded.rawValue }) {
updateToggleFilter(at: downloadedIndex, with: bottomSegmentedControl.isSelected(for: .downloaded))
}
}
if unwatchedSegmentSelected != bottomSegmentedControl.isSelected(for: .unwatched) {
if let unwatchedIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.isUnwatched.rawValue }) {
updateToggleFilter(at: unwatchedIndex, with: bottomSegmentedControl.isSelected(for: .unwatched))
}
}
favoriteSegmentSelected = bottomSegmentedControl.isSelected(for: .favorite)
downloadedSegmentSelected = bottomSegmentedControl.isSelected(for: .downloaded)
unwatchedSegmentSelected = bottomSegmentedControl.isSelected(for: .unwatched)
}
@IBAction func searchFieldAction(_ sender: Any) {
guard let textIndex = effectiveFilters.index(where: { $0.identifier == FilterIdentifier.text.rawValue }) else { return }
updateTextualFilter(at: textIndex, with: searchField.stringValue)
}
@IBAction func filterButtonAction(_ sender: Any) {
setFilters(hidden: !eventsPopUp.isHidden)
}
override func viewDidLoad() {
super.viewDidLoad()
setFilters(hidden: true)
updateUI()
}
func setFilters(hidden: Bool) {
filterButton.state = NSControl.StateValue(rawValue: hidden ? 0 : 1)
eventsPopUp.isHidden = hidden
focusesPopUp.isHidden = hidden
tracksPopUp.isHidden = hidden
bottomSegmentedControl.isHidden = hidden
}
private func updateMultipleChoiceFilter(at filterIndex: Int, with popUp: NSPopUpButton) {
guard let selectedItem = popUp.selectedItem else { return }
guard let menu = popUp.menu else { return }
guard var filter = effectiveFilters[filterIndex] as? MultipleChoiceFilter else { return }
selectedItem.state = (selectedItem.state == .off) ? .on : .off
let selected = menu.items.filter({ $0.state == .on }).flatMap({ $0.representedObject as? FilterOption })
filter.selectedOptions = selected
var updatedFilters = effectiveFilters
updatedFilters[filterIndex] = filter
delegate?.searchFiltersViewController(self, didChangeFilters: updatedFilters)
popUp.title = filter.title
effectiveFilters = updatedFilters
}
private func updateToggleFilter(at filterIndex: Int, with state: Bool) {
guard var filter = effectiveFilters[filterIndex] as? ToggleFilter else { return }
filter.isOn = state
var updatedFilters = effectiveFilters
updatedFilters[filterIndex] = filter
delegate?.searchFiltersViewController(self, didChangeFilters: updatedFilters)
effectiveFilters = updatedFilters
}
private func updateTextualFilter(at filterIndex: Int, with text: String) {
guard var filter = effectiveFilters[filterIndex] as? TextualFilter else { return }
guard filter.value != text else { return }
filter.value = text
var updatedFilters = effectiveFilters
updatedFilters[filterIndex] = filter
delegate?.searchFiltersViewController(self, didChangeFilters: updatedFilters)
effectiveFilters = updatedFilters
}
private func popUpButton(for filter: MultipleChoiceFilter) -> NSPopUpButton? {
guard let filterIdentifier = FilterIdentifier(rawValue: filter.identifier) else { return nil }
switch filterIdentifier {
case .event:
return eventsPopUp
case .focus:
return focusesPopUp
case .track:
return tracksPopUp
default: return nil
}
}
private func updateUI() {
guard isViewLoaded else { return }
let activeFilters = filters.filter { !$0.isEmpty }
let count = activeFilters.count
if count == 0 {
setFilters(hidden: true)
} else if count == 1 && activeFilters[0] is TextualFilter {
setFilters(hidden: true)
} else {
setFilters(hidden: false)
}
for filter in filters {
switch filter {
case let filter as MultipleChoiceFilter:
guard let popUp = popUpButton(for: filter) else { return }
popUp.removeAllItems()
popUp.addItem(withTitle: filter.title)
filter.options.forEach { option in
let item = NSMenuItem(title: option.title, action: nil, keyEquivalent: "")
item.representedObject = option
item.state = filter.selectedOptions.contains(option) ? .on : .off
popUp.menu?.addItem(item)
}
case let filter as TextualFilter:
if let value = filter.value {
searchField.stringValue = value
}
case let filter as ToggleFilter:
guard let filterID = FilterIdentifier(rawValue: filter.identifier), let segmentIndex = FilterSegment(filterID)?.rawValue else {
break
}
bottomSegmentedControl.setSelected(filter.isOn, forSegment: segmentIndex)
default:
break
}
}
favoriteSegmentSelected = bottomSegmentedControl.isSelected(for: .favorite)
downloadedSegmentSelected = bottomSegmentedControl.isSelected(for: .downloaded)
unwatchedSegmentSelected = bottomSegmentedControl.isSelected(for: .unwatched)
}
}
| bsd-2-clause | 4b3562ef3cf45757e6ceb14f0a124456 | 33.338403 | 166 | 0.661721 | 5.076447 | false | false | false | false |
Legoless/Alpha | Demo/UIKitCatalog/CustomInputAccessoryView.swift | 1 | 1827 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A `UIView` subclass that is used to add a custom title to the text input screens for `UITextField`s.
*/
import UIKit
class CustomInputAccessoryView: UIView {
// MARK: Properties
let titleLabel = UILabel(frame: CGRect.zero)
// MARK: Initialization
init(title: String) {
/*
Call the designated initializer with an inital zero frame. The final
frame will be determined by the layout constraints added later.
*/
super.init(frame: CGRect.zero)
// Setup the label and add it to the view.
titleLabel.font = UIFont.systemFont(ofSize: 60, weight: UIFontWeightMedium)
titleLabel.text = title
addSubview(titleLabel)
/*
Turn off automatic transaltion of resizing masks into constraints as
we'll be specifying our own layout constraints.
*/
translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
/*
Add layout constraints to the label that specifies it must fill the
containing view with an additional 60pts of bottom padding.
*/
let viewsDictionary = ["titleLabel": titleLabel]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-|", options: [], metrics: nil, views: viewsDictionary))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[titleLabel]-60-|", options: [], metrics: nil, views: viewsDictionary))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented.")
}
}
| mit | eee7a0d5fe7a22291342f63a353fc53e | 35.5 | 148 | 0.65589 | 5.464072 | false | false | false | false |
ryanipete/AmericanChronicle | Tests/UnitTests/FakeViewController.swift | 1 | 958 | import UIKit
final class FakeViewController: UIViewController {
// MARK: Test stuff
typealias PresentParams = (vc: UIViewController, animated: Bool, completion: (() -> Void)?)
let present_recorder = InvocationRecorder<PresentParams, Void>(name: "present")
typealias DismissParams = (animated: Bool, completion: (() -> Void)?)
let dismiss_recorder = InvocationRecorder<DismissParams, Void>(name: "dismiss")
func fake_dismiss_completion() {
for call in dismiss_recorder.callLog {
call.params.completion?()
}
}
// MARK: UIViewController overrides
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) {
present_recorder.record((viewControllerToPresent, flag, completion))
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
dismiss_recorder.record((flag, completion))
}
}
| mit | e41e2af01127f7eb62d0727fe2f3df2d | 33.214286 | 120 | 0.676409 | 4.79 | false | false | false | false |
Matzo/Kamishibai | Kamishibai/Classes/Kamishibai.swift | 1 | 5479 | //
// Kamishibai.swift
// Hello
//
// Created by Keisuke Matsuo on 2017/08/12.
//
//
import Foundation
public protocol KamishibaiSceneIdentifierType {
var intValue: Int { get }
// static var count: Int { get }
}
public extension KamishibaiSceneIdentifierType where Self: RawRepresentable, Self.RawValue == Int {
var intValue: Int {
return rawValue
}
}
public protocol KamishibaiCustomViewAnimation: class {
func show(animated: Bool, fulfill: @escaping () -> Void)
func hide(animated: Bool, fulfill: @escaping () -> Void)
}
public func == (l: KamishibaiSceneIdentifierType?, r: KamishibaiSceneIdentifierType?) -> Bool {
guard let l = l, let r = r else { return false }
return l.intValue == r.intValue
}
public class Kamishibai {
// MARK: Properties
public weak var currentViewController: UIViewController?
public var userInfo = [AnyHashable: Any]()
public weak var currentTodo: KamishibaiScene?
public var scenes = [KamishibaiScene]()
public var completion: (() -> Void)?
public let transition = KamishibaiTransitioning()
public var focus = KamishibaiFocusViewController.create()
// MARK: Initialization
public init(initialViewController: UIViewController) {
currentViewController = initialViewController
focus.kamishibai = self
}
// MARK: Private Methods
func nextTodo() -> KamishibaiScene? {
guard let current = currentTodo else { return nil }
guard let startIndex = scenes.index(where: { $0 == current }) else { return nil }
guard scenes.count > startIndex + 1 else { return nil }
for i in (startIndex + 1)..<scenes.count {
if scenes[i].isFinished {
continue
}
return scenes[i]
}
return nil
}
// MARK: Public Methods
/**
sceneを開始する
*/
public func startStory() {
guard let scene = scenes.first else {
finish()
return
}
invoke(scene)
}
/**
scenes の中にある sceneItentifier が一致する scene を終了させる
その後、現在実行中の scene であれば、次のまだ終了していない scene を実行する
*/
public func fulfill(identifier: KamishibaiSceneIdentifierType) {
guard self.currentTodo?.identifier == identifier else { return }
}
/**
渡された scene を終了させる
その後、現在実行中の scene であれば、次のまだ終了していない scene を実行する
*/
public func fulfill(scene: KamishibaiScene) {
if scene.isFinished { return }
// scene を終了させる
scene.isFinished = true
// 現在の scene なら次へ
if let current = currentTodo, current == scene {
self.next()
}
}
/**
現在実行中の scene を終了させる
その後、次のまだ終了していない scene を実行する
*/
public func fulfill() {
}
/**
全てのsceneが完了した際に呼ばれます
*/
public func finish() {
completion?()
}
public func skip(identifier: KamishibaiSceneIdentifierType) {
guard self.currentTodo?.identifier == identifier else { return }
}
/**
終了処理を呼び出します
*/
public func skipAll() {
completion?()
}
/**
Go back to previous ToDo
*/
public func back() {
}
/**
Go to next ToDo
*/
public func next() {
// 全部終了していれば finish()
if scenes.filter({ !$0.isFinished }).count == 0 {
finish()
return
}
// 次があれば scene を選択して実行する
if let scene = nextTodo() {
invoke(scene)
}
}
public func invoke(_ scene: KamishibaiScene) {
currentTodo = scene
if let transition = scene.transition, let vc = currentViewController {
focus.dismiss(animated: true) {
self.transition.transision(fromVC: vc, type: transition, animated: true) { [weak self] (nextVC) in
self?.currentViewController = nextVC
scene.sceneBlock(scene)
}
}
} else {
scene.sceneBlock(scene)
}
}
public func append(_ scene: KamishibaiScene) {
if scenes.contains(where: { $0.identifier == scene.identifier }) {
assertionFailure("Can't use same Identifier")
}
scene.kamishibai = self
self.scenes.append(scene)
}
/**
*/
public func insertNext(_ scene: KamishibaiScene) {
if scenes.contains(where: { $0.identifier == scene.identifier }) {
assertionFailure("Can't use same Identifier")
}
scene.kamishibai = self
if let current = currentTodo, let index = scenes.index(where: { $0 == current }), scenes.count > index + 1 {
self.scenes.insert(scene, at: index + 1)
} else {
self.scenes.append(scene)
}
}
public func clean() {
completion = nil
userInfo.removeAll()
currentTodo = nil
scenes.removeAll()
focus.dismiss(animated: true, completion: { [weak self] in
self?.focus.clean()
self?.focus = KamishibaiFocusViewController.create()
})
}
}
| mit | 6160da2d36ebc5d9e1a07b0483388c9c | 24.653266 | 116 | 0.582958 | 4.381974 | false | false | false | false |
iamtomcat/color | Color/ColorSpace.swift | 1 | 2208 | //
// ColorSpace.swift
//
// Created by Tom Clark on 2015-04-22.
// Copyright (c) 2015 FluidDynamics. All rights reserved.
//
#if os(iOS)
import UIKit
public typealias OSColor = UIColor
#else
import Cocoa
public typealias OSColor = NSColor
#endif
public protocol OSColorProtocol {
var toOSColor: OSColor { get }
}
protocol ColorData {
var toRGB: RGB { get }
var toHSL: HSL { get }
var toHSV: HSV { get }
}
extension ColorSpace: OSColorProtocol {
public var toOSColor: OSColor {
let hsv = data.toHSV
return OSColor(hue: hsv.h, saturation: hsv.s, brightness: hsv.v, alpha: hsv.a)
}
}
extension ColorSpace: Equatable {}
public func ==(lhs: ColorSpace, rhs: ColorSpace) -> Bool {
return lhs.rgb == rhs.rgb
}
public struct ColorSpace {
private let data: ColorData
public init (h360: CGFloat, s: CGFloat, v: CGFloat, a: CGFloat=1.0) {
let h = h360.clamp(0.0, max: 360.0) / 360.0
self.data = HSV(h: h, s: s, v: v, a: a)
}
public init(h: CGFloat, s: CGFloat, v: CGFloat, a: CGFloat=1.0) {
self.data = HSV(h: h, s: s, v: v, a: a)
}
public init (hsv: (h: CGFloat, s: CGFloat, v: CGFloat)) {
let h = hsv.h.clamp(0.0, max: 360.0) / 360.0
self.data = HSV(h: h, s: hsv.s, v: hsv.v, a: 1.0)
}
public init (h360: CGFloat, s: CGFloat, l: CGFloat, a: CGFloat=1.0) {
let h = h360.clamp(0.0, max: 360.0) / 360.0
self.data = HSL(h: h, s: s, l: l, a: a)
}
public init(h: CGFloat, s: CGFloat, l: CGFloat, a: CGFloat=1.0) {
self.data = HSL(h: h, s: s, l: l, a: a)
}
public init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat=1.0) {
self.data = RGB(r: r, g: g, b: b, a: a)
}
public init(hsl: HSL) {
self.data = hsl
}
public func roundColor(byValue value: CGFloat) -> ColorSpace {
let hsl = self.data.toHSL
var s = hsl.s, l = hsl.l
if hsl.s >= 0.7 {
s -= value
} else if s <= 0.3 {
s += value
}
if l >= 0.7 {
l -= value
} else if l <= 0.3 {
l += value
}
return ColorSpace(h: hsl.h, s: s, l: l)
}
public var rgb: RGB {
return data.toRGB
}
public var hsl: HSL {
return data.toHSL
}
public var hsv: HSV {
return data.toHSV
}
}
| mit | 06967b3ecc33e7a8561784944ca02ad3 | 20.861386 | 82 | 0.586051 | 2.76 | false | false | false | false |
NunoAlexandre/broccoli_mobile | ios/Carthage/Checkouts/Eureka/Eureka.playground/Contents.swift | 2 | 6156 | //: **Eureka Playground** - let us walk you through Eureka! cool features, we will show how to
//: easily create powerful forms using Eureka!
//: It allows us to create complex dynamic table view forms and obviously simple static table view. It's ideal for data entry task or settings pages.
import UIKit
import XCPlayground
import PlaygroundSupport
//: Start by importing Eureka module
import Eureka
//: Any **Eureka** form must extend from `FromViewController`
let formController = FormViewController()
PlaygroundPage.current.liveView = formController.view
let b = Array<Int>()
b.last
let f = Form()
f.last
//: ## Operators
//: ### +++
//: Adds a Section to a Form when the left operator is a Form
let form = Form() +++ Section()
//: When both operators are a Section it creates a new Form containing both Section and return the created form.
let form2 = Section("First") +++ Section("Second") +++ Section("Third")
//: Notice that you don't need to add parenthesis in the above expresion, +++ operator is left associative so it will create a form containing the 2 first sections and then append last Section (Third) to the created form.
//: form and form2 don't have any row and are not useful at all. Let's add some rows.
//: ### +++
//: Can be used to append a row to a form without having to create a Section to contain the row. The form section is implicitly created as a result of the +++ operator.
formController.form +++ TextRow("Text")
//: it can also be used to append a Section like this:
formController.form +++ Section()
//: ### <<<
//: Can be used to append rows to a section.
formController.form.last! <<< SwitchRow("Switch") { $0.title = "Switch"; $0.value = true }
//: it can also be used to create a section and append rows to it. Let's use that to add a new section to the form
formController.form +++ PhoneRow("Phone"){ $0.title = "Phone"}
<<< IntRow("IntRow"){ $0.title = "Int"; $0.value = 5 }
formController.view
//: # Callbacks
//: Rows might have several closures associated to be called at different events. Let's see them one by one. Sadly, we can not interact with it in our playground.
//: ### onChange callback
//: Will be called when the value of a row changes. Lots of things can be done with this feature. Let's create a new section for the new rows:
formController.form +++ Section("Callbacks") <<< SwitchRow("scr1"){ $0.title = "Switch to turn red"; $0.value = false }
.onChange({ row in
if row.value == true {
row.cell.backgroundColor = .red
}
else {
row.cell.backgroundColor = .black
}
})
//: Now when we change the value of this row its background color will change to red. Try that by (un)commenting the following line:
formController.view
formController.form.last?.last?.baseValue = true
formController.view
//: Notice that we set the `baseValue` attribute because we did not downcast the result of `formController.form.last?.last`. It is essentially the same as the `value` attribute
//: ### cellSetup and cellUpdate callbacks
//: The cellSetup will be called when the cell of this row is configured (just once at the beginning) and the cellUpdate will be called when it is updated (each time it reappears on screen). Here you should define the appearance of the cell
formController.form.last! <<< SegmentedRow<String>("Segments") { $0.title = "Choose an animal"; $0.value = "🐼"; $0.options = ["🐼", "🐶", "🐻"]}.cellSetup({ cell, row in
cell.backgroundColor = .red
}).cellUpdate({ (cell, row) -> () in
cell.textLabel?.textColor = .yellow
})
//: ### onSelection and onPresent callbacks
//: OnSelection will be called when this row is selected (tapped by the user). It might be useful for certain rows instead of the onChange callback.
//: OnPresent will be called when a row that presents another view controller is tapped. It might be useful to set up the presented view controller.
//: We can not try them out in the playground but they can be set just like the others.
formController.form.last! <<< SegmentedRow<String>("Segments2") { $0.title = "Choose an animal"; $0.value = "🐼"; $0.options = ["🐼", "🐶", "🐻"]
}.onCellSelection{ cell, row in
print("\(cell) for \(row) got selected")
}
formController.view
//: ### Hiding rows
//: We can hide rows by defining conditions that will tell if they should appear on screen or not. Let's create a row that will hide when the previous one is "🐼".
formController.form.last! <<< LabelRow("Confirm") {
$0.title = "Are you sure you do not want the 🐼?"
$0.hidden = "$Segments2 == '🐼'"
}
//: Now let's see how this works:
formController.view
formController.form.rowBy(tag: "Segments2")?.baseValue = "🐶"
formController.view
//: We can do the same using functions. Functions are specially useful for more complicated conditions. This applies when the value of the row we depend on is not compatible with NSPredicates (which is not the current case, but anyway).
formController.form.last! <<< LabelRow("Confirm2") {
$0.title = "Well chosen!!"
$0.hidden = Condition.function(["Segments2"]){ form in
if let r:SegmentedRow<String> = form.rowBy(tag: "Segments2") {
return r.value != "🐼"
}
return true
}
}
//: Now let's see how this works:
formController.view
formController.form.rowBy(tag: "Segments2")?.baseValue = "🐼"
formController.view
| mit | 00dc6f1b46ca9a240c30289f7707cb5a | 47.92 | 700 | 0.6158 | 4.600451 | false | false | false | false |
jad6/DataStore | DataStore/DataStore-Common/DataStoreNotifications.swift | 1 | 11542 | //
// DataStoreNotifications.swift
// DataStore
//
// Created by Jad Osseiran on 29/11/2014.
// Copyright (c) 2015 Jad Osseiran. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import CoreData
public extension DataStore {
/**
* Convenient notifications struct containing the names and keys used
* throughout the DataStore.
*/
public struct Notifications {
/// Notification sent when one of the sibling contexts saves. The
/// notification object is the DataStore object and the userInfo contains:
/// - DSSaveContextKey: the context which has been saved.
/// - DSMergedContextKey: the context which has been merged.
public static let contextSavedAndMerge = "DSContextSavedAndMerge"
/// Notification sent after a save when the stores are about to be
/// swapped and there are changes on the context(s). The notification
/// object is the DataStore object and the userInfo contains:
/// - DSPersistentStoreCoordinatorKey: The persistent store who's stores are swapped.
/// - DSErrorKey (optional): If there was an error in the save this key-value will be populated with it.
public static let changesSavedFromTemporaryStore = "DSChangesSavedFromTemporaryStore"
public static let storeDidMoveToLocalFileSystemDirectory = "storeDidMoveToLocalFileSystemDirectory"
public static let storeDidMoveToCloudFileSystemDirectory = "DSstoreDidMoveToCloudFileSystemDirectory"
/**
* The keys used for the notifications userInfo.
*/
public struct Keys {
/// The error key which will be included when errors are found.
public static let error = "DSErrorKey"
/// The persistent store coordinator attached to the notification.
public static let persistentStoreCoordinator = "DSPersistentStoreCoordinatorKey"
/// The context which has been saved.
public static let saveContext = "DSSaveContextKey"
/// The context which has been merged.
public static let mergedContext = "DSMergedContextKey"
public static let directoryPath = "DSDirectoryPathKey"
}
}
/**
* Helper method to handle all the notification registrations and/or handlings.
*/
func handleNotifications() {
let notificationCenter = NSNotificationCenter.defaultCenter()
// Register a selector to handle this notification.
notificationCenter.addObserver(self, selector: "handlePersistentStoresDidChangeNotification:", name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: persistentStoreCoordinator)
notificationCenter.addObserver(self, selector: "handlePersistentStoresWillChangeNotification:", name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: persistentStoreCoordinator)
// Register a selector for the notification in the case Core Data posts
// content changes from iCloud.
notificationCenter.addObserver(self, selector: "handleImportChangesNotification:", name:
NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: persistentStoreCoordinator)
// Register for the sibling contexts save notifications on their
// respective queues.
notificationCenter.addObserver(self, selector: "handleMainContextSaveNotification:", name:
NSManagedObjectContextDidSaveNotification, object: mainManagedObjectContext)
notificationCenter.addObserver(self, selector: "handleBackgroundContextSaveNotification:", name:
NSManagedObjectContextDidSaveNotification, object: backgroundManagedObjectContext)
}
/**
* Notification method to handle logic just before stores swaping.
*
* - parameter notification: The notification object posted before the stores swap.
*/
func handlePersistentStoresWillChangeNotification(notification: NSNotification) {
// FIXME: What was this meant to do?
// let transitionType: NSPersistentStoreUbiquitousTransitionType?
// Perform operations on the parent (root) context.
writerManagedObjectContext.performBlock {
if self.hasChanges {
// Create the user info dictionary.
var userInfo: [String: AnyObject] = [Notifications.Keys.persistentStoreCoordinator: self.persistentStoreCoordinator]
// If there are changes on the temporary contexts before the
// store swap then save them.
do {
try self.saveAndWait()
} catch let error as NSError {
userInfo = [Notifications.Keys.error: error]
} catch {
assertionFailure("Well looks like the save method on NSManagedObjectContext throws something that is not an NSError... - \(__FUNCTION__) @ \(__LINE__)")
}
// Post the save temporary store notification.
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.changesSavedFromTemporaryStore, object: self, userInfo: userInfo)
// On a transition Core Data gives the app only one chance to save;
// it won’t post another NSPersistentStoreCoordinatorStoresWillChangeNotification
// notification. Therefore reset the contexts after a save.
// if transitionType != nil {
// TODO: Test that this occurs on transtions, not initial set-up.
self.resetContexts()
// }
} else {
// Reset the managed object contexts as! the data they hold is
// now invalid due to the store swap.
self.resetContexts()
}
}
}
func handlePersistentStoresDidChangeNotification(notification: NSNotification) {
if let coordinator = notification.object as? NSPersistentStoreCoordinator {
let stores = coordinator.persistentStores
for store in stores {
var userInfo: [NSObject: AnyObject]?
// Move the store to the right directory.
if store.options?[NSPersistentStoreUbiquitousContentNameKey] != nil {
do {
try placeStoreInCloudDirectory(store, options: store.options)
} catch let error as NSError {
userInfo = [Notifications.Keys.error: error]
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.storeDidMoveToCloudFileSystemDirectory, object: store, userInfo: userInfo)
} else {
do {
try placeStoreInLocalDirectory(store, options: store.options)
} catch let error as NSError {
userInfo = [Notifications.Keys.error: error]
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.storeDidMoveToLocalFileSystemDirectory, object: store, userInfo: userInfo)
}
}
}
}
/**
* Notification method to handle logic for cloud store imports.
*
* - parameter notification: The notification object posted when data was imported.
*/
func handleImportChangesNotification(notification: NSNotification) {
// Inline closure to merge a context.
let mergeContext = { (context: NSManagedObjectContext) -> Void in
context.performBlock() {
context.mergeChangesFromContextDidSaveNotification(notification)
}
}
// Merge all contexts.
mergeContext(writerManagedObjectContext)
mergeContext(mainManagedObjectContext)
mergeContext(backgroundManagedObjectContext)
}
/**
* Notification method to handle logic once the main context has saved.
*
* - parameter notification: The notification object posted when mainManagedObjectContext was saved.
*/
func handleMainContextSaveNotification(notification: NSNotification) {
if let mainContext = notification.object as? NSManagedObjectContext where mainContext == mainManagedObjectContext {
// Merge the changes for the backgroundManagedObjectContext asynchronously.
backgroundManagedObjectContext.performBlock() {
self.backgroundManagedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
// Send the save and merge notification.
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.contextSavedAndMerge, object: self, userInfo: [Notifications.Keys.mergedContext: self.backgroundManagedObjectContext, Notifications.Keys.saveContext: mainContext])
}
}
}
}
/**
* Notification method to handle logic once the bacground context has saved.
*
* - parameter notification: The notification object posted when backgroundManagedObjectContext was saved.
*/
func handleBackgroundContextSaveNotification(notification: NSNotification) {
if let backgroundContext = notification.object as? NSManagedObjectContext where backgroundContext == backgroundManagedObjectContext {
// Merge the changes for the mainManagedObjectContext asynchronously.
mainManagedObjectContext.performBlock() {
self.mainManagedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
// Send the save and merge notification.
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.contextSavedAndMerge, object: self, userInfo: [Notifications.Keys.mergedContext: self.mainManagedObjectContext, Notifications.Keys.saveContext: backgroundContext])
}
}
}
}
} | bsd-2-clause | 324d3580484d1588740df862a845e730 | 51.459091 | 255 | 0.675303 | 6.007288 | false | false | false | false |
cozkurt/coframework | COFramework/COFramework/Swift/Components/UIStyling/AppearanceTextView.swift | 1 | 932 | //
// AppearanceTextView.swift
// COLibrary
//
// Created by Cenker Ozkurt on 07/14/16.
// Copyright (c) 2015 Cenker Ozkurt. All rights reserved.
//
import UIKit
public class AppearanceTextView: UITextView {
@IBInspectable public var appearanceId: String? {
didSet {
if self.appearanceId != "" {
AppearanceController.sharedInstance.customizeTextView(self)
}
}
}
@IBInspectable public var useDefaultFont: Bool = false
public override func awakeFromNib() {
super.awakeFromNib()
setDefaults()
}
public func setDefaults() {
if useDefaultFont {
if let font = self.font {
self.font = font.appearanceFont(fontDefault: defaultFontName, size: font.pointSize)
}
self.textColor = AppearanceController.sharedInstance.color("default.text")
}
}
}
| gpl-3.0 | 409eb9888e10feefb344fe8fc218f811 | 24.189189 | 99 | 0.603004 | 4.829016 | false | false | false | false |
salemoh/GoldenQuraniOS | GoldenQuranSwift/Pods/GRDB.swift/GRDB/Record/Record.swift | 2 | 13619 | // MARK: - Record
/// Record is a class that wraps a table row, or the result of any query. It is
/// designed to be subclassed.
open class Record : RowConvertible, TableMapping, Persistable {
// MARK: - Initializers
/// Creates a Record.
public init() {
}
/// Creates a Record from a row.
///
/// The input row may not come straight from the database. When you want to
/// complete your initialization after being fetched, override
/// awakeFromFetch(row:).
required public init(row: Row) {
if row.isFetched {
// Take care of the hasPersistentChangedValues flag.
//
// Row may be a reused row which will turn invalid as soon as the
// SQLite statement is iterated. We need to store an
// immutable copy.
referenceRow = row.copy()
}
}
/// Do not call this method directly.
///
/// This method is called in an arbitrary dispatch queue, after a record
/// has been fetched from the database.
///
/// Record subclasses have an opportunity to complete their initialization.
///
/// *Important*: subclasses must invoke super's implementation.
open func awakeFromFetch(row: Row) {
}
// MARK: - Core methods
/// The name of a database table.
///
/// This table name is required by the insert, update, save, delete,
/// and exists methods.
///
/// class Person : Record {
/// override class var databaseTableName: String {
/// return "persons"
/// }
/// }
///
/// The implementation of the base class Record raises a fatal error.
///
/// - returns: The name of a database table.
open class var databaseTableName: String {
// Programmer error
fatalError("subclass must override")
}
/// The policy that handles SQLite conflicts when records are inserted
/// or updated.
///
/// This property is optional: its default value uses the ABORT policy
/// for both insertions and updates, and has GRDB generate regular
/// INSERT and UPDATE queries.
///
/// If insertions are resolved with .ignore policy, the
/// `didInsert(with:for:)` method is not called upon successful insertion,
/// even if a row was actually inserted without any conflict.
///
/// See https://www.sqlite.org/lang_conflict.html
open class var persistenceConflictPolicy: PersistenceConflictPolicy {
return PersistenceConflictPolicy(insert: .abort, update: .abort)
}
/// This flag tells whether the hidden "rowid" column should be fetched
/// with other columns.
///
/// Its default value is false:
///
/// // SELECT * FROM persons
/// try Person.fetchAll(db)
///
/// When true, the rowid column is fetched:
///
/// // SELECT *, rowid FROM persons
/// try Person.fetchAll(db)
open class var selectsRowID: Bool {
return false
}
/// The values that should be stored in the database.
///
/// Keys of the returned dictionary must match the column names of the
/// target database table (see Record.databaseTableName()).
///
/// In particular, primary key columns, if any, must be included.
///
/// class Person : Record {
/// var id: Int64?
/// var name: String?
///
/// override var persistentDictionary: [String: DatabaseValueConvertible?] {
/// return ["id": id, "name": name]
/// }
/// }
///
/// The implementation of the base class Record returns an empty dictionary.
open var persistentDictionary: [String: DatabaseValueConvertible?] {
return [:]
}
/// Notifies the record that it was succesfully inserted.
///
/// Do not call this method directly: it is called for you, in a protected
/// dispatch queue, with the inserted RowID and the eventual
/// INTEGER PRIMARY KEY column name.
///
/// The implementation of the base Record class does nothing.
///
/// class Person : Record {
/// var id: Int64?
/// var name: String?
///
/// func didInsert(with rowID: Int64, for column: String?) {
/// id = rowID
/// }
/// }
///
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
open func didInsert(with rowID: Int64, for column: String?) {
}
// MARK: - Copy
/// Returns a copy of `self`, initialized from the values of
/// persistentDictionary.
///
/// Note that the eventual primary key is copied, as well as the
/// hasPersistentChangedValues flag.
///
/// - returns: A copy of self.
open func copy() -> Self {
let copy = type(of: self).init(row: Row(persistentDictionary))
copy.referenceRow = referenceRow
return copy
}
// MARK: - Changes Tracking
/// A boolean that indicates whether the record has changes that have not
/// been saved.
///
/// This flag is purely informative, and does not prevent insert(),
/// update(), and save() from performing their database queries.
///
/// A record is *edited* if its *persistentDictionary* has been changed
/// since last database synchronization (fetch, update, insert). Comparison
/// is performed on *values*: setting a property to the same value does not
/// trigger the edited flag.
///
/// You can rely on the Record base class to compute this flag for you, or
/// you may set it to true or false when you know better. Setting it to
/// false does not prevent it from turning true on subsequent modifications
/// of the record.
public var hasPersistentChangedValues: Bool {
get { return makePersistentChangedValuesIterator().next() != nil }
set { referenceRow = newValue ? nil : Row(persistentDictionary) }
}
/// A dictionary of changes that have not been saved.
///
/// Its keys are column names, and values the old values that have been
/// changed since last fetching or saving of the record.
///
/// Unless the record has actually been fetched or saved, the old values
/// are nil.
///
/// See `hasPersistentChangedValues` for more information.
public var persistentChangedValues: [String: DatabaseValue?] {
var persistentChangedValues: [String: DatabaseValue?] = [:]
for (key, value) in makePersistentChangedValuesIterator() {
persistentChangedValues[key] = value
}
return persistentChangedValues
}
// A change iterator that is used by both hasPersistentChangedValues and
// persistentChangedValues properties.
private func makePersistentChangedValuesIterator() -> AnyIterator<(column: String, old: DatabaseValue?)> {
let oldRow = referenceRow
var newValueIterator = persistentDictionary.makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let new = newValue?.databaseValue ?? .null
guard let oldRow = oldRow, let old: DatabaseValue = oldRow.value(named: column) else {
return (column: column, old: nil)
}
if new != old {
return (column: column, old: old)
}
}
return nil
}
}
/// Reference row for the *hasPersistentChangedValues* property.
var referenceRow: Row?
// MARK: - CRUD
/// Executes an INSERT statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Records whose primary key is declared as "INTEGER PRIMARY KEY" have
/// their id automatically set after successful insertion, if it was nil
/// before the insertion.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
open func insert(_ db: Database) throws {
// The simplest code would be:
//
// try performInsert(db)
// hasPersistentChangedValues = false
//
// But this triggers two calls to persistentDictionary, and this is both
// costly, and ambiguous. Costly because persistentDictionary is slow.
// Ambiguous because persistentDictionary may return a different value.
//
// So let's provide our custom implementation of insert, which uses the
// same persistentDictionary for both insertion, and change tracking.
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
let dao = try DAO(db, self)
var persistentDictionary = dao.persistentDictionary
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
if !conflictResolutionForInsert.invalidatesLastInsertedRowID {
let rowID = db.lastInsertedRowID
let rowIDColumn = dao.primaryKey.rowIDColumn
didInsert(with: rowID, for: rowIDColumn)
// Update persistentDictionary with inserted id, so that we can
// set hasPersistentChangedValues to false:
if let rowIDColumn = rowIDColumn {
if persistentDictionary[rowIDColumn] != nil {
persistentDictionary[rowIDColumn] = rowID
} else {
let rowIDColumn = rowIDColumn.lowercased()
for column in persistentDictionary.keys where column.lowercased() == rowIDColumn {
persistentDictionary[column] = rowID
break
}
}
}
}
// Set hasPersistentChangedValues to false
referenceRow = Row(persistentDictionary)
}
/// Executes an UPDATE statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have updated a row in the database if it
/// returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
open func update(_ db: Database, columns: Set<String>) throws {
// The simplest code would be:
//
// try performUpdate(db, columns: columns)
// hasPersistentChangedValues = false
//
// But this triggers two calls to persistentDictionary, and this is both
// costly, and ambiguous. Costly because persistentDictionary is slow.
// Ambiguous because persistentDictionary may return a different value.
//
// So let's provide our custom implementation of insert, which uses the
// same persistentDictionary for both update, and change tracking.
let dao = try DAO(db, self)
guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else {
// Nil primary key
throw PersistenceError.recordNotFound(self)
}
try statement.execute()
if db.changesCount == 0 {
throw PersistenceError.recordNotFound(self)
}
// Set hasPersistentChangedValues to false
referenceRow = Row(dao.persistentDictionary)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// If the record has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have inserted or updated a row in the
/// database if it returns without error.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
final public func save(_ db: Database) throws {
try performSave(db)
}
/// Executes a DELETE statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to true.
///
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
open func delete(_ db: Database) throws -> Bool {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
// hasPersistentChangedValues flag:
hasPersistentChangedValues = true
}
return try performDelete(db)
}
}
| mit | 68658bddc429c654113a1d7246738aff | 37.148459 | 160 | 0.610911 | 4.937999 | false | false | false | false |
rsaenzi/MyCurrencyConverterApp | MyCurrencyConverterApp/MyCurrencyConverterApp/App/AccessControllers/ApiAccess/ApiRequest.swift | 1 | 3028 | //
// ApiRequest.swift
// MyCurrencyConverterApp
//
// Created by Rigoberto Sáenz Imbacuán on 8/6/16.
// Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved.
//
import Alamofire
class ApiRequest {
// --------------------------------------------------
// Members
// --------------------------------------------------
// Servers
private var serverUrl = "https://api.fixer.io"
// Endpoints
private let endpointGetExchangeRatesURL = /* GET */ "/latest?base=USD"
// --------------------------------------------------
// Methods: Public Interface
// --------------------------------------------------
func endpointGetExchangeRates(onSuccess: callbackSuccessGetExchangeRates, onError: callbackError){
// Request configuration data
let method = Alamofire.Method.GET
let urlString = "\(serverUrl)\(endpointGetExchangeRatesURL)"
// Request headers
let headers = [
"Content-Type": "application/json",
"charset": "utf-8"
]
// Create the request and print all its info
let request = Alamofire.request(method, urlString, headers: headers)
CurrencyConverter.app.control.log.printRequest(request, requestName: #function)
CurrencyConverter.app.control.log.printHeaders(headers)
// Execute the request
request.responseString { response in
CurrencyConverter.app.control.log.printResponseStatus(response)
// If server gave us a proper response to our request
if response.result.isSuccess {
CurrencyConverter.app.control.log.printResponseSuccess(response)
CurrencyConverter.app.control.apiResponse.successGetExchangeRates(response, onSuccess: onSuccess)
}else { // Error flow
CurrencyConverter.app.control.log.errorGeneral(response, onError: onError)
}
}
}
// --------------------------------------------------
// Singleton: Unique Instance
// --------------------------------------------------
private static let instance = ApiRequest()
private init() {}
// --------------------------------------------------
// Singleton: One-Time Access
// --------------------------------------------------
private static var instanceDelivered = false
/**
Creates and returns the unique allowed instance of this class
- returns: Unique instance the first time this method is called, nil otherwise
*/
static func getUniqueInstance() -> ApiRequest? {
// If this is the first time this method is called...
if instanceDelivered == false {
// Create and return the instance
instanceDelivered = true
return instance
}
return nil
}
} | mit | 276b6b0137c697f2f8bb560be82a3419 | 32.977528 | 113 | 0.521006 | 5.725379 | false | false | false | false |
kylebshr/Linchi | Linchi/Socket/PassiveSocket.swift | 4 | 2920 | //
// PassiveSocket.swift
// Linchi
//
import Darwin
/// “A passive socket is not connected, but rather awaits an incoming connection, which will spawn a new active socket”
internal struct PassiveSocket : Socket {
/// File Descriptor
let fd : CInt
private init(_ fd: CInt) { self.fd = fd }
/// Use this when you have to create a socket and don't want to play with optionals
static func defaultInvalidSocket() -> PassiveSocket {
return PassiveSocket(-1)
}
/**
Initialize the socket by doing the following things:
- Apply some basic options (currently LocalAddressReuse and NoSigPipe)
- Bind it to the loopback address and given port
- Make it listen for connections
The initialization will fail and print the reason of the failure if any of these steps fail.
*/
init?(listeningToPort port: in_port_t) {
var hints = addrinfo()
var res = UnsafeMutablePointer<addrinfo>()
hints.ai_family = AF_INET6
hints.ai_socktype = SOCK_STREAM
hints.ai_flags = AI_PASSIVE
let stringport = String(port).utf8.map {Int8($0)} + [0]
let infoSuccess = getaddrinfo(nil, stringport, &hints, &res)
guard infoSuccess == 0 else { return nil }
defer { freeaddrinfo(res) }
for var addressPointer = res; addressPointer != nil; addressPointer = addressPointer.memory.ai_next {
let address = addressPointer.memory
let sockfd = socket(address.ai_family, address.ai_socktype, address.ai_protocol)
let sock = PassiveSocket(sockfd)
do {
try sock.applyOptions(.LocalAddressReuse, .NoSigPipe)
try sock.bindToAddress(address)
try sock.listenToMaxPendingConnections(20)
self = sock
return
}
catch SocketError.CannotSetOption(option: let opt) { print("Cannot set option: \(opt)") }
catch PassiveSocket.Error.BindFailed { print("Bind failed")}
catch PassiveSocket.Error.ListenFailed { print("Listen failed") }
catch {
print("Could not create passive socket for unknown reasons")
}
}
return nil
}
private func bindToAddress(addr: addrinfo) throws {
let bindSuccess = bind(fd, addr.ai_addr, addr.ai_addrlen)
guard bindSuccess != -1 else { throw PassiveSocket.Error.BindFailed }
}
private func listenToMaxPendingConnections(p: Int32) throws {
let success = listen(fd, p)
if success == -1 { throw PassiveSocket.Error.ListenFailed }
}
enum Error : ErrorType {
case CannotGetAddress
case SocketNotAccepted
case BindFailed
case ListenFailed
}
}
| mit | 21b3679403f66ab394b1f9bce74148d1 | 31.764045 | 119 | 0.601852 | 4.643312 | false | false | false | false |
exoplatform/exo-ios | eXo/Sources/Models/Cookies/CookiesInterceptor.swift | 1 | 2115 | //
// CookiesInterceptor.swift
// eXo
//
// Created by Paweł Walczak on 29.01.2018.
// Copyright © 2018 eXo. All rights reserved.
//
import Foundation
protocol CookiesInterceptor {
func intercept(_ cookies: [HTTPCookie], url: URL)
}
class CookiesInterceptorFactory {
func create() -> CookiesInterceptor {
return CookiesInterceptorProxy(interceptors: [SessionCookieInterceptor(), RememberMeCookieInterceptor(), UsernameCookieInterceptor()])
}
}
fileprivate class CookiesInterceptorProxy: CookiesInterceptor {
private let interceptors: [CookiesInterceptor]
init(interceptors: [CookiesInterceptor]) {
self.interceptors = interceptors
}
func intercept(_ cookies: [HTTPCookie], url: URL) {
interceptors.forEach { $0.intercept(cookies, url: url) }
}
}
fileprivate class SessionCookieInterceptor: CookiesInterceptor {
func intercept(_ cookies: [HTTPCookie], url: URL) {
if let session = cookies.first(where: { $0.name == Cookies.session.rawValue })?.value {
PushTokenRestClient.shared.sessionCookieValue = session
}
if let sessionSso = cookies.first(where: { $0.name == Cookies.sessionSso.rawValue })?.value {
PushTokenRestClient.shared.sessionSsoCookieValue = sessionSso
}
}
}
fileprivate class RememberMeCookieInterceptor: CookiesInterceptor {
func intercept(_ cookies: [HTTPCookie], url: URL) {
guard let rememberMe = cookies.first(where: { $0.name == Cookies.rememberMe.rawValue })?.value else { return }
PushTokenRestClient.shared.rememberMeCookieValue = rememberMe
}
}
fileprivate class UsernameCookieInterceptor: CookiesInterceptor {
func intercept(_ cookies: [HTTPCookie], url: URL) {
if let usernameCookie = cookies.first(where: { $0.name == Cookies.username.rawValue}) {
PushTokenSynchronizer.shared.username = usernameCookie.value
PushTokenSynchronizer.shared.url = url.absoluteString.serverDomainWithProtocolAndPort
}
PushTokenSynchronizer.shared.trySynchronizeToken()
}
}
| lgpl-3.0 | 5282f2b21773d9ee67e24fdf34600789 | 33.639344 | 142 | 0.699479 | 4.476695 | false | false | false | false |
haskellswift/swift-package-manager | Sources/PackageDescription/Package.swift | 2 | 7816 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
/// The description for a complete package.
public final class Package {
/// The description for a package dependency.
public class Dependency {
public let versionRange: Range<Version>
public let url: String
init(_ url: String, _ versionRange: Range<Version>) {
self.url = url
self.versionRange = versionRange
}
convenience init(_ url: String, _ versionRange: ClosedRange<Version>) {
self.init(url, versionRange.lowerBound..<versionRange.upperBound.successor())
}
public class func Package(url: String, versions: Range<Version>) -> Dependency {
return Dependency(url, versions)
}
public class func Package(url: String, versions: ClosedRange<Version>) -> Dependency {
return Package(url: url, versions: versions.lowerBound..<versions.upperBound.successor())
}
public class func Package(url: String, majorVersion: Int) -> Dependency {
return Dependency(url, Version(majorVersion, 0, 0)..<Version(majorVersion, .max, .max))
}
public class func Package(url: String, majorVersion: Int, minor: Int) -> Dependency {
return Dependency(url, Version(majorVersion, minor, 0)..<Version(majorVersion, minor, .max))
}
public class func Package(url: String, _ version: Version) -> Dependency {
return Dependency(url, version...version)
}
}
/// The name of the package.
public let name: String
/// pkgconfig name to use for C Modules. If present, swiftpm will try to search for
/// <name>.pc file to get the additional flags needed for the system module.
public let pkgConfig: String?
/// Providers array for System module
public let providers: [SystemPackageProvider]?
/// The list of targets.
public var targets: [Target]
/// The list of dependencies.
public var dependencies: [Dependency]
/// The list of folders to exclude.
public var exclude: [String]
/// Construct a package.
public init(name: String, pkgConfig: String? = nil, providers: [SystemPackageProvider]? = nil, targets: [Target] = [], dependencies: [Dependency] = [], exclude: [String] = []) {
self.name = name
self.pkgConfig = pkgConfig
self.providers = providers
self.targets = targets
self.dependencies = dependencies
self.exclude = exclude
// Add custom exit handler to cause package to be dumped at exit, if requested.
//
// FIXME: This doesn't belong here, but for now is the mechanism we use
// to get the interpreter to dump the package when attempting to load a
// manifest.
// FIXME: Additional hackery here to avoid accessing 'arguments' in a
// process whose 'main' isn't generated by Swift.
// See https://bugs.swift.org/browse/SR-1119.
if CommandLine.argc > 0 {
if let fileNoOptIndex = CommandLine.arguments.index(of: "-fileno"),
let fileNo = Int32(CommandLine.arguments[fileNoOptIndex + 1]) {
dumpPackageAtExit(self, fileNo: fileNo)
}
}
}
}
public enum SystemPackageProvider {
case Brew(String)
case Apt(String)
}
extension SystemPackageProvider {
public var nameValue: (String, String) {
switch self {
case .Brew(let name):
return ("Brew", name)
case .Apt(let name):
return ("Apt", name)
}
}
}
// MARK: Equatable
extension Package : Equatable { }
public func ==(lhs: Package, rhs: Package) -> Bool {
return (lhs.name == rhs.name &&
lhs.targets == rhs.targets &&
lhs.dependencies == rhs.dependencies)
}
extension Package.Dependency : Equatable { }
public func ==(lhs: Package.Dependency, rhs: Package.Dependency) -> Bool {
return lhs.url == rhs.url && lhs.versionRange == rhs.versionRange
}
// MARK: Package JSON serialization
extension SystemPackageProvider {
func toJSON() -> JSON {
let (name, value) = nameValue
return .dictionary(["name": .string(name),
"value": .string(value)
])
}
}
extension Package.Dependency {
func toJSON() -> JSON {
return .dictionary([
"url": .string(url),
"version": .dictionary([
"lowerBound": .string(versionRange.lowerBound.description),
"upperBound": .string(versionRange.upperBound.description)
])
])
}
}
extension Package {
func toJSON() -> JSON {
var dict: [String: JSON] = [:]
dict["name"] = .string(name)
if let pkgConfig = self.pkgConfig {
dict["pkgConfig"] = .string(pkgConfig)
}
dict["dependencies"] = .array(dependencies.map { $0.toJSON() })
dict["exclude"] = .array(exclude.map { .string($0) })
dict["targets"] = .array(targets.map { $0.toJSON() })
if let providers = self.providers {
dict["providers"] = .array(providers.map { $0.toJSON() })
}
return .dictionary(dict)
}
}
extension Target {
func toJSON() -> JSON {
return .dictionary([
"name": .string(name),
"dependencies": .array(dependencies.map { $0.toJSON() })
])
}
}
extension Target.Dependency {
func toJSON() -> JSON {
switch self {
case .Target(let name):
return .string(name)
}
}
}
extension Product {
func toJSON() -> JSON {
var dict: [String: JSON] = [:]
dict["name"] = .string(name)
dict["type"] = .string(type.description)
dict["modules"] = .array(modules.map(JSON.string))
return .dictionary(dict)
}
}
// MARK: Package Dumping
struct Errors {
/// Storage to hold the errors.
private var errors = [String]()
/// Adds error to global error array which will be serialized and dumped in JSON at exit.
mutating func add(_ str: String) {
// FIXME: This will produce invalid JSON if string contains quotes. Assert it for now
// and fix when we have escaping in JSON.
assert(!str.characters.contains("\""), "Error string shouldn't have quotes in it.")
errors += [str]
}
func toJSON() -> JSON {
return .array(errors.map(JSON.string))
}
}
func manifestToJSON(_ package: Package) -> String {
var dict: [String: JSON] = [:]
dict["package"] = package.toJSON()
dict["products"] = .array(products.map { $0.toJSON() })
dict["errors"] = errors.toJSON()
return JSON.dictionary(dict).toString()
}
// FIXME: This function is public to let other modules get the JSON representation
// of the package without exposing the enum JSON defined in this module (because that'll
// leak to clients of PackageDescription i.e every Package.swift file).
public func jsonString(package: Package) -> String {
return package.toJSON().toString()
}
var errors = Errors()
private var dumpInfo: (package: Package, fileNo: Int32)? = nil
private func dumpPackageAtExit(_ package: Package, fileNo: Int32) {
func dump() {
guard let dumpInfo = dumpInfo else { return }
let fd = fdopen(dumpInfo.fileNo, "w")
guard fd != nil else { return }
fputs(manifestToJSON(dumpInfo.package), fd)
fclose(fd)
}
dumpInfo = (package, fileNo)
atexit(dump)
}
| apache-2.0 | a194423dff49aae9aa0f2d11f7a9b98a | 31.702929 | 181 | 0.617579 | 4.266376 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/Pods/Quick/Sources/Quick/Example.swift | 15 | 4217 | import Foundation
private var numberOfExamplesRun = 0
private var numberOfIncludedExamples = 0
// `#if swift(>=3.2) && (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE`
// does not work as expected.
#if swift(>=3.2)
#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE
@objcMembers
public class _ExampleBase: NSObject {}
#else
public class _ExampleBase: NSObject {}
#endif
#else
public class _ExampleBase: NSObject {}
#endif
/**
Examples, defined with the `it` function, use assertions to
demonstrate how code should behave. These are like "tests" in XCTest.
*/
final public class Example: _ExampleBase {
/**
A boolean indicating whether the example is a shared example;
i.e.: whether it is an example defined with `itBehavesLike`.
*/
public var isSharedExample = false
/**
The site at which the example is defined.
This must be set correctly in order for Xcode to highlight
the correct line in red when reporting a failure.
*/
public var callsite: Callsite
weak internal var group: ExampleGroup?
private let internalDescription: String
private let closure: () -> Void
private let flags: FilterFlags
internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () -> Void) {
self.internalDescription = description
self.closure = closure
self.callsite = callsite
self.flags = flags
}
public override var description: String {
return internalDescription
}
/**
The example name. A name is a concatenation of the name of
the example group the example belongs to, followed by the
description of the example itself.
The example name is used to generate a test method selector
to be displayed in Xcode's test navigator.
*/
public var name: String {
guard let groupName = group?.name else { return description }
return "\(groupName), \(description)"
}
/**
Executes the example closure, as well as all before and after
closures defined in the its surrounding example groups.
*/
public func run() {
let world = World.sharedWorld
if numberOfIncludedExamples == 0 {
numberOfIncludedExamples = world.includedExampleCount
}
if numberOfExamplesRun == 0 {
world.suiteHooks.executeBefores()
}
let exampleMetadata = ExampleMetadata(example: self, exampleIndex: numberOfExamplesRun)
world.currentExampleMetadata = exampleMetadata
defer {
world.currentExampleMetadata = nil
}
world.exampleHooks.executeBefores(exampleMetadata)
group!.phase = .beforesExecuting
for before in group!.befores {
before(exampleMetadata)
}
group!.phase = .beforesFinished
closure()
group!.phase = .aftersExecuting
for after in group!.afters {
after(exampleMetadata)
}
group!.phase = .aftersFinished
world.exampleHooks.executeAfters(exampleMetadata)
numberOfExamplesRun += 1
if !world.isRunningAdditionalSuites && numberOfExamplesRun >= numberOfIncludedExamples {
world.suiteHooks.executeAfters()
}
}
/**
Evaluates the filter flags set on this example and on the example groups
this example belongs to. Flags set on the example are trumped by flags on
the example group it belongs to. Flags on inner example groups are trumped
by flags on outer example groups.
*/
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
for (key, value) in group!.filterFlags {
aggregateFlags[key] = value
}
return aggregateFlags
}
}
extension Example {
/**
Returns a boolean indicating whether two Example objects are equal.
If two examples are defined at the exact same callsite, they must be equal.
*/
@nonobjc public static func == (lhs: Example, rhs: Example) -> Bool {
return lhs.callsite == rhs.callsite
}
}
| bsd-3-clause | 225d515188bb7148b019f7c1ef46464c | 30.470149 | 111 | 0.64572 | 4.841561 | false | false | false | false |
rnystrom/GitHawk | Local Pods/SwipeCellKit/Source/SwipeTableViewCell+Accessibility.swift | 2 | 3357 | //
// SwipeTableViewCell+Accessibility.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
extension SwipeTableViewCell {
/// :nodoc:
open override func accessibilityElementCount() -> Int {
guard state != .center else {
return super.accessibilityElementCount()
}
return 1
}
/// :nodoc:
open override func accessibilityElement(at index: Int) -> Any? {
guard state != .center else {
return super.accessibilityElement(at: index)
}
return actionsView
}
/// :nodoc:
open override func index(ofAccessibilityElement element: Any) -> Int {
guard state != .center else {
return super.index(ofAccessibilityElement: element)
}
return element is SwipeActionsView ? 0 : NSNotFound
}
}
extension SwipeTableViewCell {
/// :nodoc:
open override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
guard let tableView = tableView, let indexPath = tableView.indexPath(for: self) else {
return super.accessibilityCustomActions
}
let leftActions = delegate?.tableView(tableView, editActionsForRowAt: indexPath, for: .left) ?? []
let rightActions = delegate?.tableView(tableView, editActionsForRowAt: indexPath, for: .right) ?? []
let actions = [rightActions.first, leftActions.first].flatMap({ $0 }) + rightActions.dropFirst() + leftActions.dropFirst()
if actions.count > 0 {
return actions.map({ SwipeAccessibilityCustomAction(action: $0,
indexPath: indexPath,
target: self,
selector: #selector(performAccessibilityCustomAction(accessibilityCustomAction:))) })
} else {
return super.accessibilityCustomActions
}
}
set {
super.accessibilityCustomActions = newValue
}
}
@objc func performAccessibilityCustomAction(accessibilityCustomAction: SwipeAccessibilityCustomAction) -> Bool {
guard let tableView = tableView else { return false }
let swipeAction = accessibilityCustomAction.action
swipeAction.handler?(swipeAction, accessibilityCustomAction.indexPath)
if swipeAction.style == .destructive {
tableView.deleteRows(at: [accessibilityCustomAction.indexPath], with: .fade)
}
return true
}
}
class SwipeAccessibilityCustomAction: UIAccessibilityCustomAction {
let action: SwipeAction
let indexPath: IndexPath
init(action: SwipeAction, indexPath: IndexPath, target: Any, selector: Selector) {
guard let name = action.accessibilityLabel ?? action.title ?? action.image?.accessibilityIdentifier else {
fatalError("You must provide either a title or an image for a SwipeAction")
}
self.action = action
self.indexPath = indexPath
super.init(name: name, target: target, selector: selector)
}
}
| mit | 0842a00bd53f7860695941406acb6338 | 33.958333 | 153 | 0.592968 | 5.786207 | false | false | false | false |
tibo/SwiftRSS | SwiftRSS/RSSParser.swift | 1 | 6006 | //
// RSSParser.swift
// SwiftRSS_Example
//
// Created by Thibaut LE LEVIER on 05/09/2014.
// Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved.
//
import UIKit
class RSSParser: NSObject, NSXMLParserDelegate {
class func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
let rssParser: RSSParser = RSSParser()
rssParser.parseFeedForRequest(request, callback: callback)
}
var callbackClosure: ((feed: RSSFeed?, error: NSError?) -> Void)?
var currentElement: String = ""
var currentItem: RSSItem?
var feed: RSSFeed = RSSFeed()
// node names
let node_item: String = "item"
let node_title: String = "title"
let node_link: String = "link"
let node_guid: String = "guid"
let node_publicationDate: String = "pubDate"
let node_description: String = "description"
let node_content: String = "content:encoded"
let node_language: String = "language"
let node_lastBuildDate = "lastBuildDate"
let node_generator = "generator"
let node_copyright = "copyright"
// wordpress specifics
let node_commentsLink = "comments"
let node_commentsCount = "slash:comments"
let node_commentRSSLink = "wfw:commentRss"
let node_author = "dc:creator"
let node_category = "category"
func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if ((error) != nil)
{
callback(feed: nil, error: error)
}
else
{
self.callbackClosure = callback
var parser : NSXMLParser = NSXMLParser(data: data)
parser.delegate = self
parser.shouldResolveExternalEntities = false
parser.parse()
}
}
}
// MARK: NSXMLParserDelegate
func parserDidStartDocument(parser: NSXMLParser)
{
}
func parserDidEndDocument(parser: NSXMLParser)
{
if let closure = self.callbackClosure?
{
closure(feed: self.feed, error: nil)
}
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
if elementName == node_item
{
self.currentItem = RSSItem()
}
self.currentElement = ""
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == node_item
{
if let item = self.currentItem?
{
self.feed.items.append(item)
}
self.currentItem = nil
return
}
if let item = self.currentItem?
{
if elementName == node_title
{
item.title = self.currentElement
}
if elementName == node_link
{
item.setLink(self.currentElement)
}
if elementName == node_guid
{
item.guid = self.currentElement
}
if elementName == node_publicationDate
{
item.setPubDate(self.currentElement)
}
if elementName == node_description
{
item.itemDescription = self.currentElement
}
if elementName == node_content
{
item.content = self.currentElement
}
if elementName == node_commentsLink
{
item.setCommentsLink(self.currentElement)
}
if elementName == node_commentsCount
{
item.commentsCount = self.currentElement.toInt()
}
if elementName == node_commentRSSLink
{
item.setCommentRSSLink(self.currentElement)
}
if elementName == node_author
{
item.author = self.currentElement
}
if elementName == node_category
{
item.categories.append(self.currentElement)
}
}
else
{
if elementName == node_title
{
feed.title = self.currentElement
}
if elementName == node_link
{
feed.setLink(self.currentElement)
}
if elementName == node_description
{
feed.feedDescription = self.currentElement
}
if elementName == node_language
{
feed.language = self.currentElement
}
if elementName == node_lastBuildDate
{
feed.setlastBuildDate(self.currentElement)
}
if elementName == node_generator
{
feed.generator = self.currentElement
}
if elementName == node_copyright
{
feed.copyright = self.currentElement
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
self.currentElement += string
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if let closure = self.callbackClosure?
{
closure(feed: nil, error: parseError)
}
}
} | mit | 7713eea043fbef2c4dfa604a540714e8 | 27.469194 | 178 | 0.51382 | 5.43038 | false | false | false | false |
lucaslt89/simpsonizados | simpsonizados/simpsonizados/AppDelegate.swift | 1 | 6223 | //
// AppDelegate.swift
// simpsonizados
//
// Created by Lucas Diez de Medina on 1/16/16.
// Copyright © 2016 technopix. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationCachesDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.technopix.testtest" in the application's caches Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationCachesDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
let options = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() 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
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 64dcc4045e51999f4975e9526aaf4043 | 52.637931 | 291 | 0.720669 | 5.89763 | false | false | false | false |
Swinject/SwinjectMVVMExample | Carthage/Checkouts/ReactiveSwift/Sources/Action.swift | 2 | 7580 | import Dispatch
import Foundation
import enum Result.NoError
/// Represents an action that will do some work when executed with a value of
/// type `Input`, then return zero or more values of type `Output` and/or fail
/// with an error of type `Error`. If no failure should be possible, NoError can
/// be specified for the `Error` parameter.
///
/// Actions enforce serial execution. Any attempt to execute an action multiple
/// times concurrently will return an error.
public final class Action<Input, Output, Error: Swift.Error> {
private let deinitToken: Lifetime.Token
private let executeClosure: (Input) -> SignalProducer<Output, Error>
private let eventsObserver: Signal<Event<Output, Error>, NoError>.Observer
private let disabledErrorsObserver: Signal<(), NoError>.Observer
/// The lifetime of the Action.
public let lifetime: Lifetime
/// A signal of all events generated from applications of the Action.
///
/// In other words, this will send every `Event` from every signal generated
/// by each SignalProducer returned from apply() except `ActionError.disabled`.
public let events: Signal<Event<Output, Error>, NoError>
/// A signal of all values generated from applications of the Action.
///
/// In other words, this will send every value from every signal generated
/// by each SignalProducer returned from apply() except `ActionError.disabled`.
public let values: Signal<Output, NoError>
/// A signal of all errors generated from applications of the Action.
///
/// In other words, this will send errors from every signal generated by
/// each SignalProducer returned from apply() except `ActionError.disabled`.
public let errors: Signal<Error, NoError>
/// A signal which is triggered by `ActionError.disabled`.
public let disabledErrors: Signal<(), NoError>
/// Whether the action is currently executing.
public let isExecuting: Property<Bool>
private let _isExecuting: MutableProperty<Bool> = MutableProperty(false)
/// Whether the action is currently enabled.
public var isEnabled: Property<Bool>
private let _isEnabled: MutableProperty<Bool> = MutableProperty(false)
/// Whether the instantiator of this action wants it to be enabled.
private let isUserEnabled: Property<Bool>
/// This queue is used for read-modify-write operations on the `_executing`
/// property.
private let executingQueue = DispatchQueue(
label: "org.reactivecocoa.ReactiveSwift.Action.executingQueue",
attributes: []
)
/// Whether the action should be enabled for the given combination of user
/// enabledness and executing status.
private static func shouldBeEnabled(userEnabled: Bool, executing: Bool) -> Bool {
return userEnabled && !executing
}
/// Initializes an action that will be conditionally enabled, and creates a
/// SignalProducer for each input.
///
/// - parameters:
/// - enabledIf: Boolean property that shows whether the action is
/// enabled.
/// - execute: A closure that returns the signal producer returned by
/// calling `apply(Input)` on the action.
public init<P: PropertyProtocol>(enabledIf property: P, _ execute: @escaping (Input) -> SignalProducer<Output, Error>) where P.Value == Bool {
deinitToken = Lifetime.Token()
lifetime = Lifetime(deinitToken)
executeClosure = execute
isUserEnabled = Property(property)
(events, eventsObserver) = Signal<Event<Output, Error>, NoError>.pipe()
(disabledErrors, disabledErrorsObserver) = Signal<(), NoError>.pipe()
values = events.map { $0.value }.skipNil()
errors = events.map { $0.error }.skipNil()
isEnabled = Property(_isEnabled)
isExecuting = Property(_isExecuting)
_isEnabled <~ property.producer
.combineLatest(with: isExecuting.producer)
.map(Action.shouldBeEnabled)
}
/// Initializes an action that will be enabled by default, and creates a
/// SignalProducer for each input.
///
/// - parameters:
/// - execute: A closure that returns the signal producer returned by
/// calling `apply(Input)` on the action.
public convenience init(_ execute: @escaping (Input) -> SignalProducer<Output, Error>) {
self.init(enabledIf: Property(value: true), execute)
}
deinit {
eventsObserver.sendCompleted()
disabledErrorsObserver.sendCompleted()
}
/// Creates a SignalProducer that, when started, will execute the action
/// with the given input, then forward the results upon the produced Signal.
///
/// - note: If the action is disabled when the returned SignalProducer is
/// started, the produced signal will send `ActionError.disabled`,
/// and nothing will be sent upon `values` or `errors` for that
/// particular signal.
///
/// - parameters:
/// - input: A value that will be passed to the closure creating the signal
/// producer.
public func apply(_ input: Input) -> SignalProducer<Output, ActionError<Error>> {
return SignalProducer { observer, disposable in
var startedExecuting = false
self.executingQueue.sync {
if self._isEnabled.value {
self._isExecuting.value = true
startedExecuting = true
}
}
if !startedExecuting {
observer.send(error: .disabled)
self.disabledErrorsObserver.send(value: ())
return
}
self.executeClosure(input).startWithSignal { signal, signalDisposable in
disposable += signalDisposable
signal.observe { event in
observer.action(event.mapError(ActionError.producerFailed))
self.eventsObserver.send(value: event)
}
}
disposable += {
self._isExecuting.value = false
}
}
}
}
public protocol ActionProtocol: BindingTargetProtocol {
/// The type of argument to apply the action to.
associatedtype Input
/// The type of values returned by the action.
associatedtype Output
/// The type of error when the action fails. If errors aren't possible then
/// `NoError` can be used.
associatedtype Error: Swift.Error
/// Whether the action is currently enabled.
var isEnabled: Property<Bool> { get }
/// Extracts an action from the receiver.
var action: Action<Input, Output, Error> { get }
/// Creates a SignalProducer that, when started, will execute the action
/// with the given input, then forward the results upon the produced Signal.
///
/// - note: If the action is disabled when the returned SignalProducer is
/// started, the produced signal will send `ActionError.disabled`,
/// and nothing will be sent upon `values` or `errors` for that
/// particular signal.
///
/// - parameters:
/// - input: A value that will be passed to the closure creating the signal
/// producer.
func apply(_ input: Input) -> SignalProducer<Output, ActionError<Error>>
}
extension ActionProtocol {
public func consume(_ value: Input) {
apply(value).start()
}
}
extension Action: ActionProtocol {
public var action: Action {
return self
}
}
/// The type of error that can occur from Action.apply, where `Error` is the
/// type of error that can be generated by the specific Action instance.
public enum ActionError<Error: Swift.Error>: Swift.Error {
/// The producer returned from apply() was started while the Action was
/// disabled.
case disabled
/// The producer returned from apply() sent the given error.
case producerFailed(Error)
}
public func == <Error: Equatable>(lhs: ActionError<Error>, rhs: ActionError<Error>) -> Bool {
switch (lhs, rhs) {
case (.disabled, .disabled):
return true
case let (.producerFailed(left), .producerFailed(right)):
return left == right
default:
return false
}
}
| mit | 9daea173ceb2b03d5c16cdb316ab631b | 33.454545 | 143 | 0.715699 | 4.106176 | false | false | false | false |
ruslanskorb/CoreStore | Sources/DynamicObjectMeta.swift | 1 | 4375 | //
// DynamicObjectMeta.swift
// CoreStore iOS
//
// Created by John Estropia on 2019/08/20.
// Copyright © 2019 John Rommel Estropia. All rights reserved.
//
#if swift(>=5.1)
import CoreData
import Foundation
// MARK: - DynamicObjectMeta
@dynamicMemberLookup
public struct DynamicObjectMeta<R, D>: CustomDebugStringConvertible {
// MARK: Public
public typealias Root = R
public typealias Destination = D
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
return self.keyPathString
}
// MARK: Internal
internal let keyPathString: KeyPathString
internal init(keyPathString: KeyPathString) {
self.keyPathString = keyPathString
}
internal func appending<D2>(keyPathString: KeyPathString) -> DynamicObjectMeta<(R, D), D2> {
return .init(keyPathString: [self.keyPathString, keyPathString].joined(separator: "."))
}
}
// MARK: - DynamicObjectMeta where Destination: NSManagedObject
extension DynamicObjectMeta where Destination: NSManagedObject {
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: AllowedObjectiveCAttributeKeyPathValue>(dynamicMember member: KeyPath<Destination, V>) -> DynamicObjectMeta<(Root, Destination), V.ReturnValueType> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: NSManagedObject>(dynamicMember member: KeyPath<Destination, V>) -> DynamicObjectMeta<(Root, Destination), V> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: NSManagedObject>(dynamicMember member: KeyPath<Destination, V?>) -> DynamicObjectMeta<(Root, Destination), V> {
// TODO: not working
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: NSOrderedSet>(dynamicMember member: KeyPath<Destination, V>) -> DynamicObjectMeta<(Root, Destination), V> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: NSOrderedSet>(dynamicMember member: KeyPath<Destination, V?>) -> DynamicObjectMeta<(Root, Destination), V> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: NSSet>(dynamicMember member: KeyPath<Destination, V>) -> DynamicObjectMeta<(Root, Destination), V> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: NSSet>(dynamicMember member: KeyPath<Destination, V?>) -> DynamicObjectMeta<(Root, Destination), V> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
}
// MARK: - DynamicObjectMeta where Destination: CoreStoreObject
extension DynamicObjectMeta where Destination: CoreStoreObject {
/**
Returns the value for the property identified by a given key.
*/
public subscript<K: AttributeKeyPathStringConvertible>(dynamicMember member: KeyPath<Destination, K>) -> DynamicObjectMeta<(Root, Destination), K.ReturnValueType> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<K: RelationshipKeyPathStringConvertible>(dynamicMember member: KeyPath<Destination, K>) -> DynamicObjectMeta<(Root, Destination), K.DestinationValueType> {
let keyPathString = String(keyPath: member)
return self.appending(keyPathString: keyPathString)
}
}
#endif
| mit | 30015d5ad1dd68ba86fdb276fc30dc06 | 29.587413 | 176 | 0.699588 | 4.909091 | false | false | false | false |
nanthi1990/SwiftCharts | Examples/Examples/CoordsExample.swift | 2 | 6008 | //
// CoordsExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class CoordsExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let chartPoints = [(2, 2), (3, 1), (5, 9), (6, 7), (8, 10), (9, 9), (10, 15), (13, 8), (15, 20), (16, 17)].map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))}
let xValues = ChartAxisValuesGenerator.generateXAxisValuesWithChartPoints(chartPoints, minSegmentCount: 7, maxSegmentCount: 7, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: true)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let chartSettings = ExamplesDefaults.chartSettings
chartSettings.trailing = 20
chartSettings.labelsToAxisSpacingX = 15
chartSettings.labelsToAxisSpacingY = 15
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let showCoordsTextViewsGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in
let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc)
let w: CGFloat = 70
let h: CGFloat = 30
let text = "(\(chartPoint.x.text), \(chartPoint.y.text))"
let font = ExamplesDefaults.labelFont
let textSize = ChartUtils.textSize(text, font: font)
let x = min(screenLoc.x + 5, chart.bounds.width - textSize.width - 5)
let view = UIView(frame: CGRectMake(x, screenLoc.y - h, w, h))
let label = UILabel(frame: view.bounds)
label.text = "(\(chartPoint.x.text), \(chartPoint.y.text))"
label.font = ExamplesDefaults.labelFont
view.addSubview(label)
view.alpha = 0
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
view.alpha = 1
}, completion: nil)
return view
}
let showCoordsLinesLayer = ChartShowCoordsLinesLayer<ChartPoint>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints)
let showCoordsTextLayer = ChartPointsSingleViewLayer<ChartPoint, UIView>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: showCoordsTextViewsGenerator)
let touchViewsGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in
let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc)
let s: CGFloat = 30
let view = HandlingView(frame: CGRectMake(screenLoc.x - s/2, screenLoc.y - s/2, s, s))
view.touchHandler = {
showCoordsLinesLayer.showChartPointLines(chartPoint, chart: chart)
showCoordsTextLayer.showView(chartPoint: chartPoint, chart: chart)
}
return view
}
let touchLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: touchViewsGenerator)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor(red: 0.4, green: 0.4, blue: 1, alpha: 0.2), lineWidth: 3, animDuration: 0.7, animDelay: 0)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
let circleViewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in
let circleView = ChartPointEllipseView(center: chartPointModel.screenLoc, diameter: 24)
circleView.animDuration = 1.5
circleView.fillColor = UIColor.whiteColor()
circleView.borderWidth = 5
circleView.borderColor = UIColor.blueColor()
return circleView
}
let chartPointsCircleLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: circleViewGenerator, displayDelay: 0, delayBetweenItems: 0.05)
var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
showCoordsLinesLayer,
chartPointsLineLayer,
chartPointsCircleLayer,
showCoordsTextLayer,
touchLayer,
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 | 4f6b5d6ef28e8b943c185f09748c56ed | 53.618182 | 258 | 0.661784 | 5.29806 | false | false | false | false |
khizkhiz/swift | test/1_stdlib/Nil.swift | 3 | 1005 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
let opaqueNil: OpaquePointer = nil
if opaqueNil == nil {
print("ok opaqueNil == nil")
// CHECK: ok opaqueNil == nil
}
if opaqueNil != nil {
} else {
print("ok opaqueNil != nil is false")
// CHECK: ok opaqueNil != nil is false
}
let unsafeNil: UnsafeMutablePointer<Int> = nil
if unsafeNil == (nil as UnsafeMutablePointer<Int>) {
print("ok unsafeNil == (nil as UnsafeMutablePointer<Int>)")
// CHECK: ok unsafeNil == (nil as UnsafeMutablePointer<Int>)
}
do {
try NSFileManager.defaultManager().removeItem(at: NSURL(string:"/this/file/does/not/exist")!)
} catch {
print("ok !removed")
// CHECK: ok !removed
}
var selNil: Selector = nil
if selNil == nil {
print("ok selNil == nil")
// CHECK: ok selNil == nil
}
selNil = nil
if selNil == nil {
print("ok selNil == nil")
// CHECK: ok selNil == nil
}
| apache-2.0 | 892730762a72fd5d085e08f078576c44 | 21.840909 | 95 | 0.665672 | 3.441781 | false | false | false | false |
tkremenek/swift | test/SILGen/enum_curry_thunks.swift | 22 | 2467 | // RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s
enum PartialApplyEnumPayload<T, U> {
case left(T)
case both(T, U)
case leftWithLabel(left: T)
case bothWithLabel(left: T, right: U)
case tupleWithLabel(both: (T, U))
// Note: SILGen can emit these thunks correctly, but we disabled
// the feature since calling the constructor directly (without a
// thunk) doesn't work yet.
/* case variadic(_: Int...)
case variadicWithLabel(indices: Int...)
case variadicTuple(_: (Int, Int)...)
case variadicWithOther(String, _: Int...) */
case autoclosure(@autoclosure () -> ())
}
struct S {}
struct C {}
func partialApplyEnumCases(_ x: S, y: C) {
_ = PartialApplyEnumPayload<S, C>.left
_ = PartialApplyEnumPayload<S, C>.both
_ = PartialApplyEnumPayload<S, C>.leftWithLabel
_ = PartialApplyEnumPayload<S, C>.tupleWithLabel
/* _ = PartialApplyEnumPayload<S, C>.variadic
_ = PartialApplyEnumPayload<S, C>.variadicWithLabel
_ = PartialApplyEnumPayload<S, C>.variadicTuple
_ = PartialApplyEnumPayload<S, C>.variadicWithOther */
_ = PartialApplyEnumPayload<S, C>.autoclosure
}
// CHECK-LABEL: sil private [ossa] @$s17enum_curry_thunks21partialApplyEnumCases_1yyAA1SV_AA1CVtFAA07PartialeF7PayloadOyAeGGAEcAJmcfu_AjEcfu0_ : $@convention(thin) (S, @thin PartialApplyEnumPayload<S, C>.Type) -> @owned PartialApplyEnumPayload<S, C> {
// CHECK-LABEL: sil private [ossa] @$s17enum_curry_thunks21partialApplyEnumCases_1yyAA1SV_AA1CVtFAA07PartialeF7PayloadOyAeGGAE_AGtcAJmcfu1_AjE_AGtcfu2_ : $@convention(thin) (S, C, @thin PartialApplyEnumPayload<S, C>.Type) -> @owned PartialApplyEnumPayload<S, C> {
// CHECK-LABEL: sil private [ossa] @$s17enum_curry_thunks21partialApplyEnumCases_1yyAA1SV_AA1CVtFAA07PartialeF7PayloadOyAeGGAEcAJmcfu3_AjEcfu4_ : $@convention(thin) (S, @thin PartialApplyEnumPayload<S, C>.Type) -> @owned PartialApplyEnumPayload<S, C> {
// CHECK-LABEL: sil private [ossa] @$s17enum_curry_thunks21partialApplyEnumCases_1yyAA1SV_AA1CVtFAA07PartialeF7PayloadOyAeGGAE_AGt_tcAJmcfu5_AjE_AGt_tcfu6_ : $@convention(thin) (S, C, @thin PartialApplyEnumPayload<S, C>.Type) -> @owned PartialApplyEnumPayload<S, C> {
// CHECK-LABEL: sil private [ossa] @$s17enum_curry_thunks21partialApplyEnumCases_1yyAA1SV_AA1CVtFAA07PartialeF7PayloadOyAeGGyyXAcAJmcfu7_AJyyXAcfu8_ : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @thin PartialApplyEnumPayload<S, C>.Type) -> @owned PartialApplyEnumPayload<S, C> {
| apache-2.0 | 2b8eec04987957773cd51591662e5602 | 52.630435 | 295 | 0.745845 | 3.126743 | false | false | false | false |
sbooth/SFBAudioEngine | Device/AudioObject.swift | 1 | 27178 | //
// Copyright (c) 2020 - 2022 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
import CoreAudio
import os.log
/// A HAL audio object
public class AudioObject: CustomDebugStringConvertible {
/// The underlying audio object ID
public let objectID: AudioObjectID
/// Initializes an `AudioObject` with `objectID`
/// - precondition: `objectID` != `kAudioObjectUnknown`
/// - parameter objectID: The HAL audio object ID
init(_ objectID: AudioObjectID) {
precondition(objectID != kAudioObjectUnknown)
self.objectID = objectID
}
/// Registered audio object property listeners
private var listenerBlocks = [PropertyAddress: AudioObjectPropertyListenerBlock]()
deinit {
for (property, listenerBlock) in listenerBlocks {
var address = property.rawValue
let result = AudioObjectRemovePropertyListenerBlock(objectID, &address, DispatchQueue.global(qos: .background), listenerBlock)
if result != kAudioHardwareNoError {
os_log(.error, log: audioObjectLog, "AudioObjectRemovePropertyListenerBlock (0x%x, %{public}@) failed: '%{public}@'", objectID, property.description, UInt32(result).fourCC)
}
}
}
/// Returns `true` if `self` has `property`
/// - parameter property: The property to query
public final func hasProperty(_ property: PropertyAddress) -> Bool {
var address = property.rawValue
return AudioObjectHasProperty(objectID, &address)
}
/// Returns `true` if `property` is settable
/// - parameter property: The property to query
/// - throws: An error if `self` does not have `property`
public final func isPropertySettable(_ property: PropertyAddress) throws -> Bool {
var address = property.rawValue
var settable: DarwinBoolean = false
let result = AudioObjectIsPropertySettable(objectID, &address, &settable)
guard result == kAudioHardwareNoError else {
os_log(.error, log: audioObjectLog, "AudioObjectIsPropertySettable (0x%x, %{public}@) failed: '%{public}@'", objectID, property.description, UInt32(result).fourCC)
let userInfo = [NSLocalizedDescriptionKey: NSLocalizedString("Mutability information for the property \(property.selector) in scope \(property.scope) on audio object 0x\(String(objectID, radix: 16, uppercase: false)) could not be retrieved.", comment: "")]
throw NSError(domain: NSOSStatusErrorDomain, code: Int(result), userInfo: userInfo)
}
return settable.boolValue
}
/// A block called with one or more changed audio object properties
/// - parameter changes: An array of changed property addresses
public typealias PropertyChangeNotificationBlock = (_ changes: [PropertyAddress]) -> Void
/// Registers `block` to be performed when `property` changes
/// - parameter property: The property to observe
/// - parameter block: A closure to invoke when `property` changes or `nil` to remove the previous value
/// - throws: An error if the property listener could not be registered
public final func whenPropertyChanges(_ property: PropertyAddress, perform block: PropertyChangeNotificationBlock?) throws {
var address = property.rawValue
// Remove the existing listener block, if any, for the property
if let listenerBlock = listenerBlocks.removeValue(forKey: property) {
let result = AudioObjectRemovePropertyListenerBlock(objectID, &address, DispatchQueue.global(qos: .background), listenerBlock)
guard result == kAudioHardwareNoError else {
os_log(.error, log: audioObjectLog, "AudioObjectRemovePropertyListenerBlock (0x%x, %{public}@) failed: '%{public}@'", objectID, property.description, UInt32(result).fourCC)
let userInfo = [NSLocalizedDescriptionKey: NSLocalizedString("The listener block for the property \(property.selector) on audio object 0x\(String(objectID, radix: 16, uppercase: false)) could not be removed.", comment: "")]
throw NSError(domain: NSOSStatusErrorDomain, code: Int(result), userInfo: userInfo)
}
}
if let block = block {
let listenerBlock: AudioObjectPropertyListenerBlock = { inNumberAddresses, inAddresses in
let count = Int(inNumberAddresses)
let addresses = UnsafeBufferPointer(start: inAddresses, count: count)
let array = [PropertyAddress](unsafeUninitializedCapacity: count) { (buffer, initializedCount) in
for i in 0 ..< count {
buffer[i] = PropertyAddress(addresses[i])
}
initializedCount = count
}
block(array)
}
let result = AudioObjectAddPropertyListenerBlock(objectID, &address, DispatchQueue.global(qos: .background), listenerBlock)
guard result == kAudioHardwareNoError else {
os_log(.error, log: audioObjectLog, "AudioObjectAddPropertyListenerBlock (0x%x, %{public}@) failed: '%{public}@'", objectID, property.description, UInt32(result).fourCC)
let userInfo = [NSLocalizedDescriptionKey: NSLocalizedString("The listener block for the property \(property.selector) on audio object 0x\(String(objectID, radix: 16, uppercase: false)) could not be added.", comment: "")]
throw NSError(domain: NSOSStatusErrorDomain, code: Int(result), userInfo: userInfo)
}
listenerBlocks[property] = listenerBlock;
}
}
// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
return "<\(type(of: self)): 0x\(String(objectID, radix: 16, uppercase: false))>"
}
}
extension AudioObject: Hashable {
public static func == (lhs: AudioObject, rhs: AudioObject) -> Bool {
return lhs.objectID == rhs.objectID
}
public func hash(into hasher: inout Hasher) {
hasher.combine(objectID)
}
}
// MARK: - Scalar Properties
extension AudioObject {
/// Returns the numeric value of `property`
/// - note: The underlying audio object property must be backed by an equivalent native C type of `T`
/// - parameter property: The address of the desired property
/// - parameter type: The underlying numeric type
/// - parameter qualifier: An optional property qualifier
/// - parameter initialValue: An optional initial value for `outData` when calling `AudioObjectGetPropertyData`
/// - throws: An error if `self` does not have `property` or the property value could not be retrieved
public func getProperty<T: Numeric>(_ property: PropertyAddress, type: T.Type, qualifier: PropertyQualifier? = nil, initialValue: T = 0) throws -> T {
return try getAudioObjectProperty(property, from: objectID, type: type, qualifier: qualifier, initialValue: initialValue)
}
/// Returns the Core Foundation object value of `property`
/// - note: The underlying audio object property must be backed by a Core Foundation object and return a `CFType` with a +1 retain count
/// - parameter property: The address of the desired property
/// - parameter type: The underlying `CFType`
/// - parameter qualifier: An optional property qualifier
/// - throws: An error if `self` does not have `property` or the property value could not be retrieved
public func getProperty<T: CFTypeRef>(_ property: PropertyAddress, type: T.Type, qualifier: PropertyQualifier? = nil) throws -> T {
return try getAudioObjectProperty(property, from: objectID, type: type, qualifier: qualifier)
}
/// Returns the `AudioValueRange` value of `property`
/// - note: The underlying audio object property must be backed by `AudioValueRange`
/// - parameter property: The address of the desired property
/// - throws: An error if `self` does not have `property` or the property value could not be retrieved
public func getProperty(_ property: PropertyAddress) throws -> AudioValueRange {
var value = AudioValueRange()
try readAudioObjectProperty(property, from: objectID, into: &value)
return value
}
/// Returns the `AudioStreamBasicDescription` value of `property`
/// - note: The underlying audio object property must be backed by `AudioStreamBasicDescription`
/// - parameter property: The address of the desired property
/// - throws: An error if `self` does not have `property` or the property value could not be retrieved
public func getProperty(_ property: PropertyAddress) throws -> AudioStreamBasicDescription {
var value = AudioStreamBasicDescription()
try readAudioObjectProperty(property, from: objectID, into: &value)
return value
}
/// Sets the value of `property` to `value`
/// - note: The underlying audio object property must be backed by `T`
/// - parameter property: The address of the desired property
/// - parameter value: The desired value
/// - throws: An error if `self` does not have `property`, `property` is not settable, or the property value could not be set
public func setProperty<T>(_ property: PropertyAddress, to value: T) throws {
var data = value
try writeAudioObjectProperty(property, on: objectID, from: &data)
}
}
// MARK: - Array Properties
extension AudioObject {
/// Returns the array value of `property`
/// - note: The underlying audio object property must be backed by a C array of `T`
/// - parameter property: The address of the desired property
/// - parameter type: The underlying array element type
/// - parameter qualifier: An optional property qualifier
/// - throws: An error if `self` does not have `property` or the property value could not be retrieved
public func getProperty<T>(_ property: PropertyAddress, elementType type: T.Type, qualifier: PropertyQualifier? = nil) throws -> [T] {
return try getAudioObjectProperty(property, from: objectID, elementType: type, qualifier: qualifier)
}
/// Sets the value of `property` to `value`
/// - note: The underlying audio object property must be backed by a C array of `T`
/// - parameter property: The address of the desired property
/// - parameter value: The desired value
/// - throws: An error if `self` does not have `property`, `property` is not settable, or the property value could not be set
public func setProperty<T>(_ property: PropertyAddress, to value: [T]) throws {
var data = value
let dataSize = MemoryLayout<T>.stride * value.count
try writeAudioObjectProperty(property, on: objectID, from: &data, size: dataSize)
}
}
// MARK: - Base Audio Object Properties
extension AudioObject {
/// Returns the base class of the underlying HAL audio object
/// - remark: This corresponds to the property `kAudioObjectPropertyBaseClass`
public func baseClass() throws -> AudioClassID {
return try getProperty(PropertyAddress(kAudioObjectPropertyBaseClass), type: AudioClassID.self)
}
/// Returns the class of the underlying HAL audio object
/// - remark: This corresponds to the property `kAudioObjectPropertyClass`
public func `class`() throws -> AudioClassID {
return try getProperty(PropertyAddress(kAudioObjectPropertyClass), type: AudioClassID.self)
}
/// Returns the audio object's owning object
/// - remark: This corresponds to the property `kAudioObjectPropertyOwner`
/// - note: The system audio object does not have an owner
public func owner() throws -> AudioObject {
return AudioObject.make(try getProperty(PropertyAddress(kAudioObjectPropertyOwner), type: AudioObjectID.self))
}
/// Returns the audio object's name
/// - remark: This corresponds to the property `kAudioObjectPropertyName`
public func name() throws -> String {
return try getProperty(PropertyAddress(kAudioObjectPropertyName), type: CFString.self) as String
}
/// Returns the audio object's model name
/// - remark: This corresponds to the property `kAudioObjectPropertyModelName`
public func modelName() throws -> String {
return try getProperty(PropertyAddress(kAudioObjectPropertyModelName), type: CFString.self) as String
}
/// Returns the audio object's manufacturer
/// - remark: This corresponds to the property `kAudioObjectPropertyManufacturer`
public func manufacturer() throws -> String {
return try getProperty(PropertyAddress(kAudioObjectPropertyManufacturer), type: CFString.self) as String
}
/// Returns the name of `element`
/// - remark: This corresponds to the property `kAudioObjectPropertyElementName`
/// - parameter element: The desired element
/// - parameter scope: The desired scope
public func nameOfElement(_ element: PropertyElement, inScope scope: PropertyScope = .global) throws -> String {
return try getProperty(PropertyAddress(PropertySelector(kAudioObjectPropertyElementName), scope: scope, element: element), type: CFString.self) as String
}
/// Returns the category name of `element` in `scope`
/// - remark: This corresponds to the property `kAudioObjectPropertyElementCategoryName`
/// - parameter element: The desired element
/// - parameter scope: The desired scope
public func categoryNameOfElement(_ element: PropertyElement, inScope scope: PropertyScope = .global) throws -> String {
return try getProperty(PropertyAddress(PropertySelector(kAudioObjectPropertyElementCategoryName), scope: scope, element: element), type: CFString.self) as String
}
/// Returns the number name of `element`
/// - remark: This corresponds to the property `kAudioObjectPropertyElementNumberName`
public func numberNameOfElement(_ element: PropertyElement, inScope scope: PropertyScope = .global) throws -> String {
return try getProperty(PropertyAddress(PropertySelector(kAudioObjectPropertyElementNumberName), scope: scope, element: element), type: CFString.self) as String
}
/// Returns the audio objects owned by `self`
/// - remark: This corresponds to the property `kAudioObjectPropertyOwnedObjects`
/// - parameter type: An optional array of `AudioClassID`s to which the returned objects will be restricted
public func ownedObjects(ofType type: [AudioClassID]? = nil) throws -> [AudioObject] {
if type != nil {
var qualifierData = type!
let qualifierDataSize = MemoryLayout<AudioClassID>.stride * type!.count
let qualifier = PropertyQualifier(value: &qualifierData, size: UInt32(qualifierDataSize))
return try getProperty(PropertyAddress(kAudioObjectPropertyOwnedObjects), elementType: AudioObjectID.self, qualifier: qualifier).map { AudioObject.make($0) }
}
return try getProperty(PropertyAddress(kAudioObjectPropertyOwnedObjects), elementType: AudioObjectID.self).map { AudioObject.make($0) }
}
/// Returns `true` if the audio object's hardware is drawing attention to itself
/// - remark: This corresponds to the property `kAudioObjectPropertyIdentify`
public func identify() throws -> Bool {
return try getProperty(PropertyAddress(kAudioObjectPropertyIdentify), type: UInt32.self) != 0
}
/// Sets whether the audio object's hardware should draw attention to itself
/// - remark: This corresponds to the property `kAudioObjectPropertyIdentify`
/// - parameter value: Whether the audio hardware should draw attention to itself
public func setIdentify(_ value: Bool) throws {
try setProperty(PropertyAddress(kAudioObjectPropertyIdentify), to: UInt32(value ? 1 : 0))
}
/// Returns the audio object's serial number
/// - remark: This corresponds to the property `kAudioObjectPropertySerialNumber`
public func serialNumber() throws -> String {
return try getProperty(PropertyAddress(kAudioObjectPropertySerialNumber), type: CFString.self) as String
}
/// Returns the audio object's firmware version
/// - remark: This corresponds to the property `kAudioObjectPropertyFirmwareVersion`
public func firmwareVersion() throws -> String {
return try getProperty(PropertyAddress(kAudioObjectPropertyFirmwareVersion), type: CFString.self) as String
}
}
// MARK: - Helpers
extension AudioObjectPropertyAddress: Hashable {
public static func == (lhs: AudioObjectPropertyAddress, rhs: AudioObjectPropertyAddress) -> Bool {
return lhs.mSelector == rhs.mSelector && lhs.mScope == rhs.mScope && lhs.mElement == rhs.mElement
// Congruence?
// return ((lhs.mSelector == rhs.mSelector) || (lhs.mSelector == kAudioObjectPropertySelectorWildcard) || (rhs.mSelector == kAudioObjectPropertySelectorWildcard))
// && ((lhs.mScope == rhs.mScope) || (lhs.mScope == kAudioObjectPropertyScopeWildcard) || (rhs.mScope == kAudioObjectPropertyScopeWildcard))
// && ((lhs.mElement == rhs.mElement) || (lhs.mElement == kAudioObjectPropertyElementWildcard) || (rhs.mElement == kAudioObjectPropertyElementWildcard))
}
public func hash(into hasher: inout Hasher) {
hasher.combine(mSelector)
hasher.combine(mScope)
hasher.combine(mElement)
}
}
/// Returns the value of `kAudioObjectPropertyClass` for `objectID` or `0` on error
func AudioObjectClass(_ objectID: AudioObjectID) -> AudioClassID {
do {
var value: AudioClassID = 0
try readAudioObjectProperty(PropertyAddress(kAudioObjectPropertyClass), from: objectID, into: &value)
return value
}
catch {
return 0
}
}
/// Returns the value of `kAudioObjectPropertyBaseClass` for `objectID` or `0` on error
func AudioObjectBaseClass(_ objectID: AudioObjectID) -> AudioClassID {
do {
var value: AudioClassID = 0
try readAudioObjectProperty(PropertyAddress(kAudioObjectPropertyBaseClass), from: objectID, into: &value)
return value
}
catch {
return 0
}
}
/// Returns `true` if an audio object's class is equal to `classID`
func AudioObjectIsClass(_ objectID: AudioObjectID, _ classID: AudioClassID) -> Bool
{
return AudioObjectClass(objectID) == classID
}
/// Returns `true` if an audio object's class or base class is equal to `classID`
func AudioObjectIsClassOrSubclassOf(_ objectID: AudioObjectID, _ classID: AudioClassID) -> Bool
{
return AudioObjectClass(objectID) == classID || AudioObjectBaseClass(objectID) == classID
}
/// The log for `AudioObject` and subclasses
let audioObjectLog = OSLog(subsystem: "org.sbooth.AudioEngine", category: "AudioObject")
// MARK: - AudioObject Creation
// Class clusters in the Objective-C sense can't be implemented in Swift
// since Swift initializers don't return a value.
//
// Ideally `AudioObject.init(_ objectID: AudioObjectID)` would initialize and return
// the appropriate subclass, but since that isn't possible,
// `AudioObject.init(_ objectID: AudioObjectID)` has internal access and
// the factory method `AudioObject.make(_ objectID: AudioObjectID)` is public.
extension AudioObject {
/// Creates and returns an initialized `AudioObject`
///
/// Whenever possible this will return a specialized subclass exposing additional functionality
/// - precondition: `objectID` != `kAudioObjectUnknown`
/// - parameter objectID: The audio object ID
public class func make(_ objectID: AudioObjectID) -> AudioObject {
precondition(objectID != kAudioObjectUnknown)
if objectID == kAudioObjectSystemObject {
return AudioSystemObject.instance
}
let objectClass = AudioObjectClass(objectID)
let objectBaseClass = AudioObjectBaseClass(objectID)
switch objectBaseClass {
case kAudioObjectClassID:
switch objectClass {
case kAudioBoxClassID: return AudioBox(objectID)
case kAudioClockDeviceClassID: return AudioClockDevice(objectID)
case kAudioControlClassID: return AudioControl(objectID)
case kAudioDeviceClassID: return AudioDevice(objectID)
case kAudioPlugInClassID: return AudioPlugIn(objectID)
case kAudioStreamClassID: return AudioStream(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown audio object class '%{public}@'", objectClass.fourCC)
return AudioObject(objectID)
}
case kAudioControlClassID:
switch objectClass {
case kAudioBooleanControlClassID: return BooleanControl(objectID)
case kAudioLevelControlClassID: return LevelControl(objectID)
case kAudioSelectorControlClassID: return SelectorControl(objectID)
case kAudioSliderControlClassID: return SliderControl(objectID)
case kAudioStereoPanControlClassID: return StereoPanControl(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown audio control class '%{public}@'", objectClass.fourCC)
return AudioControl(objectID)
}
case kAudioBooleanControlClassID:
switch objectClass {
case kAudioMuteControlClassID: return MuteControl(objectID)
case kAudioSoloControlClassID: return SoloControl(objectID)
case kAudioJackControlClassID: return JackControl(objectID)
case kAudioLFEMuteControlClassID: return LFEMuteControl(objectID)
case kAudioPhantomPowerControlClassID: return PhantomPowerControl(objectID)
case kAudioPhaseInvertControlClassID: return PhaseInvertControl(objectID)
case kAudioClipLightControlClassID: return ClipLightControl(objectID)
case kAudioTalkbackControlClassID: return TalkbackControl(objectID)
case kAudioListenbackControlClassID: return ListenbackControl(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown boolean control class '%{public}@'", objectClass.fourCC)
return BooleanControl(objectID)
}
case kAudioLevelControlClassID:
switch objectClass {
case kAudioVolumeControlClassID: return VolumeControl(objectID)
case kAudioLFEVolumeControlClassID: return LFEVolumeControl(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown level control class '%{public}@'", objectClass.fourCC)
return LevelControl(objectID)
}
case kAudioSelectorControlClassID:
switch objectClass {
case kAudioDataSourceControlClassID: return DataSourceControl(objectID)
case kAudioDataDestinationControlClassID: return DataDestinationControl(objectID)
case kAudioClockSourceControlClassID: return ClockSourceControl(objectID)
case kAudioLineLevelControlClassID: return LineLevelControl(objectID)
case kAudioHighPassFilterControlClassID: return HighPassFilterControl(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown selector control class '%{public}@'", objectClass.fourCC)
return SelectorControl(objectID)
}
case kAudioDeviceClassID:
switch objectClass {
case kAudioAggregateDeviceClassID: return AudioAggregateDevice(objectID)
case kAudioEndPointDeviceClassID: return AudioEndpointDevice(objectID)
case kAudioEndPointClassID: return AudioEndpoint(objectID)
case kAudioSubDeviceClassID: return AudioSubdevice(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown audio device class '%{public}@'", objectClass.fourCC)
return AudioDevice(objectID)
}
case kAudioPlugInClassID:
switch objectClass {
case kAudioTransportManagerClassID: return AudioTransportManager(objectID)
default:
os_log(.debug, log: audioObjectLog, "Unknown audio plug-in class '%{public}@'", objectClass.fourCC)
return AudioPlugIn(objectID)
}
default:
os_log(.debug, log: audioObjectLog, "Unknown audio object base class '%{public}@'", objectClass.fourCC)
return AudioObject(objectID)
}
}
}
// MARK: -
/// A thin wrapper around a HAL audio object property selector for a specific `AudioObject` subclass
public struct AudioObjectSelector<T: AudioObject> {
/// The underlying `AudioObjectPropertySelector` value
let rawValue: AudioObjectPropertySelector
/// Creates a new instance with the specified value
/// - parameter value: The value to use for the new instance
init(_ value: AudioObjectPropertySelector) {
self.rawValue = value
}
}
extension AudioObject {
/// Returns `true` if `self` has `selector` in `scope` on `element`
/// - parameter selector: The selector of the desired property
/// - parameter scope: The desired scope
/// - parameter element: The desired element
public func hasSelector(_ selector: AudioObjectSelector<AudioObject>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master) -> Bool {
return hasProperty(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element))
}
/// Returns `true` if `selector` in `scope` on `element` is settable
/// - parameter selector: The selector of the desired property
/// - parameter scope: The desired scope
/// - parameter element: The desired element
/// - throws: An error if `self` does not have the requested property
public func isSelectorSettable(_ selector: AudioObjectSelector<AudioObject>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master) throws -> Bool {
return try isPropertySettable(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element))
}
/// Registers `block` to be performed when `selector` in `scope` on `element` changes
/// - parameter selector: The selector of the desired property
/// - parameter scope: The desired scope
/// - parameter element: The desired element
/// - parameter block: A closure to invoke when the property changes or `nil` to remove the previous value
/// - throws: An error if the property listener could not be registered
public func whenSelectorChanges(_ selector: AudioObjectSelector<AudioObject>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master, perform block: PropertyChangeNotificationBlock?) throws {
try whenPropertyChanges(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element), perform: block)
}
}
extension AudioObjectSelector where T == AudioObject {
/// The wildcard property selector `kAudioObjectPropertySelectorWildcard`
public static let wildcard = AudioObjectSelector(kAudioObjectPropertySelectorWildcard)
/// The property selector `kAudioObjectPropertyBaseClass`
public static let baseClass = AudioObjectSelector(kAudioObjectPropertyBaseClass)
/// The property selector `kAudioObjectPropertyClass`
public static let `class` = AudioObjectSelector(kAudioObjectPropertyClass)
/// The property selector `kAudioObjectPropertyOwner`
public static let owner = AudioObjectSelector(kAudioObjectPropertyOwner)
/// The property selector `kAudioObjectPropertyName`
public static let name = AudioObjectSelector(kAudioObjectPropertyName)
/// The property selector `kAudioObjectPropertyModelName`
public static let modelName = AudioObjectSelector(kAudioObjectPropertyModelName)
/// The property selector `kAudioObjectPropertyManufacturer`
public static let manufacturer = AudioObjectSelector(kAudioObjectPropertyManufacturer)
/// The property selector `kAudioObjectPropertyElementName`
public static let elementName = AudioObjectSelector(kAudioObjectPropertyElementName)
/// The property selector `kAudioObjectPropertyElementCategoryName`
public static let elementCategoryName = AudioObjectSelector(kAudioObjectPropertyElementCategoryName)
/// The property selector `kAudioObjectPropertyElementNumberName`
public static let elementNumberName = AudioObjectSelector(kAudioObjectPropertyElementNumberName)
/// The property selector `kAudioObjectPropertyOwnedObjects`
public static let ownedObjects = AudioObjectSelector(kAudioObjectPropertyOwnedObjects)
/// The property selector `kAudioObjectPropertyIdentify`
public static let identify = AudioObjectSelector(kAudioObjectPropertyIdentify)
/// The property selector `kAudioObjectPropertySerialNumber`
public static let serialNumber = AudioObjectSelector(kAudioObjectPropertySerialNumber)
/// The property selector `kAudioObjectPropertyFirmwareVersion`
public static let firmwareVersion = AudioObjectSelector(kAudioObjectPropertyFirmwareVersion)
}
extension AudioObjectSelector: CustomStringConvertible {
public var description: String {
return "\(type(of: T.self)): '\(rawValue.fourCC)'"
}
}
| mit | 085272653a305b6ab4ec70f78dd060a7 | 48.146474 | 259 | 0.765178 | 4.132908 | false | false | false | false |
Sharelink/Bahamut | Bahamut/QRCode.swift | 1 | 9594 | //
// QRCode.swift
// QRCode
//
// Created by 刘凡 on 15/5/15.
// Copyright (c) 2015年 joyios. All rights reserved.
//
import UIKit
import AVFoundation
public class QRCode: NSObject, AVCaptureMetadataOutputObjectsDelegate {
/// corner line width
var lineWidth: CGFloat
/// corner stroke color
var strokeColor: UIColor
/// the max count for detection
var maxDetectedCount: Int
/// current count for detection
var currentDetectedCount: Int = 0
/// auto remove sub layers when detection completed
var autoRemoveSubLayers: Bool
/// completion call back
var completedCallBack: ((stringValue: String) -> ())?
/// the scan rect, default is the bounds of the scan view, can modify it if need
public var scanFrame: CGRect = CGRectZero
/// init function
///
/// - parameter autoRemoveSubLayers: remove sub layers auto after detected code image, defalt is false
/// - parameter lineWidth: line width, default is 4
/// - parameter strokeColor: stroke color, default is Green
/// - parameter maxDetectedCount: max detecte count, default is 20
///
/// - returns: the scanner object
public init(autoRemoveSubLayers: Bool = false, lineWidth: CGFloat = 4, strokeColor: UIColor = UIColor.greenColor(), maxDetectedCount: Int = 20) {
self.lineWidth = lineWidth
self.strokeColor = strokeColor
self.maxDetectedCount = maxDetectedCount
self.autoRemoveSubLayers = autoRemoveSubLayers
}
deinit {
if session.running {
session.stopRunning()
}
removeAllLayers()
}
// MARK: - Generate QRCode Image
/// generate image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
/// - parameter color: the CI color for forenground, default is black
/// - parameter backColor: th CI color for background, default is white
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25, color: CIColor = CIColor(color: UIColor.blackColor()), backColor: CIColor = CIColor(color: UIColor.whiteColor())) -> UIImage? {
// generate qrcode image
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setDefaults()
qrFilter.setValue(stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), forKey: "inputMessage")
let ciImage = qrFilter.outputImage
// scale qrcode image
let colorFilter = CIFilter(name: "CIFalseColor")!
colorFilter.setDefaults()
colorFilter.setValue(ciImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backColor, forKey: "inputColor1")
let transform = CGAffineTransformMakeScale(5, 5)
let transformedImage = colorFilter.outputImage!.imageByApplyingTransform(transform)
let image = UIImage(CIImage: transformedImage)
if avatarImage != nil {
return insertAvatarImage(image, avatarImage: avatarImage!, scale: avatarScale)
}
return image
}
class func insertAvatarImage(codeImage: UIImage, avatarImage: UIImage, scale: CGFloat) -> UIImage {
let rect = CGRectMake(0, 0, codeImage.size.width, codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.drawInRect(rect)
let avatarSize = CGSizeMake(rect.size.width * scale, rect.size.height * scale)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
avatarImage.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
// MARK: - Video Scan
/// prepare scan
///
/// - parameter view: the scan view, the preview layer and the drawing layer will be insert into this view
/// - parameter completion: the completion call back
public func prepareScan(view: UIView, completion:(stringValue: String)->()) {
scanFrame = view.bounds
completedCallBack = completion
currentDetectedCount = 0
setupSession()
setupLayers(view)
}
/// start scan
public func startScan() {
if session.running {
NSLog("the capture session is running")
return
}
session.startRunning()
}
/// stop scan
public func stopScan() {
if !session.running {
NSLog("the capture session is running")
return
}
session.stopRunning()
}
func setupLayers(view: UIView) {
drawLayer.frame = view.bounds
view.layer.insertSublayer(drawLayer, atIndex: 0)
previewLayer.frame = view.bounds
view.layer.insertSublayer(previewLayer, atIndex: 0)
}
func setupSession() {
if session.running {
NSLog("the capture session is running")
return
}
if !session.canAddInput(videoInput) {
NSLog("can not add input device")
return
}
if !session.canAddOutput(dataOutput) {
NSLog("can not add output device")
return
}
session.addInput(videoInput)
session.addOutput(dataOutput)
dataOutput.metadataObjectTypes = dataOutput.availableMetadataObjectTypes;
dataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
}
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
clearDrawLayer()
for dataObject in metadataObjects {
if let codeObject = dataObject as? AVMetadataMachineReadableCodeObject {
let obj = previewLayer.transformedMetadataObjectForMetadataObject(codeObject) as! AVMetadataMachineReadableCodeObject
if CGRectContainsRect(scanFrame, obj.bounds) {
if currentDetectedCount > maxDetectedCount {
session.stopRunning()
completedCallBack!(stringValue: codeObject.stringValue)
if autoRemoveSubLayers {
removeAllLayers()
}
}
currentDetectedCount += 1
// transform codeObject
drawCodeCorners(previewLayer.transformedMetadataObjectForMetadataObject(codeObject) as! AVMetadataMachineReadableCodeObject)
}
}
}
}
public func removeAllLayers() {
previewLayer.removeFromSuperlayer()
drawLayer.removeFromSuperlayer()
}
func clearDrawLayer() {
if drawLayer.sublayers == nil {
return
}
for layer in drawLayer.sublayers! {
layer.removeFromSuperlayer()
}
}
func drawCodeCorners(codeObject: AVMetadataMachineReadableCodeObject) {
if codeObject.corners.count == 0 {
return
}
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = lineWidth
shapeLayer.strokeColor = strokeColor.CGColor
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.path = createPath(codeObject.corners).CGPath
drawLayer.addSublayer(shapeLayer)
}
func createPath(points: NSArray) -> UIBezierPath {
let path = UIBezierPath()
var point = CGPoint()
var index = 0
CGPointMakeWithDictionaryRepresentation((points[index] as! CFDictionary), &point)
path.moveToPoint(point)
index += 1
while index < points.count {
CGPointMakeWithDictionaryRepresentation((points[index] as! CFDictionary), &point)
index += 1
path.addLineToPoint(point)
}
path.closePath()
return path
}
/// previewLayer
lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
return layer
}()
/// drawLayer
lazy var drawLayer: CALayer = {
return CALayer()
}()
/// session
lazy var session: AVCaptureSession = {
return AVCaptureSession()
}()
/// input
lazy var videoInput: AVCaptureDeviceInput? = {
if let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) {
do {
return try AVCaptureDeviceInput(device: device)
} catch _ {
return nil
}
}
return nil
}()
/// output
lazy var dataOutput: AVCaptureMetadataOutput = {
return AVCaptureMetadataOutput()
}()
} | mit | 8f5c726d690a273b33f0d6ba7570ad5b | 32.764085 | 236 | 0.602628 | 5.821494 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/SEO.swift | 1 | 3067 | //
// SEO.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// SEO information.
open class SEOQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = SEO
/// The meta description.
@discardableResult
open func description(alias: String? = nil) -> SEOQuery {
addField(field: "description", aliasSuffix: alias)
return self
}
/// The SEO title.
@discardableResult
open func title(alias: String? = nil) -> SEOQuery {
addField(field: "title", aliasSuffix: alias)
return self
}
}
/// SEO information.
open class SEO: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = SEOQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "description":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: SEO.self, field: fieldName, value: fieldValue)
}
return value
case "title":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: SEO.self, field: fieldName, value: fieldValue)
}
return value
default:
throw SchemaViolationError(type: SEO.self, field: fieldName, value: fieldValue)
}
}
/// The meta description.
open var description: String? {
return internalGetDescription()
}
func internalGetDescription(alias: String? = nil) -> String? {
return field(field: "description", aliasSuffix: alias) as! String?
}
/// The SEO title.
open var title: String? {
return internalGetTitle()
}
func internalGetTitle(alias: String? = nil) -> String? {
return field(field: "title", aliasSuffix: alias) as! String?
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| mit | b156d1b2602400a227b13c80d8a3bcd8 | 30.618557 | 89 | 0.708184 | 3.947233 | false | false | false | false |
squaremeals/squaremeals-ios-app | SquareMeals/Coordinator/AppCoordinator.swift | 1 | 1477 | //
// AppCoordinator.swift
// SquareMeals
//
// Created by Zachary Shakked on 10/24/17.
// Copyright © 2017 Shakd, LLC. All rights reserved.
//
import UIKit
public final class AppCoordinator: Coordinator, AuthenticationCoordinatorDelegate {
fileprivate let rootViewController: UIViewController
fileprivate var authenticationCoordinator: AuthenticationCoordinator?
fileprivate var mainCoordinator: MainCoordinator?
public init(rootViewController: UIViewController) {
self.rootViewController = rootViewController
}
public func start() {
mainCoordinator = MainCoordinator(rootViewController: rootViewController)
mainCoordinator?.start()
// authenticationCoordinator = AuthenticationCoordinator(rootViewController: rootViewController, delegate: self)
// authenticationCoordinator?.start()
}
//MARK:- AuthenticationCoordinator
public func authenticationCoordinatorSucceeded(service: CloudKitService) {
print("CloudKit Service Established: \(service)")
let alert = UIAlertController(title: "iCloud Service Established", message: "The iCloud Service has been established.", preferredStyle: .alert)
let okay = UIAlertAction(title: "Okay", style: .default, handler: nil)
alert.addAction(okay)
rootViewController.presentedViewController?.present(alert, animated: true, completion: nil)
}
}
| mit | c4cb0dd9a816ffba33bd1ae70f1b2f66 | 32.545455 | 151 | 0.70935 | 5.569811 | false | false | false | false |
mattwelborn/HSTracker | HSTracker/Core/Categories/String.swift | 1 | 1644 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 17/02/16.
*/
import Foundation
extension String {
static func isNullOrEmpty(str: String?) -> Bool {
return str == nil || str!.isEmpty
}
func startsWith(str: String) -> Bool {
return self.hasPrefix(str)
}
func endsWith(str: String) -> Bool {
return self.hasSuffix(str)
}
func substringWithRange(start: Int, end: Int) -> String {
if start < 0 || start > self.characters.count {
print("start index \(start) out of bounds")
return ""
} else if end < 0 || end > self.characters.count {
print("end index \(end) out of bounds")
return ""
}
let range = self.startIndex.advancedBy(start) ..< self.startIndex.advancedBy(end)
return self.substringWithRange(range)
}
func substringWithRange(start: Int, location: Int) -> String {
if start < 0 || start > self.characters.count {
print("start index \(start) out of bounds")
return ""
} else if location < 0 || start + location > self.characters.count {
print("end index \(start + location) out of bounds")
return ""
}
let startPos = self.startIndex.advancedBy(start)
let endPos = self.startIndex.advancedBy(start + location)
let range = startPos ..< endPos
return self.substringWithRange(range)
}
}
| mit | 7b5e556b8e968c93748f0715465d017f | 30.018868 | 89 | 0.601582 | 4.337731 | false | false | false | false |
spire-inc/Bond | Bond/Extensions/iOS/UITextField+Bond.swift | 1 | 4302 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension UITextField {
private struct AssociatedKeys {
static var TextKey = "bnd_TextKey"
static var AttributedTextKey = "bnd_AttributedTextKey"
static var EditingKey = "bnd_editing"
}
public var bnd_text: Observable<String?> {
if let bnd_text: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.TextKey) {
return bnd_text as! Observable<String?>
} else {
let bnd_text = Observable<String?>(self.text)
objc_setAssociatedObject(self, &AssociatedKeys.TextKey, bnd_text, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var updatingFromSelf: Bool = false
bnd_text.observeNew { [weak self] (text: String?) in
if !updatingFromSelf {
self?.text = text
}
}
self.bnd_controlEvent.filter { $0 == UIControlEvents.EditingChanged }.observe { [weak self, weak bnd_text] event in
guard let unwrappedSelf = self, let bnd_text = bnd_text else { return }
updatingFromSelf = true
bnd_text.next(unwrappedSelf.text)
updatingFromSelf = false
}
return bnd_text
}
}
public var bnd_editing: Observable<Bool>{
if let bnd_editing: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.EditingKey){
return bnd_editing as! Observable<Bool>
}else{
let bnd_editing = Observable<Bool>(false)
objc_setAssociatedObject(self, &AssociatedKeys.EditingKey, bnd_editing, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.bnd_controlEvent.filter { $0 == UIControlEvents.EditingDidBegin }.observe { event in
bnd_editing.next(true)
}
self.bnd_controlEvent.filter { $0 == UIControlEvents.EditingDidEnd }.observe {event in
bnd_editing.next(false)
}
return bnd_editing
}
}
public var bnd_attributedText: Observable<NSAttributedString?> {
if let bnd_attributedText: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.AttributedTextKey) {
return bnd_attributedText as! Observable<NSAttributedString?>
} else {
let bnd_attributedText = Observable<NSAttributedString?>(self.attributedText)
objc_setAssociatedObject(self, &AssociatedKeys.AttributedTextKey, bnd_attributedText, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var updatingFromSelf: Bool = false
bnd_attributedText.observeNew { [weak self] (text: NSAttributedString?) in
if !updatingFromSelf {
self?.attributedText = text
}
}
self.bnd_controlEvent.filter { $0 == UIControlEvents.EditingChanged }.observe { [weak self, weak bnd_attributedText] event in
guard let unwrappedSelf = self, let bnd_attributedText = bnd_attributedText else { return }
updatingFromSelf = true
bnd_attributedText.next(unwrappedSelf.attributedText)
updatingFromSelf = false
}
return bnd_attributedText
}
}
public var bnd_textColor: Observable<UIColor?> {
return bnd_associatedObservableForValueForKey("textColor")
}
}
| mit | 2ce88053f7f5f54c44d6c3b3b43b0e8b | 38.109091 | 149 | 0.696885 | 4.596154 | false | false | false | false |
brunophilipe/Noto | Noto/Extensions/NSTextView+Additions.swift | 1 | 1693 | //
// Created by Bruno Philipe on 12/3/17.
// Copyright (c) 2017 Bruno Philipe. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import AppKit
extension NSTextView
{
func forceLayoutToCharacterIndex(_ index: Int)
{
var loc = index
if loc > 0, let len = self.textStorage?.length, len > 0
{
if loc >= len
{
loc = len - 1
}
/* Find out which glyph index the desired character index corresponds to */
if let glyphRange = layoutManager?.glyphRange(forCharacterRange: NSMakeRange(loc, 1), actualCharacterRange: nil),
glyphRange.location > 0
{
/* Now cause layout by asking a question which has to determine where the glyph is */
_ = layoutManager?.textContainer(forGlyphAt: glyphRange.location - 1, effectiveRange: nil)
}
}
}
}
extension EditorView
{
func setColorsFromTheme(theme: EditorTheme)
{
backgroundColor = theme.editorBackground
textColor = theme.editorForeground
lineNumbersView?.textColor = theme.lineNumbersForeground
lineNumbersView?.backgroundColor = theme.lineNumbersBackground
}
}
| gpl-3.0 | 9e97a41c381e4aa5d447cc97fcc7a1fd | 30.351852 | 116 | 0.724749 | 3.883028 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 19--Keep-On-The-Sunny-Side/Forecaster/GitHub Friends/SearchTableViewController.swift | 1 | 7376 | //
// SearchTableViewController.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/28/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
class SearchTableViewController: UITableViewController, APIControllerProtocol, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating
{
var cities = Array<CityData>()
var apiSearch: APIController!
var delegator:SearchTableViewProtocol!
var cancelSearch = true
var filteredTableData = [String]()
var shouldShowSearchResults = false
var searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad()
{
super.viewDidLoad()
//definesPresentationContext = true
//edgesForExtendedLayout = .None
title = "Add City"
apiSearch = APIController(delegate: self)
//apiSearch.searchGitHubFor("Leslie Brown")
self.tableView.registerClass(CityCell.self, forCellReuseIdentifier: "CityCell")
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
//searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200, height: 80)
//searchController.searchBar.center.y = 200
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
tableView.tableHeaderView = searchController.searchBar
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.tableView.reloadData()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Search bar methods
func searchBarTextDidBeginEditing(searchBar: UISearchBar)
{
print("me empieza! usame! soy tuya!")
shouldShowSearchResults = true
//gitHubFriends.removeAll()
tableView.reloadData()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar)
{
print("no pares!!")
shouldShowSearchResults = false
cities.removeAll()
tableView.reloadData()
dismissViewControllerAnimated(true, completion: nil) // this destroy the modal view like the popover
}
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
if !shouldShowSearchResults {
print("ahi! me tocaste el boton de buscar")
//gitHubFriends.removeAll()
shouldShowSearchResults = true
apiSearch.searchApiForData( searchBar.text!)
tableView.reloadData()
}
searchController.searchBar.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
{
print("me estas escribiendo")
shouldShowSearchResults = false
cities.removeAll()
tableView.reloadData()
}
func searchBarTextDidEndEditing(searchBar: UISearchBar)
{
print("no te demores quiero mas")
shouldShowSearchResults = true
cities.removeAll()
apiSearch.searchApiForData(searchBar.text!)
tableView.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
print("Hola papy estoy buscando")
// Reload the tableview.
tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return cities.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CityCell", forIndexPath: indexPath) as! CityCell
let friend = cities[indexPath.row]
print("friend: "+friend.name)
cell.textLabel!.text = friend.name != "" ? friend.name: "User: "+friend.login
cell.loadImage(friend.thumbnailImageURL)
//cell.detailTextLabel?.text = "Penpenuche"
return cell
}
//MARK: - API Controller Protocl
func didReceiveAPIResults(results:NSArray)
{
print("didReceiveAPIResults got: \(results)")
dispatch_async(dispatch_get_main_queue(), {
self.cities = CityData.CitiesDataWithJSON(results)
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
delegator?.cityWasFound(cities[indexPath.row].login)
print("From didSelectRowAtIndexPath SearchTableView Protocol: "+cities[indexPath.row].login)
}
/*
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.
}
}
| cc0-1.0 | e992e353a057012f86aab8898441b30f | 30.25 | 157 | 0.659932 | 5.7393 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/SelectCurrency/Views/SelectCurrencyTableViewHeader.swift | 1 | 1823 | import Library
import Prelude
import Prelude_UIKit
import UIKit
final class SelectCurrencyTableViewHeader: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
_ = (self.headerStackView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bindStyles() {
super.bindStyles()
_ = self.headerImageView
|> \.contentMode .~ .scaleAspectFill
_ = self.headerStackView
|> headerStackViewStyle
_ = self.headerLabel
|> settingsDescriptionLabelStyle
|> headerLabelStyle
}
// MARK: - Accessors
public var text: String? {
didSet {
_ = self.headerLabel |> \.text .~ self.text
}
}
// MARK: - Subviews
private lazy var headerStackView: UIStackView = {
UIStackView(arrangedSubviews: [
self.headerImageView,
self.headerLabel
])
}()
private lazy var headerImageView: UIImageView = {
UIImageView(image: image(named: "icon--currency-header", inBundle: Bundle.framework))
}()
private lazy var headerLabel: UILabel = { UILabel(frame: .zero) }()
}
// MARK: - Styles
private let headerStackViewStyle: StackViewStyle = { (stackView: UIStackView) in
stackView
|> \.axis .~ NSLayoutConstraint.Axis.vertical
|> \.alignment .~ UIStackView.Alignment.center
|> \.spacing .~ Styles.grid(2)
|> \.layoutMargins .~ UIEdgeInsets(
top: Styles.grid(4), left: Styles.grid(2), bottom: Styles.grid(2), right: Styles.grid(2)
)
|> \.isLayoutMarginsRelativeArrangement .~ true
}
private let headerLabelStyle: LabelStyle = { (label: UILabel) in
label
|> \.textColor .~ UIColor.ksr_support_400
|> \.backgroundColor .~ UIColor.ksr_support_100
}
| apache-2.0 | daf6ffd60d1ad54030ea0294261b2d05 | 23.635135 | 94 | 0.66429 | 4.414044 | false | false | false | false |
AleksanderKoko/WikimediaCommonsApi | WCApi/Classes/SignUp.swift | 1 | 3977 | import Alamofire
public class SignUp: GetTokenHandlerProtocol {
internal let handler: SignUpHandlerProtocol
internal let getToken: GetToken
internal var token: String?
internal var captchaId: String?
internal var username: String?
internal var password: String?
internal var captchaText: String?
internal var email: String?
enum SignUpResults : String {
case NeedCaptcha = "NeedCaptcha"
case Fail = "FAIL"
case Pass = "PASS"
}
public init(handler: SignUpHandlerProtocol){
self.handler = handler
self.getToken = GetToken()
self.getToken.setHandler(self)
}
public func setToken(token: String){
self.token = token
self.makeNetworkCall()
}
public func getTokenFatalError(error: GetTokenErrorFatal){
self.handler.signUpError(error)
}
public func signUp(username: String, password: String, email: String?, captchaId: String, captchaText: String?) -> Void {
self.username = username
self.password = password
self.email = email
self.captchaId = captchaId
self.captchaText = captchaText
if self.token != nil{
self.makeNetworkCall()
}else{
do {
try self.getToken.getToken(GetToken.TokenTypes.CreateUserToken)
}catch{}
}
}
internal func makeNetworkCall() -> Void{
Alamofire.request(
.POST,
Config.apiUrl,
parameters: [
"action": "createaccount",
"format": "json",
"createreturnurl": "https://commons.wikimedia.org/",
"username": self.username!,
"password": self.password!,
"retype": self.password!,
"createtoken": self.token!,
"captchaWord": self.captchaText!,
"captchaId": self.captchaId!
]
).responseJSON { response in
if let JSON = response.result.value {
print(JSON)
if let result = JSON.objectForKey("createaccount")?.objectForKey("status") {
let resultStr : String = result as! String
switch (resultStr) {
case SignUpResults.Pass.rawValue:
self.handler.signUpSuccess()
break
case SignUpResults.Fail.rawValue:
if let message = JSON.objectForKey("createaccount")?.objectForKey("message;"){
self.handler.signUpError(SignUpErrorFatal(message: message as! String))
}else{
self.handler.signUpError(SignUpErrorFatal(message: GeneralErrorMessages.FatalErrorCantProcessJSON.rawValue))
}
break
default:
self.handler.signUpError(SignUpErrorFatal(message: GeneralErrorMessages.FatalErrorCantProcessJSON.rawValue))
break
}
}else{
self.handler.signUpError(SignUpErrorFatal(message: GeneralErrorMessages.FatalErrorCantProcessJSON.rawValue))
}
}else{
self.handler.signUpError(SignUpErrorFatal(message: GeneralErrorMessages.FatalErrorCantGetResponse.rawValue))
}
}
}
}
public protocol SignUpHandlerProtocol{
func signUpSuccess()
func signUpError(error: SignUpErrorFatal)
func signUpError(error: GetTokenErrorFatal)
} | mit | f3572554ee8020be91f8454449c925db | 33 | 140 | 0.518481 | 5.665242 | false | false | false | false |
SwiftScream/ScreamRefreshControl | Source/ModernRefreshControl.swift | 1 | 5172 | // Copyright 2017 Alex Deem
//
// 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 UIKit
open class ModernRefreshControl : ScreamRefreshControl {
private var spinnerView: NewSpinnerView
public override init() {
spinnerView = NewSpinnerView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
super.init()
contentView.addSubview(spinnerView)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding unsupported")
}
open override func layoutSubviews() {
super.layoutSubviews()
spinnerView.center = CGPoint(x: contentView.bounds.midX, y: contentView.bounds.midY)
}
open override func updateTriggerProgress(_ progress: Float) {
spinnerView.progress = progress;
}
open override func beginRefreshAnimation() {
spinnerView.beginAnimating()
}
open override func endRefreshAnimation() {
spinnerView.endAnimating()
}
}
extension ModernRefreshControl {
private class NewSpinnerView : UIView {
override class var layerClass: AnyClass {
get {
return CAShapeLayer.self
}
}
override var layer: CAShapeLayer {
get {
return super.layer as! CAShapeLayer
}
}
override init(frame: CGRect) {
progress = 1.0
super.init(frame: frame)
layer.lineWidth = 1
layer.fillColor = nil
layer.strokeColor = tintColor.cgColor
layer.strokeStart = 0
layer.strokeEnd = 0
layer.path = self.path
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding unsupported")
}
override func tintColorDidChange() {
super.tintColorDidChange()
layer.strokeColor = tintColor.cgColor
}
private var path: CGPath {
get {
let size = min(self.bounds.size.width, self.bounds.size.height);
let radius = (size-2) / 2.0;
let startAngle = CGFloat(-Double.pi / 2);
let endAngle = startAngle + CGFloat((2 * Double.pi));
let center = CGPoint(x: bounds.midX, y: bounds.midY)
return UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath
}
}
var progress: Float {
didSet {
assert(0 <= progress)
assert(progress <= 1)
layer.strokeEnd = CGFloat(progress)
layer.strokeStart = CGFloat(progress * 0.15)
}
}
func beginAnimating() {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.byValue = Double.pi * 2.0;
rotationAnimation.duration = 0.8;
rotationAnimation.repeatCount = .greatestFiniteMagnitude;
layer.add(rotationAnimation, forKey: "rotation")
let pulseScaleAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseScaleAnimation.toValue = 1.18
pulseScaleAnimation.duration = 0.1
pulseScaleAnimation.autoreverses = true
layer.add(pulseScaleAnimation, forKey: "pulseScale")
let pulseWidthAnimation = CABasicAnimation(keyPath: "lineWidth")
pulseWidthAnimation.toValue = 2
pulseWidthAnimation.duration = 0.1
pulseWidthAnimation.autoreverses = true
layer.add(pulseWidthAnimation, forKey: "pulseWidth")
}
func endAnimating() {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.layer.opacity = 1
self.layer.strokeStart = 0
self.layer.strokeEnd = 0
self.layer.removeAnimation(forKey: "rotation")
}
CATransaction.setAnimationDuration(0.3)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn))
let strokeAnimation = CABasicAnimation(keyPath: "strokeStart")
strokeAnimation.fromValue = 0.15
strokeAnimation.toValue = 1
layer.add(strokeAnimation, forKey: "strokeStart")
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0
layer.add(opacityAnimation, forKey: "opacity")
self.layer.opacity = 0;
CATransaction.commit()
}
}
}
| apache-2.0 | b1e0fa965347e24c11655b9fde76cf4c | 33.026316 | 138 | 0.607115 | 5.161677 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/DataSource/ActionableDataSourceProvider.swift | 1 | 2520 | //
// ActionableDataSourceProvider.swift
// YourGoals
//
// Created by André Claaßen on 22.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
/// types of data sources
///
/// - tasks: a data source for tasks
/// - habits: a data source for habits
/// - allActionables: a data source for all actionables combined (tasks and habits
enum DataSourceType {
case tasks
case habits
case allActionables
/// convenience initializer for converting an actionable type (habit or task or nil) to an Data Source Type
///
/// - Parameter type: Actionablbe or nil
init(type: ActionableType?) {
guard let type = type else {
self = .allActionables
return
}
switch type {
case .task:
self = .tasks
case .habit:
self = .habits
}
}
}
/// Provides an appropriate Data Source for the differnt views
class ActionableDataSourceProvider:StorageManagerWorker {
/// retrieve the approriate data source for the type of the goal and the type wanted types of the actionables
///
/// - Parameters:
/// - goal: goal like user goal, strategy goal or today goal
/// - type: type like habit or task or nil for all type
/// - Returns: a appropriate data source
func dataSource(forGoal goal: Goal, andType type:ActionableType?) -> ActionableDataSource {
let dataSourceType = DataSourceType(type: type)
switch goal.goalType() {
case .todayGoal:
switch dataSourceType {
case .habits:
return HabitsDataSource(manager: self.manager)
case .tasks:
return CommittedTasksDataSource(manager: self.manager)
case .allActionables:
return TodayAllActionablesDataSource(manager: self.manager)
}
case .strategyGoal:
fatalError("This method shouldn't be used with the strategy goal")
case .userGoal:
switch dataSourceType {
case .habits:
return HabitsDataSource(manager: manager, forGoal: goal)
case .tasks:
return GoalTasksDataSource(manager: manager, forGoal: goal)
case .allActionables:
assertionFailure(".all isn't supported for user goals")
return GoalTasksDataSource(manager: manager, forGoal: goal)
}
}
}
}
| lgpl-3.0 | d8d6ce87341b6a9ece3e6c6c4f56633c | 32.092105 | 113 | 0.605567 | 4.864603 | false | false | false | false |
gabrielPeart/Localize-Swift | Localize/Localize.swift | 1 | 3706 | //
// Localize.swift
// Localize
//
// Created by Roy Marmelstein on 05/08/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
let LCLCurrentLanguageKey : String = "LCLCurrentLanguageKey"
let LCLDefaultLanguage : String = "en"
public let LCLLanguageChangeNotification : String = "LCLLanguageChangeNotification"
// MARK: Localization Syntax
// Swift 1.x friendly localization syntax, replaces NSLocalizedString
public func Localized(string: String) -> String {
let path = NSBundle.mainBundle().pathForResource(Localize.currentLanguage(), ofType: "lproj")
let bundle = NSBundle(path: path!)
let string = bundle?.localizedStringForKey(string, value: nil, table: nil)
return string!
}
// Swift 2 friendly localization syntax, replaces NSLocalizedString
public extension String {
func Localized() -> String {
let path = NSBundle.mainBundle().pathForResource(Localize.currentLanguage(), ofType: "lproj")
let bundle = NSBundle(path: path!)
let string = bundle?.localizedStringForKey(self, value: nil, table: nil)
return string!
}
}
// MARK: Language Setting Functions
public class Localize: NSObject {
// Returns a list of available localizations
public class func availableLanguages() -> [String] {
return NSBundle.mainBundle().localizations
}
// Returns the current language
public class func currentLanguage() -> String {
var currentLanguage : String = String()
if ((NSUserDefaults.standardUserDefaults().objectForKey(LCLCurrentLanguageKey)) != nil){
currentLanguage = NSUserDefaults.standardUserDefaults().objectForKey(LCLCurrentLanguageKey) as! String
}
else {
currentLanguage = self.defaultLanguage()
}
return currentLanguage
}
// Change the current language
public class func setCurrentLanguage(language: String) {
var selectedLanguage: String = String()
let availableLanguages : [String] = self.availableLanguages()
if (availableLanguages.contains(language)) {
selectedLanguage = language
}
else {
selectedLanguage = self.defaultLanguage()
}
if (selectedLanguage != currentLanguage()){
NSUserDefaults.standardUserDefaults().setObject(selectedLanguage, forKey: LCLCurrentLanguageKey)
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(LCLLanguageChangeNotification, object: nil)
}
}
// Returns the app's default language
class func defaultLanguage() -> String {
var defaultLanguage : String = String()
let preferredLanguage = NSBundle.mainBundle().preferredLocalizations.first!
let availableLanguages : [String] = self.availableLanguages()
if (availableLanguages.contains(preferredLanguage)) {
defaultLanguage = preferredLanguage
}
else {
defaultLanguage = LCLDefaultLanguage
}
return defaultLanguage
}
// Resets the current language to the default
public class func resetCurrentLanaguageToDefault() {
setCurrentLanguage(self.defaultLanguage())
}
// Returns the app's full display name in the current language
public class func displayNameForLanguage(language: String) -> String {
let currentLanguage : String = self.currentLanguage()
let locale : NSLocale = NSLocale(localeIdentifier: currentLanguage)
let displayName = locale.displayNameForKey(NSLocaleLanguageCode, value: language)
return displayName!
}
}
| mit | ebfbce47aaa7b46f7c1edb23868faa53 | 35.323529 | 114 | 0.687989 | 5.277778 | false | false | false | false |
OldBulls/swift-weibo | ZNWeibo/ZNWeibo/Classes/Home/HomeViewController.swift | 1 | 8467 | //
// HomeViewController.swift
// ZNWeibo
//
// Created by 金宝和信 on 16/7/6.
// Copyright © 2016年 zn. All rights reserved.
//
import UIKit
import SDWebImage
import MJRefresh
class HomeViewController: BaseViewController {
// MARK:- 懒加载属性
private lazy var titleBtn : TitleButton = TitleButton()
//提示label
private lazy var tipLabel : UILabel = UILabel()
private lazy var popoverAnimator : PopoverAnimator = PopoverAnimator {[weak self] (presented) -> () in
self?.titleBtn.selected = presented
}
// 微博模型数组
private lazy var ViewModels : [StatusViewModel] = [StatusViewModel]()
override func viewDidLoad() {
super.viewDidLoad()
//添加转盘动画
visitorView.addRotationAnim()
if !isLogin {
return
}
// 设置导航栏的内容
setupNavigationBar()
//根据约束自动计算
// tableView.rowHeight = UITableViewAutomaticDimension
//估算高度
tableView.estimatedRowHeight = 200
//集成下拉刷新
setupHeaderView()
//上拉加载
setupFooterView()
//设置起始的tipLabel
setupTipLabel()
}
}
// MARK:- 设置UI界面
extension HomeViewController {
//设置导航栏
private func setupNavigationBar() {
// 1.设置左侧的Item
/*
let leftBtn = UIButton()
leftBtn.setImage(UIImage(named: "navigationbar_friendattention"), forState: .Normal)
leftBtn.setImage(UIImage(named: "navigationbar_friendattention_highlighted"), forState: .Highlighted)
leftBtn.sizeToFit()
*/
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
// 2.设置右侧的Item
navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
// 3.设置titleView
titleBtn.setTitle("臻牛科技", forState: .Normal)
titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside)
navigationItem.titleView = titleBtn
}
// 设置下拉刷新控件内容
private func setupHeaderView() {
let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatus))
header.setTitle("下拉刷新", forState: .Idle)
header.setTitle("释放更新", forState: .Pulling)
header.setTitle("加载中...", forState: .Refreshing)
tableView.mj_header = header
tableView.mj_header.beginRefreshing()
}
//设置上拉加载控件
private func setupFooterView() {
tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatus))
}
//设置起始的tipLabel
private func setupTipLabel() {
navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.mainScreen().bounds.width, height: 32)
tipLabel.backgroundColor = UIColor.orangeColor()
tipLabel.alpha = 0.8
tipLabel.font = UIFont.systemFontOfSize(14)
tipLabel.textColor = UIColor.whiteColor()
tipLabel.textAlignment = .Center
tipLabel.hidden = true
}
}
// MARK:- 事件监听的函数
extension HomeViewController {
@objc private func titleBtnClick(titleBtn : TitleButton) {
// 1.创建弹出的控制器
let popoverVc = PopoverViewController()
// 2.设置控制器的modal样式
popoverVc.modalPresentationStyle = .Custom
// 3.设置转场的代理
popoverVc.transitioningDelegate = popoverAnimator
popoverAnimator.presentedFrame = CGRect(x: UIScreen.mainScreen().bounds.width * 0.5 - 90, y: 60, width: 180, height: 250)
// 4.弹出控制器
presentViewController(popoverVc, animated: true, completion: nil)
}
}
// MARK: - 请求数据
extension HomeViewController {
//下拉刷新
@objc private func loadNewStatus() {
loadStatuses(true)
}
//上拉加载
@objc private func loadMoreStatus() {
loadStatuses(false)
}
// 加载微博数据
private func loadStatuses(isNewNata : Bool) {
var since_id = 0
var max_id = 0
if isNewNata {
since_id = ViewModels.first?.status?.mid ?? 0
} else {
max_id = ViewModels.last?.status?.mid ?? 0
max_id = max_id == 0 ? 0 : (max_id - 1)
}
NetworkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (result, error) in
if error != nil {
ZNLog(error)
return
}
guard let resultArray = result else {
return
}
//临时数组,存放最新的微博数据
var tempViewModel = [StatusViewModel]()
for statusDict in resultArray {
let status = Status(dict: statusDict)
let viewModel = StatusViewModel(status: status)
tempViewModel.append(viewModel)
}
if isNewNata {
self.ViewModels = tempViewModel + self.ViewModels
self.showTipLabel(tempViewModel.count)
} else {
self.ViewModels += tempViewModel
}
self.cacheImages(tempViewModel)
}
}
// 下载图片
private func cacheImages(viewModels : [StatusViewModel]) {
// 0.创建group
let group = dispatch_group_create()
// 1.缓存图片
for viewmodel in viewModels {
for picURL in viewmodel.picURLs {
dispatch_group_enter(group)
SDWebImageManager.sharedManager().downloadImageWithURL(picURL, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
ZNLog("下载了一张图片")
dispatch_group_leave(group)
})
}
}
// 2.刷新表格
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
ZNLog("刷新表格")
self.tableView.reloadData()
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
}
}
// 显示提示的label
private func showTipLabel(count : Int) {
tipLabel.hidden = false
tipLabel.text = count == 0 ? "没有新数据" : "\(count)条新微博"
UIView.animateWithDuration(1.0, animations: {
self.tipLabel.frame.origin.y = 44
}) { (_) in
UIView.animateWithDuration(1.0, delay: 1.5, options: [], animations: {
self.tipLabel.frame.origin.y = 10
}, completion: { (_) in
self.tipLabel.hidden = true
})
}
}
}
// MARK: - tableView dataSource
extension HomeViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ViewModels.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let ID = "HomeCell"
var cell = tableView.dequeueReusableCellWithIdentifier(ID) as? HomeViewCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("HomeViewCell", owner: nil, options: nil).first as? HomeViewCell
ZNLog("tableView --\(indexPath.row)")
}
cell?.viewModel = ViewModels[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let viewModel = ViewModels[indexPath.row]
return viewModel.cellHeight
}
}
| mit | 5b29726236d8029a55b0c53501d70d0c | 28.594096 | 146 | 0.565835 | 5.238406 | false | false | false | false |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/Executions.swift | 1 | 7566 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import MBProgressHUD
public enum AAExecutionType {
case normal
case hidden
case safe
}
open class AAMenuBuilder {
open var tapClosure: ((_ index: Int) -> ())!
open var items = [String]()
open var closures: [(()->())?] = []
public init() {
tapClosure = { (index) -> () in
if index >= 0 && index <= self.closures.count {
self.closures[index]?()
}
}
}
open func add(_ title: String, closure: (()->())?) {
items.append(title)
closures.append(closure)
}
}
open class AAExecutions {
open class func execute(_ promise: ARPromise) {
executePromise(promise)
}
open class func execute(_ command: ACCommand) {
execute(command, successBlock: nil, failureBlock: nil)
}
open class func executePromise(_ promice: ARPromise){
_ = promice.startUserAction()
}
open class func executePromise(_ promice: ARPromise, successBlock: ((_ val: Any?) -> Void)?, failureBlock: ((_ val: Any?) -> Void)? ){
_ = promice.startUserAction()
_ = promice.then { result in
successBlock!(result)
}
}
open class func execute(_ command: ACCommand, type: AAExecutionType = .normal, ignore: [String] = [], successBlock: ((_ val: Any?) -> Void)?, failureBlock: ((_ val: Any?) -> Void)?) {
var hud: MBProgressHUD?
if type != .hidden {
hud = showProgress()
}
command.start(with: AACommandCallback(result: { (val:Any?) -> () in
dispatchOnUi {
hud?.hide(animated:true)
successBlock?(val)
}
}, error: { (val) -> () in
dispatchOnUi {
hud?.hide(animated:true)
if type == .safe {
// If unknown error, just try again
var tryAgain = true
if let exception = val as? ACRpcException {
// If is in ignore list, just return to UI
if ignore.contains(exception.tag) {
failureBlock?(val)
return
}
// Get error from
tryAgain = exception.canTryAgain
}
// Showing alert
if tryAgain {
errorWithError(val!, rep: { () -> () in
AAExecutions.execute(command, type: type, successBlock: successBlock, failureBlock: failureBlock)
}, cancel: { () -> () in
failureBlock?(val)
})
} else {
errorWithError(val!, cancel: { () -> () in
failureBlock?(val)
})
}
} else {
failureBlock?(val)
}
}
}))
}
open class func errorWithError(_ e: AnyObject, rep:(()->())? = nil, cancel:(()->())? = nil) {
error(Actor.getFormatter().formatErrorTextWithError(e), rep: rep, cancel: cancel)
}
open class func errorWithTag(_ tag: String, rep:(()->())? = nil, cancel:(()->())? = nil) {
error(Actor.getFormatter().formatErrorText(withTag: tag), rep: rep, cancel: cancel)
}
open class func error(_ message: String, rep:(()->())? = nil, cancel:(()->())? = nil) {
if rep != nil {
let d = UIAlertViewBlock(clickedClosure: { (index) -> () in
if index > 0 {
rep?()
} else {
cancel?()
}
})
let alert = UIAlertView(title: AALocalized("AlertError"),
message: message,
delegate: d,
cancelButtonTitle: AALocalized("AlertCancel"),
otherButtonTitles: AALocalized("AlertTryAgain"))
setAssociatedObject(alert, value: d, associativeKey: &alertViewBlockReference)
alert.show()
} else {
let d = UIAlertViewBlock(clickedClosure: { (index) -> () in
cancel?()
})
let alert = UIAlertView(title: nil,
message: message,
delegate: d,
cancelButtonTitle: AALocalized("AlertOk"))
setAssociatedObject(alert, value: d, associativeKey: &alertViewBlockReference)
alert.show()
}
}
class fileprivate func showProgress() -> MBProgressHUD {
let window = UIApplication.shared.windows[1]
let hud = MBProgressHUD(window: window)
hud.mode = MBProgressHUDMode.indeterminate
hud.removeFromSuperViewOnHide = true
window.addSubview(hud)
window.bringSubview(toFront: hud)
hud.show(animated:true)
return hud
}
}
private var alertViewBlockReference = "_block_reference"
@objc private class UIAlertViewBlock: NSObject, UIAlertViewDelegate {
fileprivate let clickedClosure: ((_ index: Int) -> ())
init(clickedClosure: @escaping ((_ index: Int) -> ())) {
self.clickedClosure = clickedClosure
}
@objc fileprivate func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
clickedClosure(buttonIndex)
}
@objc fileprivate func alertViewCancel(_ alertView: UIAlertView) {
clickedClosure(-1)
}
}
public extension UIViewController {
public func execute(_ command: ACCommand) {
AAExecutions.execute(command)
}
public func executePromise(_ promise: ARPromise) -> ARPromise {
AAExecutions.execute(promise)
return promise
}
public func executePromise(_ promise: ARPromise, successBlock: ((_ val: Any?) -> Void)?, failureBlock: ((_ val: Any?) -> Void)?) {
AAExecutions.executePromise(promise, successBlock: successBlock, failureBlock: failureBlock)
}
public func execute(_ command: ACCommand, successBlock: ((_ val: Any?) -> Void)?, failureBlock: ((_ val: Any?) -> Void)?) {
AAExecutions.execute(command, successBlock: successBlock, failureBlock: failureBlock)
}
public func execute(_ command: ACCommand, successBlock: ((_ val: Any?) -> Void)?) {
AAExecutions.execute(command, successBlock: successBlock, failureBlock: nil)
}
public func executeSafe(_ command: ACCommand, ignore: [String] = [], successBlock: ((_ val: Any?) -> Void)? = nil) {
AAExecutions.execute(command, type: .safe, ignore: ignore, successBlock: successBlock, failureBlock: { (val) -> () in
successBlock?(nil)
})
}
public func executeSafeOnlySuccess(_ command: ACCommand, successBlock: ((_ val: Any?) -> Void)?) {
AAExecutions.execute(command, type: .safe, ignore: [], successBlock: successBlock, failureBlock: nil)
}
public func executeHidden(_ command: ACCommand, successBlock: ((_ val: Any?) -> Void)? = nil) {
AAExecutions.execute(command, type: .hidden, successBlock: successBlock, failureBlock: nil)
}
}
| agpl-3.0 | 8329963819db9e0af9d91663e2c30014 | 35.028571 | 187 | 0.518504 | 5.185744 | false | false | false | false |
johnno1962/eidolon | Kiosk/App/AppViewController.swift | 1 | 3594 | import UIKit
import RxSwift
import Action
class AppViewController: UIViewController, UINavigationControllerDelegate {
var allowAnimations = true
var auctionID = AppSetup.sharedState.auctionID
@IBOutlet var countdownManager: ListingsCountdownManager!
@IBOutlet var offlineBlockingView: UIView!
@IBOutlet weak var registerToBidButton: ActionButton!
var provider: Networking!
lazy var _apiPinger: APIPingManager = {
return APIPingManager(provider: self.provider)
}()
lazy var reachability: Observable<Bool> = {
[connectedToInternetOrStubbing(), self.apiPinger].combineLatestAnd()
}()
lazy var apiPinger: Observable<Bool> = {
self._apiPinger.letOnline
}()
var registerToBidCommand = { () -> CocoaAction in
appDelegate().registerToBidCommand()
}
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> AppViewController {
return storyboard.viewControllerWithID(.AppViewController) as! AppViewController
}
var sale = Variable(Sale(id: "", name: "", isAuction: true, startDate: NSDate(), endDate: NSDate(), artworkCount: 0, state: ""))
override func viewDidLoad() {
super.viewDidLoad()
registerToBidButton.rx_action = registerToBidCommand()
countdownManager.setFonts()
countdownManager.provider = provider
reachability
.bindTo(offlineBlockingView.rx_hidden)
.addDisposableTo(rx_disposeBag)
auctionRequest(provider, auctionID: auctionID)
.bindTo(sale)
.addDisposableTo(rx_disposeBag)
sale
.asObservable()
.mapToOptional()
.bindTo(countdownManager.sale)
.addDisposableTo(rx_disposeBag)
for controller in childViewControllers {
if let nav = controller as? UINavigationController {
nav.delegate = self
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// This is the embed segue
guard let navigtionController = segue.destinationViewController as? UINavigationController else { return }
guard let listingsViewController = navigtionController.topViewController as? ListingsViewController else { return }
listingsViewController.provider = provider
}
deinit {
countdownManager.invalidate()
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
let hide = (viewController as? SaleArtworkZoomViewController != nil)
countdownManager.setLabelsHiddenIfSynced(hide)
registerToBidButton.hidden = hide
}
}
extension AppViewController {
@IBAction func longPressForAdmin(sender: UIGestureRecognizer) {
if sender.state != .Began {
return
}
let passwordVC = PasswordAlertViewController.alertView { [weak self] in
self?.performSegue(.ShowAdminOptions)
return
}
self.presentViewController(passwordVC, animated: true) {}
}
func auctionRequest(provider: Networking, auctionID: String) -> Observable<Sale> {
let auctionEndpoint: ArtsyAPI = ArtsyAPI.AuctionInfo(auctionID: auctionID)
return provider.request(auctionEndpoint)
.filterSuccessfulStatusCodes()
.mapJSON()
.mapToObject(Sale)
.logError()
.retry()
.throttle(1, scheduler: MainScheduler.instance)
}
}
| mit | 43e95b325cbda4c0adfb05e377078b75 | 31.672727 | 150 | 0.670006 | 5.356185 | false | false | false | false |
lokinfey/MyPerfectframework | Examples/WebSockets Server/WebSockets Server/PerfectHandlers.swift | 1 | 4474 | //
// PerfectHandlers.swift
// WebSockets Server
//
// Created by Kyle Jessup on 2016-01-06.
// Copyright PerfectlySoft 2016. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
// This is the function which all Perfect Server modules must expose.
// The system will load the module and call this function.
// In here, register any handlers or perform any one-time tasks.
public func PerfectServerModuleInit() {
// Initialize the routing system
Routing.Handler.registerGlobally()
// Add a default route which lets us serve the static index.html file
Routing.Routes["*"] = { _ in return StaticFileHandler() }
// Add the endpoint for the WebSocket example system
Routing.Routes["GET", "/echo"] = {
_ in
// To add a WebSocket service, set the handler to WebSocketHandler.
// Provide your closure which will return your service handler.
return WebSocketHandler(handlerProducer: {
(request: WebRequest, protocols: [String]) -> WebSocketSessionHandler? in
// Check to make sure the client is requesting our "echo" service.
guard protocols.contains("echo") else {
return nil
}
// Return our service handler.
return EchoHandler()
})
}
}
// A WebSocket service handler must impliment the `WebSocketSessionHandler` protocol.
// This protocol requires the function `handleSession(request: WebRequest, socket: WebSocket)`.
// This function will be called once the WebSocket connection has been established,
// at which point it is safe to begin reading and writing messages.
//
// The initial `WebRequest` object which instigated the session is provided for reference.
// Messages are transmitted through the provided `WebSocket` object.
// Call `WebSocket.sendStringMessage` or `WebSocket.sendBinaryMessage` to send data to the client.
// Call `WebSocket.readStringMessage` or `WebSocket.readBinaryMessage` to read data from the client.
// By default, reading will block indefinitely until a message arrives or a network error occurs.
// A read timeout can be set with `WebSocket.readTimeoutSeconds`.
// When the session is over call `WebSocket.close()`.
class EchoHandler: WebSocketSessionHandler {
// The name of the super-protocol we implement.
// This is optional, but it should match whatever the client-side WebSocket is initialized with.
let socketProtocol: String? = "echo"
// This function is called by the WebSocketHandler once the connection has been established.
func handleSession(request: WebRequest, socket: WebSocket) {
// Read a message from the client as a String.
// Alternatively we could call `WebSocket.readBytesMessage` to get binary data from the client.
socket.readStringMessage {
// This callback is provided:
// the received data
// the message's op-code
// a boolean indicating if the message is complete (as opposed to fragmented)
string, op, fin in
// The data parameter might be nil here if either a timeout or a network error, such as the client disconnecting, occurred.
// By default there is no timeout.
guard let string = string else {
// This block will be executed if, for example, the browser window is closed.
socket.close()
return
}
// Print some information to the console for informational purposes.
print("Read msg: \(string) op: \(op) fin: \(fin)")
// Echo the data we received back to the client.
// Pass true for final. This will usually be the case, but WebSockets has the concept of fragmented messages.
// For example, if one were streaming a large file such as a video, one would pass false for final.
// This indicates to the receiver that there is more data to come in subsequent messages but that all the data is part of the same logical message.
// In such a scenario one would pass true for final only on the last bit of the video.
socket.sendStringMessage(string, final: true) {
// This callback is called once the message has been sent.
// Recurse to read and echo new message.
self.handleSession(request, socket: socket)
}
}
}
}
| apache-2.0 | d0d879c763282eb9edfb4617596d45b9 | 40.045872 | 150 | 0.706303 | 4.335271 | false | false | false | false |
LoganWright/Genome | Sources/Genome/Mapping/Map.swift | 3 | 4739 | /// This class is designed to serve as an adaptor between the raw node and the values. In this way we can interject behavior that assists in mapping between the two.
public final class Map: NodeBacked {
/**
The representative type of mapping operation
- ToNode: transforming the object into a node dictionary representation
- FromNode: transforming a node dictionary representation into an object
*/
public enum OperationType {
case toNode
case fromNode
}
/// The type of operation for the current map
public let type: OperationType
/// The greater context in which the mapping takes place
public let context: Context
/// The backing Node being mapped
public var node: Node
// MARK: Private
/// The last key accessed -- Used to reverse Node Operations
internal fileprivate(set) var lastPath: [PathIndex] = []
/// The last retrieved result. Used in operators to set value
internal fileprivate(set) var result: Node? {
didSet {
if let unwrapped = result, unwrapped.isNull {
result = nil
}
}
}
// MARK: Initialization
/**
A convenience mappable initializer that takes any conforming backing data
:param: node the backing data that will be used in the mapping
:param: context the context that will be used in the mapping
*/
public convenience init(node: NodeRepresentable, in context: Context = EmptyNode) throws {
let node = try node.makeNode(context: context)
self.init(node: node, in: context)
}
/**
The designated initializer for mapping from Node
:param: node the node that will be used in the mapping
:param: context the context that will be used in the mapping
*/
public init(node: Node, in context: Context = EmptyNode) {
self.type = .fromNode
self.node = node
self.context = context
}
public convenience init(_ node: Node) {
self.init(node: node, in: EmptyNode)
}
/**
The designated initializer for mapping to Node
- returns: an initialized toNode map ready to generate a node
*/
public init() {
self.type = .toNode
self.node = [:]
self.context = EmptyNode
}
}
// MARK: Subscript
extension Map {
/**
Basic subscripting
:param: keyPath the keypath to use when getting the value from the backing node
:returns: returns an instance of self that can be passed to the mappable operator
*/
public subscript(keys: PathIndex...) -> Map {
return self[keys]
}
/**
Basic subscripting
:param: keyPath the keypath to use when getting the value from the backing node
:returns: returns an instance of self that can be passed to the mappable operator
*/
public subscript(keys: [PathIndex]) -> Map {
lastPath = keys
result = node[keys]
return self
}
public subscript(path path: String) -> Map {
let components = path.characters
.split(separator: ".")
.map { String($0) }
return self[components]
}
}
// MARK: Setting
extension Map {
internal func setToLastPath(_ newValue: Node?) throws {
guard let newValue = newValue else { return }
node[lastPath] = newValue
}
internal func setToLastPath<T : NodeConvertible>(_ any: T?) throws {
try setToLastPath(any?.makeNode())
}
internal func setToLastPath<T : NodeConvertible>(_ any: [T]?) throws {
try setToLastPath(any?.makeNode())
}
internal func setToLastPath<T : NodeConvertible>(_ any: [[T]]?) throws {
guard let any = any else { return }
let node: [Node] = try any.map { innerArray in
return try innerArray.makeNode()
}
try setToLastPath(node.makeNode())
}
internal func setToLastPath<T : NodeConvertible>(_ any: [String : T]?) throws {
guard let any = any else { return }
var node: [String : Node] = [:]
try any.forEach { key, value in
node[key] = try value.makeNode()
}
try setToLastPath(Node(node))
}
internal func setToLastPath<T : NodeConvertible>(_ any: [String : [T]]?) throws {
guard let any = any else { return }
var node: [String : Node] = [:]
try any.forEach { key, value in
node[key] = try value.makeNode()
}
try setToLastPath(Node(node))
}
internal func setToLastPath<T : NodeConvertible>(_ any: Set<T>?) throws {
try setToLastPath(any?.makeNode())
}
}
| mit | fafa137e7bfd782367755975b8bff2b6 | 28.434783 | 166 | 0.608356 | 4.618908 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/view model/TKUIHomeViewModel+Content.swift | 1 | 4017 | //
// TKUIHomeViewModel+Content.swift
// TripKit-iOS
//
// Created by Brian Huang on 28/7/20.
// Copyright © 2020 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
extension TKUIHomeViewModel {
enum Item {
case component(TKUIHomeComponentItem)
case search(TKUIAutocompletionViewModel.Item)
}
struct Section {
let identity: String
var items: [Item]
var headerConfiguration: TKUIHomeHeaderConfiguration?
init(identity: String, items: [Item], headerConfiguration: TKUIHomeHeaderConfiguration? = nil) {
self.identity = identity
self.items = items
self.headerConfiguration = headerConfiguration
}
}
}
// MARK: - Build
extension TKUIHomeViewModel {
/// Builds the full and non-customized content
static func fullContent(for components: [TKUIHomeComponentViewModel]) -> Driver<[TKUIHomeViewModel.Section]> {
let componentSections = components
.map { component in
component.homeCardSection.map { Section($0, identity: component.identity) }
}
.enumerated()
.map { index, driver in
return driver.map { (index: index, $0) }
}
let componentUpdates = Driver.merge(componentSections).asObservable()
return componentUpdates.scan(into: SectionContent(capacity: componentSections.count)) { content, update in
content.sections[update.index] = update.1
}.map { content in
// Only include existing sections that either have items or a header action
return content.sections
.compactMap { $0 }
.filter { !$0.items.isEmpty || $0.headerConfiguration?.action != nil }
}
.throttle(.milliseconds(500), latest: true, scheduler: MainScheduler.instance)
.asDriver(onErrorJustReturn: [])
.startWith([])
}
private struct SectionContent {
var sections: [Section?]
init(capacity: Int) {
sections = (0..<capacity).map { _ in Optional<TKUIHomeViewModel.Section>.none }
}
}
/// Takes the full content, applies the user's customization and provides back the filtered sections
static func customizedContent(full: Driver<[TKUIHomeViewModel.Section]>, customization: Observable<[TKUIHomeCard.CustomizedItem]>) -> Driver<[TKUIHomeViewModel.Section]> {
guard !TKUIHomeCard.config.ignoreComponentCustomization else { return full }
return Driver.combineLatest(full, customization.asDriver(onErrorJustReturn: [])) { full, customization -> [TKUIHomeViewModel.Section] in
return full
.filter { candidate in
customization.first { $0.id == candidate.identity }?.isEnabled ?? true
}
.sorted { first, second in
let firstIndex = customization.firstIndex { $0.id == first.identity }
let secondIndex = customization.firstIndex { $0.id == second.identity }
if let first = firstIndex, let second = secondIndex {
return first < second
} else if firstIndex == nil {
return false
} else {
return true
}
}
}
}
}
// MARK: - RxDataSources
extension TKUIHomeViewModel.Item: Equatable {
}
func == (lhs: TKUIHomeViewModel.Item, rhs: TKUIHomeViewModel.Item) -> Bool {
switch (lhs, rhs) {
case let (.component(left), .component(right)): return left.identity == right.identity && left.equalityToken == right.equalityToken
case let (.search(left), .search(right)): return left == right
default: return false
}
}
extension TKUIHomeViewModel.Item: IdentifiableType {
typealias Identity = String
var identity: Identity {
switch self {
case .component(let item): return item.identity
case .search(let item): return item.identity
}
}
}
extension TKUIHomeViewModel.Section: AnimatableSectionModelType {
typealias Identity = String
init(original: TKUIHomeViewModel.Section, items: [TKUIHomeViewModel.Item]) {
self = original
self.items = items
}
}
| apache-2.0 | e7cf6774e01e5c64ebd8a65d6c30127b | 28.970149 | 173 | 0.670568 | 4.594966 | false | true | false | false |
edragoev1/pdfjet | Sources/PDFjet/Times_Roman.swift | 1 | 12644 | class Times_Roman {
static let name = "Times-Roman"
static let bBoxLLx: Int16 = -168
static let bBoxLLy: Int16 = -218
static let bBoxURx: Int16 = 1000
static let bBoxURy: Int16 = 898
static let underlinePosition: Int16 = -100
static let underlineThickness: Int16 = 50
static let notice = "Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. Times is a trademark of Linotype-Hell AG and/or its subsidiaries."
static let metrics = Array<[Int16]>(arrayLiteral:
[32,250,65,-55,193,-55,194,-55,196,-55,192,-55,197,-55,195,-55,84,-18,86,-50,87,-30,89,-90,221,-90,159,-90],
[33,333],
[34,408],
[35,500],
[36,500],
[37,833],
[38,778],
[39,180],
[40,333],
[41,333],
[42,500],
[43,564],
[44,250,148,-70,146,-70],
[45,333],
[46,250,148,-70,146,-70],
[47,278],
[48,500],
[49,500],
[50,500],
[51,500],
[52,500],
[53,500],
[54,500],
[55,500],
[56,500],
[57,500],
[58,278],
[59,278],
[60,564],
[61,564],
[62,564],
[63,444],
[64,921],
[65,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[66,667,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,85,-10,218,-10,219,-10,220,-10,217,-10],
[67,667],
[68,722,65,-40,193,-40,194,-40,196,-40,192,-40,197,-40,195,-40,86,-40,87,-30,89,-55,221,-55,159,-55],
[69,611],
[70,556,65,-74,193,-74,194,-74,196,-74,192,-74,197,-74,195,-74,97,-15,225,-15,226,-15,228,-15,224,-15,229,-15,227,-15,44,-80,111,-15,243,-15,244,-15,246,-15,242,-15,248,-15,245,-15,46,-80],
[71,722],
[72,722],
[73,333],
[74,389,65,-60,193,-60,194,-60,196,-60,192,-60,197,-60,195,-60],
[75,722,79,-30,211,-30,212,-30,214,-30,210,-30,216,-30,213,-30,101,-25,233,-25,234,-25,235,-25,232,-25,111,-35,243,-35,244,-35,246,-35,242,-35,248,-35,245,-35,117,-15,250,-15,251,-15,252,-15,249,-15,121,-25,253,-25,255,-25],
[76,611,84,-92,86,-100,87,-74,89,-100,221,-100,159,-100,146,-92,121,-55,253,-55,255,-55],
[77,889],
[78,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35],
[79,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[80,556,65,-92,193,-92,194,-92,196,-92,192,-92,197,-92,195,-92,97,-15,225,-15,226,-15,228,-15,224,-15,229,-15,227,-15,44,-111,46,-111],
[81,722,85,-10,218,-10,219,-10,220,-10,217,-10],
[82,667,79,-40,211,-40,212,-40,214,-40,210,-40,216,-40,213,-40,84,-60,85,-40,218,-40,219,-40,220,-40,217,-40,86,-80,87,-55,89,-65,221,-65,159,-65],
[83,556],
[84,611,65,-93,193,-93,194,-93,196,-93,192,-93,197,-93,195,-93,79,-18,211,-18,212,-18,214,-18,210,-18,216,-18,213,-18,97,-80,225,-80,226,-80,228,-40,224,-40,229,-80,227,-40,58,-50,44,-74,101,-70,233,-70,234,-70,235,-30,232,-70,45,-92,105,-35,237,-35,111,-80,243,-80,244,-80,246,-80,242,-80,248,-80,245,-80,46,-74,114,-35,59,-55,117,-45,250,-45,251,-45,252,-45,249,-45,119,-80,121,-80,253,-80,255,-80],
[85,722,65,-40,193,-40,194,-40,196,-40,192,-40,197,-40,195,-40],
[86,722,65,-135,193,-135,194,-135,196,-135,192,-135,197,-135,195,-135,71,-15,79,-40,211,-40,212,-40,214,-40,210,-40,216,-40,213,-40,97,-111,225,-111,226,-71,228,-71,224,-71,229,-111,227,-71,58,-74,44,-129,101,-111,233,-111,234,-71,235,-71,232,-71,45,-100,105,-60,237,-60,238,-20,239,-20,236,-20,111,-129,243,-129,244,-129,246,-89,242,-89,248,-129,245,-89,46,-129,59,-74,117,-75,250,-75,251,-75,252,-75,249,-75],
[87,944,65,-120,193,-120,194,-120,196,-120,192,-120,197,-120,195,-120,79,-10,211,-10,212,-10,214,-10,210,-10,216,-10,213,-10,97,-80,225,-80,226,-80,228,-80,224,-80,229,-80,227,-80,58,-37,44,-92,101,-80,233,-80,234,-80,235,-40,232,-40,45,-65,105,-40,237,-40,111,-80,243,-80,244,-80,246,-80,242,-80,248,-80,245,-80,46,-92,59,-37,117,-50,250,-50,251,-50,252,-50,249,-50,121,-73,253,-73,255,-73],
[88,722],
[89,722,65,-120,193,-120,194,-120,196,-120,192,-120,197,-120,195,-120,79,-30,211,-30,212,-30,214,-30,210,-30,216,-30,213,-30,97,-100,225,-100,226,-100,228,-60,224,-60,229,-100,227,-60,58,-92,44,-129,101,-100,233,-100,234,-100,235,-60,232,-60,45,-111,105,-55,237,-55,111,-110,243,-110,244,-110,246,-70,242,-70,248,-110,245,-70,46,-129,59,-92,117,-111,250,-111,251,-111,252,-71,249,-71],
[90,611],
[91,333],
[92,278],
[93,333],
[94,469],
[95,500],
[96,333],
[97,444,118,-20,119,-15],
[98,500,46,-40,117,-20,250,-20,251,-20,252,-20,249,-20,118,-15],
[99,444,121,-15,253,-15,255,-15],
[100,500],
[101,444,103,-15,118,-25,119,-25,120,-15,121,-15,253,-15,255,-15],
[102,333,97,-10,225,-10,226,-10,228,-10,224,-10,229,-10,227,-10,102,-25,105,-20,237,-20,146,55],
[103,500,97,-5,225,-5,226,-5,228,-5,224,-5,229,-5,227,-5],
[104,500,121,-5,253,-5,255,-5],
[105,278,118,-25],
[106,278],
[107,500,101,-10,233,-10,234,-10,235,-10,232,-10,111,-10,243,-10,244,-10,246,-10,242,-10,248,-10,245,-10,121,-15,253,-15,255,-15],
[108,278,119,-10],
[109,778],
[110,500,118,-40,121,-15,253,-15,255,-15],
[111,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[112,500,121,-10,253,-10,255,-10],
[113,500],
[114,333,44,-40,103,-18,45,-20,46,-55],
[115,389],
[116,278],
[117,500],
[118,500,97,-25,225,-25,226,-25,228,-25,224,-25,229,-25,227,-25,44,-65,101,-15,233,-15,234,-15,235,-15,232,-15,111,-20,243,-20,244,-20,246,-20,242,-20,248,-20,245,-20,46,-65],
[119,722,97,-10,225,-10,226,-10,228,-10,224,-10,229,-10,227,-10,44,-65,111,-10,243,-10,244,-10,246,-10,242,-10,248,-10,245,-10,46,-65],
[120,500,101,-15,233,-15,234,-15,235,-15,232,-15],
[121,500,44,-65,46,-65],
[122,444],
[123,480],
[124,200],
[125,480],
[126,541],
[127,250],
[128,500],
[129,250],
[130,333],
[131,500],
[132,444],
[133,1000],
[134,500],
[135,500],
[136,333],
[137,1000],
[138,556],
[139,333],
[140,889],
[141,250],
[142,611],
[143,250],
[144,250],
[145,333,65,-80,193,-80,194,-80,196,-80,192,-80,197,-80,195,-80,145,-74],
[146,333,100,-50,108,-10,146,-74,114,-50,115,-55,154,-55,32,-74,116,-18,118,-50],
[147,444,65,-80,193,-80,194,-80,196,-80,192,-80,197,-80,195,-80],
[148,444],
[149,350],
[150,500],
[151,1000],
[152,333],
[153,980],
[154,389],
[155,333],
[156,722],
[157,250],
[158,444],
[159,722,65,-120,193,-120,194,-120,196,-120,192,-120,197,-120,195,-120,79,-30,211,-30,212,-30,214,-30,210,-30,216,-30,213,-30,97,-100,225,-100,226,-100,228,-60,224,-60,229,-100,227,-100,58,-92,44,-129,101,-100,233,-100,234,-100,235,-60,232,-60,45,-111,105,-55,237,-55,111,-110,243,-110,244,-110,246,-70,242,-70,248,-110,245,-70,46,-129,59,-92,117,-111,250,-111,251,-111,252,-71,249,-71],
[160,250],
[161,333],
[162,500],
[163,500],
[164,500],
[165,500],
[166,200],
[167,500],
[168,333],
[169,760],
[170,276],
[171,500],
[172,564],
[173,250],
[174,760],
[175,333],
[176,400],
[177,564],
[178,300],
[179,300],
[180,333],
[181,500],
[182,453],
[183,250],
[184,333],
[185,300],
[186,310],
[187,500],
[188,750],
[189,750],
[190,750],
[191,444],
[192,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[193,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[194,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[195,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[196,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[197,722,67,-40,199,-40,71,-40,79,-55,211,-55,212,-55,214,-55,210,-55,216,-55,213,-55,81,-55,84,-111,85,-55,218,-55,219,-55,220,-55,217,-55,86,-135,87,-90,89,-105,221,-105,159,-105,146,-111,118,-74,119,-92,121,-92,253,-92,255,-92],
[198,889],
[199,667],
[200,611],
[201,611],
[202,611],
[203,611],
[204,333],
[205,333],
[206,333],
[207,333],
[208,722],
[209,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35],
[210,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[211,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[212,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[213,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[214,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[215,564],
[216,722,65,-35,193,-35,194,-35,196,-35,192,-35,197,-35,195,-35,84,-40,86,-50,87,-35,88,-40,89,-50,221,-50,159,-50],
[217,722,65,-40,193,-40,194,-40,196,-40,192,-40,197,-40,195,-40],
[218,722,65,-40,193,-40,194,-40,196,-40,192,-40,197,-40,195,-40],
[219,722,65,-40,193,-40,194,-40,196,-40,192,-40,197,-40,195,-40],
[220,722,65,-40,193,-40,194,-40,196,-40,192,-40,197,-40,195,-40],
[221,722,65,-120,193,-120,194,-120,196,-120,192,-120,197,-120,195,-120,79,-30,211,-30,212,-30,214,-30,210,-30,216,-30,213,-30,97,-100,225,-100,226,-100,228,-60,224,-60,229,-100,227,-60,58,-92,44,-129,101,-100,233,-100,234,-100,235,-60,232,-60,45,-111,105,-55,237,-55,111,-110,243,-110,244,-110,246,-70,242,-70,248,-110,245,-70,46,-129,59,-92,117,-111,250,-111,251,-111,252,-71,249,-71],
[222,556],
[223,500],
[224,444,118,-20,119,-15],
[225,444,118,-20,119,-15],
[226,444,118,-20,119,-15],
[227,444,118,-20,119,-15],
[228,444,118,-20,119,-15],
[229,444,118,-20,119,-15],
[230,667],
[231,444,121,-15,253,-15,255,-15],
[232,444,103,-15,118,-25,119,-25,120,-15,121,-15,253,-15,255,-15],
[233,444,103,-15,118,-25,119,-25,120,-15,121,-15,253,-15,255,-15],
[234,444,103,-15,118,-25,119,-25,120,-15,121,-15,253,-15,255,-15],
[235,444,103,-15,118,-25,119,-25,120,-15,121,-15,253,-15,255,-15],
[236,278,118,-25],
[237,278,118,-25],
[238,278,118,-25],
[239,278,118,-25],
[240,500],
[241,500,118,-40,121,-15,253,-15,255,-15],
[242,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[243,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[244,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[245,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[246,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[247,564],
[248,500,118,-15,119,-25,121,-10,253,-10,255,-10],
[249,500],
[250,500],
[251,500],
[252,500],
[253,500,44,-65,46,-65],
[254,500],
[255,500,44,-65,46,-65]
)
}
| mit | ff1468dbc2941566e00d631147b9dd2b | 52.576271 | 419 | 0.520089 | 2.301839 | false | false | false | false |
rhildreth/Cottontown | Cottontown/MapPageViewController.swift | 1 | 4868 | //
// MapPageViewController.swift
// Cottontown
//
// Created by Ron Hildreth on 12/28/15.
// Copyright © 2015 Tappdev.com. All rights reserved.
//
import UIKit
class MapPageViewController: UIPageViewController, UIPageViewControllerDataSource, PictureContentViewControllerDelegate {
var stop: Stop?
var pageIndex = 0
var allStopContent = [[String: String]]()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
if let stop = stop {
allStopContent = stop.stopPictures + (stop.youTubes ?? []) // ?? is nil coalescing
// operator - If stop.youTubes is not nil it is unwrapped, otherwise the empty array is
// returned
}
let firstVC = viewControllerAtIndex(0)
setViewControllers([firstVC!], direction: .Forward, animated: true, completion: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(index: Int) -> UIViewController? {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// In a split view with both the master and detail view showing (Regular width class)
// it is possible that a detail view has not been selected - a map pin in this case
guard allStopContent.count > 0 else {
let stopContentVC = storyboard.instantiateViewControllerWithIdentifier("stopContentVC") as! PictureContentViewController
stopContentVC.picText = "No Stop Selected"
return stopContentVC
}
if let _ = (allStopContent[index])["picImage"] {
let stopContentVC = storyboard.instantiateViewControllerWithIdentifier("stopContentVC") as! PictureContentViewController
if let _ = stop {
stopContentVC.delegate = self
stopContentVC.picImageFileName = (allStopContent[index])["picImage"]!
stopContentVC.picText = (allStopContent[index])["picText"]!
stopContentVC.maxPages = allStopContent.count
} else {
stopContentVC.picText = "No Stop Selected"
}
stopContentVC.pageIndex = index
return stopContentVC
}else {
let youTubeContentVC = storyboard.instantiateViewControllerWithIdentifier("YouTubeVC") as! YouTubeContentViewController
youTubeContentVC.delegate = self
youTubeContentVC.maxPages = allStopContent.count
youTubeContentVC.pageIndex = index
youTubeContentVC.youTubeID = (allStopContent[index])["YouTubeID"]!
youTubeContentVC.youTubeText = (allStopContent[index])["YouTubeText"]!
return youTubeContentVC
}
}
//MARK: - UIPageViewControllerDataSource
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let stopContentVC = viewController as! PictureContentViewController
pageIndex = stopContentVC.pageIndex - 1
if pageIndex < 0 {
pageIndex = 0
return nil
} else {
return viewControllerAtIndex(pageIndex)
}
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let _ = stop else {return nil}
var pageIndex = getPageIndexForVC(viewController)
pageIndex += 1
if pageIndex > (allStopContent.count) - 1 {
pageIndex = (allStopContent.count) - 1
return nil
} else {
return viewControllerAtIndex(pageIndex)
}
}
func getPageIndexForVC(viewController: UIViewController) -> Int {
if let vc = viewController as? PictureContentViewController {
return vc.pageIndex
} else {
let vc = viewController as! YouTubeContentViewController
return vc.pageIndex
}
}
//MARK: - PictureContentViewControllerDelegate method
func pageControlChanged(sender: UIViewController, newPageIndex: Int) {
// direction doesn't matter for scroll page views
let nextVC = viewControllerAtIndex(newPageIndex)
setViewControllers([nextVC!], direction: .Forward, animated: false, completion: nil)
}
}
| mit | 0a93997aa86be059155f8de3ec914b3c | 33.51773 | 161 | 0.617834 | 5.794048 | false | false | false | false |
hjw6160602/JourneyNotes | JourneyNotes/Classes/Common/Category/UIVIew+Extension.swift | 1 | 1981 | //
// UIVIew+Extension.swift
// 贝思客Swift
//
// Created by SaiDicaprio on 15/12/24.
// Copyright © 2015年 SaiDicaprio. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
var x : CGFloat{
set{
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
get{
return self.frame.origin.x
}
}
var y : CGFloat{
set{
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
get{
return self.frame.origin.y
}
}
var centerX : CGFloat{
set{
var center = self.center
center.x = newValue
self.center = center
}
get{
return self.center.x
}
}
var centerY : CGFloat{
set{
var center = self.center
center.y = newValue
self.center = center
}
get{
return self.center.y
}
}
var width : CGFloat{
set{
var frame = self.frame
frame.size.width = newValue
self.frame = frame
}
get{
return self.frame.size.width
}
}
var height : CGFloat{
set{
var frame = self.frame
frame.size.height = newValue
self.frame = frame
}
get{
return self.frame.size.height
}
}
var size : CGSize{
set{
var frame = self.frame
frame.size = newValue
self.frame = frame
}
get{
return self.frame.size
}
}
var origin : CGPoint{
set{
var frame = self.frame
frame.origin = newValue
self.frame = frame
}
get{
return self.frame.origin
}
}
}
| mit | 174f474ef9a95667f351f498188170a7 | 18.72 | 55 | 0.445233 | 4.512586 | false | false | false | false |
IAskWind/IAWExtensionTool | IAWExtensionTool/IAWExtensionTool/Classes/CustomView/LoadProgressAnimationView.swift | 1 | 1898 | //
// LoadProgressAnimationView.swift
// CtkApp
//
// Created by winston on 16/12/9.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
open class LoadProgressAnimationView: UIView {
var viewWidth: CGFloat = 0
override open var frame: CGRect {
willSet {
if frame.size.width == viewWidth {
self.isHidden = true
}
super.frame = frame
}
}
public init(bgColor:UIColor,frame: CGRect) {
super.init(frame: frame)
viewWidth = frame.size.width
backgroundColor = bgColor
self.frame.size.width = 0
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func startLoadProgressAnimation() {
self.frame.size.width = 0
isHidden = false
weak var tmpSelf = self
UIView.animate(withDuration: 0.4, animations: { () -> Void in
tmpSelf?.frame.size.width = (tmpSelf?.viewWidth)! * 0.6
}, completion: { (finish) -> Void in
let time = DispatchTime.now() + Double(Int64(0.4 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: { () -> Void in
UIView.animate(withDuration: 0.3, animations: { () -> Void in
tmpSelf?.frame.size.width = (tmpSelf?.viewWidth)! * 0.8
})
})
})
}
public func endLoadProgressAnimation() {
weak var tmpSelf = self
UIView.animate(withDuration: 0.2, animations: { () -> Void in
tmpSelf!.frame.size.width = tmpSelf!.viewWidth
}, completion: { (finish) -> Void in
tmpSelf?.isHidden = true
})
}
}
| mit | a58f2b7a7a16ff95ddda9a98bcc68f0e | 28.609375 | 112 | 0.536675 | 4.511905 | false | false | false | false |
practicalswift/swift | test/Sema/substring_to_string_conversion_swift4.swift | 9 | 3116 | // RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s
let s = "Hello"
let ss = s[s.startIndex..<s.endIndex]
// CTP_Initialization
do {
let s1: String = { return ss }() // expected-error {{cannot convert value of type 'Substring' to closure result type 'String'}} {{29-29=String(}} {{31-31=)}}
_ = s1
}
// CTP_ReturnStmt
do {
func returnsAString() -> String {
return ss // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{12-12=String(}} {{14-14=)}}
}
}
// CTP_ThrowStmt
// Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError:
// The conversion destination of throw is always ErrorType (at the moment)
// if this ever expands, this should be a specific form like () is for
// return.
// CTP_EnumCaseRawValue
// Substrings can't be raw values because they aren't literals.
// CTP_DefaultParameter
do {
func foo(x: String = ss) {} // expected-error {{default argument value of type 'Substring' cannot be converted to type 'String'}} {{24-24=String(}} {{26-26=)}}
}
// CTP_CalleeResult
do {
func getSubstring() -> Substring { return ss }
let gottenString : String = getSubstring() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{31-31=String(}} {{45-45=)}}
_ = gottenString
}
// CTP_CallArgument
do {
func takesAString(_ s: String) {}
takesAString(ss) // expected-error {{cannot convert value of type 'Substring' to expected argument type 'String'}} {{16-16=String(}} {{18-18=)}}
}
// CTP_ClosureResult
do {
[ss].map { (x: Substring) -> String in x } // expected-error {{cannot convert value of type 'Substring' to closure result type 'String'}} {{42-42=String(}} {{43-43=)}}
}
// CTP_ArrayElement
do {
let a: [String] = [ ss ] // expected-error {{cannot convert value of type 'Substring' to expected element type 'String'}} {{23-23=String(}} {{25-25=)}}
_ = a
}
// CTP_DictionaryKey
do {
let d: [ String : String ] = [ ss : s ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary key type 'String'}} {{34-34=String(}} {{36-36=)}}
_ = d
}
// CTP_DictionaryValue
do {
let d: [ String : String ] = [ s : ss ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary value type 'String'}} {{38-38=String(}} {{40-40=)}}
_ = d
}
// CTP_CoerceOperand
do {
let s1: String = ss as String // expected-error {{cannot convert value of type 'Substring' to type 'String' in coercion}} {{20-20=String(}} {{22-22=)}}
_ = s1
}
// CTP_AssignSource
do {
let s1: String = ss // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{22-22=)}}
_ = s1
}
// Substring-to-String via subscripting in a context expecting String
func takesString(_ s: String) {}
// rdar://33474838
protocol Derivable {
func derive() -> Substring
}
func foo<T: Derivable>(t: T) -> String {
return t.derive() // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{10-10=String(}} {{20-20=)}}
}
| apache-2.0 | d24e227a41276d932c63f95ec197a091 | 33.622222 | 177 | 0.662388 | 3.497194 | false | false | false | false |
alexandrehcdc/dejavi | dejavi/MovieDetailsController.swift | 1 | 1066 | import UIKit
class MovieDetailsController: UIViewController {
@IBOutlet weak var plot: UILabel!
@IBOutlet weak var genre: UILabel!
@IBOutlet weak var runtime: UILabel!
@IBOutlet weak var movieTitle: UILabel!
@IBOutlet weak var alreadyWatchedBtn: UIButton!
@IBOutlet weak var wannaWatchBtn: UIButton!
var newPlot, newGenre, newRuntime, newMovieTitle: String?
func loadFields (newPlot: String, newGenre: String, newRuntime: String, newMovieTitle: String) {
plot.text = newPlot
genre.text = newGenre
runtime.text = newRuntime
movieTitle.text = newMovieTitle
}
override func viewDidLoad() {
super.viewDidLoad()
alreadyWatchedBtn = loadCustomButtonStyle(alreadyWatchedBtn)
wannaWatchBtn = loadCustomButtonStyle(wannaWatchBtn)
// loadFields(newPlot!, newGenre: newGenre!, newRuntime: newRuntime!, newMovieTitle: newMovieTitle!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 2bb9c80e1c0df68b08982cc56383d25b | 31.30303 | 108 | 0.684803 | 4.634783 | false | false | false | false |
jopamer/swift | test/decl/func/operator.swift | 1 | 14642 | // RUN: %target-typecheck-verify-swift
infix operator %%%
infix operator %%%%
func %%%() {} // expected-error {{operators must have one or two arguments}}
func %%%%(a: Int, b: Int, c: Int) {} // expected-error {{operators must have one or two arguments}}
struct X {}
struct Y {}
func +(lhs: X, rhs: X) -> X {} // okay
func +++(lhs: X, rhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}
infix operator ++++ : ReallyHighPrecedence
precedencegroup ReallyHighPrecedence {
higherThan: BitwiseShiftPrecedence
associativity: left
}
infix func fn_binary(_ lhs: Int, rhs: Int) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}}
func ++++(lhs: X, rhs: X) -> X {}
func ++++(lhs: Y, rhs: Y) -> Y {} // okay
func useInt(_ x: Int) {}
func test() {
var x : Int
let y : Int = 42
// Produce a diagnostic for using the result of an assignment as a value.
// rdar://12961094
useInt(x = y) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
_ = x
}
prefix operator ~~
postfix operator ~~
infix operator ~~
postfix func foo(_ x: Int) {} // expected-error {{'postfix' requires a function with an operator identifier}}
postfix func ~~(x: Int) -> Float { return Float(x) }
postfix func ~~(x: Int, y: Int) {} // expected-error {{'postfix' requires a function with one argument}}
prefix func ~~(x: Float) {}
func test_postfix(_ x: Int) {
~~x~~
}
prefix operator ~~~ // expected-note 2{{prefix operator found here}}
// Unary operators require a prefix or postfix attribute
func ~~~(x: Float) {} // expected-error{{prefix unary operator missing 'prefix' modifier}}{{1-1=prefix }}
protocol P {
static func ~~~(x: Self) // expected-error{{prefix unary operator missing 'prefix' modifier}}{{10-10=prefix }}
}
prefix func +// this should be a comment, not an operator
(arg: Int) -> Int { return arg }
prefix func -/* this also should be a comment, not an operator */
(arg: Int) -> Int { return arg }
func +*/ () {} // expected-error {{expected identifier in function declaration}} expected-error {{unexpected end of block comment}} expected-error {{closure expression is unused}} expected-error{{top-level statement cannot begin with a closure expression}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }}
func errors() {
*/ // expected-error {{unexpected end of block comment}}
// rdar://12962712 - reject */ in an operator as it should end a block comment.
*/+ // expected-error {{unexpected end of block comment}}
}
prefix operator ...
prefix func ... (arg: Int) -> Int { return arg }
func resyncParser() {}
// Operator decl refs (<op>)
infix operator +-+
prefix operator +-+
prefix operator -+-
postfix operator -+-
infix operator +-+=
infix func +-+ (x: Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}}
prefix func +-+ (x: Int) -> Int {}
prefix func -+- (y: inout Int) -> Int {} // expected-note 2{{found this candidate}}
postfix func -+- (x: inout Int) -> Int {} // expected-note 2{{found this candidate}}
infix func +-+= (x: inout Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}}
var n = 0
// Infix by context
_ = (+-+)(1, 2)
// Prefix by context
_ = (+-+)(1)
// Ambiguous -- could be prefix or postfix
(-+-)(&n) // expected-error{{ambiguous use of operator '-+-'}}
// Assignment operator refs become inout functions
_ = (+-+=)(&n, 12)
(+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{8-8=&}}
var f1 : (Int, Int) -> Int = (+-+)
var f2 : (Int) -> Int = (+-+)
var f3 : (inout Int) -> Int = (-+-) // expected-error{{ambiguous use of operator '-+-'}}
var f4 : (inout Int, Int) -> Int = (+-+=)
var r5 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (+, -)
var r6 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (b : +, a : -)
struct f6_S {
subscript(op : (Int, Int) -> Int) -> Int {
return 42
}
}
var f6_s : f6_S
var junk = f6_s[+]
// Unicode operator names
infix operator ☃
infix operator ☃⃠ // Operators can contain (but not start with) combining characters
func ☃(x: Int, y: Int) -> Bool { return x == y }
func ☃⃠(x: Int, y: Int) -> Bool { return x != y }
var x, y : Int
_ = x☃y
_ = x☃⃠y
// rdar://14705150 - crash on invalid
func test_14705150() {
let a = 4
var b! = a // expected-error {{type annotation missing in pattern}}
// expected-error @-1 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// expected-error @-2 {{expected expression}}
}
postfix operator ++
prefix operator ++
prefix postfix func ++(x: Int) {} // expected-error {{'postfix' contradicts previous modifier 'prefix'}} {{8-16=}}
postfix prefix func ++(x: Float) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}}
postfix prefix infix func ++(x: Double) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} expected-error {{'infix' contradicts previous modifier 'postfix'}} {{16-22=}}
infix prefix func +-+(x: Int, y: Int) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} expected-error{{'prefix' contradicts previous modifier 'infix'}} {{7-14=}}
// Don't allow one to define a postfix '!'; it's built into the
// language. Also illegal to have any postfix operator starting with '!'.
postfix operator ! // expected-error {{cannot declare a custom postfix '!' operator}} expected-error {{expected operator name in operator declaration}}
prefix operator & // expected-error {{cannot declare a custom prefix '&' operator}}
// <rdar://problem/14607026> Restrict use of '<' and '>' as prefix/postfix operator names
postfix operator > // expected-error {{cannot declare a custom postfix '>' operator}}
prefix operator < // expected-error {{cannot declare a custom prefix '<' operator}}
postfix func !(x: Int) { } // expected-error{{cannot declare a custom postfix '!' operator}}
postfix func!(x: Int8) { } // expected-error{{cannot declare a custom postfix '!' operator}}
prefix func & (x: Int) {} // expected-error {{cannot declare a custom prefix '&' operator}}
// Only allow operators at global scope:
func operator_in_func_bad () {
prefix func + (input: String) -> String { return "+" + input } // expected-error {{operator functions can only be declared at global or in type scope}}
}
infix operator ? // expected-error {{expected operator name in operator declaration}}
infix operator ??=
func ??= <T>(result : inout T?, rhs : Int) { // ok
}
// <rdar://problem/14296004> [QoI] Poor diagnostic/recovery when two operators (e.g., == and -) are adjacted without spaces.
_ = n*-4 // expected-error {{missing whitespace between '*' and '-' operators}} {{6-6= }} {{7-7= }}
if n==-1 {} // expected-error {{missing whitespace between '==' and '-' operators}} {{5-5= }} {{7-7= }}
prefix operator ☃⃠
prefix func☃⃠(a : Int) -> Int { return a }
postfix operator ☃⃠
postfix func☃⃠(a : Int) -> Int { return a }
_ = n☃⃠ ☃⃠ n // Ok.
_ = n ☃⃠ ☃⃠n // Ok.
_ = n ☃⃠☃⃠ n // expected-error {{use of unresolved operator '☃⃠☃⃠'}}
_ = n☃⃠☃⃠n // expected-error {{ambiguous missing whitespace between unary and binary operators}}
// expected-note @-1 {{could be binary '☃⃠' and prefix '☃⃠'}} {{12-12= }} {{18-18= }}
// expected-note @-2 {{could be postfix '☃⃠' and binary '☃⃠'}} {{6-6= }} {{12-12= }}
_ = n☃⃠☃⃠ // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}}
_ = ~!n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}}
_ = -+n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}}
_ = -++n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}}
// <rdar://problem/16230507> Cannot use a negative constant as the second operator of ... operator
_ = 3...-5 // expected-error {{ambiguous missing whitespace between unary and binary operators}} expected-note {{could be postfix '...' and binary '-'}} expected-note {{could be binary '...' and prefix '-'}}
protocol P0 {
static func %%%(lhs: Self, rhs: Self) -> Self
}
protocol P1 {
func %%%(lhs: Self, rhs: Self) -> Self // expected-error{{operator '%%%' declared in protocol must be 'static'}}{{3-3=static }}
}
struct S0 {
static func %%%(lhs: S0, rhs: S0) -> S0 { return lhs }
}
extension S0 {
static func %%%%(lhs: S0, rhs: S0) -> S0 { return lhs }
}
struct S1 {
func %%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%' declared in type 'S1' must be 'static'}}{{3-3=static }}
}
extension S1 {
func %%%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%%' declared in type 'S1' must be 'static'}}{{3-3=static }}
}
class C0 {
static func %%%(lhs: C0, rhs: C0) -> C0 { return lhs }
}
class C1 {
final func %%%(lhs: C1, rhs: C1) -> C1 { return lhs } // expected-error{{operator '%%%' declared in type 'C1' must be 'static'}}{{3-3=static }}
}
final class C2 {
class func %%%(lhs: C2, rhs: C2) -> C2 { return lhs }
}
class C3 {
class func %%%(lhs: C3, rhs: C3) -> C3 { return lhs } // expected-error{{operator '%%%' declared in non-final class 'C3' must be 'final'}}{{3-3=final }}
}
class C4 {
func %%%(lhs: C4, rhs: C4) -> C4 { return lhs } // expected-error{{operator '%%%' declared in type 'C4' must be 'static'}}{{3-3=static }}
}
struct Unrelated { }
struct S2 {
static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { }
// expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}}
static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2 { }
// expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}}
static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { }
// expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}}
// Okay: refers to S2
static func %%%(lhs: S2, rhs: Unrelated) -> Unrelated { }
static func %%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { }
static func %%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { }
static func %%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { }
static func %%%(lhs: Unrelated, rhs: S2) -> Unrelated { }
static func %%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { }
static func %%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { }
static func %%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { }
}
extension S2 {
static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { }
// expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}}
static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2 { }
// expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}}
static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { }
// expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}}
// Okay: refers to S2
static func %%%%(lhs: S2, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: S2) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { }
}
protocol P2 {
static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated
// expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}}
static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self
// expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}}
static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type
// expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}}
// Okay: refers to Self
static func %%%(lhs: Self, rhs: Unrelated) -> Unrelated
static func %%%(lhs: inout Self, rhs: Unrelated) -> Unrelated
static func %%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated
static func %%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated
static func %%%(lhs: Unrelated, rhs: Self) -> Unrelated
static func %%%(lhs: Unrelated, rhs: inout Self) -> Unrelated
static func %%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated
static func %%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated
}
extension P2 {
static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { }
// expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}}
static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self { }
// expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}}
static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type { }
// expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}}
// Okay: refers to Self
static func %%%%(lhs: Self, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: inout Self, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: Self) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: inout Self) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated { }
static func %%%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated { }
}
protocol P3 {
// Okay: refers to P3
static func %%%(lhs: P3, rhs: Unrelated) -> Unrelated
}
extension P3 {
// Okay: refers to P3
static func %%%%(lhs: P3, rhs: Unrelated) -> Unrelated { }
}
// rdar://problem/27940842 - recovery with a non-static '=='.
class C5 {
func == (lhs: C5, rhs: C5) -> Bool { return false } // expected-error{{operator '==' declared in type 'C5' must be 'static'}}
func test1(x: C5) {
_ = x == x
}
}
class C6 {
static func == (lhs: C6, rhs: C6) -> Bool { return false }
func test1(x: C6) {
if x == x && x = x { } // expected-error{{expression is not assignable: '&&' returns immutable value}}
}
}
| apache-2.0 | 4969bfacbcc650527cecd7661216d1c2 | 39.4 | 327 | 0.634145 | 3.559471 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Models/WalletPairing/WalletInfo.swift | 1 | 9671 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import WalletPayloadKit
public enum WalletInfoError: Error {
case failToDecodeBase64Component
case failToDecodeToWalletInfo(Error)
case sessionTokenMismatch(originSession: String, base64Str: String)
case missingSessionToken(originSession: String, base64Str: String)
}
public struct WalletInfo: Codable, Equatable {
// MARK: - UserType
public enum UserType: String, Codable {
/// only wallet
case wallet = "WALLET"
/// only exchange
case exchange = "EXCHANGE"
/// wallet object has embedded exchange object
case linked = "WALLET_EXCHANGE_LINKED"
/// payload has only root-level wallet & exchange objects
case notLinked = "WALLET_EXCHANGE_NOT_LINKED"
/// there are root-level wallet & exchange objects, but wallet also has embedded exchange object (e.g. tied to different e-mail & linked via legacy linking)
case both = "WALLET_EXCHANGE_BOTH"
}
// MARK: - Wallet
public struct Wallet: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case guid
case email
case twoFaType = "two_fa_type"
case emailCode = "email_code"
case isMobileSetup = "is_mobile_setup"
case hasCloudBackup = "has_cloud_backup"
case sessionId = "session_id"
case nabu
}
public var guid: String
public var email: String?
public var twoFaType: WalletAuthenticatorType?
public var emailCode: String?
public var isMobileSetup: Bool?
public var hasCloudBackup: Bool?
public var sessionId: String?
public var nabu: Nabu?
public init(
guid: String,
email: String? = nil,
twoFaType: WalletAuthenticatorType? = nil,
emailCode: String? = nil,
isMobileSetup: Bool? = nil,
hasCloudBackup: Bool? = nil,
sessionId: String? = nil,
nabu: Nabu? = nil
) {
self.guid = guid
self.email = email
self.twoFaType = twoFaType
self.emailCode = emailCode
self.isMobileSetup = isMobileSetup
self.hasCloudBackup = hasCloudBackup
self.sessionId = sessionId
self.nabu = nabu
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
guid = try container.decode(String.self, forKey: .guid)
email = try container.decodeIfPresent(String.self, forKey: .email)
twoFaType = try container.decodeIfPresent(WalletAuthenticatorType.self, forKey: .twoFaType)
emailCode = try container.decodeIfPresent(String.self, forKey: .emailCode)
isMobileSetup = try container.decodeIfPresent(Bool.self, forKey: .isMobileSetup)
hasCloudBackup = try container.decodeIfPresent(Bool.self, forKey: .hasCloudBackup)
sessionId = try container.decodeIfPresent(String.self, forKey: .sessionId)
nabu = try container.decodeIfPresent(Nabu.self, forKey: .nabu)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(guid, forKey: .guid)
try container.encodeIfPresent(email, forKey: .email)
try container.encodeIfPresent(twoFaType, forKey: .twoFaType)
try container.encodeIfPresent(emailCode, forKey: .emailCode)
try container.encodeIfPresent(isMobileSetup, forKey: .isMobileSetup)
try container.encodeIfPresent(hasCloudBackup, forKey: .hasCloudBackup)
try container.encodeIfPresent(sessionId, forKey: .sessionId)
try container.encodeIfPresent(nabu, forKey: .nabu)
}
}
// MARK: - Nabu
public struct Nabu: Codable, Equatable {
private enum CodingKeys: String, CodingKey {
case userId = "user_id"
case recoveryToken = "recovery_token"
case recoverable
}
public var userId: String
public var recoveryToken: String
public var recoverable: Bool
public init(
userId: String,
recoveryToken: String,
recoverable: Bool
) {
self.userId = userId
self.recoveryToken = recoveryToken
self.recoverable = recoverable
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
userId = try container.decode(String.self, forKey: .userId)
recoveryToken = try container.decode(String.self, forKey: .recoveryToken)
recoverable = try container.decode(Bool.self, forKey: .recoverable)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(userId, forKey: .userId)
try container.encode(recoveryToken, forKey: .recoveryToken)
try container.encode(recoverable, forKey: .recoverable)
}
}
// MARK: - Exchange
public struct Exchange: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case twoFaMode = "two_fa_mode"
case email
}
public var twoFaMode: Bool?
public var email: String?
public init(
twoFaMode: Bool? = nil,
email: String? = nil
) {
self.twoFaMode = twoFaMode
self.email = email
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
twoFaMode = try container.decodeIfPresent(Bool.self, forKey: .twoFaMode)
email = try container.decodeIfPresent(String.self, forKey: .email)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(twoFaMode, forKey: .twoFaMode)
try container.encodeIfPresent(email, forKey: .email)
}
}
private enum CodingKeys: String, CodingKey {
case sessionId = "session_id"
case product
case exchangeAuthUrl = "exchange_auth_url"
case exchange
case userType = "user_type"
case unified
case mergeable
case upgradeable
case wallet
}
public var sessionId: String?
public var product: String?
public var exchangeAuthUrl: String?
public var exchange: Exchange?
public var userType: UserType?
public var unified: Bool?
public var mergeable: Bool?
public var upgradeable: Bool?
public var wallet: Wallet?
public static var empty: WalletInfo {
self.init()
}
public init(
sessionId: String? = nil,
product: String? = nil,
exchangeAuthUrl: String? = nil,
exchange: Exchange? = nil,
userType: UserType? = nil,
unified: Bool? = nil,
mergeable: Bool? = nil,
upgradeable: Bool? = nil,
wallet: Wallet? = nil
) {
self.sessionId = sessionId
self.product = product
self.exchangeAuthUrl = exchangeAuthUrl
self.exchange = exchange
self.userType = userType
self.unified = unified
self.mergeable = mergeable
self.upgradeable = upgradeable
self.wallet = wallet
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
sessionId = try container.decodeIfPresent(String.self, forKey: .sessionId)
product = try container.decodeIfPresent(String.self, forKey: .product)
exchangeAuthUrl = try container.decodeIfPresent(String.self, forKey: .exchangeAuthUrl)
exchange = try container.decodeIfPresent(Exchange.self, forKey: .exchange)
userType = try container.decodeIfPresent(UserType.self, forKey: .userType)
unified = try container.decodeIfPresent(Bool.self, forKey: .unified)
mergeable = try container.decodeIfPresent(Bool.self, forKey: .mergeable)
upgradeable = try container.decodeIfPresent(Bool.self, forKey: .upgradeable)
wallet = try container.decodeIfPresent(Wallet.self, forKey: .wallet)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(sessionId, forKey: .sessionId)
try container.encodeIfPresent(product, forKey: .product)
try container.encodeIfPresent(exchangeAuthUrl, forKey: .exchangeAuthUrl)
try container.encodeIfPresent(exchange, forKey: .exchange)
try container.encodeIfPresent(userType, forKey: .userType)
try container.encodeIfPresent(unified, forKey: .unified)
try container.encodeIfPresent(mergeable, forKey: .mergeable)
try container.encodeIfPresent(upgradeable, forKey: .upgradeable)
try container.encodeIfPresent(wallet, forKey: .wallet)
}
}
extension WalletInfo {
/// Determine whether the account attached could be upgraded
public var shouldUpgradeAccount: Bool {
guard let unified = unified,
let upgradeable = upgradeable,
let mergeable = mergeable,
userType != nil
else {
return false
}
return !unified && (upgradeable || mergeable)
}
}
| lgpl-3.0 | 37d6bfa46e9d693c7586391a1a1fc4ed | 36.335907 | 164 | 0.631954 | 4.751843 | false | false | false | false |
joelrorseth/AtMe | AtMe/Conversation.swift | 1 | 1222 | //
// Conversation.swift
// AtMe
//
// Created by Joel Rorseth on 2017-04-27.
// Copyright © 2017 Joel Rorseth. All rights reserved.
//
import Foundation
public class Conversation {
var convoID: String
var name: String
var newestMessage: String
var newestMessageTimestamp: String
var unseenMessages: Bool
// TODO: Refactor to store date instead of string
var timestamp: Date!
var lastSeenByCurrentUser: Date!
// Assume that every convo will only have two members (current user and another)
// In ChatListViewController, we don't add current user to these lists
// Thus only the 'other user' will appear, exclusively in either inactive or active
var activeMemberUIDs = Set<String>()
var inactiveMemberUIDs = Set<String>()
/** Initializer */
init(convoID: String, name: String, newestMessage: String, timestamp: Date, newestMessageTimestamp: String, unseenMessages: Bool) {
self.convoID = convoID
self.name = name
self.newestMessage = newestMessage
self.timestamp = timestamp
self.newestMessageTimestamp = newestMessageTimestamp
self.unseenMessages = unseenMessages
}
}
| apache-2.0 | 376fa8260dbd481660d040b16ffd79a7 | 28.780488 | 135 | 0.684685 | 4.423913 | false | false | false | false |
mathiasquintero/Sweeft | Sources/Sweeft/Networking/Definition/APIEndpoint.swift | 3 | 1102 | //
// APIDescription.swift
// Pods
//
// Created by Mathias Quintero on 12/21/16.
//
//
import Foundation
/// Description for an Endpoint in an API
public protocol APIEndpoint {
/// Raw value string for the key
var rawValue: String { get }
}
extension APIEndpoint {
/// For the lazy. Creates a simple API object for your reference
public static func api(with url: String, baseHeaders: [String:String] = .empty, baseQueries: [String:String] = .empty) -> GenericAPI<Self> {
return GenericAPI(baseURL: url, baseHeaders: baseHeaders, baseQueries: baseQueries)
}
}
/// Generic easy to make API from an Endpoint Description
public struct GenericAPI<E: APIEndpoint>: API {
public typealias Endpoint = E
public let baseURL: String
public let baseHeaders: [String:String]
public let baseQueries: [String:String]
init(baseURL: String, baseHeaders: [String:String] = .empty, baseQueries: [String:String] = .empty) {
self.baseURL = baseURL
self.baseHeaders = baseHeaders
self.baseQueries = baseQueries
}
}
| mit | ab9e1bf874a0d2686880bb71a57e4400 | 26.55 | 144 | 0.676951 | 4.021898 | false | false | false | false |
wangCanHui/weiboSwift | weiboSwift/AppDelegate.swift | 1 | 2854 | //
// AppDelegate.swift
// weiboSwift
//
// Created by 王灿辉 on 15/10/26.
// Copyright © 2015年 王灿辉. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 设置全局的属性,今早设置
setupAppearance()
print(NSHomeDirectory())
// 打开数据库
CZSQLiteManager.sharedManager
print(CZUserAccount.loadAccount())
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let viewVC = UIViewController()
viewVC.view.backgroundColor = UIColor.redColor()
// let tabBarC = CZMainViewController()
// window!.rootViewController = CZNewFeatureViewController()
window!.rootViewController = defaultController()
window!.makeKeyAndVisible()
return true
}
private func defaultController() -> UIViewController {
// 判断是否登录
// 每次都需要判断
if !CZUserAccount.userLogin {
print("用户未登录")
return CZMainViewController()
}
// 判断是否是新版本
return isNewVersion() ? CZNewFeatureViewController() : CZWelcomeViewController()
}
/// 判断是否是新版本
private func isNewVersion() -> Bool {
// 获取当前的版本号
let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let currentVersion = Double(versionStr)!
print("currentVersion\(currentVersion)")
// 获取到之前的版本号
let sandboxVersionKey = "sandboxVersionKey"
let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
// 保存当前版本号
NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
NSUserDefaults.standardUserDefaults().synchronize()
if currentVersion > sandboxVersion {
print("是新版本")
}
// 对比
return currentVersion > sandboxVersion
}
// MARK: - 切换根控制器
/**
切换根控制器
- parameter isMain: true: 表示切换到MainViewController, false: welcome
*/
func switchRootController(isMain: Bool) {
window?.rootViewController = isMain ? CZMainViewController() : CZWelcomeViewController()
}
private func setupAppearance() {
// 设置全局导航栏文字颜色,尽早设置
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
}
}
| apache-2.0 | 836a80770e76d2f9ce7d9586c7b94ba1 | 26.505263 | 127 | 0.623039 | 5.455115 | false | false | false | false |
AniOSDeveloper/SearchTwitterWithOauth | SearchTwitterWithOauth/Model/TwitteModel.swift | 1 | 673 | //
// TwitteModel.swift
// SearchTwitterWithOauth
//
// Created by Larry on 16/5/16.
// Copyright © 2016年 Larry. All rights reserved.
//
import UIKit
class TwitteModel: NSObject {
var headerIcon: String
var nickName: String?
var userName: String?
var timeAgo: String
var tweet : String
var id : Int
init(headerIcon: String, nickName: String, userName: String, timeAgo: String, tweet : String, id:Int){
self.headerIcon = headerIcon
self.nickName = nickName
self.userName = userName
self.timeAgo = timeAgo
self.tweet = tweet
self.id = id
}
}
| mit | f72822bce5f0685747f695b89ed02df9 | 20.612903 | 106 | 0.6 | 4.011976 | false | false | false | false |
manavgabhawala/swift | test/SILGen/constrained_extensions.swift | 1 | 7418 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
// RUN: %target-swift-frontend -emit-ir -O %s
extension Array where Element == Int {
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlESaySiGyt1x_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int>
public init(x: ()) {
self.init()
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifg : $@convention(method) (@guaranteed Array<Int>) -> Int
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifs : $@convention(method) (Int, @inout Array<Int>) -> ()
// CHECK-LABEL: sil [transparent] [fragile] @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>, @thick Array<Int>.Type) -> ()
// CHECK-LABEL: sil [transparent] [fragile] @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public var instanceProperty: Element {
get {
return self[0]
}
set {
self[0] = newValue
}
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodSiyF : $@convention(method) (@guaranteed Array<Int>) -> Int
public func instanceMethod() -> Element {
return instanceProperty
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodS2i1e_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int
public func instanceMethod(e: Element) -> Element {
return e
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14staticPropertySifgZ : $@convention(method) (@thin Array<Int>.Type) -> Int
public static var staticProperty: Element {
return Array(x: ()).instanceProperty
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodSiyFZ : $@convention(method) (@thin Array<Int>.Type) -> Int
public static func staticMethod() -> Element {
return staticProperty
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodS2iSg1e_tFZfA_ : $@convention(thin) () -> Optional<Int>
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodS2iSg1e_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int
public static func staticMethod(e: Element? = nil) -> Element {
return e!
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE9subscriptSiycfg : $@convention(method) (@guaranteed Array<Int>) -> Int
public subscript(i: ()) -> Element {
return self[0]
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE21inoutAccessOfPropertyyyF : $@convention(method) (@inout Array<Int>) -> ()
public mutating func inoutAccessOfProperty() {
func increment(x: inout Element) {
x += 1
}
increment(x: &instanceProperty)
}
}
extension Dictionary where Key == Int {
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lEABySiq_Gyt1x_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> {
public init(x: ()) {
self.init()
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fs : $@convention(method) <Key, Value where Key == Int> (@in Value, @inout Dictionary<Int, Value>) -> ()
// CHECK-LABEL: sil [transparent] [fragile] @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fmytfU_ : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>, @thick Dictionary<Int, Value>.Type) -> ()
// CHECK-LABEL: sil [transparent] [fragile] @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fm : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public var instanceProperty: Value {
get {
return self[0]!
}
set {
self[0] = newValue
}
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14instanceMethodq_yF : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
public func instanceMethod() -> Value {
return instanceProperty
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14instanceMethodq_q_1v_tF : $@convention(method) <Key, Value where Key == Int> (@in Value, @guaranteed Dictionary<Int, Value>) -> @out Value
public func instanceMethod(v: Value) -> Value {
return v
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodSiyFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int
public static func staticMethod() -> Key {
return staticProperty
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14staticPropertySifgZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int
public static var staticProperty: Key {
return 0
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_SiSg1k_q_Sg1vtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int>
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_SiSg1k_q_Sg1vtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value>
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_SiSg1k_q_Sg1vtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value
public static func staticMethod(k: Key? = nil, v: Value? = nil) -> Value {
return v!
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE17callsStaticMethodq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value
public static func callsStaticMethod() -> Value {
return staticMethod()
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16callsConstructorq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value
public static func callsConstructor() -> Value {
return Dictionary(x: ()).instanceMethod()
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE9subscriptq_ycfg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
public subscript(i: ()) -> Value {
return self[0]!
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE21inoutAccessOfPropertyyyF : $@convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> ()
public mutating func inoutAccessOfProperty() {
func increment(x: inout Value) { }
increment(x: &instanceProperty)
}
}
| apache-2.0 | c733fca50f45d897f9edb7d6d16f09fb | 54.774436 | 313 | 0.723241 | 3.811922 | false | false | false | false |
NSJoe/ListUpdater | source/ThrottleTask.swift | 1 | 1084 | //
// ThrottleTask.swift
// ListUpdater
//
// Created by Joe's MacBook Pro on 2017/7/9.
// Copyright © 2017年 joe. All rights reserved.
//
import Foundation
open class ThrottleTask {
public typealias Task = (Void) -> Void
private var throttle:Float = 0.0
private var tasks = [Task]()
private let queue = DispatchQueue(label: "throttle.task.serial.queue", attributes: .init(rawValue:0))
public init(throttle:Float) {
self.throttle = throttle
}
public func add(task:@escaping Task) -> Void {
objc_sync_enter(self)
self.tasks.append(task)
if self.tasks.count == 1 {
self.execute()
}
objc_sync_exit(self)
}
func execute() -> Void {
queue.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(self.throttle * 1000.0))) {
objc_sync_enter(self)
guard let task = self.tasks.last else { return }
self.tasks.removeAll()
objc_sync_exit(self)
task()
}
}
}
| mit | 8f66d5ec5f1630904aa700a2c72d4d05 | 24.738095 | 121 | 0.583719 | 3.959707 | false | false | false | false |
pvbaleeiro/movie-aholic | movieaholic/movieaholic/util/DateUtil.swift | 1 | 1039 | //
// DateUtil.swift
// movieaholic
//
// Created by Victor Baleeiro on 24/09/17.
// Copyright © 2017 Victor Baleeiro. All rights reserved.
//
import Foundation
class Dateutil {
//-------------------------------------------------------------------------------------------------------------
// MARK: Datas
//-------------------------------------------------------------------------------------------------------------
class func friendlyDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
guard let date = dateFormatter.date(from: date) else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM EEEE"
dateFormatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let timeStamp = dateFormatter.string(from: date)
return timeStamp
}
}
| mit | ca5a44a9c8037f91593c0bb52a429b0c | 31.4375 | 115 | 0.473988 | 5.492063 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | Source/RemoteImage.swift | 3 | 7090 | //
// RemoteImage.swift
// edX
//
// Created by Michael Katz on 9/24/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
protocol RemoteImage {
var placeholder: UIImage? { get }
var brokenImage: UIImage? { get }
var image: UIImage? { get }
/** Callback should be on main thread */
func fetchImage(completion: (remoteImage : NetworkResult<RemoteImage>) -> ()) -> Removable
}
private let imageCache = NSCache()
class RemoteImageImpl: RemoteImage {
let placeholder: UIImage?
let url: String
var localImage: UIImage?
let networkManager: NetworkManager
let persist: Bool
init(url: String, networkManager: NetworkManager, placeholder: UIImage?, persist: Bool) {
self.url = url
self.placeholder = placeholder
self.networkManager = networkManager
self.persist = persist
}
private var filename: String {
return url.oex_md5
}
private var localFile: String {
let cachesDir = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
let remoteImageDir = (cachesDir as NSString).stringByAppendingPathComponent("remoteimages")
if !NSFileManager.defaultManager().fileExistsAtPath(remoteImageDir) {
_ = try? NSFileManager.defaultManager().createDirectoryAtPath(remoteImageDir, withIntermediateDirectories: true, attributes: nil)
}
return (remoteImageDir as NSString).stringByAppendingPathComponent(filename)
}
var image: UIImage? {
if localImage != nil { return localImage }
if let cachedImage = imageCache.objectForKey(filename) {
return cachedImage as? UIImage
}
else if let localImage = UIImage(contentsOfFile: localFile) {
let cost = Int(localImage.size.height * localImage.size.width)
imageCache.setObject(localImage, forKey: filename, cost: cost)
return localImage
}
else {
return nil
}
}
private func imageDeserializer(response: NSHTTPURLResponse, data: NSData) -> Result<RemoteImage> {
if let newImage = UIImage(data: data) {
let result = self
result.localImage = newImage
let cost = data.length
imageCache.setObject(newImage, forKey: filename, cost: cost)
if persist {
data.writeToFile(localFile, atomically: false)
}
return Success(result)
}
return Failure(NSError.oex_unknownError())
}
func fetchImage(completion: (remoteImage : NetworkResult<RemoteImage>) -> ()) -> Removable {
// Only authorize requests to the API host
// This is necessary for two reasons:
// 1. We don't want to leak credentials by loading random images
// 2. Some servers will explicitly reject our credentials even if
// the image is public. Causing the load to fail
let host = NSURL(string: url).flatMap { $0.host }
let noHost = host?.isEmpty ?? true
let matchesBaseHost = host == self.networkManager.baseURL.host
let requiresAuth = noHost || matchesBaseHost
let request = NetworkRequest(method: .GET,
path: url,
requiresAuth: requiresAuth,
deserializer: .DataResponse(imageDeserializer)
)
return networkManager.taskForRequest(request, handler: completion)
}
}
struct RemoteImageJustImage : RemoteImage {
let placeholder: UIImage?
var image: UIImage?
init (image: UIImage?) {
self.image = image
self.placeholder = image
}
}
extension RemoteImage {
var brokenImage:UIImage? { return placeholder }
func fetchImage(completion: (remoteImage : NetworkResult<RemoteImage>) -> ()) -> Removable {
let result = NetworkResult<RemoteImage>(request: nil, response: nil, data: self, baseData: nil, error: nil)
completion(remoteImage: result)
return BlockRemovable {}
}
}
extension UIImageView {
private struct AssociatedKeys {
static var SpinerName = "remoteimagespinner"
static var LastRemoteTask = "lastremotetask"
static var HidesLoadingSpinner = "hidesLoadingSpinner"
}
var spinner: SpinnerView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.SpinerName) as? SpinnerView
}
set {
if let oldSpinner = objc_getAssociatedObject(self, &AssociatedKeys.SpinerName) as? SpinnerView {
oldSpinner.removeFromSuperview()
}
if newValue != nil {
objc_setAssociatedObject(self, &AssociatedKeys.SpinerName, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
var lastRemoteTask: Removable? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.LastRemoteTask) as? Removable
}
set {
if let oldTask = objc_getAssociatedObject(self, &AssociatedKeys.LastRemoteTask) as? Removable {
oldTask.remove()
}
if let newTask = newValue as? AnyObject {
objc_setAssociatedObject(self, &AssociatedKeys.LastRemoteTask, newTask, .OBJC_ASSOCIATION_RETAIN)
}
}
}
var hidesLoadingSpinner : Bool {
get {
return (objc_getAssociatedObject(self, &AssociatedKeys.HidesLoadingSpinner) as? NSNumber)?.boolValue ?? false
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.HidesLoadingSpinner, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN)
}
}
var remoteImage: RemoteImage? {
get { return RemoteImageJustImage(image: image) }
set {
guard let ri = newValue else { image = nil; return }
let localImage = ri.image
if localImage != nil {
image = localImage
return
}
image = ri.placeholder
if !hidesLoadingSpinner {
startSpinner()
}
lastRemoteTask = ri.fetchImage(self.handleRemoteLoaded)
}
}
func handleRemoteLoaded(result : NetworkResult<RemoteImage>) {
self.stopSpinner()
if let remoteImage = result.data {
if let im = remoteImage.image {
image = im
} else {
image = remoteImage.brokenImage
}
}
}
func startSpinner() {
let spinner = self.spinner ?? SpinnerView(size: .Large, color: .Primary)
self.spinner = spinner
superview?.addSubview(spinner)
spinner.snp_makeConstraints { (make) -> Void in
make.center.equalTo(snp_center)
}
spinner.startAnimating()
spinner.hidden = false
}
func stopSpinner() {
spinner?.stopAnimating()
spinner?.removeFromSuperview()
}
} | apache-2.0 | de047f883868631065cddd277595d081 | 31.976744 | 141 | 0.605163 | 5.089017 | false | false | false | false |
Ferrick90/Fusuma | Sources/FusumaViewController.swift | 1 | 16688 | //
// FusumaViewController.swift
// Fusuma
//
// Created by Yuta Akizuki on 2015/11/14.
// Copyright © 2015年 ytakzk. All rights reserved.
//
import UIKit
import Photos
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
@objc public protocol FusumaDelegate: class {
func fusumaImageSelected(_ image: UIImage)
@objc optional func fusumaDismissedWithImage(_ image: UIImage)
func fusumaVideoCompleted(withFileURL fileURL: URL)
func fusumaCameraRollUnauthorized()
@objc optional func fusumaClosed()
}
public var fusumaBaseTintColor = UIColor.hex("#FFFFFF", alpha: 1.0)
public var fusumaTintColor = UIColor.hex("#009688", alpha: 1.0)
public var fusumaBackgroundColor = UIColor.hex("#212121", alpha: 1.0)
public var fusumaAlbumImage : UIImage? = nil
public var fusumaCameraImage : UIImage? = nil
public var fusumaVideoImage : UIImage? = nil
public var fusumaCheckImage : UIImage? = nil
public var fusumaCloseImage : UIImage? = nil
public var fusumaFlashOnImage : UIImage? = nil
public var fusumaFlashOffImage : UIImage? = nil
public var fusumaFlipImage : UIImage? = nil
public var fusumaShotImage : UIImage? = nil
public var fusumaVideoStartImage : UIImage? = nil
public var fusumaVideoStopImage : UIImage? = nil
public var fusumaCropImage: Bool = true
public var fusumaCameraRollTitle = "CAMERA ROLL"
public var fusumaCameraTitle = "PHOTO"
public var fusumaVideoTitle = "VIDEO"
public var fusumaTintIcons : Bool = true
public enum FusumaModeOrder {
case cameraFirst
case libraryFirst
}
//@objc public class FusumaViewController: UIViewController, FSCameraViewDelegate, FSAlbumViewDelegate {
public final class FusumaViewController: UIViewController {
enum Mode {
case camera
case library
case video
}
public var hasVideo = false
var mode: Mode = Mode.camera
public var modeOrder: FusumaModeOrder = .libraryFirst
var willFilter = true
@IBOutlet weak var photoLibraryViewerContainer: UIView!
@IBOutlet weak var cameraShotContainer: UIView!
@IBOutlet weak var videoShotContainer: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var menuView: UIView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var libraryButton: UIButton!
@IBOutlet weak var cameraButton: UIButton!
@IBOutlet weak var videoButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet var libraryFirstConstraints: [NSLayoutConstraint]!
@IBOutlet var cameraFirstConstraints: [NSLayoutConstraint]!
lazy var albumView = FSAlbumView.instance()
lazy var cameraView = FSCameraView.instance()
lazy var videoView = FSVideoCameraView.instance()
fileprivate var hasGalleryPermission: Bool {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
public weak var delegate: FusumaDelegate? = nil
override public func loadView() {
if let view = UINib(nibName: "FusumaViewController", bundle: Bundle(for: self.classForCoder)).instantiate(withOwner: self, options: nil).first as? UIView {
self.view = view
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = fusumaBackgroundColor
cameraView.delegate = self
albumView.delegate = self
videoView.delegate = self
menuView.backgroundColor = fusumaBackgroundColor
menuView.addBottomBorder(UIColor.black, width: 1.0)
let bundle = Bundle(for: self.classForCoder)
// Get the custom button images if they're set
let albumImage = fusumaAlbumImage != nil ? fusumaAlbumImage : UIImage(named: "ic_insert_photo", in: bundle, compatibleWith: nil)
let cameraImage = fusumaCameraImage != nil ? fusumaCameraImage : UIImage(named: "ic_photo_camera", in: bundle, compatibleWith: nil)
let videoImage = fusumaVideoImage != nil ? fusumaVideoImage : UIImage(named: "ic_videocam", in: bundle, compatibleWith: nil)
let checkImage = fusumaCheckImage != nil ? fusumaCheckImage : UIImage(named: "ic_check", in: bundle, compatibleWith: nil)
let closeImage = fusumaCloseImage != nil ? fusumaCloseImage : UIImage(named: "ic_close", in: bundle, compatibleWith: nil)
if fusumaTintIcons {
libraryButton.setImage(albumImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
libraryButton.setImage(albumImage?.withRenderingMode(.alwaysTemplate), for: .highlighted)
libraryButton.setImage(albumImage?.withRenderingMode(.alwaysTemplate), for: .selected)
libraryButton.tintColor = fusumaTintColor
libraryButton.adjustsImageWhenHighlighted = false
cameraButton.setImage(cameraImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
cameraButton.setImage(cameraImage?.withRenderingMode(.alwaysTemplate), for: .highlighted)
cameraButton.setImage(cameraImage?.withRenderingMode(.alwaysTemplate), for: .selected)
cameraButton.tintColor = fusumaTintColor
cameraButton.adjustsImageWhenHighlighted = false
closeButton.setImage(closeImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
closeButton.setImage(closeImage?.withRenderingMode(.alwaysTemplate), for: .highlighted)
closeButton.setImage(closeImage?.withRenderingMode(.alwaysTemplate), for: .selected)
closeButton.tintColor = fusumaBaseTintColor
videoButton.setImage(videoImage, for: UIControlState())
videoButton.setImage(videoImage, for: .highlighted)
videoButton.setImage(videoImage, for: .selected)
videoButton.tintColor = fusumaTintColor
videoButton.adjustsImageWhenHighlighted = false
doneButton.setImage(checkImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
doneButton.tintColor = fusumaBaseTintColor
} else {
libraryButton.setImage(albumImage, for: UIControlState())
libraryButton.setImage(albumImage, for: .highlighted)
libraryButton.setImage(albumImage, for: .selected)
libraryButton.tintColor = nil
cameraButton.setImage(cameraImage, for: UIControlState())
cameraButton.setImage(cameraImage, for: .highlighted)
cameraButton.setImage(cameraImage, for: .selected)
cameraButton.tintColor = nil
videoButton.setImage(videoImage, for: UIControlState())
videoButton.setImage(videoImage, for: .highlighted)
videoButton.setImage(videoImage, for: .selected)
videoButton.tintColor = nil
closeButton.setImage(closeImage, for: UIControlState())
doneButton.setImage(checkImage, for: UIControlState())
}
cameraButton.clipsToBounds = true
libraryButton.clipsToBounds = true
videoButton.clipsToBounds = true
changeMode(Mode.library)
photoLibraryViewerContainer.addSubview(albumView)
cameraShotContainer.addSubview(cameraView)
videoShotContainer.addSubview(videoView)
titleLabel.textColor = fusumaBaseTintColor
// if modeOrder != .LibraryFirst {
// libraryFirstConstraints.forEach { $0.priority = 250 }
// cameraFirstConstraints.forEach { $0.priority = 1000 }
// }
if !hasVideo {
videoButton.removeFromSuperview()
self.view.addConstraint(NSLayoutConstraint(
item: self.view,
attribute: .trailing,
relatedBy: .equal,
toItem: cameraButton,
attribute: .trailing,
multiplier: 1.0,
constant: 0
)
)
self.view.layoutIfNeeded()
}
if fusumaCropImage {
cameraView.fullAspectRatioConstraint.isActive = false
cameraView.croppedAspectRatioConstraint.isActive = true
} else {
cameraView.fullAspectRatioConstraint.isActive = true
cameraView.croppedAspectRatioConstraint.isActive = false
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
albumView.frame = CGRect(origin: CGPoint.zero, size: photoLibraryViewerContainer.frame.size)
albumView.layoutIfNeeded()
cameraView.frame = CGRect(origin: CGPoint.zero, size: cameraShotContainer.frame.size)
cameraView.layoutIfNeeded()
albumView.initialize()
cameraView.initialize()
if hasVideo {
videoView.frame = CGRect(origin: CGPoint.zero, size: videoShotContainer.frame.size)
videoView.layoutIfNeeded()
videoView.initialize()
}
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.stopAll()
}
override public var prefersStatusBarHidden : Bool {
return true
}
@IBAction func closeButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: {
self.delegate?.fusumaClosed?()
})
}
@IBAction func libraryButtonPressed(_ sender: UIButton) {
changeMode(Mode.library)
}
@IBAction func photoButtonPressed(_ sender: UIButton) {
changeMode(Mode.camera)
}
@IBAction func videoButtonPressed(_ sender: UIButton) {
changeMode(Mode.video)
}
@IBAction func doneButtonPressed(_ sender: UIButton) {
let view = albumView.imageCropView
if fusumaCropImage {
let normalizedX = (view?.contentOffset.x)! / (view?.contentSize.width)!
let normalizedY = (view?.contentOffset.y)! / (view?.contentSize.height)!
let normalizedWidth = (view?.frame.width)! / (view?.contentSize.width)!
let normalizedHeight = (view?.frame.height)! / (view?.contentSize.height)!
let cropRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight)
DispatchQueue.global(qos: .default).async(execute: {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.normalizedCropRect = cropRect
options.resizeMode = .exact
let targetWidth = floor(CGFloat(self.albumView.phAsset.pixelWidth) * cropRect.width)
let targetHeight = floor(CGFloat(self.albumView.phAsset.pixelHeight) * cropRect.height)
let dimension = max(min(targetHeight, targetWidth), 1024 * UIScreen.main.scale)
let targetSize = CGSize(width: dimension, height: dimension)
PHImageManager.default().requestImage(for: self.albumView.phAsset, targetSize: targetSize,
contentMode: .aspectFill, options: options) {
result, info in
DispatchQueue.main.async(execute: {
self.delegate?.fusumaImageSelected(result!)
self.dismiss(animated: true, completion: {
self.delegate?.fusumaDismissedWithImage?(result!)
})
})
}
})
} else {
print("no image crop ")
delegate?.fusumaImageSelected((view?.image)!)
self.dismiss(animated: true, completion: {
self.delegate?.fusumaDismissedWithImage?((view?.image)!)
})
}
}
}
extension FusumaViewController: FSAlbumViewDelegate, FSCameraViewDelegate, FSVideoCameraViewDelegate {
// MARK: FSCameraViewDelegate
func cameraShotFinished(_ image: UIImage) {
delegate?.fusumaImageSelected(image)
self.dismiss(animated: true, completion: {
self.delegate?.fusumaDismissedWithImage?(image)
})
}
// MARK: FSAlbumViewDelegate
public func albumViewCameraRollUnauthorized() {
delegate?.fusumaCameraRollUnauthorized()
}
func videoFinished(withFileURL fileURL: URL) {
delegate?.fusumaVideoCompleted(withFileURL: fileURL)
self.dismiss(animated: true, completion: nil)
}
}
private extension FusumaViewController {
func stopAll() {
if hasVideo {
self.videoView.stopCamera()
}
self.cameraView.stopCamera()
}
func changeMode(_ mode: Mode) {
if self.mode == mode {
return
}
//operate this switch before changing mode to stop cameras
switch self.mode {
case .library:
break
case .camera:
self.cameraView.stopCamera()
case .video:
self.videoView.stopCamera()
}
self.mode = mode
dishighlightButtons()
switch mode {
case .library:
titleLabel.text = NSLocalizedString(fusumaCameraRollTitle, comment: fusumaCameraRollTitle)
doneButton.isHidden = false
highlightButton(libraryButton)
self.view.bringSubview(toFront: photoLibraryViewerContainer)
case .camera:
titleLabel.text = NSLocalizedString(fusumaCameraTitle, comment: fusumaCameraTitle)
doneButton.isHidden = true
highlightButton(cameraButton)
self.view.bringSubview(toFront: cameraShotContainer)
cameraView.startCamera()
case .video:
titleLabel.text = fusumaVideoTitle
doneButton.isHidden = true
highlightButton(videoButton)
self.view.bringSubview(toFront: videoShotContainer)
videoView.startCamera()
}
doneButton.isHidden = !hasGalleryPermission
self.view.bringSubview(toFront: menuView)
}
func dishighlightButtons() {
cameraButton.tintColor = fusumaBaseTintColor
libraryButton.tintColor = fusumaBaseTintColor
if cameraButton.layer.sublayers?.count > 1 {
for layer in cameraButton.layer.sublayers! {
if let borderColor = layer.borderColor , UIColor(cgColor: borderColor) == fusumaTintColor {
layer.removeFromSuperlayer()
}
}
}
if libraryButton.layer.sublayers?.count > 1 {
for layer in libraryButton.layer.sublayers! {
if let borderColor = layer.borderColor , UIColor(cgColor: borderColor) == fusumaTintColor {
layer.removeFromSuperlayer()
}
}
}
if let videoButton = videoButton {
videoButton.tintColor = fusumaBaseTintColor
if videoButton.layer.sublayers?.count > 1 {
for layer in videoButton.layer.sublayers! {
if let borderColor = layer.borderColor , UIColor(cgColor: borderColor) == fusumaTintColor {
layer.removeFromSuperlayer()
}
}
}
}
}
func highlightButton(_ button: UIButton) {
button.tintColor = fusumaTintColor
button.addBottomBorder(fusumaTintColor, width: 3)
}
}
| mit | 436acbe5dd9a667b37fbdd82a1ec6be4 | 33.68815 | 163 | 0.609829 | 5.545032 | false | false | false | false |
tlax/looper | looper/Metal/MetalFilterBlender.swift | 1 | 1281 | import MetalPerformanceShaders
class MetalFilterBlender:MetalFilter
{
private let kIndexBaseTexture:Int = 0
private let kIndexOverTexture:Int = 1
private let kIndexMapTexture:Int = 2
private let kIndexDestinationTexture:Int = 3
//MARK: public
func render(
overlayTexture:MTLTexture,
baseTexture:MTLTexture,
mapTexture:MTLTexture)
{
guard
let commandEncoder:MTLComputeCommandEncoder = self.commandEncoder,
let pipeline:MTLComputePipelineState = self.pipeline,
let threadgroupCounts:MTLSize = self.threadgroupCounts,
let threadgroups:MTLSize = self.threadgroups
else
{
return
}
commandEncoder.setComputePipelineState(pipeline)
commandEncoder.setTexture(baseTexture, at:kIndexBaseTexture)
commandEncoder.setTexture(overlayTexture, at:kIndexOverTexture)
commandEncoder.setTexture(mapTexture, at:kIndexMapTexture)
commandEncoder.setTexture(baseTexture, at:kIndexDestinationTexture)
commandEncoder.dispatchThreadgroups(
threadgroups,
threadsPerThreadgroup:threadgroupCounts)
commandEncoder.endEncoding()
}
}
| mit | 3cb8173d1d568347336f67af005944ec | 31.025 | 78 | 0.672912 | 5.427966 | false | false | false | false |
microeditionbiz/ML-client | ML-client/View Controllers/AmountViewController.swift | 1 | 5470 | //
// AmountViewController.swift
// ML-client
//
// Created by Pablo Romero on 8/13/17.
// Copyright © 2017 Pablo Romero. All rights reserved.
//
import UIKit
class AmountViewController: UIViewController {
@IBOutlet weak var amountTextField: UITextField!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var nextButtonBottomConstraint: NSLayoutConstraint!
lazy var paymentInfo: PaymentInfo = {
return PaymentInfo(paymentHandler: { [unowned self] paymentInfo in
self.completePaymentFlow(withPaymentInfo: paymentInfo)
})
}()
override func viewDidLoad() {
super.viewDidLoad()
refreshNextButtonEnabledState()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyboardNotificationsObserver()
amountTextField.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
amountTextField.resignFirstResponder()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
removeKeyboardNotificatiosObserver()
}
// MARK: - Action
@IBAction func nextAction(sender: UIButton) {
showPaymentMethodViewController()
}
// MARK: - Next button
fileprivate func refreshNextButtonEnabledState() {
let enabled = paymentInfo.amount.compare(NSNumber(value: 0)) == .orderedDescending
nextButton.isEnabled = enabled
nextButton.backgroundColor = enabled ? UIColor.mpBlue : UIColor.lightGray.withAlphaComponent(0.25)
}
// MARK: - Keyboard
private func addKeyboardNotificationsObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(AmountViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(AmountViewController.keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
}
private func removeKeyboardNotificatiosObserver() {
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil)
}
@objc private func keyboardWillShow(_ notification: Notification) {
let keyBoardInfo = notification.userInfo!
let keyboardFrame = keyBoardInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
let duration = keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int
nextButtonBottomConstraint.constant = keyboardFrame.cgRectValue.size.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(duration)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
self.view.layoutIfNeeded()
UIView.commitAnimations()
}
@objc private func keyboardWillHide(_ notification: Notification) {
let keyBoardInfo = notification.userInfo!
let duration = keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int
nextButtonBottomConstraint.constant = 0
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(duration)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
self.view.layoutIfNeeded()
UIView.commitAnimations()
}
// MARK: - Navigation
func showPaymentMethodViewController() {
performSegue(withIdentifier: "ShowPaymentMethods", sender: nil)
}
func completePaymentFlow(withPaymentInfo paymentInfo: PaymentInfo) {
self.navigationController?.popToRootViewController(animated: true)
guard let paymentMethodName = paymentInfo.paymentMethod?.name, let cardIssuerName = paymentInfo.cardIssuer?.name, let recommendedMessage = paymentInfo.payerCost?.recommendedMessage else {
assertionFailure("Missing required info")
return
}
amountTextField.text = ""
let message = "Usted pagó \(recommendedMessage) con el medio de pago \(paymentMethodName) del banco \(cardIssuerName)."
UIAlertController.presentAlert(withTitle: "Pago", message: message, overViewController: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? PaymentMethodsViewController {
viewController.paymentInfo = paymentInfo
}
}
}
extension AmountViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var newValue = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
newValue = newValue?.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined()
paymentInfo.setAmount(string: newValue!)
textField.text = paymentInfo.formattedAmount
refreshNextButtonEnabledState()
return false
}
}
| mit | 941651644448b95e425066479e7a95fa | 36.452055 | 195 | 0.696964 | 5.707724 | false | false | false | false |
abelsanchezali/ViewBuilder | Source/Document/Core/DocumentBuilder+Build.swift | 1 | 1905 | //
// DocumentBuilder+Build.swift
// ViewBuilder
//
// Created by Abel Sanchez on 11/13/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import UIKit
// MARK: Build
extension DocumentBuilder {
/**
Create an instance of given type T from document.
If document does not match type or path is not valid will fail.
- Parameter path: Path to Document.
- Parameter options: Options to be used during build process.
- Returns: An instance of type T described in document.
*/
public func load<T>(_ path: String, options: BuildOptions? = nil) -> T? {
let options = options ?? defaultOptions()
guard let document = loadDocument(path, options: options.document) else {
return nil
}
let factory = createFactory(document, options: options.factory)
return factory.build(options.instantiation)
}
/**
Create an any instance reoresented in document. If document path is not valid will fail.
- Parameter path: Path to Document.
- Parameter options: Options to be used during build process.
- Returns: An instance of type T described in document.
*/
public func loadObject(_ path: String, options: BuildOptions? = nil) -> Any? {
let options = options ?? defaultOptions()
guard let document = loadDocument(path, options: options.document) else {
return nil
}
let factory = createFactory(document, options: options.factory)
return factory.buildObject(options.instantiation)
}
}
// MARK: UIKit
extension DocumentBuilder {
public func loadView(_ path: String, options: BuildOptions? = nil) -> UIView? {
return load(path, options: options)
}
public func loadResources(_ path: String, options: BuildOptions? = nil) -> Resources? {
return load(path, options: options)
}
}
| mit | 5b71b424c18cb7026b0fb280bed133b0 | 30.213115 | 93 | 0.652836 | 4.397229 | false | false | false | false |
srn214/Floral | Floral/Floral/Classes/Expand/Extensions/RxSwift/Cocoa/IndexPath+Rx.swift | 1 | 996 | //
// IndexPath+Rx.swift
// RxSwiftX
//
// Created by Pircate on 2018/7/9.
// Copyright © 2018年 Pircate. All rights reserved.
//
import RxSwift
import RxCocoa
public extension ObservableType where Element == IndexPath {
func section(_ section: Int) -> Observable<Element> {
return filter { $0.section == section }
}
func row(_ row: Int) -> Observable<Element> {
return filter { $0.row == row }
}
func item(_ item: Int) -> Observable<Element> {
return filter { $0.item == item }
}
}
public extension Driver where Element == IndexPath {
func section(_ section: Int) -> SharedSequence<SharingStrategy, Element> {
return filter { $0.section == section }
}
func row(_ row: Int) -> SharedSequence<SharingStrategy, Element> {
return filter { $0.row == row }
}
func item(_ item: Int) -> SharedSequence<SharingStrategy, Element> {
return filter { $0.item == item }
}
}
| mit | 48a1bb34f602cad92acfa190b5a75b46 | 23.825 | 78 | 0.599194 | 4.004032 | false | false | false | false |
iltercengiz/ICViewPager | ICViewPager/ICViewPager/Tab/TabCollectionViewLayout.swift | 1 | 4948 | //
// TabCollectionViewLayout.swift
// ICViewPager
//
// Created by Ilter Cengiz on 18/5/18.
// Copyright © 2018 Ilter Cengiz. All rights reserved.
//
import UIKit
final class TabCollectionViewLayout: UICollectionViewFlowLayout {
private enum Constants {
static let indicatorHeight: CGFloat = 2.0
}
private var indicatorAttributes: TabIndicatorAttributes!
private var invalidationContext: UICollectionViewFlowLayoutInvalidationContext = {
let context = UICollectionViewFlowLayoutInvalidationContext()
context.invalidateFlowLayoutAttributes = false
context.invalidateFlowLayoutDelegateMetrics = false
context.invalidateDecorationElements(ofKind: TabIndicatorView.kind,
at: [TabIndicatorAttributes.Constants.indicatorIndexPath])
return context
}()
var configuration: ViewPagerConfiguration!
var currentPage: Int = 0
var numberOfViews: Int = 0
// MARK: Init
override init() {
super.init()
setUpLayout()
registerDecorationView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpLayout()
registerDecorationView()
}
// MARK: Layout
override func prepare() {
super.prepare()
if numberOfViews > 0 {
indicatorAttributes = indicatorAttributes(for: currentPage)
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes = super.layoutAttributesForElements(in: rect)
if numberOfViews > 0 {
attributes?.append(indicatorAttributes)
}
return attributes
}
override func layoutAttributesForDecorationView(ofKind elementKind: String,
at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard elementKind == TabIndicatorView.kind else { return nil }
return indicatorAttributes
}
// MARK: Public functions
func updateIndicator(direction: ScrollDirection) {
let currentIndicatorAttributes = indicatorAttributes(for: currentPage)
switch direction {
case .left(let percentage):
let previousIndicatorAttributes = indicatorAttributes(for: currentPage - 1)
let frame = currentIndicatorAttributes.frame
currentIndicatorAttributes.frame = CGRect(x: frame.minX - (frame.minX - previousIndicatorAttributes.frame.minX) * percentage,
y: frame.minY,
width: frame.width - (frame.width - previousIndicatorAttributes.frame.width) * percentage,
height: frame.height)
indicatorAttributes = currentIndicatorAttributes
case .right(let percentage):
let nextIndicatorAttributes = indicatorAttributes(for: currentPage + 1)
let frame = currentIndicatorAttributes.frame
currentIndicatorAttributes.frame = CGRect(x: frame.minX + (nextIndicatorAttributes.frame.minX - frame.minX) * percentage,
y: frame.minY,
width: frame.width - (frame.width - nextIndicatorAttributes.frame.width) * percentage,
height: frame.height)
indicatorAttributes = currentIndicatorAttributes
case .stationary:
break
}
invalidateLayout(with: invalidationContext)
}
}
private extension TabCollectionViewLayout {
func setUpLayout() {
scrollDirection = .horizontal
minimumInteritemSpacing = 0.0
minimumLineSpacing = 0.0
}
func registerDecorationView() {
register(TabIndicatorView.self,
forDecorationViewOfKind: TabIndicatorView.kind)
}
func indicatorAttributes(for page: Int) -> TabIndicatorAttributes {
guard let tabItemAttributes = layoutAttributesForItem(at: IndexPath(item: page, section: 0)) else {
fatalError("Called `indicatorAttributes(for:)` before super did its preparations.")
}
let tabItemFrame = tabItemAttributes.frame
let indicatorAttributes = TabIndicatorAttributes(backgroundColor: configuration.tabIndicatorColor)
indicatorAttributes.frame = CGRect(x: tabItemFrame.minX, y: tabItemFrame.maxY - Constants.indicatorHeight,
width: tabItemFrame.width, height: Constants.indicatorHeight)
return indicatorAttributes
}
}
| mit | 72d3b6aeb556c66e0ab2d3c3b77a2805 | 35.91791 | 144 | 0.604811 | 6.130112 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/word-break-ii.swift | 2 | 1863 | /**
* https://leetcode.com/problems/word-break-ii/
*
*
*/
// Date: Thu Jul 30 11:10:43 PDT 2020
class Solution {
private func wordBreakable(_ s: String, _ wordDict: [String]) -> Bool {
let dict = Set(wordDict)
let s = Array(s)
var valid = Array(repeating: false, count: s.count + 1)
valid[0] = true
for end in 1 ... s.count {
// print("End in: \(end)")
for start in stride(from: end - 1, through: 0, by: -1) {
let word = String(s[start ..< end])
// print("---start from: \(start) with \(word)")
if valid[start], dict.contains(word) {
valid[end] = true
break
}
}
}
return valid[s.count]
}
/// - Complexity:
/// - Time: O(n^2), n is the length of string s.
/// - Space: O(n^3), n is the length of string s.
///
func wordBreak(_ s: String, _ wordDict: [String]) -> [String] {
if wordBreakable(s, wordDict) == false { return [] }
let dict = Set(wordDict)
let s = Array(s)
var valid = Array(repeating: [String](), count: s.count + 1)
valid[0] = [""]
for end in 1 ... s.count {
// print("End in: \(end)")
for word in dict {
if word.count <= end {
let start = end - word.count
// print("---start: \(start) with: \(word)")
if String(s[start ..< end]) == word, valid[start].isEmpty == false {
for cand in valid[start] {
valid[end].append(cand + word + " ")
}
}
}
}
}
return valid[s.count].map { $0.trimmingCharacters(in: .whitespaces) }
}
}
| mit | 884bf30441818040a67ce92492310bef | 34.826923 | 88 | 0.441761 | 3.913866 | false | false | false | false |
nRewik/swift-corelibs-foundation | TestFoundation/TestNSRange.swift | 1 | 1646 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSRange : XCTestCase {
var allTests : [(String, () -> Void)] {
return [
// currently disabled due to pending requirements for NSString
// ("test_NSRangeFromString", test_NSRangeFromString ),
]
}
func test_NSRangeFromString() {
let emptyRangeStrings = [
"",
"{}",
"{a, b}",
]
let emptyRange = NSMakeRange(0, 0)
for string in emptyRangeStrings {
XCTAssert(NSEqualRanges(NSRangeFromString(string), emptyRange))
}
let partialRangeStrings = [
"12",
"[12]",
"{12",
"{12,",
]
let partialRange = NSMakeRange(12, 0)
for string in partialRangeStrings {
XCTAssert(NSEqualRanges(NSRangeFromString(string), partialRange))
}
let fullRangeStrings = [
"{12, 34}",
"[12, 34]",
"12.34",
]
let fullRange = NSMakeRange(12, 34)
for string in fullRangeStrings {
XCTAssert(NSEqualRanges(NSRangeFromString(string), fullRange))
}
}
} | apache-2.0 | 9841539fd356a0040e30cb26aefd4d0e | 26 | 78 | 0.581409 | 4.716332 | false | true | false | false |
verticon/MecklenburgTrailOfHistory | Trail of History/PageSwiper.swift | 1 | 942 | //
// PageSwiper.swift
// Trail of History
//
// Created by Robert Vaessen on 1/17/18.
// Copyright © 2018 Robert Vaessen. All rights reserved.
//
import UIKit
class PageSwiper: UIView {
enum Direction {
case left
case right
}
var direction: Direction = .left {
didSet { setNeedsDisplay() }
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
var x: CGFloat = direction == .left ? 1 : bounds.maxX - 1
var deltaY: CGFloat = 3.0
for _ in 1...3 {
context.move(to: CGPoint(x: x, y: center.y - deltaY))
context.addLine(to: CGPoint(x: x, y: center.y + deltaY))
x += direction == .left ? 2 : -2
deltaY += 3
}
context.setStrokeColor(UIColor.tohTerracotaColor.cgColor)
context.setLineWidth(1)
context.strokePath()
}
}
| mit | b4d240c300e6d0a6942d7faa6fdf10c1 | 23.128205 | 68 | 0.566419 | 3.88843 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/Frameworks/Datum/Datum/CoreDataModels/CD_Reminder.swift | 1 | 2662 | //
// CD_Reminder.swift
// Datum
//
// Created by Jeffrey Bergier on 2020/05/21.
// Copyright © 2020 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import CoreData
@objc(CD_Reminder)
internal class CD_Reminder: CD_Base {
@NSManaged var interval: Int32
@NSManaged var kindString: String
@NSManaged var descriptionString: String?
@NSManaged var nextPerformDate: Date?
@NSManaged var lastPerformDate: Date?
@NSManaged var note: String?
@NSManaged var performed: NSSet
@NSManaged var vessel: CD_ReminderVessel
override func awakeFromInsert() {
super.awakeFromInsert()
self.kindString = ReminderKind.kCaseWaterValue
self.interval = Int32(ReminderConstants.defaultInterval)
}
internal func updateDates(basedOnAppendedPerformDate newDate: Date) {
self.lastPerformDate = newDate
let cal = Calendar.current
self.nextPerformDate = cal.dateByAddingNumberOfDays(Int(self.interval),
to: newDate)
}
}
@objc(CD_ReminderPerform)
internal class CD_ReminderPerform: CD_Base {
@NSManaged var date: Date
@NSManaged var reminder: CD_Reminder
override func awakeFromInsert() {
super.awakeFromInsert()
self.date = Date()
}
}
extension CD_Reminder {
static func sortDescriptor(for sortOrder: ReminderSortOrder,
ascending: Bool) -> NSSortDescriptor
{
switch sortOrder {
case .interval:
return .init(key: #keyPath(CD_Reminder.interval), ascending: ascending)
case .kind:
return .init(key: #keyPath(CD_Reminder.kindString), ascending: ascending)
case .nextPerformDate:
return .init(key: #keyPath(CD_Reminder.nextPerformDate), ascending: ascending)
case .note:
return .init(key: #keyPath(CD_Reminder.note), ascending: ascending)
}
}
}
| gpl-3.0 | 4b43874601dba819715614b9bb5a2c3e | 32.683544 | 90 | 0.665163 | 4.340946 | false | false | false | false |
CocoaheadsSaar/Treffen | Treffen2/Autolayout Teil 2/AutolayoutTests2/AutolayoutTests/Kontakte/KontakteDataProvider.swift | 1 | 2440 | //
// KontakteDataProvider.swift
// AutolayoutTests
//
// Created by Markus Schmitt on 25.02.16.
// Copyright © 2016 Insecom - Markus Schmitt. All rights reserved.
//
import UIKit
class KontakteDataProvider: NSObject, UITableViewDataSource, UITableViewDelegate {
var cellIdentifier = "Cell"
var caller: KontakteViewController?
// Daten der Cells
var data = [
["Name 01", "Unternehmen 1"],
["Name 02", "Unternehmen 1"],
["Name 03", "Unternehmen 1"],
["Name 04", "Unternehmen 2"],
["Name 05", "Unternehmen 2"],
["Name 06", "Unternehmen 2"],
["Name 07", "Unternehmen 3"],
["Name 08", "Unternehmen 3"],
["Name 09", "Unternehmen 3"],
["Name 10", "Unternehmen 4"]
]
func addData(name: String, company: String) {
data.append([name, company])
}
// die Custom Cell muss als gültige Zelle registriert werden
func registerCellsForTableView(tableView: UITableView) {
tableView.registerClass(KontakteTableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
// Anzahl der Zellen, hier fest auf 10, was später geändert wird
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
// Daten der Zelle, hier quasi statisch
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! KontakteTableViewCell
cell.myLabel1.text = data[indexPath.row][1]
cell.myLabel2.text = data[indexPath.row][0]
return cell
}
// Methode beim Auswählen
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Cell #\(indexPath.row) ausgewählt")
// lade die Detail View
let details: KontakteDetailsViewController = KontakteDetailsViewController()
details.setName = data[indexPath.row][0]
details.setCompany = data[indexPath.row][1]
details.title = "Kontaktdetails"
caller!.navigationController?.pushViewController(details, animated: true)
}
// Höhe setzen
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
}
| gpl-2.0 | 2b1f17644051de30b82451520919f678 | 32.791667 | 129 | 0.654336 | 4.187608 | false | false | false | false |
gonzalezreal/Markup | Sources/Markup/MarkupParser.swift | 1 | 1871 | // Markup
//
// Copyright (c) 2017 Guille Gonzalez
// See LICENSE file for license
//
import Foundation
public struct MarkupParser {
public static func parse(text: String) -> [MarkupNode] {
var parser = MarkupParser(text: text)
return parser.parse()
}
private var tokenizer: MarkupTokenizer
private var openingDelimiters: [UnicodeScalar] = []
private init(text: String) {
tokenizer = MarkupTokenizer(string: text)
}
private mutating func parse() -> [MarkupNode] {
var elements: [MarkupNode] = []
while let token = tokenizer.nextToken() {
switch token {
case .text(let text):
elements.append(.text(text))
case .leftDelimiter(let delimiter):
// Recursively parse all the tokens following the delimiter
openingDelimiters.append(delimiter)
elements.append(contentsOf: parse())
case .rightDelimiter(let delimiter) where openingDelimiters.contains(delimiter):
guard let containerNode = close(delimiter: delimiter, elements: elements) else {
fatalError("There is no MarkupNode for \(delimiter)")
}
return [containerNode]
default:
elements.append(.text(token.description))
}
}
// Convert orphaned opening delimiters to plain text
let textElements: [MarkupNode] = openingDelimiters.map { .text(String($0)) }
elements.insert(contentsOf: textElements, at: 0)
openingDelimiters.removeAll()
return elements
}
private mutating func close(delimiter: UnicodeScalar, elements: [MarkupNode]) -> MarkupNode? {
var newElements = elements
// Convert orphaned opening delimiters to plain text
while openingDelimiters.count > 0 {
let openingDelimiter = openingDelimiters.popLast()!
if openingDelimiter == delimiter {
break
} else {
newElements.insert(.text(String(openingDelimiter)), at: 0)
}
}
return MarkupNode(delimiter: delimiter, children: newElements)
}
}
| mit | b38e6a0d0fdaa4ed590b75aa4df2ffc3 | 25.728571 | 95 | 0.718332 | 3.906054 | false | false | false | false |
darioalessandro/Theater | Pods/Nimble/Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlBadInstructionException.swift | 12 | 3743 | //
// CwlBadInstructionException.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#if (os(macOS) || os(iOS)) && arch(x86_64)
import Foundation
#if canImport(NimbleCwlMachBadInstructionHandler)
import NimbleCwlMachBadInstructionHandler
#endif
private func raiseBadInstructionException() {
BadInstructionException().raise()
}
/// A simple NSException subclass. It's not required to subclass NSException (since the exception type is represented in the name) but this helps for identifying the exception through runtime type.
@objc(BadInstructionException)
public class BadInstructionException: NSException {
static var name: String = "com.cocoawithlove.BadInstruction"
init() {
super.init(name: NSExceptionName(rawValue: BadInstructionException.name), reason: nil, userInfo: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// An Objective-C callable function, invoked from the `mach_exc_server` callback function `catch_mach_exception_raise_state` to push the `raiseBadInstructionException` function onto the stack.
@objc(receiveReply:)
public class func receiveReply(_ value: NSValue) -> NSNumber {
var reply = bad_instruction_exception_reply_t(exception_port: 0, exception: 0, code: nil, codeCnt: 0, flavor: nil, old_state: nil, old_stateCnt: 0, new_state: nil, new_stateCnt: nil)
withUnsafeMutablePointer(to: &reply) { value.getValue(UnsafeMutableRawPointer($0)) }
let old_state: UnsafePointer<natural_t> = reply.old_state!
let old_stateCnt: mach_msg_type_number_t = reply.old_stateCnt
let new_state: thread_state_t = reply.new_state!
let new_stateCnt: UnsafeMutablePointer<mach_msg_type_number_t> = reply.new_stateCnt!
// Make sure we've been given enough memory
if old_stateCnt != x86_THREAD_STATE64_COUNT || new_stateCnt.pointee < x86_THREAD_STATE64_COUNT {
return NSNumber(value: KERN_INVALID_ARGUMENT)
}
// Read the old thread state
var state = old_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { return $0.pointee }
// 1. Decrement the stack pointer
state.__rsp -= __uint64_t(MemoryLayout<Int>.size)
// 2. Save the old Instruction Pointer to the stack.
if let pointer = UnsafeMutablePointer<__uint64_t>(bitPattern: UInt(state.__rsp)) {
pointer.pointee = state.__rip
} else {
return NSNumber(value: KERN_INVALID_ARGUMENT)
}
// 3. Set the Instruction Pointer to the new function's address
var f: @convention(c) () -> Void = raiseBadInstructionException
withUnsafePointer(to: &f) {
state.__rip = $0.withMemoryRebound(to: __uint64_t.self, capacity: 1) { return $0.pointee }
}
// Write the new thread state
new_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { $0.pointee = state }
new_stateCnt.pointee = x86_THREAD_STATE64_COUNT
return NSNumber(value: KERN_SUCCESS)
}
}
#endif
| apache-2.0 | fd0157a3ec35964840e7c6a97c242644 | 41.044944 | 197 | 0.74078 | 3.708622 | false | false | false | false |
benlangmuir/swift | test/IRGen/prespecialized-metadata/enum-inmodule-4argument-1distinct_use.swift | 13 | 4175 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOyS4iGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwCP{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwxx{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwcp{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwca{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwtk{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwta{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@swift_getMultiPayloadEnumTagSinglePayload{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@swift_storeMultiPayloadEnumTagSinglePayload{{[^)]*}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwug{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOwup{{[^)]*}} to i8*)
// CHECK-SAME i8* bitcast ({{[^@]+}}@"$s4main5ValueOwui{{[^)]*}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOyS4iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOyS4iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: [[INT]] {{32|16}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First, Second, Third, Fourth> {
case first(First)
case second(First, Second)
case third(First, Second, Third)
case fourth(First, Second, Third, Fourth)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS4iGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.fourth(13, 14, 15, 16) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, i8** %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_BUFFER]],
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | f18b0f7dd9f23254bc7b90d160ac3ded | 41.602041 | 157 | 0.57509 | 2.977889 | false | false | false | false |
cmoulton/grokSwiftREST_v1.2 | grokSwiftREST/MasterViewController.swift | 1 | 14087 | //
// MasterViewController.swift
// grokSwiftREST
//
// Created by Christina Moulton on 2016-04-02.
// Copyright © 2016 Teak Mobile Inc. All rights reserved.
//
import UIKit
import PINRemoteImage
import SafariServices
import Alamofire
import BRYXBanner
class MasterViewController: UITableViewController,
LoginViewDelegate,
SFSafariViewControllerDelegate {
@IBOutlet weak var gistSegmentedControl: UISegmentedControl!
var errorBanner: Banner?
var detailViewController: DetailViewController? = nil
var safariViewController: SFSafariViewController?
var gists = [Gist]()
var nextPageURLString: String?
var isLoading = false
var dateFormatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
// add refresh control for pull to refresh
if (self.refreshControl == nil) {
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self,
action: #selector(refresh(_:)),
forControlEvents: UIControlEvents.ValueChanged)
}
self.dateFormatter.dateStyle = .ShortStyle
self.dateFormatter.timeStyle = .LongStyle
super.viewWillAppear(animated)
}
func loadGists(urlToLoad: String?) {
GitHubAPIManager.sharedInstance.clearCache()
self.isLoading = true
let completionHandler: (Result<[Gist], NSError>, String?) -> Void = { (result, nextPage) in
self.isLoading = false
self.nextPageURLString = nextPage
// tell refresh control it can stop showing up now
if self.refreshControl != nil && self.refreshControl!.refreshing {
self.refreshControl?.endRefreshing()
}
guard result.error == nil else {
self.handleLoadGistsError(result.error!)
return
}
guard let fetchedGists = result.value else {
print("no gists fetched")
return
}
if urlToLoad == nil {
// empty out the gists because we're not loading another page
self.gists = []
}
self.gists += fetchedGists
let path:Path = [.Public, .Starred, .MyGists][self.gistSegmentedControl.selectedSegmentIndex]
let success = PersistenceManager.saveArray(self.gists, path: path)
if !success {
self.showOfflineSaveFailedBanner()
}
// update "last updated" title for refresh control
let now = NSDate()
let updateString = "Last Updated at " + self.dateFormatter.stringFromDate(now)
self.refreshControl?.attributedTitle = NSAttributedString(string: updateString)
self.tableView.reloadData()
}
switch gistSegmentedControl.selectedSegmentIndex {
case 0:
GitHubAPIManager.sharedInstance.fetchPublicGists(urlToLoad, completionHandler:
completionHandler)
case 1:
GitHubAPIManager.sharedInstance.fetchMyStarredGists(urlToLoad, completionHandler:
completionHandler)
case 2:
GitHubAPIManager.sharedInstance.fetchMyGists(urlToLoad, completionHandler:
completionHandler)
default:
print("got an index that I didn't expect for selectedSegmentIndex")
}
}
func handleLoadGistsError(error: NSError) {
print(error)
nextPageURLString = nil
isLoading = false
if error.domain != NSURLErrorDomain {
return
}
if error.code == NSURLErrorUserAuthenticationRequired {
showOAuthLoginView()
} else if error.code == NSURLErrorNotConnectedToInternet {
let path:Path = [.Public, .Starred, .MyGists][self.gistSegmentedControl.selectedSegmentIndex]
if let archived:[Gist] = PersistenceManager.loadArray(path) {
gists = archived
} else {
gists = [] // don't have any saved gists
}
tableView.reloadData()
showNotConnectedBanner()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (!GitHubAPIManager.sharedInstance.isLoadingOAuthToken) {
loadInitialData()
}
}
func loadInitialData() {
isLoading = true
GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler = { error in
guard error == nil else {
print(error)
self.isLoading = false
if error?.domain == NSURLErrorDomain && error?.code == NSURLErrorNotConnectedToInternet {
self.showNotConnectedBanner()
} else {
// Something went wrong, try again
self.showOAuthLoginView()
}
return
}
if let _ = self.safariViewController {
self.dismissViewControllerAnimated(false) {}
}
self.loadGists(nil)
}
if (!GitHubAPIManager.sharedInstance.hasOAuthToken()) {
showOAuthLoginView()
return
}
loadGists(nil)
}
func showOAuthLoginView() {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
GitHubAPIManager.sharedInstance.isLoadingOAuthToken = true
guard let loginVC = storyboard.instantiateViewControllerWithIdentifier(
"LoginViewController") as? LoginViewController else {
assert(false, "Misnamed view controller")
return
}
loginVC.delegate = self
self.presentViewController(loginVC, animated: true, completion: nil)
}
func didTapLoginButton() {
self.dismissViewControllerAnimated(false) {
guard let authURL = GitHubAPIManager.sharedInstance.URLToStartOAuth2Login() else {
GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler?(NSError(domain: GitHubAPIManager.ErrorDomain, code: -1,
userInfo: [NSLocalizedDescriptionKey:
"Could not create an OAuth authorization URL",
NSLocalizedRecoverySuggestionErrorKey: "Please retry your request"]))
return
}
self.safariViewController = SFSafariViewController(URL: authURL)
self.safariViewController?.delegate = self
guard let webViewController = self.safariViewController else {
return
}
self.presentViewController(webViewController, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Creation
func insertNewObject(sender: AnyObject) {
let createVC = CreateGistViewController(nibName: nil, bundle: nil)
self.navigationController?.pushViewController(createVC, animated: true)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let gist = gists[indexPath.row] as Gist
if let detailViewController = (segue.destinationViewController as!
UINavigationController).topViewController as?
DetailViewController {
detailViewController.gist = gist
detailViewController.navigationItem.leftBarButtonItem =
self.splitViewController?.displayModeButtonItem()
detailViewController.navigationItem.leftItemsSupplementBackButton = true
}
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let gist = gists[indexPath.row]
cell.textLabel?.text = gist.gistDescription
cell.detailTextLabel?.text = gist.ownerLogin
// set cell.imageView to display image at gist.ownerAvatarURL
if let urlString = gist.ownerAvatarURL, url = NSURL(string: urlString) {
cell.imageView?.pin_setImageFromURL(url, placeholderImage:
UIImage(named: "placeholder.png"))
} else {
cell.imageView?.image = UIImage(named: "placeholder.png")
}
// See if we need to load more gists
if !isLoading {
let rowsLoaded = gists.count
let rowsRemaining = rowsLoaded - indexPath.row
let rowsToLoadFromBottom = 5
if rowsRemaining <= rowsToLoadFromBottom {
if let nextPage = nextPageURLString {
self.loadGists(nextPage)
}
}
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath:
NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return gistSegmentedControl.selectedSegmentIndex == 2
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle:
UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let gistToDelete = gists[indexPath.row]
guard let idToDelete = gistToDelete.id else {
return
}
// remove from array of gists
gists.removeAtIndex(indexPath.row)
// remove table view row
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// delete from API
GitHubAPIManager.sharedInstance.deleteGist(idToDelete) {
(error) in
if let _ = error {
print(error)
// Put it back
self.gists.insert(gistToDelete, atIndex: indexPath.row)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Right)
// tell them it didn't work
let alertController = UIAlertController(title: "Could not delete gist",
message: "Sorry, your gist couldn't be deleted. Maybe GitHub is "
+ "down or you don't have an internet connection.",
preferredStyle: .Alert)
// add ok button
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(okAction)
// show the alert
self.presentViewController(alertController, animated:true, completion: nil)
}
}
} 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.
}
}
// MARK: - Pull to Refresh
func refresh(sender:AnyObject) {
GitHubAPIManager.sharedInstance.isLoadingOAuthToken = false
nextPageURLString = nil // so it doesn't try to append the results
GitHubAPIManager.sharedInstance.clearCache()
loadInitialData()
}
// MARK: - Safari View Controller Delegate
func safariViewController(controller: SFSafariViewController, didCompleteInitialLoad
didLoadSuccessfully: Bool) {
// Detect not being able to load the OAuth URL
if (!didLoadSuccessfully) {
controller.dismissViewControllerAnimated(true, completion: nil)
GitHubAPIManager.sharedInstance.isAPIOnline { isOnline in
if !isOnline {
print("error: api offline")
GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler?(NSError(domain: NSURLErrorDomain, code:
NSURLErrorNotConnectedToInternet,
userInfo: [NSLocalizedDescriptionKey: "No Internet Connection or GitHub is Offline",
NSLocalizedRecoverySuggestionErrorKey: "Please retry your request"]))
}
}
}
}
@IBAction func segmentedControlValueChanged(sender: UISegmentedControl) {
// clear out the table view
gists = []
tableView.reloadData()
// only show add & edit buttons for my gists
if (gistSegmentedControl.selectedSegmentIndex == 2) {
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add,
target: self,
action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
} else {
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.rightBarButtonItem = nil
}
// then load the new list of gists
loadGists(nil)
}
func showNotConnectedBanner() {
// show not connected error & tell em to try again when they do have a connection
// check for existing banner
if let existingBanner = self.errorBanner {
existingBanner.dismiss()
}
self.errorBanner = Banner(title: "No Internet Connection",
subtitle: "Could not load gists." +
" Try again when you're connected to the internet",
image: nil,
backgroundColor: UIColor.redColor())
self.errorBanner?.dismissesOnSwipe = true
self.errorBanner?.show(duration: nil)
}
func showOfflineSaveFailedBanner() {
if let existingBanner = self.errorBanner {
existingBanner.dismiss()
}
self.errorBanner = Banner(title: "Could not save gists to view offline",
subtitle: "Your iOS device is almost out of free space.\n" +
"You will only be able to see your gists when you have an internet connection.",
image: nil,
backgroundColor: UIColor.orangeColor())
self.errorBanner?.dismissesOnSwipe = true
self.errorBanner?.show(duration: nil)
}
}
| mit | 5913f81184a636b28d5a4022d8781c89 | 34.660759 | 140 | 0.661437 | 5.394868 | false | false | false | false |
larrynatalicio/15DaysofAnimationsinSwift | Animation 03 - MapLocationAnimation/MapLocationAnimation/ViewController.swift | 1 | 2277 | //
// ViewController.swift
// MapLocationAnimation
//
// Created by Larry Natalicio on 4/17/16.
// Copyright © 2016 Larry Natalicio. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
// MARK: - Types
struct Constants {
struct MapViewIdentifiers {
static let sonarAnnotationView = "sonarAnnotationView"
}
}
// MARK: - Properties
@IBOutlet var mapView: MKMapView!
let regionRadius: CLLocationDistance = 3000
let latitude = 40.758873
let longitude = -73.985134
// MARK: - View Life Cycle
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Set initial location for map view.
let initialLocation = CLLocation(latitude: latitude, longitude: longitude)
centerMapOnLocation(initialLocation)
// Add annotation to map based on location.
let annotation = Annotation(coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), title: nil, subtitle: nil)
mapView.addAnnotation(annotation)
}
// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
// Reuse the annotation if possible.
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: Constants.MapViewIdentifiers.sonarAnnotationView)
if annotationView == nil {
annotationView = SonarAnnotationView(annotation: annotation, reuseIdentifier: Constants.MapViewIdentifiers.sonarAnnotationView)
} else {
annotationView!.annotation = annotation
}
return annotationView
}
// MARK: - Convenience
func centerMapOnLocation(_ location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: false)
}
// MARK: - Status Bar
override var prefersStatusBarHidden : Bool {
return true
}
}
| mit | e6f5f5c7f0367f5f92b5d9f34a813e33 | 27.810127 | 140 | 0.655975 | 5.762025 | false | false | false | false |
KrishMunot/swift | test/1_stdlib/Unmanaged.swift | 1 | 1557 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
// Check that the generic parameter is called 'Instance'.
protocol TestProtocol1 {}
extension Unmanaged where Instance : TestProtocol1 {
var _instanceIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var UnmanagedTests = TestSuite("Unmanaged")
UnmanagedTests.test("fromOpaque()/trap")
.skip(.custom(
{ !_isDebugAssertConfiguration() },
reason: "init(bitPattern:) does a _debugPrecondition() for null pointers"))
.code {
let null: OpaquePointer = getPointer(nil)
expectCrashLater()
let unmanaged = Unmanaged<AnyObject>.fromOpaque(null)
_blackHole(unmanaged)
}
class FooClass {}
UnmanagedTests.test("unsafeBitCast(Unmanaged, Int)") {
let ref = FooClass()
expectNotEqual(
0,
unsafeBitCast(
Unmanaged.passUnretained(ref) as Unmanaged<AnyObject>,
to: Int.self))
_fixLifetime(ref)
}
class Foobar {
func foo() -> Int { return 1 }
}
UnmanagedTests.test("_withUnsafeGuaranteedRef") {
var ref = Foobar()
var unmanaged = Unmanaged.passUnretained(ref)
withExtendedLifetime(ref) {
unmanaged._withUnsafeGuaranteedRef {
expectTrue(ref === $0)
}
unmanaged._withUnsafeGuaranteedRef {
expectEqual(1, $0.foo())
}
}
}
UnmanagedTests.test("_withUnsafeGuaranteedRef/return") {
var ref = Foobar()
var unmanaged = Unmanaged.passUnretained(ref)
withExtendedLifetime(ref) {
expectEqual(1, unmanaged._withUnsafeGuaranteedRef {
return $0.foo()
})
}
}
runAllTests()
| apache-2.0 | b16d35be683cd0142097b0dc0c0abc0e | 21.242857 | 79 | 0.700706 | 4.242507 | false | true | false | false |
cocoascientist/Passengr | Passengr/Reachable.swift | 1 | 1753 | //
// Reachable.swift
// Passengr
//
// Created by Andrew Shepard on 12/7/15.
// Copyright © 2015 Andrew Shepard. All rights reserved.
//
import Foundation
import SystemConfiguration
public enum ReachabilityType {
case online
case offline
}
protocol Reachable {
var reachable: ReachabilityType { get }
}
extension Reachable {
var reachable: ReachabilityType {
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
var reachability: ReachabilityType = ReachabilityType.offline
let _ = withUnsafePointer(to: &address, { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1, { (addr) -> Void in
guard let reachable = SCNetworkReachabilityCreateWithAddress(nil, addr) else { return }
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(reachable, &flags) { return }
reachability = ReachabilityType(reachabilityFlags: flags)
})
})
return reachability
}
}
extension ReachabilityType {
public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
self = (!connectionRequired && isReachable) ? .online : .offline
}
}
extension ReachabilityType: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .online:
return "online"
case .offline:
return "offline"
}
}
}
| mit | 92374d724c0a0d3d7bf40f3fde7f3f79 | 27.721311 | 103 | 0.624429 | 5.107872 | false | false | false | false |
ahoppen/swift | benchmark/single-source/ObjectiveCBridgingStubs.swift | 10 | 13637 | //===--- ObjectiveCBridgingStubs.swift ------------------------------------===//
//
// This source file is part of the Swift.org 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
#if _runtime(_ObjC)
import ObjectiveCTests
#endif
let t: [BenchmarkCategory] = [.validation, .bridging]
let ts: [BenchmarkCategory] = [.validation, .String, .bridging]
let bs: [BenchmarkCategory] = [.String, .bridging]
public let benchmarks = [
BenchmarkInfo(name: "ObjectiveCBridgeStubDataAppend",
runFunction: run_ObjectiveCBridgeStubDataAppend, tags: t,
legacyFactor: 20),
BenchmarkInfo(name: "ObjectiveCBridgeStubDateAccess",
runFunction: run_ObjectiveCBridgeStubDateAccess, tags: t),
BenchmarkInfo(name: "ObjectiveCBridgeStubDateMutation",
runFunction: run_ObjectiveCBridgeStubDateMutation, tags: t),
BenchmarkInfo(name: "ObjectiveCBridgeStubFromArrayOfNSString2",
runFunction: run_ObjectiveCBridgeStubFromArrayOfNSString, tags: t,
legacyFactor: 10),
BenchmarkInfo(name: "ObjectiveCBridgeStubFromNSDate",
runFunction: run_ObjectiveCBridgeStubFromNSDate, tags: t,
legacyFactor: 10),
BenchmarkInfo(name: "ObjectiveCBridgeStubFromNSString",
runFunction: run_ObjectiveCBridgeStubFromNSString, tags: t),
BenchmarkInfo(name: "ObjectiveCBridgeStubToArrayOfNSString2",
runFunction: run_ObjectiveCBridgeStubToArrayOfNSString, tags: t,
legacyFactor: 20),
BenchmarkInfo(name: "ObjectiveCBridgeStubToNSDate2",
runFunction: run_ObjectiveCBridgeStubToNSDate, tags: t,
legacyFactor: 10),
BenchmarkInfo(name: "ObjectiveCBridgeStubToNSString",
runFunction: run_ObjectiveCBridgeStubToNSString, tags: t,
legacyFactor: 10),
BenchmarkInfo(name: "ObjectiveCBridgeStubURLAppendPath2",
runFunction: run_ObjectiveCBridgeStubURLAppendPath, tags: t,
legacyFactor: 10),
BenchmarkInfo(name: "ObjectiveCBridgeStringIsEqual",
runFunction: run_ObjectiveCBridgeStringIsEqual, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringIsEqual2",
runFunction: run_ObjectiveCBridgeStringIsEqual2, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringIsEqualAllSwift",
runFunction: run_ObjectiveCBridgeStringIsEqualAllSwift, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringCompare",
runFunction: run_ObjectiveCBridgeStringCompare, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringCompare2",
runFunction: run_ObjectiveCBridgeStringCompare2, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringGetASCIIContents",
runFunction: run_ObjectiveCBridgeStringGetASCIIContents, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringGetUTF8Contents",
runFunction: run_ObjectiveCBridgeStringGetUTF8Contents, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringRangeOfString", //should be BridgeString.find.mixed
runFunction: run_ObjectiveCBridgeStringRangeOfString, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "BridgeString.find.native",
runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwift, tags: bs,
setUpFunction: setup_SpecificRangeOfStringBridging),
BenchmarkInfo(name: "BridgeString.find.native.nonASCII",
runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftNonASCII, tags: bs,
setUpFunction: setup_SpecificRangeOfStringBridging),
BenchmarkInfo(name: "BridgeString.find.native.long",
runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystack, tags: bs,
setUpFunction: setup_SpecificRangeOfStringBridging),
BenchmarkInfo(name: "BridgeString.find.native.longBoth",
runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackLongNeedle, tags: bs,
setUpFunction: setup_SpecificRangeOfStringBridging),
BenchmarkInfo(name: "BridgeString.find.native.longNonASCII",
runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackNonASCII, tags: bs,
setUpFunction: setup_SpecificRangeOfStringBridging),
BenchmarkInfo(name: "ObjectiveCBridgeStringHash",
runFunction: run_ObjectiveCBridgeStringHash, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringUTF8String",
runFunction: run_ObjectiveCBridgeStringUTF8String, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
BenchmarkInfo(name: "ObjectiveCBridgeStringCStringUsingEncoding",
runFunction: run_ObjectiveCBridgeStringCStringUsingEncoding, tags: ts,
setUpFunction: setup_StringBridgeBenchmark),
]
var b:BridgeTester! = nil
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubFromNSString() {
let b = BridgeTester()
var str = ""
for _ in 0 ..< 10_000 {
str = b.testToString()
}
check(str != "" && str == "Default string value no tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubFromNSString(_ n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubFromNSString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubToNSString() {
let b = BridgeTester()
let str = "hello world"
for _ in 0 ..< 1_000 {
b.test(from: str)
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubToNSString(_ n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubToNSString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubFromArrayOfNSString() {
let b = BridgeTester()
var arr : [String] = []
var str = ""
for _ in 0 ..< 100 {
arr = b.testToArrayOfStrings()
str = arr[0]
}
check(str != "" && str == "Default string value no tagged pointer")
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubFromArrayOfNSString(_ n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubFromArrayOfNSString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubToArrayOfNSString() {
let b = BridgeTester()
let str = "hello world"
let arr = [str, str, str, str, str, str, str, str, str, str]
for _ in 0 ..< 50 {
b.test(fromArrayOf: arr)
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubToArrayOfNSString(_ n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubToArrayOfNSString()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubFromNSDate() {
let b = BridgeTester()
for _ in 0 ..< 10_000 {
let bridgedBegin = b.beginDate()
let bridgedEnd = b.endDate()
let _ = bridgedEnd.timeIntervalSince(bridgedBegin)
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubFromNSDate(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubFromNSDate()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
public func testObjectiveCBridgeStubToNSDate() {
let b = BridgeTester()
let d = Date()
for _ in 0 ..< 1_000 {
b.use(d)
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubToNSDate(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubToNSDate()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubDateAccess() {
var remainders = 0.0
let d = Date()
for _ in 0 ..< 100_000 {
remainders += d.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 10)
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubDateAccess(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubDateAccess()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubDateMutation() {
var d = Date()
for _ in 0 ..< 100_000 {
d += 1
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubDateMutation(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubDateMutation()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubURLAppendPath() {
let startUrl = URL(string: "/")!
for _ in 0 ..< 10 {
var url = startUrl
for _ in 0 ..< 10 {
url.appendPathComponent("foo")
}
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubURLAppendPath(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubURLAppendPath()
}
}
#endif
}
#if _runtime(_ObjC)
@inline(never)
func testObjectiveCBridgeStubDataAppend() {
let proto = Data()
var value: UInt8 = 1
for _ in 0 ..< 50 {
var d = proto
for _ in 0 ..< 100 {
d.append(&value, count: 1)
}
}
}
#endif
@inline(never)
public func run_ObjectiveCBridgeStubDataAppend(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
testObjectiveCBridgeStubDataAppend()
}
}
#endif
}
@inline(never)
internal func getStringsToBridge() -> [String] {
let strings1 = ["hello", "the quick brown fox jumps over the lazy dog", "the quick brown fox jumps over the lazy dög"]
return strings1 + strings1.map { $0 + $0 } //mix of literals and non-literals
}
@inline(never)
public func run_ObjectiveCBridgeStringIsEqual(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testIsEqualToString()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringIsEqual2(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testIsEqualToString2()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringIsEqualAllSwift(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testIsEqualToStringAllSwift()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringCompare(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testCompare()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringCompare2(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testCompare2()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringGetASCIIContents(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testGetASCIIContents()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringGetUTF8Contents(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testGetUTF8Contents()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringRangeOfString(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testRangeOfString()
}
}
#endif
}
@inline(__always)
func run_rangeOfStringSpecific(needle: String, haystack: String, n: Int) {
#if _runtime(_ObjC)
b.testRangeOfStringSpecific(withNeedle: needle, haystack: haystack, n: n)
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringRangeOfStringAllSwift(n: Int) {
run_rangeOfStringSpecific(needle: "y", haystack: "The quick brown fox jumps over the lazy dog", n: 100 * n)
}
var longNativeASCII: String! = nil
var longNativeNonASCII: String! = nil
public func setup_SpecificRangeOfStringBridging() {
setup_StringBridgeBenchmark()
longNativeASCII = Array(repeating: "The quick brown fox jump over the lazy dog", count: 1000).joined() + "s"
longNativeNonASCII = "ü" + longNativeASCII + "ö"
}
@inline(never)
public func run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystack(n: Int) {
run_rangeOfStringSpecific(needle: "s", haystack: longNativeASCII, n: n)
}
@inline(never)
public func run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackNonASCII(n: Int) {
run_rangeOfStringSpecific(needle: "s", haystack: longNativeNonASCII, n: n)
}
@inline(never)
public func run_ObjectiveCBridgeStringRangeOfStringAllSwiftNonASCII(n: Int) {
run_rangeOfStringSpecific(needle: "ü", haystack: "The quick brown fox jump over the lazy dogü", n: 100 * n)
}
@inline(never)
public func run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackLongNeedle(n: Int) {
run_rangeOfStringSpecific(needle: "The quick brown fox jump over the lazy dogs", haystack: longNativeASCII, n: n)
}
@inline(never)
public func run_ObjectiveCBridgeStringHash(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testHash()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringUTF8String(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testUTF8String()
}
}
#endif
}
@inline(never)
public func run_ObjectiveCBridgeStringCStringUsingEncoding(n: Int) {
#if _runtime(_ObjC)
for _ in 0 ..< n {
autoreleasepool {
b.testCStringUsingEncoding()
}
}
#endif
}
@inline(never)
public func setup_StringBridgeBenchmark() {
#if _runtime(_ObjC)
b = BridgeTester()
b.setUpStringTests(getStringsToBridge())
#endif
}
| apache-2.0 | 166cd2e449228b98c6cf794f0afc602b | 25.887574 | 120 | 0.711048 | 3.908257 | false | true | false | false |
ahoppen/swift | test/SILOptimizer/definite_init_cross_module.swift | 16 | 9066 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/OtherModule.swiftmodule %S/Inputs/definite_init_cross_module/OtherModule.swift
// RUN: %target-swift-frontend -emit-sil -verify -I %t -swift-version 5 %s > /dev/null -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/definite_init_cross_module/BridgingHeader.h
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/OtherModule.swiftmodule %S/Inputs/definite_init_cross_module/OtherModule.swift
// RUN: %target-swift-frontend -emit-sil -verify -I %t -swift-version 5 %s > /dev/null -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/definite_init_cross_module/BridgingHeader.h
import OtherModule
extension Point {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: Point) {
// This is OK
self = other
}
init(other: Point, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: Point, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: Point, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: Point, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
// Test failable initializer.
init?(p: Point) {
if p.x > 0 {
self = p
}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericPoint {
init(xx: T, yy: T) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: T, yyy: T) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<T>) {
// This is OK
self = other
}
init(other: GenericPoint<T>, x: T) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<T>, xx: T) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: GenericPoint<T>, x: T, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<T>, xx: T, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericPoint where T == Double {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<Double>) {
// This is OK
self = other
}
init(other: GenericPoint<Double>, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<Double>, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: GenericPoint<Double>, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<Double>, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
typealias MyGenericPoint<Q> = GenericPoint<Q>
extension MyGenericPoint {
init(myX: T, myY: T) {
self.x = myX // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = myY // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension CPoint {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: CPoint) {
// This is OK
self = other
}
init(other: CPoint, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: CPoint, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self = other
}
init(other: CPoint, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: CPoint, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension NonnullWrapper {
init(p: UnsafeMutableRawPointer) {
self.ptr = p // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
// No suggestion for "self.init()" because this struct does not support a
// zeroing initializer.
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension PrivatePoint {
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: PrivatePoint) {
// This is OK
self = other
}
init(other: PrivatePoint, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init() {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension Empty {
init(x: Double) {
// This is OK
self.init()
}
init(other: Empty) {
// This is okay
self = other
}
init(other: Empty, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericEmpty {
init(x: Double) {
// This is OK
self.init()
}
init(other: GenericEmpty<T>) {
// This is okay
self = other
}
init(other: GenericEmpty<T>, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
class AcceptsVisibleNoArgsDesignatedInit: VisibleNoArgsDesignatedInit {
var y: Float
init(y: Float) {
self.y = y
// no error
}
}
open class InModuleVisibleNoArgsDesignatedInit {
var x: Float
public init() { x = 0.0 }
// Add a designated init the subclass cannot see.
private init(x: Float) { self.x = x }
}
class AcceptsInModuleVisibleNoArgsDesignatedInit: InModuleVisibleNoArgsDesignatedInit {
var y: Float
init(y: Float) {
self.y = y
// no error
}
}
| apache-2.0 | 69e42ccaf3a6000c5c4832cb0010b51e | 31.378571 | 227 | 0.645268 | 3.476227 | false | false | false | false |
ceecer1/open-muvr | ios/Predef/Result.swift | 7 | 4024 | //
// Result.swift
// swiftz
//
// Created by Maxwell Swadling on 9/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
import class Foundation.NSError
/// Result is similar to an Either, except specialized to have an Error case that can
/// only contain an NSError.
public enum Result<V> {
case Error(NSError)
case Value(Box<V>)
public init(_ e: NSError?, _ v: V) {
if let ex = e {
self = Result.Error(ex)
} else {
self = Result.Value(Box(v))
}
}
/// Converts a Result to a more general Either type.
public func toEither() -> Either<NSError, V> {
switch self {
case let Error(e):
return .Left(Box(e))
case let Value(v):
return Either.Right(Box(v.value))
}
}
/// Much like the ?? operator for Optional types, takes a value and a function,
/// and if the Result is Error, returns the error, otherwise maps the function over
/// the value in Value and returns that value.
public func fold<B>(value: B, f: V -> B) -> B {
switch self {
case Error(_):
return value
case let Value(v):
return f(v.value)
}
}
/// Catamorphism
public func cata<B>(l: NSError -> B, r: V -> B) -> B {
switch self {
case let Error(e):
return l(e)
case let Value(v):
return r(v.value)
}
}
/// Named function for `>>-`. If the Result is Error, simply returns
/// a New Error with the value of the receiver. If Value, applies the function `f`
/// and returns the result.
public func flatMap<S>(f: V -> Result<S>) -> Result<S> {
return self >>- f
}
/// Creates an Error with the given value.
public static func error(e: NSError) -> Result<V> {
return .Error(e)
}
/// Creates a Value with the given value.
public static func value(v: V) -> Result<V> {
return .Value(Box(v))
}
}
// Equatable
public func ==<V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
switch (lhs, rhs) {
case let (.Error(l), .Error(r)) where l == r:
return true
case let (.Value(l), .Value(r)) where l.value == r.value:
return true
default:
return false
}
}
public func !=<V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
return !(lhs == rhs)
}
/// Applicative `pure` function, lifts a value into a Value.
public func pure<V>(a: V) -> Result<V> {
return .Value(Box(a))
}
/// Functor `fmap`. If the Result is Error, ignores the function and returns the Error.
/// If the Result is Value, applies the function to the Right value and returns the result
/// in a new Value.
public func <^><VA, VB>(f: VA -> VB, a: Result<VA>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return Result.Value(Box(f(r.value)))
}
}
/// Applicative Functor `apply`. Given an Result<VA -> VB> and an Result<VA>,
/// returns a Result<VB>. If the `f` or `a' param is an Error, simply returns an Error with the
/// same value. Otherwise the function taken from Value(f) is applied to the value from Value(a)
/// And a Value is returned.
public func <*><VA, VB>(f: Result<VA -> VB>, a: Result<VA>) -> Result<VB> {
switch (a, f) {
case let (.Error(l), _):
return .Error(l)
case let (.Value(r), .Error(m)):
return .Error(m)
case let (.Value(r), .Value(g)):
return Result<VB>.Value(Box(g.value(r.value)))
}
}
/// Monadic `bind`. Given an Result<VA>, and a function from VA -> Result<VB>,
/// applies the function `f` if `a` is Value, otherwise the function is ignored and an Error
/// with the Error value from `a` is returned.
public func >>-<VA, VB>(a: Result<VA>, f: VA -> Result<VB>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return f(r.value)
}
} | apache-2.0 | 63617602588d0906a0a98dd8f53db78d | 29.263158 | 96 | 0.574056 | 3.551633 | false | false | false | false |
karstengresch/layout_studies | countidon/countidon/IndividualCounterSettingsViewController.swift | 1 | 2897 | //
// IndividualCounterSettingsViewController.swift
// countidon
//
// Created by Karsten Gresch on 21.01.16.
// Copyright © 2016 Closure One. All rights reserved.
//
import UIKit
import Foundation
protocol IndividualCounterSettingsViewControllerDelegate: class {
}
class IndividualCounterSettingsViewController: UITableViewController {
var coutidonItem = CountidonItem()
weak var delegate: IndividualCounterSettingsViewControllerDelegate?
// MARK: IB related
@IBAction func cancel() {
print("cancel")
dismiss(animated: true, completion: nil)
}
@IBAction func navigationBarButtonLeftClicked(sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
// MARK: UITextField related.
@IBOutlet weak var timeToCountdownTextField: NumericTextField!
@IBOutlet weak var beepEveryTextField: NumericTextField!
@IBOutlet weak var counterNameTextField: UITextField!
@IBAction func timeToCountdownTextFieldEditingEnded(_ sender: NumericTextField) {
print("Text of timeToCountdownTextField: \(timeToCountdownTextField.text ?? "EMPTY!")")
}
@IBAction func beepEveryTextFieldEditingEnded(_ sender: NumericTextField) {
print("Text of beepEveryTextField: \(beepEveryTextField.text ?? "EMPTY!")")
}
@IBAction func counterNameEditingEnded(_ sender: UITextField) {
print("Text of counterNameTextField: \(counterNameTextField.text ?? "EMPTY!")")
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
// MARK: Table View related.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == .none {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("indexPath.row: \((indexPath as NSIndexPath).row)" )
// TODO
var cell: UITableViewCell
let row = (indexPath as NSIndexPath).row
switch row {
case 0 :
cell = tableView.dequeueReusableCell(withIdentifier: "TimeToCountdownCell", for: indexPath)
default:
cell = tableView.dequeueReusableCell(withIdentifier: "TimeToCountdownCell", for: indexPath)
}
return cell
}
*/
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
}
| unlicense | aa27a9a38828bf0a7dd501c9d0f75c1b | 26.065421 | 107 | 0.703384 | 4.85906 | false | false | false | false |
torinmb/Routinely | Routinely/DragDropBehavior.swift | 1 | 4922 | //
// DragDropBehavior.swift
// DesignerNewsApp
//
// Created by James Tang on 22/1/15.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
import Spring
@objc public protocol DragDropBehaviorDelegate : class {
func dragDropBehavior(behavior: DragDropBehavior, viewDidDrop view:UIView)
}
public class DragDropBehavior : NSObject {
@IBOutlet public var referenceView : UIView! {
didSet {
if let referenceView = referenceView {
animator = UIDynamicAnimator(referenceView: referenceView)
}
}
}
@IBOutlet public var targetView : UIView! {
didSet {
if let targetView = targetView {
self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handleGesture:")
targetView.addGestureRecognizer(self.panGestureRecognizer)
}
}
}
@IBOutlet public weak var delegate : NSObject? // Should really be DragDropBehaviorDelegate but to workaround forming connection issue with protocols
// MARK: UIDynamicAnimator
private var dynamic : UIDynamicItemBehavior!
private var animator : UIDynamicAnimator!
private var attachmentBehavior : UIAttachmentBehavior!
private var gravityBehaviour : UIGravityBehavior!
private var snapBehavior : UISnapBehavior!
public private(set) var panGestureRecognizer : UIPanGestureRecognizer!
// UIDynamicItemBehavior *dynamic = [[UIDynamicItemBehavior alloc] initWithItems:@[gesture.view]];
// [dynamic addLinearVelocity:velocity forItem:gesture.view];
// [dynamic addAngularVelocity:angularVelocity forItem:gesture.view];
// [dynamic setAngularResistance:2];
//
// // when the view no longer intersects with its superview, go ahead and remove it
//
// dynamic.action = ^{
// if (!CGRectIntersectsRect(gesture.view.superview.bounds, gesture.view.frame)) {
// [self.animator removeAllBehaviors];
// [gesture.view removeFromSuperview];
//
// [self.animator addBehavior:dynamic];
func handleGesture(sender: AnyObject) {
let location = sender.locationInView(referenceView)
let boxLocation = sender.locationInView(targetView)
if sender.state == UIGestureRecognizerState.Began {
animator.removeBehavior(snapBehavior)
let centerOffset = UIOffsetMake(boxLocation.x - CGRectGetMidX(targetView.bounds), boxLocation.y - CGRectGetMidY(targetView.bounds));
attachmentBehavior = UIAttachmentBehavior(item: targetView, offsetFromCenter: centerOffset, attachedToAnchor: location)
attachmentBehavior.frequency = 0
animator.addBehavior(attachmentBehavior)
}
else if sender.state == UIGestureRecognizerState.Changed {
attachmentBehavior.anchorPoint = location
}
else if sender.state == UIGestureRecognizerState.Ended {
animator.removeBehavior(attachmentBehavior)
snapBehavior = UISnapBehavior(item: targetView, snapToPoint: referenceView.center)
animator.addBehavior(snapBehavior)
let translation = sender.translationInView(referenceView)
if translation.y > 100 {
animator.removeAllBehaviors()
var gravity = UIGravityBehavior(items: [targetView])
gravity.gravityDirection = CGVectorMake(0, 10)
animator.addBehavior(gravity)
dynamic = UIDynamicItemBehavior(items: [targetView])
dynamic.action = {
let frame = self.targetView.frame
let dismissFrame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: frame.height + 500)
// let dismissFrame = CGRect(origin: CGPoint(x: self.targetView.center.x, y:self.targetView.frame.maxY), size: CGSize(width: 2, height: 10))
if (!CGRectIntersectsRect(self.referenceView.frame, dismissFrame)) {
self.animator.removeAllBehaviors()
delay(0.3) { [weak self] in
if let strongSelf = self {
(strongSelf.delegate as? DragDropBehaviorDelegate)?.dragDropBehavior(strongSelf, viewDidDrop: strongSelf.targetView)
}
}
delay(0.3){
// self.targetView.hidden = true
self.snapBehavior = UISnapBehavior(item: self.targetView, snapToPoint: self.referenceView.center)
self.animator.addBehavior(self.snapBehavior)
}
}
}
animator.addBehavior(dynamic)
}
}
}
}
| mit | 53a24710391209233af35497cde3ebdf | 41.068376 | 159 | 0.61987 | 5.517937 | false | false | false | false |
davidprochazka/HappyDay | HappyDaysCollectionVersion/HappyDaysCollectionVersion/PersonDetailViewController.swift | 1 | 3311 | //
// NewPersonViewController.swift
// HappyDaysCollectionVersion
//
// Created by David Prochazka on 19/05/16.
// Copyright © 2016 David Prochazka. All rights reserved.
//
import UIKit
import MobileCoreServices
import UIImage_Resize
class PersonDetailViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var imageView: UIImageView!
var selectedTeam : Team? = nil
var editedPerson : Person? = nil
override func viewDidLoad() {
super.viewDidLoad()
if (editedPerson != nil){
navigationController?.navigationBar.topItem?.title = "Edit your person"
fillForm()
}
// Do any additional setup after loading the view.
}
func fillForm(){
nameTextField.text = editedPerson?.name
if editedPerson!.image != nil {
imageView.image = UIImage(data: editedPerson!.image!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save(sender: AnyObject) {
if let personName = nameTextField.text {
if personName != "" {
if (editedPerson == nil){
Person.createPersonWithName(personName, andImage: imageView.image, andTeam: selectedTeam!)
} else {
editedPerson?.updatePersonWithName(personName, andImage: imageView.image, andTeam: selectedTeam!)
}
dismissViewControllerAnimated(true, completion: nil)
} else {
nameTextField.becomeFirstResponder()
}
} else {
nameTextField.becomeFirstResponder()
}
}
@IBAction func cancel(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - ImagePicker
@IBAction func loadPhoto(sender : AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
picker.mediaTypes = [kUTTypeImage as String]
self.presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
var image: UIImage? = nil
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
image = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
image = possibleImage
}
if image != nil {
// resize image
let size = CGSize(width: config.imageSize.width, height: config.imageSize.height)
imageView.image = image!.resizedImageToFitInSize(size, scaleIfSmaller: false)
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
dismissViewControllerAnimated(true, completion: nil)
}
}
| gpl-3.0 | be5e4275f135f621a1428eb2626627e3 | 32.1 | 123 | 0.633233 | 5.697074 | false | false | false | false |
mightydeveloper/swift | test/SILGen/enum_resilience.swift | 9 | 2131 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s
import resilient_enum
// Resilient enums are always address-only, and switches must include
// a default case
// CHECK-LABEL: sil hidden @_TF15enum_resilience15resilientSwitchFO14resilient_enum6MediumT_ : $@convention(thin) (@in Medium) -> ()
// CHECK: [[BOX:%.*]] = alloc_stack $Medium
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]#1
// CHECK-NEXT: switch_enum_addr [[BOX]]#1 : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[BOX]]#0
// CHECK-NEXT: br bb6
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[BOX]]#0
// CHECK-NEXT: br bb6
// CHECK: bb3:
// CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]#1
// CHECK-NEXT: [[INDIRECT:%.*]] = load [[INDIRECT_ADDR]]
// CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]]
// CHECK-NEXT: strong_release [[INDIRECT]]
// CHECK-NEXT: dealloc_stack [[BOX]]#0
// CHECK-NEXT: br bb6
// CHECK: bb4:
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]#1
// CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]]
// CHECK-NEXT: dealloc_stack [[BOX]]#0
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: unreachable
// CHECK: bb6:
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
func resilientSwitch(m: Medium) {
switch m {
case .Paper: ()
case .Canvas: ()
case .Pamphlet: ()
case .Postcard: ()
}
}
// Indirect enums are still address-only, because the discriminator is stored
// as part of the value, so we cannot resiliently make assumptions about the
// enum's size
// CHECK-LABEL: sil hidden @_TF15enum_resilience21indirectResilientEnumFO14resilient_enum16IndirectApproachT_ : $@convention(thin) (@in IndirectApproach) -> ()
func indirectResilientEnum(ia: IndirectApproach) {}
| apache-2.0 | cdfb7675152604610a7e9d22108232e9 | 40.784314 | 211 | 0.647114 | 3.345369 | false | false | false | false |
jphacks/TK_08 | iOS/AirMeet/AirMeet/MyNavigationController.swift | 1 | 1635 | //
// MyNavigationController.swift
// AirMeet
//
// Created by koooootake on 2015/12/01.
// Copyright © 2015年 koooootake. All rights reserved.
//
import UIKit
class MyNavigationController: ENSideMenuNavigationController, ENSideMenuDelegate {
override func viewDidLoad() {
super.viewDidLoad()
sideMenu = ENSideMenu(sourceView: self.view, menuViewController: MyMenuTableViewController(), menuPosition:.Left)
//sideMenu?.delegate = self //optional
sideMenu?.menuWidth = 180.0 // optional, default is 160
//sideMenu?.bouncingEnabled = false
//sideMenu?.allowPanGesture = false
// make navigation bar showing over side menu
view.bringSubviewToFront(navigationBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - ENSideMenu Delegate
func sideMenuWillOpen() {
print("sideMenuWillOpen")
}
func sideMenuWillClose() {
print("sideMenuWillClose")
}
func sideMenuDidClose() {
print("sideMenuDidClose")
}
func sideMenuDidOpen() {
print("sideMenuDidOpen")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 4fc0ebda8218af5268eec6205089e931 | 27.137931 | 121 | 0.65625 | 5.230769 | false | false | false | false |
huonw/swift | test/Driver/Dependencies/private.swift | 36 | 4169 | // a ==> b --> c ==> d | e ==> c
// RUN: rm -rf %t && cp -r %S/Inputs/private/ %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// CHECK-INITIAL-NOT: warning
// CHECK-INITIAL: Handled a.swift
// CHECK-INITIAL: Handled b.swift
// CHECK-INITIAL: Handled c.swift
// CHECK-INITIAL: Handled d.swift
// CHECK-INITIAL: Handled e.swift
// RUN: touch -t 201401240006 %t/a.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/a.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt
// RUN: %FileCheck -check-prefix=CHECK-A-NEG %s < %t/a.txt
// CHECK-A: Handled a.swift
// CHECK-A-DAG: Handled b.swift
// CHECK-A-DAG: Handled c.swift
// CHECK-A-NEG-NOT: Handled d.swift
// CHECK-A-NEG-NOT: Handled e.swift
// RUN: touch -t 201401240006 %t/b.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/b.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-B %s < %t/b.txt
// RUN: %FileCheck -check-prefix=CHECK-B-NEG %s < %t/b.txt
// CHECK-B-NEG-NOT: Handled a.swift
// CHECK-B: Handled b.swift
// CHECK-B: Handled c.swift
// CHECK-B-NEG-NOT: Handled d.swift
// CHECK-B-NEG-NOT: Handled e.swift
// RUN: touch -t 201401240006 %t/c.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/c.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-C %s < %t/c.txt
// RUN: %FileCheck -check-prefix=CHECK-C-NEG %s < %t/c.txt
// CHECK-C-NEG-NOT: Handled a.swift
// CHECK-C-NEG-NOT: Handled b.swift
// CHECK-C: Handled c.swift
// CHECK-C: Handled d.swift
// CHECK-C-NEG-NOT: Handled e.swift
// RUN: touch -t 201401240006 %t/d.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/d.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-D %s < %t/d.txt
// RUN: %FileCheck -check-prefix=CHECK-D-NEG %s < %t/d.txt
// CHECK-D-NEG-NOT: Handled a.swift
// CHECK-D-NEG-NOT: Handled b.swift
// CHECK-D-NEG-NOT: Handled c.swift
// CHECK-D: Handled d.swift
// CHECK-D-NEG-NOT: Handled e.swift
// RUN: touch -t 201401240006 %t/e.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/e.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-E %s < %t/e.txt
// RUN: %FileCheck -check-prefix=CHECK-E-NEG %s < %t/e.txt
// CHECK-E-NEG-NOT: Handled a.swift
// CHECK-E-NEG-NOT: Handled b.swift
// CHECK-E: Handled e.swift
// CHECK-E-DAG: Handled c.swift
// CHECK-E-DAG: Handled d.swift
// RUN: touch -t 201401240007 %t/a.swift %t/e.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift -module-name main -j1 -v > %t/ae.txt 2>&1
// RUN: %FileCheck -check-prefix=CHECK-AE %s < %t/ae.txt
// RUN: %FileCheck -check-prefix=CHECK-AE-NEG %s < %t/ae.txt
// CHECK-AE: Handled a.swift
// CHECK-AE: Handled e.swift
// CHECK-AE-DAG: Handled b.swift
// CHECK-AE-DAG: Handled c.swift
// CHECK-AE-DAG: Handled d.swift
// CHECK-AE-NEG: Handled
| apache-2.0 | 77dd3e658bba99bee330e935a50ef392 | 51.1125 | 296 | 0.680979 | 2.705386 | false | false | true | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Model/HotRecommendsSubItem.swift | 1 | 409 | //
// HotRecommendsSubItem.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/22.
// Copyright © 2016年 CoderST. All rights reserved.
//
import UIKit
class HotRecommendsSubItem: BaseModel {
var id : Int64 = 0
var albumId : Int64 = 0
var uid : Int64 = 0
var nickname : String = ""
var title : String = ""
var albumCoverUrl290 : String = ""
var trackTitle : String = ""
}
| mit | 8c41a04031bc70c5f4923673fb58f6b4 | 19.3 | 51 | 0.628079 | 3.625 | false | false | false | false |
barteljan/VISPER | VISPER-Swift/Classes/AnyVISPERApp.swift | 1 | 4384 | //
// AnyApplication.swift
// SwiftyVISPER
//
// Created by bartel on 18.11.17.
//
import Foundation
import VISPER_Redux
import VISPER_Core
import VISPER_Reactive
import VISPER_Wireframe
// some base class needed for type erasure, ignore it if possible
class _AnyApplication<AppState> : VISPERAppType{
typealias ApplicationState = AppState
var state: ObservableProperty<AppState> {
fatalError("override me")
}
var wireframe : Wireframe {
fatalError("override me")
}
var redux : Redux<AppState> {
fatalError("override me")
}
func add(feature: Feature) throws {
fatalError("override me")
}
func add(featureObserver: FeatureObserver) {
fatalError("override me")
}
func add<T: StatefulFeatureObserver>(featureObserver: T) where T.AppState == AppState {
fatalError("override me")
}
func add(featureObserver: WireframeFeatureObserver) {
fatalError("override me")
}
func navigateOn(_ controller: UIViewController) {
fatalError("override me")
}
func controllerToNavigate(matches: (UIViewController?) -> Bool) -> UIViewController? {
fatalError("override me")
}
}
// some box class needed for type erasure, ignore it if possible
final class _AnyApplicationBox<Base: VISPERAppType>: _AnyApplication<Base.ApplicationState> {
var base: Base
init(_ base: Base) { self.base = base }
override var state: ObservableProperty<Base.ApplicationState> {
return self.base.state
}
override var wireframe: Wireframe {
return self.base.wireframe
}
override var redux: Redux<Base.ApplicationState> {
return self.base.redux
}
override func add(feature: Feature) throws {
try self.base.add(feature: feature)
}
override func add<T: StatefulFeatureObserver>(featureObserver: T) where Base.ApplicationState == T.AppState {
self.base.add(featureObserver: featureObserver)
}
override func add(featureObserver: FeatureObserver) {
self.base.add(featureObserver: featureObserver)
}
override func add(featureObserver: WireframeFeatureObserver) {
self.base.add(featureObserver: featureObserver)
}
override func navigateOn(_ controller: UIViewController) {
self.base.navigateOn(controller)
}
override func controllerToNavigate(matches: (UIViewController?) -> Bool) -> UIViewController? {
return self.base.controllerToNavigate(matches: matches)
}
}
@available(*, unavailable, message: "replace this class with AnyVISPERApp",renamed: "AnyVISPERApp")
public typealias AnyApplication<AppState> = AnyVISPERApp<AppState>
/// Type erasure for the generic ApplicationType protocol
/// (you need this to reference it as a full type, to use it in arrays or variable definitions,
/// since generic protocols can only be used in generic definitions)
open class AnyVISPERApp<AppState> : VISPERAppType {
public typealias ApplicationState = AppState
private let box: _AnyApplication<AppState>
public init<Base: VISPERAppType>(_ base: Base) where Base.ApplicationState == AppState {
box = _AnyApplicationBox(base)
}
open var state: ObservableProperty<AppState> {
return self.box.state
}
open var wireframe: Wireframe {
return self.box.wireframe
}
open var redux: Redux<AppState> {
return self.box.redux
}
open func add(feature: Feature) throws {
try self.box.add(feature: feature)
}
public func add(featureObserver: FeatureObserver) {
self.box.add(featureObserver: featureObserver)
}
open func add<T: StatefulFeatureObserver>(featureObserver: T) where T.AppState == AppState {
self.box.add(featureObserver: featureObserver)
}
open func add(featureObserver: WireframeFeatureObserver) {
self.box.add(featureObserver: featureObserver)
}
open func navigateOn(_ controller: UIViewController) {
self.box.navigateOn(controller)
}
public func controllerToNavigate(matches: (UIViewController?) -> Bool) -> UIViewController? {
return self.box.controllerToNavigate(matches: matches)
}
}
| mit | 7bcd05ef829c941cebb8ffb1829febca | 26.923567 | 113 | 0.667655 | 4.678762 | false | false | false | false |
PJayRushton/StarvingStudentGuide | StarvingStudentGuide/SettingsViewController.swift | 1 | 4307 | //
// SettingsViewController.swift
// StarvingStudentGuide
//
// Created by Parker Rushton on 4/2/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
enum SettingsRow: Int {
case reset
case website
var titleString: String {
switch self {
case .reset:
return "reset all deals (testing)"
case .website:
return "www.starvingstudentcard.com"
}
}
var titleTextColor: UIColor {
switch self {
case .reset: return .redColor()
case .website: return .linkBlue()
}
}
var accessoryType: UITableViewCellAccessoryType {
switch self {
case .reset, .website: return .DisclosureIndicator
}
}
}
enum SettingsSection: Int {
case reset
case website
var rows: [SettingsRow] {
switch self {
case .reset:
return [.reset]
case .website:
return [.website]
}
}
static let count: Int = {
var count: Int = 0
while let _ = SettingsSection(rawValue: count) { count += 1 }
return count
}()
}
@IBOutlet weak var versionLabel: UILabel!
private let coreDataHelper = CoreDataHelper()
override func viewDidLoad() {
super.viewDidLoad()
versionLabel.text = "v\(VersionHelper.currentVersionNumber)"
}
@IBAction func xButtonPressed(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
}
extension SettingsViewController {
private func launchCompletionAlert() {
let alertController = UIAlertController(title: "All deals reset", message: "(This is for testing only. Don't get any bright ideas)", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
private func handleWebsiteCellTapped() {
let urlString = "http://www.starvingstudentcard.com"
guard let url = NSURL(string: urlString) where UIApplication.sharedApplication().canOpenURL(url) else { fatalError("Unable to launch url: \(urlString)") }
UIApplication.sharedApplication().openURL(url)
}
}
extension SettingsViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return SettingsSection.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let theSection = SettingsSection(rawValue: section) else { fatalError("Settings enum is messed up") }
return theSection.rows.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let theSection = SettingsSection(rawValue: indexPath.section) else { fatalError() }
let theRow = theSection.rows[indexPath.row]
guard let cell = tableView.dequeueReusableCellWithIdentifier(CenteredTextCell.reuseIdentifier) as? CenteredTextCell else { fatalError() }
cell.titleLabel.text = theRow.titleString
cell.titleLabel.textColor = theRow.titleTextColor
cell.accessoryType = theRow.accessoryType
return cell
}
}
extension SettingsViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
guard let theSection = SettingsSection(rawValue: indexPath.section) else { fatalError() }
let theRow = theSection.rows[indexPath.row]
switch theRow {
case .reset:
coreDataHelper.deleteAllCoreDataEntities()
coreDataHelper.loadInitialDataWithResource(JSONLoader.JSONResource.BYUCard)
launchCompletionAlert()
case .website:
handleWebsiteCellTapped()
}
}
}
| mit | 892301d2c8ceb57b4ba0cf9d29d7ed39 | 30.430657 | 164 | 0.625871 | 5.362391 | false | false | false | false |
zisko/swift | test/SILGen/partial_apply_super.swift | 1 | 24069 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
import resilient_class
func doFoo(_ f: () -> ()) {
f()
}
public class Parent {
public init() {}
public func method() {}
public final func finalMethod() {}
public class func classMethod() {}
public final class func finalClassMethod() {}
}
public class GenericParent<A> {
let a: A
public init(a: A) {
self.a = a
}
public func method() {}
public final func finalMethod() {}
public class func classMethod() {}
public final class func finalClassMethod() {}
}
class Child : Parent {
// CHECK-LABEL: sil hidden @$S19partial_apply_super5ChildC6methodyyF : $@convention(method) (@guaranteed Child) -> ()
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S19partial_apply_super6ParentC6methodyyFTcTd : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super5ChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super5ChildC11classMethodyyFZ : $@convention(method) (@thick Child.Type) -> () {
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S19partial_apply_super6ParentC11classMethodyyFZTcTd : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super5ChildC20callFinalSuperMethodyyF : $@convention(method) (@guaranteed Child) -> ()
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S19partial_apply_super6ParentC11finalMethodyyFTc : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
// CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[APPLIED_SELF]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super5ChildC20callFinalSuperMethodyyF'
func callFinalSuperMethod() {
doFoo(super.finalMethod)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super5ChildC25callFinalSuperClassMethodyyFZ : $@convention(method) (@thick Child.Type) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S19partial_apply_super6ParentC16finalClassMethodyyFZTc : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
// CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[APPLIED_SELF]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
class func callFinalSuperClassMethod() {
doFoo(super.finalClassMethod)
}
}
class GenericChild<A> : GenericParent<A> {
override init(a: A) {
super.init(a: a)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super12GenericChildC6methodyyF : $@convention(method) <A> (@guaranteed GenericChild<A>) -> ()
// CHECK: bb0([[SELF:%.*]] : $GenericChild<A>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChild<A> to $GenericParent<A>
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S19partial_apply_super13GenericParentC6methodyyFTcTd : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_guaranteed () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_guaranteed () -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super12GenericChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super12GenericChildC11classMethodyyFZ : $@convention(method) <A> (@thick GenericChild<A>.Type) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChild<A>.Type to $@thick GenericParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S19partial_apply_super13GenericParentC11classMethodyyFZTcTd : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_guaranteed () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_guaranteed () -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class ChildToFixedOutsideParent : OutsideParent {
// CHECK-LABEL: sil hidden @$S19partial_apply_super25ChildToFixedOutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $ChildToFixedOutsideParent):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $ChildToFixedOutsideParent to $OutsideParent
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $ChildToFixedOutsideParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super25ChildToFixedOutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super25ChildToFixedOutsideParentC11classMethodyyFZ
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToFixedOutsideParent.Type to $@thick OutsideParent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToFixedOutsideParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> (){{.*}}
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideParent.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class ChildToResilientOutsideParent : ResilientOutsideParent {
// CHECK-LABEL: sil hidden @$S19partial_apply_super29ChildToResilientOutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $ChildToResilientOutsideParent):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $ChildToResilientOutsideParent to $ResilientOutsideParent
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $ChildToResilientOutsideParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super29ChildToResilientOutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super29ChildToResilientOutsideParentC11classMethodyyFZ
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToResilientOutsideParent.Type to $@thick ResilientOutsideParent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToResilientOutsideParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GrandchildToFixedOutsideChild : OutsideChild {
// CHECK-LABEL: sil hidden @$S19partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GrandchildToFixedOutsideChild):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GrandchildToFixedOutsideChild to $OutsideChild
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GrandchildToFixedOutsideChild, #OutsideChild.method!1 : (OutsideChild) -> () -> (), $@convention(method) (@guaranteed OutsideChild) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideChild) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super29GrandchildToFixedOutsideChildC11classMethodyyFZ
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToFixedOutsideChild.Type to $@thick OutsideChild.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToFixedOutsideChild.Type, #OutsideChild.classMethod!1 : (OutsideChild.Type) -> () -> (), $@convention(method) (@thick OutsideChild.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideChild.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GrandchildToResilientOutsideChild : ResilientOutsideChild {
// CHECK-LABEL: sil hidden @$S19partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GrandchildToResilientOutsideChild):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GrandchildToResilientOutsideChild to $ResilientOutsideChild
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GrandchildToResilientOutsideChild, #ResilientOutsideChild.method!1 : (ResilientOutsideChild) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
// CHEC: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super33GrandchildToResilientOutsideChildC11classMethodyyFZ
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToResilientOutsideChild.Type to $@thick ResilientOutsideChild.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToResilientOutsideChild.Type, #ResilientOutsideChild.classMethod!1 : (ResilientOutsideChild.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GenericChildToFixedGenericOutsideParent<A> : GenericOutsideParent<A> {
// CHECK-LABEL: sil hidden @$S19partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GenericChildToFixedGenericOutsideParent<A>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChildToFixedGenericOutsideParent<A> to $GenericOutsideParent<A>
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GenericChildToFixedGenericOutsideParent<A>, #GenericOutsideParent.method!1 : <A> (GenericOutsideParent<A>) -> () -> (), $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super019GenericChildToFixedD13OutsideParentC11classMethodyyFZ
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type to $@thick GenericOutsideParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type, #GenericOutsideParent.classMethod!1 : <A> (GenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GenericChildToResilientGenericOutsideParent<A> : ResilientGenericOutsideParent<A> {
// CHECK-LABEL: sil hidden @$S19partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GenericChildToResilientGenericOutsideParent<A>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChildToResilientGenericOutsideParent<A> to $ResilientGenericOutsideParent<A>
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GenericChildToResilientGenericOutsideParent<A>, #ResilientGenericOutsideParent.method!1 : <A> (ResilientGenericOutsideParent<A>) -> () -> (), $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: } // end sil function '$S19partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @$S19partial_apply_super023GenericChildToResilientD13OutsideParentC11classMethodyyFZ
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type to $@thick ResilientGenericOutsideParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type, #ResilientGenericOutsideParent.classMethod!1 : <A> (ResilientGenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [[PARTIAL_APPLY]]
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @$S19partial_apply_super5doFooyyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
| apache-2.0 | 719c6f1f47e92a87aac0d35c39bcfae1 | 81.628866 | 325 | 0.660012 | 3.64705 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/TableView/TableItem.swift | 1 | 749 | class TableItem: NSObject {
var first: Bool = false
var last: Bool = false
var selectionBlock: (() -> Void)?
func shouldHighlight() -> Bool {
return true
}
var estimatedCellHeight: CGFloat {
return 40
}
func cellHeight(tableWidth: CGFloat) -> CGFloat {
return 40.0
}
func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
assertionFailure("TableItem subclass has to override cell creation")
return UITableViewCell()
}
static func setFirstAndLast(items: [TableItem]) {
for i in 0..<items.count {
let item = items[i]
item.first = (i == 0)
item.last = (i == items.count - 1)
}
}
}
| mit | 3a31240ad593715744e290a295579f52 | 23.966667 | 80 | 0.578104 | 4.512048 | false | false | false | false |
domenicosolazzo/practice-swift | Views/Pickers/CountdownTimer/CountdownTimer/ViewController.swift | 1 | 625 | //
// ViewController.swift
// CountdownTimer
//
// Created by Domenico Solazzo on 04/05/15.
// License MIT
//
import UIKit
class ViewController: UIViewController {
// DatePicker
var datePicker: UIDatePicker?
override func viewDidLoad() {
super.viewDidLoad()
datePicker = UIDatePicker()
datePicker?.center = self.view.center
datePicker?.datePickerMode = UIDatePickerMode.countDownTimer
let interval = (2 * 60) as TimeInterval
datePicker?.countDownDuration = interval
self.view.addSubview(datePicker!)
}
}
| mit | cc14bb002de5770edef545b56ffecd76 | 19.833333 | 68 | 0.6272 | 5.165289 | false | false | false | false |
gbuela/github-users-coord | github-users/DetailViewModel.swift | 1 | 1867 | //
// DetailViewModel.swift
// github-users
//
// Created by German Buela on 5/20/16.
// Copyright © 2016 German Buela. All rights reserved.
//
import Foundation
import ReactiveCocoa
class DetailViewModel {
let userImage: MutableProperty<UIImage?> = MutableProperty(nil)
let name: MutableProperty<String> = MutableProperty("")
let location: MutableProperty<String> = MutableProperty("")
let publicRepos: MutableProperty<String> = MutableProperty("")
var fetchUserAction: Action<Void, User, FetchError>!
private var user: User!
private let api: GithubAPI!
init(_ network:NetworkProtocol, user: User) {
self.api = GithubAPI(network)
self.user = user
fetchUserAction = Action<Void, User, FetchError> { [unowned self] _ in
return self.userFetchSignalProducer()
}
self.name <~ fetchUserAction.values.map { $0.name ?? "" }
self.location <~ fetchUserAction.values.map { $0.location ?? "" }
self.publicRepos <~ fetchUserAction.values.map { self.formatRepos($0.publicRepos) ?? "" }
fetchUserAction.values.observeNext { self.user = $0 }
}
private func formatRepos(repos: Int?) -> String? {
guard let r = repos else { return nil }
switch r {
case 0:
return "No repos"
case 1:
return "1 repo"
default:
return "\(r) repos"
}
}
// MARK: - Exposed methods
func userName() -> String {
return user.userName
}
func imageFetchSignalProducer() -> SignalProducer<UIImage, FetchError> {
return api.imageFetchSignalProducer(self.user.avatarUrl)
}
func userFetchSignalProducer() -> SignalProducer<User, FetchError> {
return api.userFetchSignalProducer(self.user.userName)
}
} | gpl-3.0 | 586b894f7908a46119b32300c7ffc639 | 28.171875 | 98 | 0.621651 | 4.464115 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.