repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
TonyStark106/NiceKit | NiceKit/Sources/Service/Debug/TinyConsole.swift | 1 | 2502 | //
// TinyConsole.swift
// Pods
//
// Created by 吕嘉豪 on 2017/4/20.
//
//
import Foundation
private class TinyConsoleWindow: UIWindow {
init() {
super.init(frame: CGRect.zero)
windowLevel = UIWindowLevelStatusBar * 2 - 1
var frame = UIScreen.main.bounds
frame.size.height *= 0.5
frame.origin.y = frame.size.height
self.frame = frame
let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(sender:)))
addGestureRecognizer(pan)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func pan(sender: UIPanGestureRecognizer) {
if let keyWindow = UIApplication.shared.keyWindow, let view = sender.view {
let translatedPoint = sender.translation(in: keyWindow)
let x = view.center.x
let y = view.center.y + translatedPoint.y
sender.view?.center = CGPoint(x: x, y: y)
sender.setTranslation(CGPoint.zero, in: keyWindow)
}
}
}
public class TinyConsole: UIViewController {
private static var window: TinyConsoleWindow = TinyConsoleWindow()
private(set) public static var isShowing = false
public static func show() {
if isShowing == false {
if window.rootViewController == nil {
window.rootViewController = shared
}
shared.textView.text = Log.history
isShowing = true
window.isHidden = false
}
}
public static func dismiss() {
if isShowing {
isShowing = false
window.isHidden = true
shared.textView.text = nil
}
}
public static let shared = TinyConsole()
fileprivate lazy var textView: UITextView = {
let tv = UITextView()
tv.isEditable = false
tv.font = UIFont.systemFont(ofSize: 15)
tv.textColor = UIColor.white
tv.backgroundColor = UIColor.black
return tv
}()
private init() {
super.init(nibName: nil, bundle: nil)
view.backgroundColor = UIColor.white
view.addSubview(textView)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
textView.frame = view.bounds
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
BGDigital/mckuai2.0 | mckuai/mckuai/main/mainSubCell.swift | 1 | 3126 | //
// mainSubCell.swift
// mckuai
//
// Created by XingfuQiu on 15/4/21.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class mainSubCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var username: UIButton!
@IBOutlet weak var replys: UIButton!
@IBOutlet weak var times: UILabel!
@IBOutlet weak var imgJian: UIImageView!
@IBOutlet weak var imgJing: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.selectionStyle = .None
self.username.imageView?.layer.masksToBounds = true
self.username.imageView?.layer.cornerRadius = 10
self.replys.titleEdgeInsets = UIEdgeInsetsMake(-2, 0, 0, 0)
imgJian.hidden = true
imgJing.hidden = true
self.username.titleEdgeInsets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 0)
//底部线 +50是为了滑动删除时样式的同步
var iWidth = UIScreen.mainScreen().bounds.size.width;
var linetop = UIView(frame: CGRectMake(0, self.frame.size.height-0.5, iWidth, 0.5))
linetop.backgroundColor = UIColor(hexString: "#E1E3E5")
self.addSubview(linetop)
var line1 = UIView(frame: CGRectMake(0, 8, iWidth, 0.5))
line1.backgroundColor = UIColor(hexString: "#E1E3E5")
self.addSubview(line1)
var line = UIView(frame: CGRectMake(0, 0, iWidth, 8))
line.backgroundColor = UIColor(hexString: "#EFF0F2")
self.addSubview(line)
}
func update(json: JSON) {
// println(json)
self.title.text = json["talkTitle"].stringValue
self.title.sizeOfMultiLineLabel()
var imgPath = json["headImg"].string != nil ? json["headImg"].stringValue : json["icon"].stringValue
var disName = json["userName"].string != nil ? json["userName"].stringValue : json["forumName"].stringValue
if !imgPath.isEmpty {
self.username.sd_setImageWithURL(NSURL(string: imgPath), forState: .Normal, placeholderImage: DefaultUserAvatar_small, completed: { img,_,_,url in
if(img != nil){
var rect = CGRectMake(0, 0, 20, 20)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
img.drawInRect(rect)
var newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.username.setImage(newImage, forState: .Normal)
}
})
}
self.username.setTitle(disName, forState: .Normal)
self.replys.setTitle(json["replyNum"].stringValue, forState: .Normal)
self.times.text = MCUtils.compDate(json["replyTime"].stringValue)
imgJian.hidden = "1" == json["isDing"].stringValue
imgJing.hidden = "1" == json["isJing"].stringValue
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
fortmarek/Supl | Supl/suplModel.swift | 1 | 1599 | //
// suplModel.swift
// Supl
//
// Created by Marek Fořt on 14.09.15.
// Copyright © 2015 Marek Fořt. All rights reserved.
//
import Foundation
class suplStruct: NSObject, NSCoding {
var group: String?
var hour: String?
var change: String?
var professorForChange: String?
var schoolroom: String?
var subject: String?
var professorUsual: String?
var avs: String?
required convenience init(coder aDecoder: NSCoder) {
self.init()
self.group = aDecoder.decodeObject(forKey: "group") as? String
self.hour = aDecoder.decodeObject(forKey: "hour") as? String
self.change = aDecoder.decodeObject(forKey: "change") as? String
self.professorForChange = aDecoder.decodeObject(forKey: "professorForChange") as? String
self.schoolroom = aDecoder.decodeObject(forKey: "schoolroom") as? String
self.subject = aDecoder.decodeObject(forKey: "subject") as? String
self.professorUsual = aDecoder.decodeObject(forKey: "professorUsual") as? String
self.avs = aDecoder.decodeObject(forKey: "avs") as? String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(group, forKey: "group")
aCoder.encode(hour, forKey: "hour")
aCoder.encode(change, forKey: "change")
aCoder.encode(professorForChange, forKey: "professorForChange")
aCoder.encode(schoolroom, forKey: "schoolroom")
aCoder.encode(subject, forKey: "subject")
aCoder.encode(professorUsual, forKey: "professorUsual")
aCoder.encode(avs, forKey: "avs")
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/02051-swift-tupletype-get.swift | 1 | 241 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S : CollectionType
}
struct Q<T where g: NSObject {
var : U -> (
| mit |
therealbnut/swift | test/Constraints/generics.swift | 2 | 19123 | // RUN: %target-typecheck-verify-swift
infix operator +++
protocol ConcatToAnything {
static func +++ <T>(lhs: Self, other: T)
}
func min<T : Comparable>(_ x: T, y: T) -> T {
if y < x { return y }
return x
}
func weirdConcat<T : ConcatToAnything, U>(_ t: T, u: U) {
t +++ u
t +++ 1
u +++ t // expected-error{{argument type 'U' does not conform to expected type 'ConcatToAnything'}}
}
// Make sure that the protocol operators don't get in the way.
var b1, b2 : Bool
_ = b1 != b2
extension UnicodeScalar {
func isAlpha2() -> Bool {
return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z")
}
}
protocol P {
static func foo(_ arg: Self) -> Self
}
struct S : P {
static func foo(_ arg: S) -> S {
return arg
}
}
func foo<T : P>(_ arg: T) -> T {
return T.foo(arg)
}
// Associated types and metatypes
protocol SomeProtocol {
associatedtype SomeAssociated
}
func generic_metatypes<T : SomeProtocol>(_ x: T)
-> (T.Type, T.SomeAssociated.Type)
{
return (type(of: x), type(of: x).SomeAssociated.self)
}
// Inferring a variable's type from a call to a generic.
struct Pair<T, U> { } // expected-note 4 {{'T' declared as parameter to type 'Pair'}} expected-note {{'U' declared as parameter to type 'Pair'}}
func pair<T, U>(_ x: T, _ y: U) -> Pair<T, U> { }
var i : Int, f : Float
var p = pair(i, f)
// Conformance constraints on static variables.
func f1<S1 : Sequence>(_ s1: S1) {}
var x : Array<Int> = [1]
f1(x)
// Inheritance involving generics and non-generics.
class X {
func f() {}
}
class Foo<T> : X {
func g() { }
}
class Y<U> : Foo<Int> {
}
func genericAndNongenericBases(_ x: Foo<Int>, y: Y<()>) {
x.f()
y.f()
y.g()
}
func genericAndNongenericBasesTypeParameter<T : Y<()>>(_ t: T) {
t.f()
t.g()
}
protocol P1 {}
protocol P2 {}
func foo<T : P1>(_ t: T) -> P2 {
return t // expected-error{{return expression of type 'T' does not conform to 'P2'}}
}
func foo2(_ p1: P1) -> P2 {
return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}}
}
// <rdar://problem/14005696>
protocol BinaryMethodWorkaround {
associatedtype MySelf
}
protocol Squigglable : BinaryMethodWorkaround {
}
infix operator ~~~
func ~~~ <T : Squigglable>(lhs: T, rhs: T) -> Bool where T.MySelf == T {
return true
}
extension UInt8 : Squigglable {
typealias MySelf = UInt8
}
var rdar14005696 : UInt8
_ = rdar14005696 ~~~ 5
// <rdar://problem/15168483>
public struct SomeIterator<C: Collection, Indices: Sequence>
: IteratorProtocol, Sequence
where C.Index == Indices.Iterator.Element {
var seq : C
var indices : Indices.Iterator
public typealias Element = C.Iterator.Element
public mutating func next() -> Element? {
fatalError()
}
public init(elements: C, indices: Indices) {
fatalError()
}
}
func f1<T>(seq: Array<T>) {
let x = (seq.indices).lazy.reversed()
SomeIterator(elements: seq, indices: x) // expected-warning{{unused}}
SomeIterator(elements: seq, indices: seq.indices.reversed()) // expected-warning{{unused}}
}
// <rdar://problem/16078944>
func count16078944<T>(_ x: Range<T>) -> Int { return 0 }
func test16078944 <T: Comparable>(lhs: T, args: T) -> Int {
return count16078944(lhs..<args) // don't crash
}
// <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy()
class r22409190ManagedBuffer<Value, Element> {
final var value: Value { get {} set {}}
func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) -> R) -> R {
}
}
class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> {
deinit {
self.withUnsafeMutablePointerToElements { elems -> Void in
elems.deinitialize(count: self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
}
}
}
// <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))'
func r22459135() {
func h<S : Sequence>(_ sequence: S) -> S.Iterator.Element
where S.Iterator.Element : Integer {
return 0
}
func g(_ x: Any) {}
func f(_ x: Int) {
g(h([3]))
}
func f2<TargetType: AnyObject>(_ target: TargetType, handler: @escaping (TargetType) -> ()) {
let _: (AnyObject) -> () = { internalTarget in
handler(internalTarget as! TargetType)
}
}
}
// <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set"
// <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context
_ = [] as Set // expected-error {{generic parameter 'Element' could not be inferred in cast to 'Set<_>}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{14-14=<<#Element: Hashable#>>}}
//<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness
func r22509125<T>(_ a : T?) { // expected-note {{in call to function 'r22509125'}}
r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}}
}
// <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int'
struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}}
static func foo() -> Int {}
}
var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{24-24=<Any>}}
// https://bugs.swift.org/browse/SR-599
func SR599<T: Integer>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599'}}
_ = SR599() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type
protocol Q19215114 {}
protocol P19215114 {}
// expected-note @+1 {{in call to function 'body9215114'}}
func body9215114<T: P19215114, U: Q19215114>(_ t: T) -> (_ u: U) -> () {}
func test9215114<T: P19215114, U: Q19215114>(_ t: T) -> (U) -> () {
//Should complain about not being able to infer type of U.
let f = body9215114(t) // expected-error {{generic parameter 'T' could not be inferred}}
return f
}
// <rdar://problem/21718970> QoI: [uninferred generic param] cannot invoke 'foo' with an argument list of type '(Int)'
class Whatever<A: IntegerArithmetic, B: IntegerArithmetic> { // expected-note 2 {{'A' declared as parameter to type 'Whatever'}}
static func foo(a: B) {}
static func bar() {}
}
Whatever.foo(a: 23) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: IntegerArithmetic#>, <#B: IntegerArithmetic#>>}}
// <rdar://problem/21718955> Swift useless error: cannot invoke 'foo' with no arguments
Whatever.bar() // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: IntegerArithmetic#>, <#B: IntegerArithmetic#>>}}
// <rdar://problem/27515965> Type checker doesn't enforce same-type constraint if associated type is Any
protocol P27515965 {
associatedtype R
func f() -> R
}
struct S27515965 : P27515965 {
func f() -> Any { return self }
}
struct V27515965 {
init<T : P27515965>(_ tp: T) where T.R == Float {}
}
func test(x: S27515965) -> V27515965 {
return V27515965(x) // expected-error {{generic parameter 'T' could not be inferred}}
}
protocol BaseProto {}
protocol SubProto: BaseProto {}
@objc protocol NSCopyish {
func copy() -> Any
}
struct FullyGeneric<Foo> {} // expected-note 6 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 6 {{generic type 'FullyGeneric' declared here}}
struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}}
struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}}
struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}}
struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}}
struct ObjCProtoBound<Foo: NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound'}} expected-note {{generic type 'ObjCProtoBound' declared here}}
struct ObjCProtoBound2<Foo> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound2'}}
struct ClassBound<Foo: X> {} // expected-note {{generic type 'ClassBound' declared here}}
struct ClassBound2<Foo> where Foo: X {} // expected-note {{generic type 'ClassBound2' declared here}}
struct ProtosBound<Foo> where Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound'}} expected-note {{generic type 'ProtosBound' declared here}}
struct ProtosBound2<Foo: SubProto & NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound2'}}
struct ProtosBound3<Foo: SubProto> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound3'}}
struct AnyClassAndProtoBound<Foo> where Foo: AnyObject, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound'}}
struct AnyClassAndProtoBound2<Foo> where Foo: SubProto, Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound2'}}
struct ClassAndProtoBound<Foo> where Foo: X, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtoBound'}}
struct ClassAndProtosBound<Foo> where Foo: X, Foo: SubProto, Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound'}}
struct ClassAndProtosBound2<Foo> where Foo: X, Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound2'}}
extension Pair {
init(first: T) {}
init(second: U) {}
var first: T { fatalError() }
var second: U { fatalError() }
}
func testFixIts() {
_ = FullyGeneric() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<Any>}}
_ = FullyGeneric<Any>()
_ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}}
_ = AnyClassBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'AnyObject'}}
_ = AnyClassBound<AnyObject>()
_ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}}
_ = AnyClassBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'AnyObject'}}
_ = AnyClassBound2<AnyObject>()
_ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}}
_ = ProtoBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: SubProto#>>}}
_ = ProtoBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ObjCProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<NSCopyish>}}
_ = ObjCProtoBound<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound<NSCopyish>()
_ = ObjCProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{22-22=<NSCopyish>}}
_ = ObjCProtoBound2<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound2<NSCopyish>()
_ = ProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound3() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = AnyClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{28-28=<<#Foo: AnyObject & SubProto#>>}}
_ = AnyClassAndProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{29-29=<<#Foo: AnyObject & SubProto#>>}}
_ = ClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<<#Foo: X & SubProto#>>}}
_ = ClassAndProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<<#Foo: X & NSCopyish & SubProto#>>}}
_ = ClassAndProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{27-27=<<#Foo: X & NSCopyish & SubProto#>>}}
_ = Pair() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, Any>}}
_ = Pair(first: S()) // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<S, Any>}}
_ = Pair(second: S()) // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, S>}}
}
func testFixItClassBound() {
// We infer a single class bound for simple cases in expressions...
let x = ClassBound()
let x1: String = x // expected-error {{cannot convert value of type 'ClassBound<X>' to specified type 'String'}}
let y = ClassBound2()
let y1: String = y // expected-error {{cannot convert value of type 'ClassBound2<X>' to specified type 'String'}}
// ...but not in types.
let z1: ClassBound // expected-error {{reference to generic type 'ClassBound' requires arguments in <...>}} {{21-21=<X>}}
let z2: ClassBound2 // expected-error {{reference to generic type 'ClassBound2' requires arguments in <...>}} {{22-22=<X>}}
}
func testFixItCasting(x: Any) {
_ = x as! FullyGeneric // expected-error {{generic parameter 'Foo' could not be inferred in cast to 'FullyGeneric<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
}
func testFixItContextualKnowledge() {
// FIXME: These could propagate backwards.
let _: Int = Pair().first // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}}
let _: Int = Pair().second // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}}
}
func testFixItTypePosition() {
let _: FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{22-22=<Any>}}
let _: ProtoBound // expected-error {{reference to generic type 'ProtoBound' requires arguments in <...>}} {{20-20=<<#Foo: SubProto#>>}}
let _: ObjCProtoBound // expected-error {{reference to generic type 'ObjCProtoBound' requires arguments in <...>}} {{24-24=<NSCopyish>}}
let _: AnyClassBound // expected-error {{reference to generic type 'AnyClassBound' requires arguments in <...>}} {{23-23=<AnyObject>}}
let _: ProtosBound // expected-error {{reference to generic type 'ProtosBound' requires arguments in <...>}} {{21-21=<<#Foo: NSCopyish & SubProto#>>}}
}
func testFixItNested() {
_ = Array<FullyGeneric>() // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{25-25=<Any>}}
_ = [FullyGeneric]() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any>}}
_ = FullyGeneric<FullyGeneric>() // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{32-32=<Any>}}
_ = Pair<
FullyGeneric, // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{17-17=<Any>}}
FullyGeneric // FIXME: We could diagnose both of these, but we don't.
>()
_ = Pair<
FullyGeneric<Any>,
FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{17-17=<Any>}}
>()
_ = Pair<
FullyGeneric, // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{17-17=<Any>}}
FullyGeneric<Any>
>()
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}}
FullyGeneric()
)
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric<Any>(),
FullyGeneric() // expected-note {{explicitly specify the generic arguments to fix this issue}}
)
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}}
FullyGeneric<Any>()
)
}
// rdar://problem/26845038
func occursCheck26845038(a: [Int]) {
_ = Array(a)[0]
}
// rdar://problem/29633747
extension Array where Element: Hashable {
public func trimmed(_ elements: [Element]) -> SubSequence {
return []
}
}
func rdar29633747(characters: String.CharacterView) {
let _ = Array(characters).trimmed(["("])
}
// Null pointer dereference in noteArchetypeSource()
class GenericClass<A> {}
// expected-note@-1 {{'A' declared as parameter to type 'GenericClass'}}
func genericFunc<T>(t: T) {
_ = [T: GenericClass] // expected-error {{generic parameter 'A' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// expected-error@-2 2 {{type 'T' does not conform to protocol 'Hashable'}}
}
| apache-2.0 |
cherrywoods/swift-meta-serialization | MoreTests/ShortExample.swift | 1 | 6247 | //
// SuperShortExample.swift
// MoreTests
//
// Copyright 2018 cherrywoods
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MetaSerialization
// this example is based on example3
struct ShortExampleSerialization: Serialization {
typealias Raw = String
func provideNewDecoder() -> MetaDecoder {
return MetaDecoder(unwrapper: ShortExampleTranslator())
}
func provideNewEncoder() -> MetaEncoder {
return MetaEncoder(metaSupplier: ShortExampleTranslator())
}
func convert(meta: Meta) throws -> String {
// convert from an (unnested) array or dictionary to a pure string with markers
// see README.md for more details
if let string = meta as? String {
return "*\(string)*"
} else if let array = meta as? [Meta] {
// actually elements should be strings
var result = "unkeyed;"
for element in array {
result += "*\(element)*,"
}
return result
} else if let dictionary = meta as? [String : Meta] {
var result = "keyed;"
for (key, value) in dictionary {
result += "*\(key)*:*\(value)*,"
}
return result
} else {
preconditionFailure("Wrong meta!")
}
}
func convert(raw: String) throws -> Meta {
if raw.starts(with: "*") {
return String( raw.dropFirst().dropLast() )
} else if raw.starts(with: "unkeyed;") {
var meta = [Meta]()
// this will sufficently split values and komma separators
let elements = raw.dropFirst( "unkeyed;".count ).split(separator: "*")
// now filter out the separators by dropping every secoding element which should be ,
for index in (elements.startIndex..<elements.endIndex) {
if (index - elements.startIndex) % 2 == 1 {
guard elements[index] == "," else {
preconditionFailure("String not valid")
}
// do not copy to meta, which is dropping
} else {
meta.append(String(elements[index]))
}
}
return meta
} else if raw.starts(with: "keyed;") {
var meta = [String : Meta]()
// this will sufficently split values and komma separators
let elements = raw.dropFirst( "keyed;".count ).split(separator: "*")
// now filter out the separators by dropping every secoding element
// but check that the element separators are right
for index in (elements.startIndex..<elements.endIndex) {
switch (index - elements.startIndex) % 4 {
case 1:
// this should be colons
guard elements[index] == ":" else {
preconditionFailure("String not valid")
}
// and drop it / not copy it to meta
case 3:
// this should be kommas
guard elements[index] == "," else {
preconditionFailure("String not valid")
}
// also drop it
case 0:
// here we get the keys, the values are calculatable
guard elements.count > index + 2 /* the index value should be found at */ else {
preconditionFailure("String not valid")
}
meta[ String(elements[index]) ] = String(elements[index+2])
default:
// this are the values.
// we already handled them, so just ignore
break
}
}
return meta
} else {
preconditionFailure("String not valid")
}
}
}
struct ShortExampleTranslator: MetaSupplier, Unwrapper {
func wrap<T>(_ value: T, for encoder: MetaEncoder) throws -> Meta? where T : Encodable {
guard !(value is NilMarker) else {
return nil
}
// supply metas for all LosslessStringConvertible types
// nil also works because NilMarker is already extended in Example2
guard let description = (value as? LosslessStringConvertible)?.description else {
return nil
}
return description
}
// use default keyed and unkeyed containers
// will be Arrays of String and Dictionarys of Strings and Strings
func unwrap<T>(meta: Meta, toType type: T.Type, for decoder: MetaDecoder) throws -> T? where T : Decodable {
guard type is LosslessStringConvertible.Type else {
return nil
}
guard let string = meta as? String else {
return nil
}
return (type as! LosslessStringConvertible.Type).init(string) as! T?
}
}
| apache-2.0 |
humblehacker/Dispatch3 | Dispatch3/Classes/DispatchQueue.swift | 1 | 7684 | //
// Dispatch3.swift
// Dispatch3
//
// Created by David Whetstone on 6/21/16.
// Copyright © 2016 humblehacker. All rights reserved.
//
import Foundation
import Dispatch
public
class DispatchQueue: DispatchObject<dispatch_queue_t>
{
public convenience
init(__label label: UnsafePointer<Int8>, attr: dispatch_queue_attr_t?)
{
let queue = dispatch_queue_create(label, attr)
self.init(underlyingObject: queue)
}
public convenience
init(label: String, attributes: DispatchQueueAttributes = .serial, target: DispatchQueue? = nil)
{
let queue = dispatch_queue_create(label, attributes.underlyingAttributes)
self.init(underlyingObject: queue)
}
override
init(underlyingObject: dispatch_queue_t)
{
super.init(underlyingObject: underlyingObject)
annotateQueue()
}
public var label: String { return String(UTF8String: dispatch_queue_get_label(underlyingObject)) ?? "" }
public var qos: DispatchQoS
{
return DispatchQoS(underlyingQoSClass: dispatch_queue_get_qos_class(underlyingObject, nil))
}
public static var main: DispatchQueue = DispatchQueue(underlyingObject: dispatch_get_main_queue())
public class func global(attributes attributes: DispatchQueue.GlobalAttributes = .qosDefault) -> DispatchQueue
{
return DispatchQueue(underlyingObject: dispatch_get_global_queue(attributes.underlyingQoSClass, 0))
}
}
extension DispatchQueue
{
private
func annotateQueue()
{
// Use `passUnretained` to avoid reference cycle
let unmanaged: Unmanaged<DispatchQueue> = Unmanaged.passUnretained(self)
setSpecific(key: kCurrentQueueKey, value: unmanaged)
}
public struct GlobalAttributes : OptionSetType {
public let rawValue: UInt64
public init(rawValue: UInt64)
{
self.rawValue = rawValue
}
public static let qosUserInteractive = DispatchQueue.GlobalAttributes(rawValue: 1 << 1)
public static let qosUserInitiated = DispatchQueue.GlobalAttributes(rawValue: 1 << 2)
public static let qosDefault = DispatchQueue.GlobalAttributes(rawValue: 1 << 3)
public static let qosUtility = DispatchQueue.GlobalAttributes(rawValue: 1 << 4)
public static let qosBackground = DispatchQueue.GlobalAttributes(rawValue: 1 << 5)
var underlyingQoSClass: qos_class_t
{
if contains(GlobalAttributes.qosUserInteractive) { return QOS_CLASS_USER_INTERACTIVE }
if contains(GlobalAttributes.qosUserInitiated) { return QOS_CLASS_USER_INITIATED}
if contains(GlobalAttributes.qosDefault) { return QOS_CLASS_DEFAULT }
if contains(GlobalAttributes.qosUtility) { return QOS_CLASS_UTILITY }
if contains(GlobalAttributes.qosBackground) { return QOS_CLASS_BACKGROUND }
return QOS_CLASS_BACKGROUND
}
}
}
// MARK: - Perform work
extension DispatchQueue
{
/// Implementation mostly from [this Apple Dev Forum post](https://forums.developer.apple.com/thread/8002#24898)
public func sync<T>(flags flags: DispatchWorkItemFlags = DispatchWorkItemFlags(), @noescape execute work: () throws -> T) rethrows -> T
{
var result: T?
func rethrow(myerror: ErrorType) throws ->() { throw myerror }
func perform_sync_impl(queue: dispatch_queue_t, @noescape block: () throws -> T, block2:((myerror:ErrorType) throws -> ()) ) rethrows
{
var blockError: ErrorType? = nil
if flags.contains(.barrier)
{
DispatchHelper.dispatch_barrier_sync_noescape(queue) { do { result = try block() } catch { blockError = error } }
}
else
{
DispatchHelper.dispatch_sync_noescape(queue) { do { result = try block() } catch { blockError = error } }
}
if let blockError = blockError { try block2(myerror: blockError) }
}
try perform_sync_impl(underlyingObject, block: work, block2: rethrow)
return result!
}
public
func async(group group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void)
{
let work = DispatchWorkItem(group: group, qos: qos, flags: flags, block: work)
async(execute: work)
}
public
func after(when: DispatchTime, execute work: @convention(block) () -> Void)
{
dispatch_after(when.rawValue, underlyingObject, work)
}
public
func sync(execute workItem: DispatchWorkItem)
{
sync { workItem.block() }
}
public
func async(execute workItem: DispatchWorkItem)
{
if let group = workItem.group
{
dispatch_group_async(group.underlyingObject, underlyingObject, workItem.block)
return
}
dispatch_async(underlyingObject, workItem.block)
}
}
// MARK: - Specific Values
final public class DispatchSpecificKey<T>
{
public init() {}
}
final private class DispatchSpecificValue<T>
{
var value: T
init(value: T)
{
self.value = value
}
class
func from(mutableVoidPointer mutableVoidPointer: UnsafeMutablePointer<Void>) -> DispatchSpecificValue<T>
{
let cOpaquePointer: COpaquePointer = COpaquePointer(mutableVoidPointer)
let unmanaged: Unmanaged<DispatchSpecificValue<T>> = Unmanaged.fromOpaque(cOpaquePointer)
return unmanaged.takeUnretainedValue()
}
var mutableVoidPointer: UnsafeMutablePointer<Void>
{
let unmanagedRetained: Unmanaged<DispatchSpecificValue<T>> = Unmanaged.passRetained(self)
let cOpaquePointer: COpaquePointer = unmanagedRetained.toOpaque()
return UnsafeMutablePointer<Void>(cOpaquePointer)
}
}
public
extension DispatchQueue
{
public class
func getSpecific<T>(key key: DispatchSpecificKey<T>) -> T?
{
let storedKey = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(key).toOpaque())
let p = dispatch_get_specific(storedKey)
guard p != nil else { return nil }
let specificValue: DispatchSpecificValue<T> = DispatchSpecificValue.from(mutableVoidPointer: p)
return specificValue.value
}
public
func getSpecific<T>(key key: DispatchSpecificKey<T>) -> T?
{
let storedKey = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(key).toOpaque())
let p = dispatch_queue_get_specific(underlyingObject, storedKey)
guard p != nil else { return nil }
let specificValue: DispatchSpecificValue<T> = DispatchSpecificValue.from(mutableVoidPointer: p)
return specificValue.value
}
public
func setSpecific<T>(key key: DispatchSpecificKey<T>, value:T?)
{
let storedKey = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(key).toOpaque())
if let val = value
{
let wrappedValue = DispatchSpecificValue(value: val)
let mutableVoidPointer: UnsafeMutablePointer<Void> = wrappedValue.mutableVoidPointer
dispatch_queue_set_specific(underlyingObject, storedKey, mutableVoidPointer, releaseSpecificValue)
}
else
{
dispatch_queue_set_specific(underlyingObject, storedKey, nil, nil)
}
}
}
private
func releaseSpecificValue(specificValue mutableVoidPointer: UnsafeMutablePointer<Void>)
{
let cOpaquePointer = COpaquePointer(mutableVoidPointer)
let unmanaged = Unmanaged<AnyObject>.fromOpaque(cOpaquePointer)
unmanaged.release()
}
| mit |
Noambaron/NBPoliteObserver | PoliteObserverExample/PoliteObserverExample/ViewController.swift | 1 | 714 | //
// ViewController.swift
// PoliteObserverExample
//
// Created by Noam on 11/22/16.
// Copyright © 2016 Noam. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var object:NSObject? = NSObject()
object!.addPoliteObserver(self, forKeyPath: "keyPath", options: [], context: nil)
object = nil //This would crash with a plain KVO oserver...
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
SoneeJohn/WWDC | ConfCore/RoomsJSONAdapter.swift | 1 | 933 | //
// RoomsJSONAdapter.swift
// WWDC
//
// Created by Guilherme Rambo on 08/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import SwiftyJSON
private enum RoomKeys: String, JSONSubscriptType {
case name, mapName, floor
case identifier = "id"
var jsonKey: JSONKey {
return JSONKey.key(rawValue)
}
}
final class RoomsJSONAdapter: Adapter {
typealias InputType = JSON
typealias OutputType = Room
func adapt(_ input: JSON) -> Result<Room, AdapterError> {
guard let identifier = input[RoomKeys.identifier].int else {
return .error(.missingKey(RoomKeys.identifier))
}
guard let name = input[RoomKeys.name].string else {
return .error(.missingKey(RoomKeys.name))
}
let room = Room.make(identifier: "\(identifier)", name: name, mapName: "", floor: "")
return .success(room)
}
}
| bsd-2-clause |
armcknight/pkpassgenerator | ImagesSizeChecker/main.swift | 1 | 817 | //
// main.swift
// ImagesSizeChecker
//
// Created by Andrew McKnight on 5/1/16.
//
//
import Foundation
let args = ProcessInfo.processInfo.arguments
let backgroundImageSet = parseImageSet(basePath: args[2])
let footerImageSet = parseImageSet(basePath: args[3])
let iconImageSet = parseImageSet(basePath: args[4])
let logoImageSet = parseImageSet(basePath: args[5])
let stripImageSet = parseImageSet(basePath: args[6])
let thumbnailImageSet = parseImageSet(basePath: args[7])
let passImages = PassImages(
background: backgroundImageSet,
footer: footerImageSet,
icon: iconImageSet,
logo: logoImageSet,
strip: stripImageSet,
thumbnail: thumbnailImageSet
)
let passPath = args[1]
let pass = parsePass(path: passPath, images: passImages)
checkSizesInPass(pass: pass)
print("Finished!")
| mit |
pj4533/OpenPics | Pods/AlamofireImage/Source/UIImageView+AlamofireImage.swift | 4 | 21637 | // UIImageView+AlamofireImage.swift
//
// Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import UIKit
extension UIImageView {
// MARK: - ImageTransition
/// Used to wrap all `UIView` animation transition options alongside a duration.
public enum ImageTransition {
case None
case CrossDissolve(NSTimeInterval)
case CurlDown(NSTimeInterval)
case CurlUp(NSTimeInterval)
case FlipFromBottom(NSTimeInterval)
case FlipFromLeft(NSTimeInterval)
case FlipFromRight(NSTimeInterval)
case FlipFromTop(NSTimeInterval)
case Custom(
duration: NSTimeInterval,
animationOptions: UIViewAnimationOptions,
animations: (UIImageView, Image) -> Void,
completion: (Bool -> Void)?
)
private var duration: NSTimeInterval {
switch self {
case None: return 0.0
case CrossDissolve(let duration): return duration
case CurlDown(let duration): return duration
case CurlUp(let duration): return duration
case FlipFromBottom(let duration): return duration
case FlipFromLeft(let duration): return duration
case FlipFromRight(let duration): return duration
case FlipFromTop(let duration): return duration
case Custom(let duration, _, _, _): return duration
}
}
private var animationOptions: UIViewAnimationOptions {
switch self {
case None: return .TransitionNone
case CrossDissolve: return .TransitionCrossDissolve
case CurlDown: return .TransitionCurlDown
case CurlUp: return .TransitionCurlUp
case FlipFromBottom: return .TransitionFlipFromBottom
case FlipFromLeft: return .TransitionFlipFromLeft
case FlipFromRight: return .TransitionFlipFromRight
case FlipFromTop: return .TransitionFlipFromTop
case Custom(_, let animationOptions, _, _): return animationOptions
}
}
private var animations: ((UIImageView, Image) -> Void) {
switch self {
case Custom(_, _, let animations, _):
return animations
default:
return { $0.image = $1 }
}
}
private var completion: (Bool -> Void)? {
switch self {
case Custom(_, _, _, let completion):
return completion
default:
return nil
}
}
}
// MARK: - Private - AssociatedKeys
private struct AssociatedKeys {
static var ImageDownloaderKey = "af_UIImageView.ImageDownloader"
static var SharedImageDownloaderKey = "af_UIImageView.SharedImageDownloader"
static var ActiveRequestReceiptKey = "af_UIImageView.ActiveRequestReceipt"
static var ActiveDownloadIDKey = "af_UIImageView.ActiveDownloadID"
}
// MARK: - Properties
/// The instance image downloader used to download all images. If this property is `nil`, the `UIImageView` will
/// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a
/// custom instance image downloader is when images are behind different basic auth credentials.
public var af_imageDownloader: ImageDownloader? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ImageDownloaderKey) as? ImageDownloader
}
set(downloader) {
objc_setAssociatedObject(self, &AssociatedKeys.ImageDownloaderKey, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// The shared image downloader used to download all images. By default, this is the default `ImageDownloader`
/// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory
/// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the
/// `af_imageDownloader` is `nil`.
public class var af_sharedImageDownloader: ImageDownloader {
get {
if let downloader = objc_getAssociatedObject(self, &AssociatedKeys.SharedImageDownloaderKey) as? ImageDownloader {
return downloader
} else {
return ImageDownloader.defaultInstance
}
}
set(downloader) {
objc_setAssociatedObject(self, &AssociatedKeys.SharedImageDownloaderKey, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var af_activeRequestReceipt: RequestReceipt? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey) as? RequestReceipt
}
set(receipt) {
objc_setAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey, receipt, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Image Download Methods
/**
Asynchronously downloads an image from the specified URL and sets it once the request is finished.
If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
set immediately, and then the remote image will be set once the image request is finished.
- parameter URL: The URL used for the image request.
- parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the
image view will not change its image until the image request finishes. `nil` by
default.
*/
public func af_setImageWithURL(URL: NSURL, placeholderImage: UIImage? = nil) {
af_setImageWithURLRequest(
URLRequestWithURL(URL),
placeholderImage: placeholderImage,
filter: nil,
imageTransition: .None,
completion: nil
)
}
/**
Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded
image and sets it once finished.
If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
set immediately, and then the remote image will be set once the image request is finished.
- parameter URL: The URL used for the image request.
- parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the
image view will not change its image until the image request finishes. `nil` by
default.
- parameter filter: The image filter applied to the image after the image request is finished.
*/
public func af_setImageWithURL(URL: NSURL, placeholderImage: UIImage? = nil, filter: ImageFilter) {
af_setImageWithURLRequest(
URLRequestWithURL(URL),
placeholderImage: placeholderImage,
filter: filter,
imageTransition: .None,
completion: nil
)
}
/**
Asynchronously downloads an image from the specified URL and sets it once the request is finished while
executing the image transition.
If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
set immediately, and then the remote image will be set once the image request is finished.
- parameter URL: The URL used for the image request.
- parameter placeholderImage: The image to be set initially until the image request finished. If
`nil`, the image view will not change its image until the image
request finishes. `nil` by default.
- parameter imageTransition: The image transition animation applied to the image when set.
- parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults
to `false`.
*/
public func af_setImageWithURL(
URL: NSURL,
placeholderImage: UIImage? = nil,
imageTransition: ImageTransition,
runImageTransitionIfCached: Bool = false)
{
af_setImageWithURLRequest(
URLRequestWithURL(URL),
placeholderImage: placeholderImage,
filter: nil,
imageTransition: imageTransition,
runImageTransitionIfCached: runImageTransitionIfCached,
completion: nil
)
}
/**
Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded
image and sets it once finished while executing the image transition.
If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
set immediately, and then the remote image will be set once the image request is finished.
- parameter URL: The URL used for the image request.
- parameter placeholderImage: The image to be set initially until the image request finished. If
`nil`, the image view will not change its image until the image
request finishes.
- parameter filter: The image filter applied to the image after the image request is
finished.
- parameter imageTransition: The image transition animation applied to the image when set.
- parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults
to `false`.
*/
public func af_setImageWithURL(
URL: NSURL,
placeholderImage: UIImage?,
filter: ImageFilter?,
imageTransition: ImageTransition,
runImageTransitionIfCached: Bool = false)
{
af_setImageWithURLRequest(
URLRequestWithURL(URL),
placeholderImage: placeholderImage,
filter: filter,
imageTransition: imageTransition,
runImageTransitionIfCached: runImageTransitionIfCached,
completion: nil
)
}
/**
Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded
image and sets it once finished while executing the image transition.
If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
set immediately, and then the remote image will be set once the image request is finished.
The `completion` closure is called after the image download and filtering are complete, but before the start of
the image transition. Please note it is no longer the responsibility of the `completion` closure to set the
image. It will be set automatically. If you require a second notification after the image transition completes,
use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when
the image transition is finished.
- parameter URL: The URL used for the image request.
- parameter placeholderImage: The image to be set initially until the image request finished. If
`nil`, the image view will not change its image until the image
request finishes.
- parameter filter: The image filter applied to the image after the image request is
finished.
- parameter imageTransition: The image transition animation applied to the image when set.
- parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults
to `false`.
- parameter completion: A closure to be executed when the image request finishes. The closure
has no return value and takes three arguments: the original request,
the response from the server and the result containing either the
image or the error that occurred. If the image was returned from the
image cache, the response will be `nil`.
*/
public func af_setImageWithURL(
URL: NSURL,
placeholderImage: UIImage?,
filter: ImageFilter?,
imageTransition: ImageTransition,
runImageTransitionIfCached: Bool = false,
completion: (Response<UIImage, NSError> -> Void)?)
{
af_setImageWithURLRequest(
URLRequestWithURL(URL),
placeholderImage: placeholderImage,
filter: filter,
imageTransition: imageTransition,
runImageTransitionIfCached: runImageTransitionIfCached,
completion: completion
)
}
/**
Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded
image and sets it once finished while executing the image transition.
If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
set immediately, and then the remote image will be set once the image request is finished.
The `completion` closure is called after the image download and filtering are complete, but before the start of
the image transition. Please note it is no longer the responsibility of the `completion` closure to set the
image. It will be set automatically. If you require a second notification after the image transition completes,
use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when
the image transition is finished.
- parameter URLRequest: The URL request.
- parameter placeholderImage: The image to be set initially until the image request finished. If
`nil`, the image view will not change its image until the image
request finishes.
- parameter filter: The image filter applied to the image after the image request is
finished.
- parameter imageTransition: The image transition animation applied to the image when set.
- parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults
to `false`.
- parameter completion: A closure to be executed when the image request finishes. The closure
has no return value and takes three arguments: the original request,
the response from the server and the result containing either the
image or the error that occurred. If the image was returned from the
image cache, the response will be `nil`.
*/
public func af_setImageWithURLRequest(
URLRequest: URLRequestConvertible,
placeholderImage: UIImage?,
filter: ImageFilter?,
imageTransition: ImageTransition,
runImageTransitionIfCached: Bool = false,
completion: (Response<UIImage, NSError> -> Void)?)
{
guard !isURLRequestURLEqualToActiveRequestURL(URLRequest) else { return }
af_cancelImageRequest()
let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader
let imageCache = imageDownloader.imageCache
// Use the image from the image cache if it exists
if let image = imageCache?.imageForRequest(URLRequest.URLRequest, withAdditionalIdentifier: filter?.identifier) {
let response = Response<UIImage, NSError>(
request: URLRequest.URLRequest,
response: nil,
data: nil,
result: .Success(image)
)
completion?(response)
if runImageTransitionIfCached {
let tinyDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.001 * Float(NSEC_PER_SEC)))
// Need to let the runloop cycle for the placeholder image to take affect
dispatch_after(tinyDelay, dispatch_get_main_queue()) {
self.runImageTransition(imageTransition, withImage: image)
}
} else {
self.image = image
}
return
}
// Set the placeholder since we're going to have to download
if let placeholderImage = placeholderImage { self.image = placeholderImage }
// Generate a unique download id to check whether the active request has changed while downloading
let downloadID = NSUUID().UUIDString
// Download the image, then run the image transition or completion handler
let requestReceipt = imageDownloader.downloadImage(
URLRequest: URLRequest,
receiptID: downloadID,
filter: filter,
completion: { [weak self] response in
guard let strongSelf = self else { return }
completion?(response)
guard
strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) &&
strongSelf.af_activeRequestReceipt?.receiptID == downloadID
else {
return
}
if let image = response.result.value {
strongSelf.runImageTransition(imageTransition, withImage: image)
}
strongSelf.af_activeRequestReceipt = nil
}
)
af_activeRequestReceipt = requestReceipt
}
// MARK: - Image Download Cancellation Methods
/**
Cancels the active download request, if one exists.
*/
public func af_cancelImageRequest() {
guard let activeRequestReceipt = af_activeRequestReceipt else { return }
let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader
imageDownloader.cancelRequestForRequestReceipt(activeRequestReceipt)
af_activeRequestReceipt = nil
}
// MARK: - Private - Image Transition
private func runImageTransition(imageTransition: ImageTransition, withImage image: Image) {
UIView.transitionWithView(
self,
duration: imageTransition.duration,
options: imageTransition.animationOptions,
animations: {
imageTransition.animations(self, image)
},
completion: imageTransition.completion
)
}
// MARK: - Private - URL Request Helper Methods
private func URLRequestWithURL(URL: NSURL) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: URL)
for mimeType in Request.acceptableImageContentTypes {
mutableURLRequest.addValue(mimeType, forHTTPHeaderField: "Accept")
}
return mutableURLRequest
}
private func isURLRequestURLEqualToActiveRequestURL(URLRequest: URLRequestConvertible?) -> Bool {
if let
currentRequest = af_activeRequestReceipt?.request.task.originalRequest
where currentRequest.URLString == URLRequest?.URLRequest.URLString
{
return true
}
return false
}
}
| gpl-3.0 |
anddygon/RNDemo | ios/RNDemo/JSEventEmitter.swift | 1 | 2522 | //
// EventDispatcher.swift
// RNDemo
//
// Created by xiaoP on 2017/5/25.
// Copyright © 2017年 Chicv. All rights reserved.
//
import Foundation
import React
// MARK: 继承自RCTEventEmitter
@objc(JSEventEmitter)
class JSEventEmitter: RCTEventEmitter {
//定义内部枚举 因为枚举只会在这个文件和js端用到,所以定义为内部
fileprivate enum EventName: String {
case uploadProgress
case XXX
func toNotificationName() -> Notification.Name {
return Notification.Name(rawValue: rawValue)
}
static var all: [String] {
let arr: [EventName] = [.uploadProgress, .XXX]
return arr.map{ $0.rawValue }
}
}
//必须重载 要暴露给js的方法名
override func supportedEvents() -> [String]! {
return EventName.all
}
///这里的bridge是react会自动设置的
override var bridge: RCTBridge! {
didSet{
NotificationCenter.default
.addObserver(self,
selector: #selector(JSEventEmitter.handle(notification:)),
name: EventName.uploadProgress.toNotificationName(),
object: nil)
}
}
// 这里真正的发送native事件给js
@objc fileprivate func handle(notification: Notification) {
let eventName = notification.name.rawValue
let params = notification.userInfo
sendEvent(withName: eventName,
body: params)
}
/*
//供原生外部调用 外部调用的时候回忆notification形势发送出去 而这个实例在ract创建的时候也被创建了 而且在该实例被创建的时候订阅了这notification 然后收到后又会调用handle真正的发送出去
这里之所以要走这么麻烦的推送流程主要是因为我们不能手动创建这个JSEventEmitter实例,必须由react创建才能成功发送事件
然后又不想把各种逻辑写在这个工具管理类里,采用notification的方式来解决
*/
class func sendToJS(progress: Int) {
NotificationCenter.default
.post(name: NSNotification.Name.init(rawValue: EventName.uploadProgress.rawValue),
object: self,
userInfo: nil)
}
deinit {
NotificationCenter.default
.removeObserver(self, name: EventName.uploadProgress.toNotificationName(), object: nil)
}
}
| mit |
BalestraPatrick/Tweetometer | Tweetometer/SettingsViewController.swift | 2 | 2412 | //
// SettingsViewController.swift
// TweetsCounter
//
// Created by Patrick Balestra on 1/22/16.
// Copyright © 2016 Patrick Balestra. All rights reserved.
//
import TweetometerKit
import ValueStepper
final class SettingsViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tweetsStepper: ValueStepper!
@IBOutlet weak var twitterClientControl: UISegmentedControl!
@IBOutlet weak var twitterSupportButton: UIButton!
@IBOutlet weak var emailSupportButton: UIButton!
@IBOutlet weak var aboutButton: UIButton!
@IBOutlet weak var githubButton: UIButton!
let settings = Settings.shared
let linkOpener = LinkOpener()
weak var coordinator: SettingsCoordinator!
override func viewDidLoad() {
super.viewDidLoad()
tweetsStepper.value = Double(settings.maximumNumberOfTweets)
tweetsStepper.numberFormatter.maximumFractionDigits = 0
twitterClientControl.selectedSegmentIndex = TwitterClient.toIndex(settings.preferredTwitterClient)
twitterSupportButton.layer.cornerRadius = 5.0
emailSupportButton.layer.cornerRadius = 5.0
aboutButton.layer.cornerRadius = 5.0
githubButton.layer.cornerRadius = 5.0
view.backgroundColor = .menuDarkBlue()
twitterClientControl.setEnabled(linkOpener.isTwitterAvailable, forSegmentAt: 1)
twitterClientControl.setEnabled(linkOpener.isTweetbotAvailable, forSegmentAt: 2)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func stepperChanged(_ sender: ValueStepper) {
settings.maximumNumberOfTweets = Int(sender.value)
}
@IBAction func clientChanged(_ sender: UISegmentedControl) {
settings.preferredTwitterClient = TwitterClient.fromIndex(sender.selectedSegmentIndex)
}
// MARK: Navigation
@IBAction func emailSupport(_ sender: Any) {
coordinator.presentEmailSupport()
}
@IBAction func twitterSupport(_ sender: Any) {
coordinator.presentTwitterSupport()
}
@IBAction func developedBy(_ sender: Any) {
coordinator.presentAbout()
}
@IBAction func openGithub(_ sender: Any) {
coordinator.presentGithub()
}
@IBAction func dismiss(_ sender: AnyObject) {
coordinator.dismiss()
}
}
| mit |
lostatseajoshua/SwiftExpression | Sources/String+Extension.swift | 2 | 1239 | //
// String+Extension.swift
// SwiftExpression
//
// Created by Joshua Alvarado on 12/3/18.
//
import Foundation.NSRange
extension String {
/**
Finds regex matches in the string. This method will find multiple matches in the string.
- Parameter regex: `Regex` object that holds the pattern to find matches with
- Returns: A `Match` based on the matching result
*/
public func match(_ regex: Regex) -> Regex.Match {
return regex.matches(in: self)
}
/**
Finds regex matches in the string and replaces those matches with the replacement string.
- Parameter regex: `Regex` object that holds the pattern to find matches with
- Parameter with: The replacement `String` to insert in place of the match
- Returns: A new `String` with the replacements applied
*/
public func replace(_ regex: Regex, with str: String) -> String {
return regex.replaceMatches(in: self, with: str)
}
/**
Searches the string to find a match.
- Parameter regex: `Regex` object that holds the pattern to find matches with
- Returns: `true` if a match is found
*/
public func find(_ regex: Regex) -> Bool {
return regex.find(in: self)
}
}
| mit |
romankisil/eqMac2 | native/app/Source/User/User.swift | 1 | 385 | //
// User.swift
// eqMac
//
// Created by Roman Kisil on 24/12/2017.
// Copyright © 2017 Roman Kisil. All rights reserved.
//
import Cocoa
class User: NSObject {
static public var isFirstLaunch: Bool {
var firstLaunch = Storage[.isFirstLaunch]
if (firstLaunch == nil) {
firstLaunch = true
}
Storage[.isFirstLaunch] = false
return firstLaunch!
}
}
| mit |
TENDIGI/Obsidian-UI-iOS | src/UIColorExtensions.swift | 1 | 2362 | //
// UIColorExtensions.swift
// Alfredo
//
// Created by Nick Lee on 9/21/15.
// Copyright © 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
public extension UIColor {
/// Returns a 1x1pt image filled with the receiver's color
public var image: UIImage {
let rect = CGRect(origin: CGPoint.zero, size: CGSize(width: 1, height: 1))
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
/**
Blends two UIColors
- parameter color1: The first color to blend
- parameter color2: The second color to blend
- parameter mode: The function to use when blending the channels
- parameter premultiplyAlpha: Whether or not each color's alpha channel should be premultiplied across the RGB channels prior to the blending
- returns: The UIColor resulting from the blend operation
*/
public func blendColor(_ color1: UIColor, _ color2: UIColor, _ mode: @escaping ((CGFloat, CGFloat) -> CGFloat), _ premultiplyAlpha: Bool = false) -> UIColor {
func transform(_ a: CGFloat, _ b: CGFloat) -> CGFloat {
return min(1.0, max(0.0, mode(a, b)))
}
var r1: CGFloat = 0, g1: CGFloat = 0, b1: CGFloat = 0, a1: CGFloat = 0
var r2: CGFloat = 0, g2: CGFloat = 0, b2: CGFloat = 0, a2: CGFloat = 0
color1.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
color2.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
if premultiplyAlpha {
r1 *= a1
g1 *= a1
b1 *= a1
r2 *= a2
g2 *= a2
b2 *= a2
}
let newColor = UIColor(red: transform(r1, r2), green: transform(g1, g2), blue: transform(b1, b2), alpha: premultiplyAlpha ? 1.0 : transform(a1, a2))
return newColor
}
/// :nodoc:
/// Adds the RGBA channels of color1 and color2
public func + (color1: UIColor, color2: UIColor) -> UIColor {
return blendColor(color1, color2, +)
}
/// :nodoc:
/// Subtracts the RGBA channels of color2 from color1
public func - (color1: UIColor, color2: UIColor) -> UIColor {
return blendColor(color1, color2, -)
}
/// :nodoc:
/// Multiplies the RGBA channels of color1 and color2
public func * (color1: UIColor, color2: UIColor) -> UIColor {
return blendColor(color1, color2, *)
}
| mit |
lukszar/PeselSwift | Example/PeselSwiftDemo/ViewController.swift | 1 | 3269 | //
// ViewController.swift
// PeselSwiftDemo
//
// Created by Łukasz Szarkowicz on 23.06.2017.
// Copyright © 2017 Łukasz Szarkowicz. All rights reserved.
//
import UIKit
import PeselSwift
class ViewController: UIViewController {
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var birthdateLabel: UILabel!
@IBAction func validateAction(_ sender: Any) {
if let text = inputField.text {
let pesel = Pesel(pesel: text)
let result = pesel.validate()
switch result {
case .success:
peselCorrect()
case .error(let error):
peselIncorrect(with: error)
}
showBirthDate(pesel.birthdate())
}
inputField.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
statusLabel.text = nil
birthdateLabel.text = nil
peselReset()
inputField.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func peselReset() {
let newColor = UIColor(red: 100.0 / 255.0, green: 150.0 / 255.0, blue: 180.0 / 255.0, alpha: 1.0)
statusLabel.text = nil
statusLabel.textColor = newColor
inputField.tintColor = newColor
inputField.backgroundColor = UIColor.clear
}
func peselCorrect() {
statusLabel.text = "PESEL number is validated succesfully"
statusLabel.textColor = UIColor.green
inputField.tintColor = UIColor.green
inputField.backgroundColor = UIColor.green.withAlphaComponent(0.3)
}
func peselIncorrect(with error: Pesel.ValidateError) {
var errorReason = "PESEL number validation failure:\n"
switch error {
case .otherThanDigits:
errorReason.append("should contains only digits.")
case .wrongChecksum:
errorReason.append("number is not valid.")
case .wrongLength:
errorReason.append("number should be 11 digits only.")
}
statusLabel.text = errorReason
statusLabel.textColor = UIColor.red
inputField.tintColor = UIColor.red
inputField.backgroundColor = UIColor.red.withAlphaComponent(0.3)
}
func birthDateReset() {
birthdateLabel.text = nil
}
func showBirthDate(_ date: Date?) {
guard let date = date else {
birthDateReset()
return
}
let birthDate = DateFormatter.localizedString(from: date, dateStyle: DateFormatter.Style.medium, timeStyle: DateFormatter.Style.none)
birthdateLabel.text = "Birthday: ".appending(birthDate)
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldClear(_ textField: UITextField) -> Bool {
birthDateReset()
peselReset()
return true
}
}
| mit |
rnystrom/GitHawk | Pods/cmark-gfm-swift/Source/TableRow.swift | 1 | 200 | //
// TableRow.swift
// cmark-gfm-swift
//
// Created by Ryan Nystrom on 3/31/18.
//
import Foundation
public enum TableRow {
case header(cells: [TextLine])
case row(cells: [TextLine])
}
| mit |
ben-ng/swift | test/SILGen/errors.swift | 1 | 44483 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s
import Swift
class Cat {}
enum HomeworkError : Error {
case TooHard
case TooMuch
case CatAteIt(Cat)
}
func someValidPointer<T>() -> UnsafePointer<T> { fatalError() }
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
// CHECK: sil hidden @_TF6errors10make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: return [[T2]] : $Cat
func make_a_cat() throws -> Cat {
return Cat()
}
// CHECK: sil hidden @_TF6errors15dont_make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[BOX]]
func dont_make_a_cat() throws -> Cat {
throw HomeworkError.TooHard
}
// CHECK: sil hidden @_TF6errors11dont_return{{.*}} : $@convention(thin) <T> (@in T) -> (@out T, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: destroy_addr %1 : $*T
// CHECK-NEXT: throw [[BOX]]
func dont_return<T>(_ argument: T) throws -> T {
throw HomeworkError.TooMuch
}
// CHECK: sil hidden @_TF6errors16all_together_nowFSbCS_3Cat : $@convention(thin) (Bool) -> @owned Cat {
// CHECK: bb0(%0 : $Bool):
// CHECK: [[DR_FN:%.*]] = function_ref @_TF6errors11dont_returnur{{.*}} :
// Branch on the flag.
// CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]]
// In the true case, call make_a_cat().
// CHECK: [[FLAG_TRUE]]:
// CHECK: [[MAC_FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]]
// CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat)
// In the false case, call dont_make_a_cat().
// CHECK: [[FLAG_FALSE]]:
// CHECK: [[DMAC_FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]]
// CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat)
// Merge point for the ternary operator. Call dont_return with the result.
// CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat
// CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]]
// CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat
// CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]]
// CHECK: [[DR_NORMAL]]({{%.*}} : $()):
// CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: dealloc_stack [[ARG_TEMP]]
// CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat)
// Return block.
// CHECK: [[RETURN]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: return [[T0]] : $Cat
// Catch dispatch block.
// CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error
// CHECK-NEXT: store [[ERROR]] to [init] [[SRC_TEMP]]
// CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError
// CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]]
// Catch HomeworkError.
// CHECK: [[IS_HWE]]:
// CHECK-NEXT: [[T0:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError
// CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]]
// Catch HomeworkError.CatAteIt.
// CHECK: [[MATCH]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: destroy_addr [[SRC_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat)
// Catch other HomeworkErrors.
// CHECK: [[NO_MATCH]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch other types.
// CHECK: [[NOT_HWE]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch all.
// CHECK: [[CATCHALL]]:
// CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: destroy_value [[ERROR]] : $Error
// CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat)
// Landing pad.
// CHECK: [[MAC_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DR_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
func all_together_now(_ flag: Bool) -> Cat {
do {
return try dont_return(flag ? make_a_cat() : dont_make_a_cat())
} catch HomeworkError.CatAteIt(let cat) {
return cat
} catch _ {
return Cat()
}
}
// Catch in non-throwing context.
// CHECK-LABEL: sil hidden @_TF6errors11catch_a_catFT_CS_3Cat : $@convention(thin) () -> @owned Cat
// CHECK-NEXT: bb0:
// CHECK: [[F:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]])
// CHECK-NEXT: return [[V]] : $Cat
func catch_a_cat() -> Cat {
do {
return Cat()
} catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
}
// Initializers.
class HasThrowingInit {
var field: Int
init(value: Int) throws {
field = value
}
}
// CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) {
// CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $HasThrowingInit
// CHECK-NEXT: assign %0 to [[T1]] : $*Int
// CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit
// CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitC{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error)
// CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit
// CHECK: [[T0:%.*]] = function_ref @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2
// CHECK: bb1([[SELF:%.*]] : $HasThrowingInit):
// CHECK-NEXT: return [[SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[ERROR]]
enum ColorError : Error {
case Red, Green, Blue
}
//CHECK-LABEL: sil hidden @_TF6errors6IThrowFzT_Vs5Int32
//CHECK: builtin "willThrow"
//CHECK-NEXT: throw
func IThrow() throws -> Int32 {
throw ColorError.Red
return 0 // expected-warning {{will never be executed}}
}
// Make sure that we are not emitting calls to 'willThrow' on rethrow sites.
//CHECK-LABEL: sil hidden @_TF6errors12DoesNotThrowFzT_Vs5Int32
//CHECK-NOT: builtin "willThrow"
//CHECK: return
func DoesNotThrow() throws -> Int32 {
_ = try IThrow()
return 2
}
// rdar://20782111
protocol Doomed {
func check() throws
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors12DoomedStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*DoomedStruct
// CHECK: [[T0:%.*]] = function_ref @_TFV6errors12DoomedStruct5check{{.*}} : $@convention(method) (DoomedStruct) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[SELF]])
// CHECK: bb1([[T0:%.*]] : $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: dealloc_stack [[TEMP]]
// CHECK: throw [[T0]] : $Error
struct DoomedStruct : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors11DoomedClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error Error {
// CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*DoomedClass
// CHECK: [[T0:%.*]] = class_method [[SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> () , $@convention(method) (@guaranteed DoomedClass) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[SELF]])
// CHECK: bb1([[T0:%.*]] : $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: destroy_value [[SELF]] : $DoomedClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: destroy_value [[SELF]] : $DoomedClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: throw [[T0]] : $Error
class DoomedClass : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors11HappyStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*HappyStruct
// CHECK: [[T0:%.*]] = function_ref @_TFV6errors11HappyStruct5check{{.*}} : $@convention(method) (HappyStruct) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T1]] : $()
struct HappyStruct : Doomed {
func check() {}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors10HappyClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*HappyClass
// CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> () , $@convention(method) (@guaranteed HappyClass) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: destroy_value [[SELF]] : $HappyClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T1]] : $()
class HappyClass : Doomed {
func check() {}
}
func create<T>(_ fn: () throws -> T) throws -> T {
return try fn()
}
func testThunk(_ fn: () throws -> Int) throws -> Int {
return try create(fn)
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSizoPs5Error__XFo__iSizoPS___ : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error)
// CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error Error)):
// CHECK: try_apply %1()
// CHECK: bb1([[T0:%.*]] : $Int):
// CHECK: store [[T0]] to [trivial] %0 : $*Int
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: return [[T0]]
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: throw [[T0]] : $Error
func createInt(_ fn: () -> Int) throws {}
func testForceTry(_ fn: () -> Int) {
try! createInt(fn)
}
// CHECK-LABEL: sil hidden @_TF6errors12testForceTryFFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> ()
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> Int):
// CHECK: [[FUNC:%.*]] = function_ref @_TF6errors9createIntFzFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: try_apply [[FUNC]]([[ARG_COPY]])
// CHECK: destroy_value [[ARG]]
// CHECK: return
// CHECK: builtin "unexpectedError"
// CHECK: unreachable
func testForceTryMultiple() {
_ = try! (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_TF6errors20testForceTryMultipleFT_T_
// CHECK-NEXT: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat)
// CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error)
// CHECK-NEXT: unreachable
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors20testForceTryMultipleFT_T_'
// Make sure we balance scopes correctly inside a switch.
// <rdar://problem/20923654>
enum CatFood {
case Canned
case Dry
}
// Something we can switch on that throws.
func preferredFood() throws -> CatFood {
return CatFood.Canned
}
func feedCat() throws -> Int {
switch try preferredFood() {
case .Canned:
return 0
case .Dry:
return 1
}
}
// CHECK-LABEL: sil hidden @_TF6errors7feedCatFzT_Si : $@convention(thin) () -> (Int, @error Error)
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: %1 = function_ref @_TF6errors13preferredFoodFzT_OS_7CatFood : $@convention(thin) () -> (CatFood, @error Error)
// CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5
// CHECK: bb1([[VAL:%.*]] : $CatFood):
// CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3
// CHECK: bb5([[ERROR:%.*]] : $Error)
// CHECK: throw [[ERROR]] : $Error
// Throwing statements inside cases.
func getHungryCat(_ food: CatFood) throws -> Cat {
switch food {
case .Canned:
return try make_a_cat()
case .Dry:
return try dont_make_a_cat()
}
}
// errors.getHungryCat throws (errors.CatFood) -> errors.Cat
// CHECK-LABEL: sil hidden @_TF6errors12getHungryCatFzOS_7CatFoodCS_3Cat : $@convention(thin) (CatFood) -> (@owned Cat, @error Error)
// CHECK: bb0(%0 : $CatFood):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3
// CHECK: bb1:
// CHECK: [[FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6
// CHECK: bb3:
// CHECK: [[FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK: br bb8([[ERROR:%.*]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK: br bb8([[ERROR]] : $Error)
// CHECK: bb8([[ERROR:%.*]] : $Error):
// CHECK: throw [[ERROR]] : $Error
func take_many_cats(_ cats: Cat...) throws {}
func test_variadic(_ cat: Cat) throws {
try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_TF6errors13test_variadicFzCS_3CatT_ : $@convention(thin) (@owned Cat) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : $Cat):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: [[TAKE_FN:%.*]] = function_ref @_TF6errors14take_many_catsFztGSaCS_3Cat__T_ : $@convention(thin) (@owned Array<Cat>) -> @error Error
// CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4
// CHECK: [[T0:%.*]] = function_ref @_TFs27_allocateUninitializedArray
// CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]])
// CHECK: [[ARRAY:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 0
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 1
// CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat
// Element 0.
// CHECK: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]]
// CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]]
// Element 1.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1
// CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]]
// Element 2.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2
// CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]]
// CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]]
// Element 3.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3
// CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]]
// CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]]
// Complete the call and return.
// CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]]
// CHECK: [[NORM_CALL]]([[T0:%.*]] : $()):
// CHECK-NEXT: destroy_value %0 : $Cat
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return
// Failure from element 0.
// CHECK: [[ERR_0]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error)
// Failure from element 2.
// CHECK: [[ERR_2]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from element 3.
// CHECK: [[ERR_3]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[ELT2]]
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from call.
// CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Rethrow.
// CHECK: [[RETHROW]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value %0 : $Cat
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors13test_variadicFzCS_3CatT_'
// rdar://20861374
// Clear out the self box before delegating.
class BaseThrowingInit : HasThrowingInit {
var subField: Int
init(value: Int, subField: Int) throws {
self.subField = subField
try super.init(value: value)
}
}
// CHECK: sil hidden @_TFC6errors16BaseThrowingInitc{{.*}} : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error)
// CHECK: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <BaseThrowingInit>
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[PB]]
// Initialize subField.
// CHECK: [[T0:%.*]] = load_borrow [[MARKED_BOX]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField
// CHECK-NEXT: assign %1 to [[T1]]
// Super delegation.
// CHECK-NEXT: [[T0:%.*]] = load_borrow [[MARKED_BOX]]
// CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit
// CHECK: [[T3:%[0-9]+]] = function_ref @_TFC6errors15HasThrowingInitcfzT5valueSi_S0_ : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: apply [[T3]](%0, [[T2]])
// Cleanups for writebacks.
protocol Supportable {
mutating func support() throws
}
protocol Buildable {
associatedtype Structure : Supportable
var firstStructure: Structure { get set }
subscript(name: String) -> Structure { get set }
}
func supportFirstStructure<B: Buildable>(_ b: inout B) throws {
try b.firstStructure.support()
}
// CHECK-LABEL: sil hidden @_TF6errors21supportFirstStructure{{.*}} : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error {
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: throw [[ERROR]]
func supportStructure<B: Buildable>(_ b: inout B, name: String) throws {
try b[name].support()
}
// CHECK-LABEL: sil hidden @_TF6errors16supportStructure
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: [[INDEX_COPY:%.*]] = copy_value [[INDEX:%1]] : $String
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[INDEX_COPY]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: destroy_value [[INDEX]] : $String
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: destroy_value [[INDEX]] : $String
// CHECK: throw [[ERROR]]
struct Pylon {
var name: String
mutating func support() throws {}
}
struct Bridge {
var mainPylon : Pylon
subscript(name: String) -> Pylon {
get {
return mainPylon
}
set {}
}
}
func supportStructure(_ b: inout Bridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_ : $@convention(thin) (@inout Bridge, @owned String) -> @error Error {
// CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support
// CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[ARG2]] : $String
// CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon
// CHECK-NEXT: [[BASE:%.*]] = load [copy] [[ARG1]] : $*Bridge
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFV6errors6Bridgeg9subscriptFSSVS_5Pylon :
// CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]])
// CHECK-NEXT: destroy_value [[BASE]]
// CHECK-NEXT: store [[T0]] to [init] [[TEMP]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[ARG1]])
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: destroy_value [[INDEX]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// We end up with ugly redundancy here because we don't want to
// consume things during cleanup emission. It's questionable.
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]]
// CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[ARG1]])
// CHECK-NEXT: destroy_addr [[TEMP]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY
// CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String
// CHECK-NEXT: destroy_value [[INDEX]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_'
struct OwnedBridge {
var owner : Builtin.UnknownObject
subscript(name: String) -> Pylon {
addressWithOwner { return (someValidPointer(), owner) }
mutableAddressWithOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout OwnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_ :
// CHECK: bb0([[ARG1:%.*]] : $*OwnedBridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors11OwnedBridgeaO9subscriptFSSVS_5Pylon :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]])
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0
// CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_'
struct PinnedBridge {
var owner : Builtin.NativeObject
subscript(name: String) -> Pylon {
addressWithPinnedNativeOwner { return (someValidPointer(), owner) }
mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout PinnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_ :
// CHECK: bb0([[ARG1:%.*]] : $*PinnedBridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors12PinnedBridgeap9subscriptFSSVS_5Pylon :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]])
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0
// CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]]
// CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: destroy_value [[OWNER]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_'
// ! peepholes its argument with getSemanticsProvidingExpr().
// Test that that doesn't look through try!.
// rdar://21515402
func testForcePeephole(_ f: () throws -> Int?) -> Int {
let x = (try! f())!
return x
}
// CHECK-LABEL: sil hidden @_TF6errors15testOptionalTryFT_T_
// CHECK-NEXT: bb0:
// CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>)
// CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>)
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors15testOptionalTryFT_T_'
func testOptionalTry() {
_ = try? make_a_cat()
}
// CHECK-LABEL: sil hidden @_TF6errors18testOptionalTryVarFT_T_
// CHECK-NEXT: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Optional<Cat>>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat)
// CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var τ_0_0 } <Optional<Cat>>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors18testOptionalTryVarFT_T_'
func testOptionalTryVar() {
var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_TF6errors26testOptionalTryAddressOnly
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return
// CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : $()):
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors26testOptionalTryAddressOnlyurFxT_'
func testOptionalTryAddressOnly<T>(_ obj: T) {
_ = try? dont_return(obj)
}
// CHECK-LABEL: sil hidden @_TF6errors29testOptionalTryAddressOnlyVar
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Optional<T>>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return
// CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : $()):
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var τ_0_0 } <Optional<T>>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors29testOptionalTryAddressOnlyVarurFxT_'
func testOptionalTryAddressOnlyVar<T>(_ obj: T) {
var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_TF6errors23testOptionalTryMultipleFT_T_
// CHECK: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat)
// CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>)
// CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>)
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_TF6errors23testOptionalTryMultipleFT_T_'
func testOptionalTryMultiple() {
_ = try? (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_TF6errors25testOptionalTryNeverFailsFT_T_
// CHECK: bb0:
// CHECK-NEXT: [[VALUE:%.+]] = tuple ()
// CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '_TF6errors25testOptionalTryNeverFailsFT_T_'
func testOptionalTryNeverFails() {
_ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @_TF6errors28testOptionalTryNeverFailsVarFT_T_
// CHECK: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Optional<()>>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var τ_0_0 } <Optional<()>>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '_TF6errors28testOptionalTryNeverFailsVarFT_T_'
func testOptionalTryNeverFailsVar() {
var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_TF6errors36testOptionalTryNeverFailsAddressOnly
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '_TF6errors36testOptionalTryNeverFailsAddressOnlyurFxT_'
func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) {
_ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @_TF6errors39testOptionalTryNeverFailsAddressOnlyVar
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Optional<T>>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var τ_0_0 } <Optional<T>>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '_TFC6errors13OtherErrorSubCfT_S0_'
func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) {
var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
class SomeErrorClass : Error { }
// CHECK-LABEL: sil_vtable SomeErrorClass
// CHECK-NEXT: #SomeErrorClass.deinit!deallocator: _TFC6errors14SomeErrorClassD
// CHECK-NEXT: #SomeErrorClass.init!initializer.1: _TFC6errors14SomeErrorClasscfT_S0_
// CHECK-NEXT: }
class OtherErrorSub : OtherError { }
// CHECK-LABEL: sil_vtable OtherErrorSub {
// CHECK-NEXT: #OtherError.init!initializer.1: _TFC6errors13OtherErrorSubcfT_S0_ // OtherErrorSub.init() -> OtherErrorSub
// CHECK-NEXT: #OtherErrorSub.deinit!deallocator: _TFC6errors13OtherErrorSubD // OtherErrorSub.__deallocating_deinit
// CHECK-NEXT:}
| apache-2.0 |
nineteen-apps/swift | lessons-02/lesson3/Sources/cpf.swift | 1 | 2451 | // -*-swift-*-
// The MIT License (MIT)
//
// Copyright (c) 2017 - Nineteen
//
// 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.
//
// Created: 2017-06-20 by Ronaldo Faria Lima
//
// This file purpose: Classe que realiza o cálculo do dígito verificador do CPF
// para verificação de sua validade.
import Foundation
struct CPF: Checksum {
let cpf: String
fileprivate var checkDigits: Int? {
return Int(cpf.substring(from: cpf.index(cpf.endIndex, offsetBy: -2)))
}
init (cpf: String) {
self.cpf = cpf
}
func isValid() -> Bool {
return checkDigits == calculateCheckDigits()
}
fileprivate func calculateCheckDigits() -> Int? {
if let firstDigit = calculateCheckDigit(for: 10), let secondDigit = calculateCheckDigit(for: 11) {
return firstDigit * 10 + secondDigit
}
return nil
}
private func calculateCheckDigit(for weight: Int) -> Int? {
var ckDigit = 0
var currWeight = weight
for i in cpf.characters.indices {
if currWeight < 1 {
break
}
if let digit = Int(String(cpf[i])) {
ckDigit += digit * currWeight
} else {
return nil
}
currWeight -= 1
}
let remainder = ckDigit % 11
ckDigit = remainder < 2 ? 0 : 11 - remainder
return ckDigit
}
}
| mit |
Seanalair/GreenAR | Example/GreenAR/ViewController.swift | 1 | 32377 | //
// ViewController.swift
// GreenAR
//
// Created by Daniel Grenier on 10/17/2017.
// Copyright (c) 2017 Daniel Grenier. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
import GreenAR
class ViewController: UIViewController, ARSCNViewDelegate, AVCaptureMetadataOutputObjectsDelegate {
let kTransitionAnimationDuration = 0.25
let kCornerNodeRadius = CGFloat(0.05)
let kDefaultRoomName = "TestRoom"
@IBOutlet var sceneView: ARSCNView!
@IBOutlet var startingFooter: UIView!
@IBOutlet var mappingFooter: UIView!
@IBOutlet var shareTypeFooter: UIView!
@IBOutlet var referenceTypeFooter: UIView!
@IBOutlet var referenceSelectFooter: UIView!
@IBOutlet var finishedFooter: UIView!
@IBOutlet var failedFooter: UIView!
@IBOutlet var mappingBackButton: UIButton!
@IBOutlet var mappingDoneButton: UIButton!
@IBOutlet var referencePositionDoneButton: UIButton!
@IBOutlet var finishedFooterShareButton: UIView!
@IBOutlet var referenceSelectLabel: UILabel!
@IBOutlet var finishedLabel: UILabel!
@IBOutlet var failedLabel: UILabel!
enum AppState: String {
case PreInitialization
case StartScreen
case Mapping
case ShareTypeSelect
case ReferenceTypeSelect
case ReferencePositionSelect
case Finished
case Failed
}
enum ShareType: String {
case NearbyDevice
case LocalFile
}
enum ReferenceType: String {
case DeviceLocation
case ObjectLocation
case QRCodeLocation
}
var appState: AppState = .PreInitialization
var shareType: ShareType?
var referenceType: ReferenceType?
var wallCornerNodes = [SCNNode]()
var referencePositionNode: SCNNode?
var qrCodeText: String?
var qrCodePosition: SCNVector3?
var referencePosition: SCNVector3?
var roomMapping: RoomMapping?
var multipeerManager: MultipeerManager?
override func viewDidLoad() {
super.viewDidLoad()
sceneView.showsStatistics = false
// Set the view's delegate
sceneView.delegate = self
layoutFooterView(startingFooter)
layoutFooterView(mappingFooter)
layoutFooterView(referenceTypeFooter)
layoutFooterView(shareTypeFooter)
layoutFooterView(referenceSelectFooter)
layoutFooterView(finishedFooter)
layoutFooterView(failedFooter)
startingFooter.alpha = 1
let tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(self.sceneViewTapped(_:)))
sceneView.addGestureRecognizer(tapRecognizer)
updateAppState(.StartScreen)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
configuration.worldAlignment = .gravityAndHeading
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
func layoutFooterView(_ footerView: UIView) {
footerView.frame.origin = CGPoint(x:0, y:sceneView.bounds.height - footerView.bounds.height)
footerView.frame.size.width = self.view.frame.size.width
sceneView.addSubview(footerView)
footerView.alpha = 0
}
@IBAction func createRoomButtonTapped(_ sender: UIButton) {
updateAppState(.Mapping)
}
@IBAction func loadRoomButtonTapped(_ sender: UIButton) {
updateAppState(.ShareTypeSelect)
}
@IBAction func mappingBackButtonTapped(_ sender: UIButton) {
if (wallCornerNodes.count > 0) {
wallCornerNodes.last!.removeFromParentNode()
wallCornerNodes.removeLast()
if (wallCornerNodes.count < 4) {
mappingDoneButton.alpha = 0.25
mappingDoneButton.isUserInteractionEnabled = false
}
} else {
updateAppState(.StartScreen)
}
}
@IBAction func mappingFinishedButtonTapped(_ sender: UIButton) {
var corners = [SCNVector3]()
for cornerNode in wallCornerNodes {
corners.append(cornerNode.position)
}
if let newRoomMapping = RoomMapping.init(floorCorners: corners) {
roomMapping = newRoomMapping
sceneView.scene.rootNode.addChildNode(roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
updateAppState(.ShareTypeSelect)
}
}
@IBAction func nearbyDeviceButtonTapped(_ sender: UIButton) {
shareType = .NearbyDevice
updateAppState(.ReferenceTypeSelect)
}
@IBAction func localFileButtonTapped(_ sender: UIButton) {
shareType = .LocalFile
updateAppState(.ReferenceTypeSelect)
}
@IBAction func shareTypeBackButtonTapped(_ sender: UIButton) {
if (roomMapping != nil) {
updateAppState(.Mapping)
mappingDoneButton.alpha = 1
mappingDoneButton.isUserInteractionEnabled = true
} else {
updateAppState(.StartScreen)
}
}
@IBAction func deviceLocationButtonTapped(_ sender: UIButton) {
referenceType = .DeviceLocation
updateAppState(.ReferencePositionSelect)
}
@IBAction func objectLocationButtonTapped(_ sender: UIButton) {
referenceType = .ObjectLocation
updateAppState(.ReferencePositionSelect)
}
@IBAction func qrCodeLocationButtonTapped(_ sender: UIButton) {
referenceType = .QRCodeLocation
updateAppState(.ReferencePositionSelect)
}
@IBAction func referenceTypeBackButtonTapped(_ sender: UIButton) {
shareType = nil
updateAppState(.ShareTypeSelect)
}
@IBAction func referencePositionBackButtonTapped(_ sender: UIButton) {
if (referencePositionNode != nil) {
referencePositionNode?.removeFromParentNode()
referencePositionNode = nil
}
referencePosition = nil
referenceType = nil
updateAppState(.ReferenceTypeSelect)
}
@IBAction func referencePositionDoneButtonTapped(_ sender: UIButton) {
switch referenceType! {
case .DeviceLocation:
referencePosition = sceneView.pointOfView!.position
if (roomMapping != nil) {
roomMapping!.referencePosition = referencePosition
MappingManager.saveRoomMapping(roomMapping!, fileName: kDefaultRoomName)
updateAppState(.Finished)
if (shareType == .NearbyDevice) {
multipeerManager = MultipeerManager(fileToSend: kDefaultRoomName, completion: { (success) in
if (success) {
print("Room sent successfully.")
} else {
print("Failed to send room.")
self.updateAppState(.Failed)
}
self.multipeerManager!.disconnect()
self.multipeerManager = nil
})
}
} else {
if (shareType == .NearbyDevice) {
multipeerManager = MultipeerManager(targetFileLocation: kDefaultRoomName, completion: { (success) in
if (success) {
print("Room received successfully.")
if let newRoomMapping = MappingManager.loadRoomMapping(fileName: self.kDefaultRoomName,
referencePosition: self.referencePosition!) {
self.roomMapping = newRoomMapping
self.sceneView.scene.rootNode.addChildNode(self.roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
self.updateAppState(.Finished)
self.finishedLabel.text = "Room received! At this point, the clients could continue communicating to facilitate real-time multiplayer (with all locations relative to the reference point)"
} else {
self.updateAppState(.Failed)
}
} else {
print("Failed to receive room.")
self.updateAppState(.Failed)
}
self.multipeerManager!.disconnect()
self.multipeerManager = nil
})
} else {
if let newRoomMapping = MappingManager.loadRoomMapping(fileName: kDefaultRoomName,
referencePosition: referencePosition!) {
roomMapping = newRoomMapping
sceneView.scene.rootNode.addChildNode(roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
updateAppState(.Finished)
finishedLabel.text = "Room loaded and interpreted successfully! To share this room with a nearby device, tap the share button."
finishedFooterShareButton.alpha = 1
finishedFooterShareButton.isUserInteractionEnabled = true
} else {
updateAppState(.Failed)
}
}
}
case .ObjectLocation:
if (referencePositionNode != nil) {
referencePosition = referencePositionNode!.position
if (roomMapping != nil) {
roomMapping!.referencePosition = referencePosition
MappingManager.saveRoomMapping(roomMapping!, fileName: kDefaultRoomName)
updateAppState(.Finished)
if (shareType == .NearbyDevice) {
multipeerManager = MultipeerManager(fileToSend: kDefaultRoomName, completion: { (success) in
if (success) {
print("Room sent successfully.")
} else {
print("Failed to send room.")
self.updateAppState(.Failed)
}
self.multipeerManager!.disconnect()
self.multipeerManager = nil
})
}
} else {
if (shareType == .NearbyDevice) {
multipeerManager = MultipeerManager(targetFileLocation: kDefaultRoomName, completion: { (success) in
if (success) {
print("Room received successfully.")
if let newRoomMapping = MappingManager.loadRoomMapping(fileName: self.kDefaultRoomName,
referencePosition: self.referencePosition!) {
self.roomMapping = newRoomMapping
self.sceneView.scene.rootNode.addChildNode(self.roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
self.updateAppState(.Finished)
self.finishedLabel.text = "Room received! At this point, the clients could continue communicating to facilitate real-time multiplayer (with all locations relative to the reference point)"
} else {
self.updateAppState(.Failed)
}
} else {
print("Failed to receive room.")
self.updateAppState(.Failed)
}
self.multipeerManager!.disconnect()
self.multipeerManager = nil
})
} else {
if let newRoomMapping = MappingManager.loadRoomMapping(fileName: kDefaultRoomName,
referencePosition: referencePosition!) {
roomMapping = newRoomMapping
sceneView.scene.rootNode.addChildNode(roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
updateAppState(.Finished)
finishedLabel.text = "Room loaded and interpreted successfully! To share this room with a nearby device, tap the share button."
finishedFooterShareButton.alpha = 1
finishedFooterShareButton.isUserInteractionEnabled = true
} else {
updateAppState(.Failed)
}
}
}
}
case .QRCodeLocation:
if (referencePositionNode != nil) {
referencePosition = referencePositionNode!.position
if (roomMapping != nil) {
roomMapping!.referencePosition = referencePosition
MappingManager.saveRoomMapping(roomMapping!, fileName: qrCodeText!)
updateAppState(.Finished)
if (shareType == .NearbyDevice) {
multipeerManager = MultipeerManager(fileToSend: qrCodeText!, completion: { (success) in
if (success) {
print("Room sent successfully.")
} else {
print("Failed to send room.")
self.updateAppState(.Failed)
}
self.multipeerManager!.disconnect()
self.multipeerManager = nil
})
}
} else {
if (shareType == .NearbyDevice) {
multipeerManager = MultipeerManager(targetFileLocation: qrCodeText!, completion: { (success) in
if (success) {
print("Room received successfully.")
if let newRoomMapping = MappingManager.loadRoomMapping(fileName: self.qrCodeText!,
referencePosition: self.referencePosition!) {
self.roomMapping = newRoomMapping
self.sceneView.scene.rootNode.addChildNode(self.roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
self.updateAppState(.Finished)
self.finishedLabel.text = "Room received! At this point, the clients could continue communicating to facilitate real-time multiplayer (with all locations relative to the reference point)"
} else {
self.updateAppState(.Failed)
}
} else {
print("Failed to receive room.")
self.updateAppState(.Failed)
}
self.multipeerManager!.disconnect()
self.multipeerManager = nil
})
} else {
if let newRoomMapping = MappingManager.loadRoomMapping(fileName: qrCodeText!,
referencePosition: referencePosition!) {
roomMapping = newRoomMapping
sceneView.scene.rootNode.addChildNode(roomMapping!.createMappingNode(cornerInsetDistance:0.25,
visible: true))
updateAppState(.Finished)
finishedLabel.text = "Room loaded and interpreted successfully! To share this room with a nearby device, tap the share button."
finishedFooterShareButton.alpha = 1
finishedFooterShareButton.isUserInteractionEnabled = true
} else {
updateAppState(.Failed)
}
}
}
}
}
}
@IBAction func finishedFooterShareButtonTapped(_ sender: UIButton) {
referenceType = nil
referencePosition = nil
shareType = .NearbyDevice
updateAppState(.ReferenceTypeSelect)
}
func metadataOutput(_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection) {
}
func testStateChangeValidity(_ oldAppState: AppState, newAppState: AppState) {
var validStateChange = false
switch newAppState {
case .PreInitialization:
break
case .StartScreen:
validStateChange = (oldAppState == .PreInitialization ||
oldAppState == .Mapping ||
oldAppState == .ShareTypeSelect)
case .Mapping:
validStateChange = (oldAppState == .StartScreen)
case .ShareTypeSelect:
validStateChange = (oldAppState == .StartScreen ||
oldAppState == .Mapping ||
oldAppState == .ReferenceTypeSelect)
case .ReferenceTypeSelect:
validStateChange = (oldAppState == .ShareTypeSelect ||
oldAppState == .ReferencePositionSelect ||
oldAppState == .Finished)
case .ReferencePositionSelect:
validStateChange = (oldAppState == .ReferenceTypeSelect)
case .Finished:
validStateChange = (oldAppState == .ReferencePositionSelect)
case .Failed:
validStateChange = (oldAppState == .ReferencePositionSelect)
}
assert(validStateChange, "Attempted invalid appState transition - old state: \(oldAppState.rawValue) new state: \(newAppState.rawValue)")
}
func updateAppState(_ newAppState: AppState) {
let oldAppState = appState
if (oldAppState == newAppState) {
return
}
testStateChangeValidity(oldAppState, newAppState:newAppState)
self.startingFooter.isUserInteractionEnabled = false
self.mappingFooter.isUserInteractionEnabled = false
self.shareTypeFooter.isUserInteractionEnabled = false
self.referenceTypeFooter.isUserInteractionEnabled = false
self.referenceSelectFooter.isUserInteractionEnabled = false
self.mappingDoneButton.alpha = 0.25
self.mappingDoneButton.isUserInteractionEnabled = false
self.referencePositionDoneButton.alpha = 0.25
self.referencePositionDoneButton.isUserInteractionEnabled = false
finishedFooterShareButton.alpha = 0
finishedFooterShareButton.isUserInteractionEnabled = false
switch newAppState {
case .PreInitialization:
break
case .StartScreen:
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.mappingFooter.alpha = 0
self.shareTypeFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.startingFooter.alpha = 1
}) { (completed) in
self.startingFooter.isUserInteractionEnabled = true
}
}
case .Mapping:
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.startingFooter.alpha = 0
self.shareTypeFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.mappingFooter.alpha = 1
}) { (completed) in
self.mappingFooter.isUserInteractionEnabled = true
}
}
case .ShareTypeSelect:
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.startingFooter.alpha = 0
self.mappingFooter.alpha = 0
self.referenceTypeFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.shareTypeFooter.alpha = 1
}) { (completed) in
self.shareTypeFooter.isUserInteractionEnabled = true
}
}
case .ReferenceTypeSelect:
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.finishedFooter.alpha = 0
self.shareTypeFooter.alpha = 0
self.referenceSelectFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.referenceTypeFooter.alpha = 1
}) { (completed) in
self.referenceTypeFooter.isUserInteractionEnabled = true
}
}
case .ReferencePositionSelect:
if (roomMapping != nil) {
switch referenceType! {
case .DeviceLocation:
referencePositionDoneButton.alpha = 1
referencePositionDoneButton.isUserInteractionEnabled = true
if (shareType == .NearbyDevice) {
referenceSelectLabel.text = "Set your device down, tap the done button, and set the receiving device on top of it."
} else {
referenceSelectLabel.text = "Place your device in a memorable and easily reproduced location, such as in the corner of a table, and tap the done button."
}
case .ObjectLocation:
referenceSelectLabel.text = "Tap on an object in the world until you get a good collision result (represented by a green ball on the object), and tap the done button."
case .QRCodeLocation:
referenceSelectLabel.text = "Tap on a QRCode in the world until you get a good read (indicated by a green ball on the code), and tap the done button."
}
} else {
switch referenceType! {
case .DeviceLocation:
referencePositionDoneButton.alpha = 1
referencePositionDoneButton.isUserInteractionEnabled = true
if (shareType == .NearbyDevice) {
referenceSelectLabel.text = "Set your device down on top of the device sharing a room and tap the done button."
} else {
referenceSelectLabel.text = "Place your device in the same location you did to save the room and tap the done button."
}
case .ObjectLocation:
referenceSelectLabel.text = "Tap on the object you used as a reference when you saved the room. Try to get the green ball to be in the same spot as before, then tap the done button."
case .QRCodeLocation:
referenceSelectLabel.text = "Tap on the QR Code you used to save the room. When you see a green ball indicating a successful read, tap the done button."
}
}
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.referenceTypeFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.referenceSelectFooter.alpha = 1
}) { (completed) in
self.referenceSelectFooter.isUserInteractionEnabled = true
}
}
case .Finished:
if (roomMapping != nil) {
switch referenceType! {
case .DeviceLocation:
if (shareType == .NearbyDevice) {
finishedLabel.text = "Without moving this device, set the other device on top of it and step through the load room prompts."
} else {
finishedLabel.text = "You're all set! Close the app and reopen it to see how loading the room works."
}
case .ObjectLocation:
if (shareType == .NearbyDevice) {
finishedLabel.text = "Have the other device step through the loading prompts and choose the same reference object (without moving it)."
} else {
finishedLabel.text = "You're all set! Close the app and reopen it to see how loading the room works."
}
case .QRCodeLocation:
if (shareType == .NearbyDevice) {
finishedLabel.text = "Have the other device step through the loading prompts and choose the same reference QR Code (without moving it)."
} else {
finishedLabel.text = "You're all set! Close the app and reopen it to see how loading the room works."
}
}
}
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.referenceSelectFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.finishedFooter.alpha = 1
}) { (completed) in
}
}
case .Failed:
failedLabel.text = "Something went wrong when saving or loading the room mapping. Please create an issue on the github repo explaining how you got to this state so I can try to fix the problem."
UIView.animate(withDuration: kTransitionAnimationDuration, animations: {
self.referenceSelectFooter.alpha = 0
}) { (completed) in
UIView.animate(withDuration: self.kTransitionAnimationDuration,
animations: {
self.failedFooter.alpha = 1
}) { (completed) in
}
}
}
appState = newAppState
}
// MARK - Scene tapped
@objc func sceneViewTapped(_ tapGestureRecognizer: UITapGestureRecognizer) {
let pointInView = tapGestureRecognizer.location(in: sceneView)
if (appState == .Mapping) {
let results = sceneView.hitTest(pointInView, types: .featurePoint)
if let hitTestResult = results.first {
print(hitTestResult.distance, hitTestResult.worldTransform)
createWallCornerNode(hitTestResult.worldTransform)
mappingBackButton.alpha = 1
mappingBackButton.isUserInteractionEnabled = true
if (wallCornerNodes.count >= 4) {
mappingDoneButton.alpha = 1
mappingDoneButton.isUserInteractionEnabled = true
}
}
} else if (appState == .ReferencePositionSelect && referenceType == .ObjectLocation) {
let results = sceneView.hitTest(pointInView, types: .featurePoint)
if let hitTestResult = results.first {
let x = hitTestResult.worldTransform[3][0]
let y = hitTestResult.worldTransform[3][1]
let z = hitTestResult.worldTransform[3][2]
createReferencePositionNode(SCNVector3(x, y, z))
self.referencePositionDoneButton.alpha = 1
self.referencePositionDoneButton.isUserInteractionEnabled = true
}
} else if (appState == .ReferencePositionSelect && referenceType == .QRCodeLocation) {
(qrCodeText, qrCodePosition) = QRCodeLocator.captureAndLocateQRCode(sceneView: sceneView)
if let codePosition = qrCodePosition {
createReferencePositionNode(codePosition)
self.referencePositionDoneButton.alpha = 1
self.referencePositionDoneButton.isUserInteractionEnabled = true
}
}
}
func createWallCornerNode(_ worldTransform:matrix_float4x4) {
let ballGeometry = SCNSphere(radius: kCornerNodeRadius)
ballGeometry.materials.first?.diffuse.contents = UIColor.white
let newCornerNode = SCNNode(geometry: ballGeometry)
newCornerNode.simdWorldTransform = worldTransform
newCornerNode.opacity = 0.25
sceneView.scene.rootNode.addChildNode(newCornerNode)
wallCornerNodes.append(newCornerNode)
}
func createReferencePositionNode(_ position:SCNVector3) {
if (referencePositionNode != nil) {
referencePositionNode?.removeFromParentNode()
referencePositionNode = nil
}
let ballGeometry = SCNSphere(radius: kCornerNodeRadius)
ballGeometry.materials.first?.diffuse.contents = UIColor.green
referencePositionNode = SCNNode(geometry: ballGeometry)
referencePositionNode!.position = position
referencePositionNode!.opacity = 0.5
sceneView.scene.rootNode.addChildNode(referencePositionNode!)
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| mit |
ephread/Instructions | Sources/Instructions/Helpers/Internal/Enums/CoachMarkPosition.swift | 2 | 587 | // Copyright (c) 2015-present Frédéric Maquin <fred@ephread.com> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
/// Define the horizontal position of the coach mark.
enum CoachMarkPosition {
var layoutAttribute: NSLayoutConstraint.Attribute {
switch self {
case .leading: return .leading
case .center: return .centerX
case .trailing: return .trailing
}
}
case leading
case center
case trailing
}
/// Define the horizontal position of the arrow.
typealias ArrowPosition = CoachMarkPosition
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/27765-swift-typechecker-typecheckpatternbinding.swift | 4 | 294 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a<T where h:b{let:{{
class d{
let f={t}}}}class B{let a{
b
f{}}class b<a
| apache-2.0 |
DrawKit/DrawKit | DrawKitSwift/DKGeometryUtilitiesAdditions.swift | 1 | 1821 | //
// DKGeometryUtilitiesAdditions.swift
// DrawKitSwift
//
// Created by C.W. Betts on 3/8/18.
// Copyright © 2018 DrawKit. All rights reserved.
//
import DKDrawKit.DKGeometryUtilities
@available(*, unavailable, renamed: "UnionOfRects(in:)")
public func UnionOfRectsInSet(_ aSet: [NSRect]) -> NSRect {
fatalError("Unavailable function \(#function) called!")
}
/// Returns the smallest rect that encloses all rects in the array.
/// - parameter aSet: An array of `NSRect`s.
/// - returns: The rectangle that encloses all rects.
public func UnionOfRects(in aSet: [NSRect]) -> NSRect {
var ur = NSRect.zero
for val in aSet {
ur = UnionOfTwoRects(ur, val)
}
return ur
}
/// Returns the area that is different between two input rects, as a list of rects
///
/// This can be used to optimize upates. If `a` and `b` are "before and after" rects of a visual change,
/// the resulting list is the area to update assuming that nothing changed in the common area,
/// which is frequently so. If a and b are equal, the result is empty. If `a` and `b` do not intersect,
/// the result contains `a` and `b`.
/// - parameter a: The first rect.
/// - parameter b: The second rect.
/// - returns: An array of `NSRect`s. The values are in no particular order.
public func DifferenceOfTwoRects(_ a: NSRect, _ b: NSRect) -> [NSRect] {
let preRetVal = __DifferenceOfTwoRects(a, b)
return preRetVal.map({$0.rectValue})
}
/// Subtracts `b` from `a`, returning the pieces left over.
///
/// Subtracts `b` from `a`, returning the pieces left over. If `a` and `b` don't intersect, the result is correct
/// but unnecessary, so the caller should test for intersection first.
public func SubtractTwoRects(_ a: NSRect, _ b: NSRect) -> [NSRect] {
let preRetVal = __SubtractTwoRects(a, b)
return preRetVal.map({$0.rectValue})
}
| mpl-2.0 |
momotofu/UI-Color-Picker---Swift | ColorPicker/StateSwitcher.swift | 1 | 7441 | //
// StateSwitcher.swift
// ColorPicker
//
// Created by Christopher REECE on 2/4/15.
// Copyright (c) 2015 Christopher Reece. All rights reserved.
//
import UIKit
// declare swatch protocol
protocol StateSwitcherDelegate: class {
var state: HSBA {get set}
}
class StateSwitcher: UIView {
private var _state: HSBA = .hue
private let _nib: Shape!
private var _nibClosestSlot: Shape?
weak private var _timer: NSTimer?
weak var Delegate:StateSwitcherDelegate?
// drawing properties
let width: CGFloat!
let height: CGFloat!
let circleSize: CGFloat!
// declare x axis variables
let hueX: CGFloat!
let satX: CGFloat!
let briX: CGFloat!
let alpX: CGFloat!
override func drawRect(rect: CGRect) {
let context: CGContext = UIGraphicsGetCurrentContext()
// background drawing
if width > height {
// draw path for sliders
CGContextMoveToPoint(context, height / 4, height / 4 + 2)
CGContextAddLineToPoint(context, width - (height / 4) + 1, height / 4 + 2)
CGContextAddLineToPoint(context, width - (height / 4) + 1, height - (height / 4) - 1)
CGContextAddLineToPoint(context, height / 4, height - (height / 4) - 1)
CGContextClosePath(context)
CGContextSetFillColorWithColor(context, UIColor.darkGrayColor().CGColor)
CGContextDrawPath(context, kCGPathFill)
} else {
// draw path for sliders
CGContextMoveToPoint(context, width / 4, width / 4)
CGContextAddLineToPoint(context, height - (width / 4), width / 4)
CGContextAddLineToPoint(context, height - (width / 4), width - (width / 4))
CGContextAddLineToPoint(context, width / 4, width - (width / 4))
CGContextClosePath(context)
CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor)
CGContextDrawPath(context, kCGPathFill)
}
}
override init(frame: CGRect) {
// drawing properties
width = max(frame.width, frame.height)
height = min(frame.width, frame.height)
circleSize = height! * 0.95
// declare x axis variables
hueX = 0
satX = width! / 4 + circleSize! / 2
briX = width! / 2 + circleSize!
alpX = width! - height!
let nobSize = circleSize * 0.7
let slotPoints = [hueX, satX, briX, alpX]
// create a nob
let nibFrame = CGRectMake(0, 0, height, height)
let nibColor = UIColor(white: 1, alpha: 0.9)
_nib = Shape(frame: nibFrame, setColor: nibColor, shape: .circle, multiplier: 0.6, state: HSBA(rawValue: 1)!)
super.init(frame: frame)
// create slots
for i in 0...3 {
let frame = CGRectMake(slotPoints[i], 0, height, height)
let slotColor = UIColor.darkGrayColor()
let hueSlot: Shape = Shape(frame: frame, setColor: slotColor, shape: .circle, multiplier: 1, state: HSBA(rawValue: i + 1)!)
addSubview(hueSlot)
}
addSubview(_nib)
backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
if let touch = touches.first as? UITouch
{
let touchPoint = touch.locationInView(self)
for view in subviews {
if CGRectContainsPoint(view.frame, touchPoint) {
_nib!.shapeState = (view as! Shape).shapeState
println("shape: \(_nib.shapeState.rawValue)")
}
}
_nib!.center.x = touchPoint.x
pointLimitations(_nib!, comparingPoint: touchPoint)
Delegate?.state = _nib.shapeState
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)
{
if let touch = touches.first as? UITouch
{
let touchPoint = touch.locationInView(self)
for view in subviews {
if CGRectContainsPoint(view.frame, touchPoint) {
_nib!.shapeState = (view as! Shape).shapeState
}
}
_nib!.center.x = touchPoint.x
pointLimitations(_nib!, comparingPoint: touchPoint)
Delegate?.state = _nib.shapeState
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent)
{
if let touch = touches.first as? UITouch
{
let touchPoint = touch.locationInView(self)
for view in subviews {
if _nibClosestSlot == nil {
checkDistanceBetween(_nib, and: (view as! Shape))
}
}
}
}
func pointLimitations(shape: Shape?, comparingPoint: CGPoint)
{
if shape!.center.x >= width - height {
shape!.frame.origin.x = width - height
} else if shape!.center.x < 0 {
shape!.frame.origin.x = 0
}
}
func checkDistanceBetween(nib: Shape?, and slot:Shape)
{
let xDif = nib!.center.x - slot.center.x
let distance = abs(xDif)
if distance <= width / 6 {
_nibClosestSlot = slot
let myRunLoop = NSRunLoop.currentRunLoop()
let animationTimer = NSTimer(timeInterval: 0.025, target: self, selector: "gravitate:", userInfo: nil, repeats: true)
myRunLoop.addTimer(animationTimer, forMode: NSDefaultRunLoopMode)
println("timer should have fired")
}
}
func gravitate(timer: NSTimer)
{
// if _nib!.center.x != _nibClosestSlot!.center.x {
// if _nib!.center.x != _nibClosestSlot!.center.x {
// get quadrant of _nib
let nib = _nib!.center
let neb = _nibClosestSlot!.center
var angle = atan2f(Float(nib.y - neb.y), Float(nib.x - neb.x))
let gravity = CGFloat(Forces.gravity)
_nib!.center.x += CGFloat(cosf(angle) * -1) * gravity
Forces.gravity *= 1.05
let nibPoint = CGPointMake(_nib!.center.x, _nib!.center.y)
if CGRectContainsPoint(_nibClosestSlot!.frame, nibPoint) {
_nib!.center = neb
_nib!.shapeState = _nibClosestSlot!.shapeState
Delegate?.state = _nib.shapeState
timer.invalidate()
_nibClosestSlot = nil
Forces.gravity = 1.0
}
// }
println("gravitate fired")
}
struct Forces
{
static private var _gravity: Float = 1.0
static var gravity: Float {
get {
return _gravity
} set {
_gravity = newValue
}
}
}
}
| cc0-1.0 |
habr/ChatTaskAPI | IQKeyboardManager/Demo/Swift_Demo/ViewController/ScrollViewController.swift | 15 | 2261 | //
// ScrollViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import Foundation
import UIKit
class ScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet private var scrollViewDemo : UIScrollView!
@IBOutlet private var simpleTableView : UITableView!
@IBOutlet private var scrollViewOfTableViews : UIScrollView!
@IBOutlet private var tableViewInsideScrollView : UITableView!
@IBOutlet private var scrollViewInsideScrollView : UIScrollView!
@IBOutlet private var topTextField : UITextField!
@IBOutlet private var bottomTextField : UITextField!
@IBOutlet private var topTextView : UITextView!
@IBOutlet private var bottomTextView : UITextView!
override func viewDidLoad() {
super.viewDidLoad()
scrollViewDemo.contentSize = CGSizeMake(0, 321)
scrollViewInsideScrollView.contentSize = CGSizeMake(0,321)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "\(indexPath.section) \(indexPath.row)"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)
cell?.selectionStyle = UITableViewCellSelectionStyle.None
cell?.backgroundColor = UIColor.clearColor()
let textField = UITextField(frame: CGRectInset(cell!.contentView.bounds, 5, 5))
textField.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleWidth]
textField.placeholder = identifier
textField.borderStyle = UITextBorderStyle.RoundedRect
cell?.contentView.addSubview(textField)
}
return cell!
}
override func shouldAutorotate() -> Bool {
return true
}
}
| mit |
LoveZYForever/HXWeiboPhotoPicker | Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift | 3 | 3967 | //
// KFImageRenderer.swift
// Kingfisher
//
// Created by onevcat on 2021/05/08.
//
// Copyright (c) 2021 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(SwiftUI) && canImport(Combine)
import SwiftUI
import Combine
/// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`.
/// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
struct KFImageRenderer<HoldingView> : View where HoldingView: KFImageHoldingView {
@StateObject var binder: KFImage.ImageBinder = .init()
let context: KFImage.Context<HoldingView>
var body: some View {
ZStack {
context.configurations
.reduce(HoldingView.created(from: binder.loadedImage, context: context)) {
current, config in config(current)
}
.opacity(binder.loaded ? 1.0 : 0.0)
if binder.loadedImage == nil {
Group {
if let placeholder = context.placeholder, let view = placeholder(binder.progress) {
view
} else {
Color.clear
}
}
.onAppear { [weak binder = self.binder] in
guard let binder = binder else {
return
}
if !binder.loadingOrSucceeded {
binder.start(context: context)
}
}
.onDisappear { [weak binder = self.binder] in
guard let binder = binder else {
return
}
if context.cancelOnDisappear {
binder.cancel()
}
}
}
}
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension Image {
// Creates an Image with either UIImage or NSImage.
init(crossPlatformImage: KFCrossPlatformImage?) {
#if canImport(UIKit)
self.init(uiImage: crossPlatformImage ?? KFCrossPlatformImage())
#elseif canImport(AppKit)
self.init(nsImage: crossPlatformImage ?? KFCrossPlatformImage())
#endif
}
}
#if canImport(UIKit)
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension UIImage.Orientation {
func toSwiftUI() -> Image.Orientation {
switch self {
case .down: return .down
case .up: return .up
case .left: return .left
case .right: return .right
case .upMirrored: return .upMirrored
case .downMirrored: return .downMirrored
case .leftMirrored: return .leftMirrored
case .rightMirrored: return .rightMirrored
@unknown default: return .up
}
}
}
#endif
#endif
| mit |
chernyog/SQLite-Note | SQLite/SQLiteTests/SQLiteTests.swift | 1 | 890 | //
// SQLiteTests.swift
// SQLiteTests
//
// Created by 陈勇 on 15/3/15.
// Copyright (c) 2015年 zhssit. All rights reserved.
//
import UIKit
import XCTest
class SQLiteTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Octadero/TensorFlow | Sources/Proto/tools/api/lib/api_objects.pb.swift | 1 | 19677 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: tensorflow/tools/api/lib/api_objects.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public struct ThirdParty_Tensorflow_Tools_Api_TFAPIMember {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var name: String {
get {return _name ?? String()}
set {_name = newValue}
}
/// Returns true if `name` has been explicitly set.
public var hasName: Bool {return self._name != nil}
/// Clears the value of `name`. Subsequent reads from it will return its default value.
public mutating func clearName() {self._name = nil}
public var mtype: String {
get {return _mtype ?? String()}
set {_mtype = newValue}
}
/// Returns true if `mtype` has been explicitly set.
public var hasMtype: Bool {return self._mtype != nil}
/// Clears the value of `mtype`. Subsequent reads from it will return its default value.
public mutating func clearMtype() {self._mtype = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _name: String? = nil
fileprivate var _mtype: String? = nil
}
public struct ThirdParty_Tensorflow_Tools_Api_TFAPIMethod {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var name: String {
get {return _name ?? String()}
set {_name = newValue}
}
/// Returns true if `name` has been explicitly set.
public var hasName: Bool {return self._name != nil}
/// Clears the value of `name`. Subsequent reads from it will return its default value.
public mutating func clearName() {self._name = nil}
public var path: String {
get {return _path ?? String()}
set {_path = newValue}
}
/// Returns true if `path` has been explicitly set.
public var hasPath: Bool {return self._path != nil}
/// Clears the value of `path`. Subsequent reads from it will return its default value.
public mutating func clearPath() {self._path = nil}
public var argspec: String {
get {return _argspec ?? String()}
set {_argspec = newValue}
}
/// Returns true if `argspec` has been explicitly set.
public var hasArgspec: Bool {return self._argspec != nil}
/// Clears the value of `argspec`. Subsequent reads from it will return its default value.
public mutating func clearArgspec() {self._argspec = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _name: String? = nil
fileprivate var _path: String? = nil
fileprivate var _argspec: String? = nil
}
public struct ThirdParty_Tensorflow_Tools_Api_TFAPIModule {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var member: [ThirdParty_Tensorflow_Tools_Api_TFAPIMember] = []
public var memberMethod: [ThirdParty_Tensorflow_Tools_Api_TFAPIMethod] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
public struct ThirdParty_Tensorflow_Tools_Api_TFAPIClass {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var isInstance: [String] = []
public var member: [ThirdParty_Tensorflow_Tools_Api_TFAPIMember] = []
public var memberMethod: [ThirdParty_Tensorflow_Tools_Api_TFAPIMethod] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
public struct ThirdParty_Tensorflow_Tools_Api_TFAPIProto {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var descriptor: Google_Protobuf_DescriptorProto {
get {return _storage._descriptor ?? Google_Protobuf_DescriptorProto()}
set {_uniqueStorage()._descriptor = newValue}
}
/// Returns true if `descriptor` has been explicitly set.
public var hasDescriptor: Bool {return _storage._descriptor != nil}
/// Clears the value of `descriptor`. Subsequent reads from it will return its default value.
public mutating func clearDescriptor() {_storage._descriptor = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
public struct ThirdParty_Tensorflow_Tools_Api_TFAPIObject {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var path: String {
get {return _storage._path ?? String()}
set {_uniqueStorage()._path = newValue}
}
/// Returns true if `path` has been explicitly set.
public var hasPath: Bool {return _storage._path != nil}
/// Clears the value of `path`. Subsequent reads from it will return its default value.
public mutating func clearPath() {_storage._path = nil}
public var tfModule: ThirdParty_Tensorflow_Tools_Api_TFAPIModule {
get {return _storage._tfModule ?? ThirdParty_Tensorflow_Tools_Api_TFAPIModule()}
set {_uniqueStorage()._tfModule = newValue}
}
/// Returns true if `tfModule` has been explicitly set.
public var hasTfModule: Bool {return _storage._tfModule != nil}
/// Clears the value of `tfModule`. Subsequent reads from it will return its default value.
public mutating func clearTfModule() {_storage._tfModule = nil}
public var tfClass: ThirdParty_Tensorflow_Tools_Api_TFAPIClass {
get {return _storage._tfClass ?? ThirdParty_Tensorflow_Tools_Api_TFAPIClass()}
set {_uniqueStorage()._tfClass = newValue}
}
/// Returns true if `tfClass` has been explicitly set.
public var hasTfClass: Bool {return _storage._tfClass != nil}
/// Clears the value of `tfClass`. Subsequent reads from it will return its default value.
public mutating func clearTfClass() {_storage._tfClass = nil}
public var tfProto: ThirdParty_Tensorflow_Tools_Api_TFAPIProto {
get {return _storage._tfProto ?? ThirdParty_Tensorflow_Tools_Api_TFAPIProto()}
set {_uniqueStorage()._tfProto = newValue}
}
/// Returns true if `tfProto` has been explicitly set.
public var hasTfProto: Bool {return _storage._tfProto != nil}
/// Clears the value of `tfProto`. Subsequent reads from it will return its default value.
public mutating func clearTfProto() {_storage._tfProto = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "third_party.tensorflow.tools.api"
extension ThirdParty_Tensorflow_Tools_Api_TFAPIMember: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TFAPIMember"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "mtype"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self._name)
case 2: try decoder.decodeSingularStringField(value: &self._mtype)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._name {
try visitor.visitSingularStringField(value: v, fieldNumber: 1)
}
if let v = self._mtype {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: ThirdParty_Tensorflow_Tools_Api_TFAPIMember) -> Bool {
if self._name != other._name {return false}
if self._mtype != other._mtype {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ThirdParty_Tensorflow_Tools_Api_TFAPIMethod: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TFAPIMethod"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "path"),
3: .same(proto: "argspec"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self._name)
case 2: try decoder.decodeSingularStringField(value: &self._path)
case 3: try decoder.decodeSingularStringField(value: &self._argspec)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._name {
try visitor.visitSingularStringField(value: v, fieldNumber: 1)
}
if let v = self._path {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
}
if let v = self._argspec {
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: ThirdParty_Tensorflow_Tools_Api_TFAPIMethod) -> Bool {
if self._name != other._name {return false}
if self._path != other._path {return false}
if self._argspec != other._argspec {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ThirdParty_Tensorflow_Tools_Api_TFAPIModule: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TFAPIModule"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "member"),
2: .standard(proto: "member_method"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedMessageField(value: &self.member)
case 2: try decoder.decodeRepeatedMessageField(value: &self.memberMethod)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.member.isEmpty {
try visitor.visitRepeatedMessageField(value: self.member, fieldNumber: 1)
}
if !self.memberMethod.isEmpty {
try visitor.visitRepeatedMessageField(value: self.memberMethod, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: ThirdParty_Tensorflow_Tools_Api_TFAPIModule) -> Bool {
if self.member != other.member {return false}
if self.memberMethod != other.memberMethod {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ThirdParty_Tensorflow_Tools_Api_TFAPIClass: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TFAPIClass"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "is_instance"),
2: .same(proto: "member"),
3: .standard(proto: "member_method"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedStringField(value: &self.isInstance)
case 2: try decoder.decodeRepeatedMessageField(value: &self.member)
case 3: try decoder.decodeRepeatedMessageField(value: &self.memberMethod)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.isInstance.isEmpty {
try visitor.visitRepeatedStringField(value: self.isInstance, fieldNumber: 1)
}
if !self.member.isEmpty {
try visitor.visitRepeatedMessageField(value: self.member, fieldNumber: 2)
}
if !self.memberMethod.isEmpty {
try visitor.visitRepeatedMessageField(value: self.memberMethod, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: ThirdParty_Tensorflow_Tools_Api_TFAPIClass) -> Bool {
if self.isInstance != other.isInstance {return false}
if self.member != other.member {return false}
if self.memberMethod != other.memberMethod {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ThirdParty_Tensorflow_Tools_Api_TFAPIProto: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TFAPIProto"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "descriptor"),
]
fileprivate class _StorageClass {
var _descriptor: Google_Protobuf_DescriptorProto? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_descriptor = source._descriptor
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._descriptor, !v.isInitialized {return false}
return true
}
}
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &_storage._descriptor)
default: break
}
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._descriptor {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: ThirdParty_Tensorflow_Tools_Api_TFAPIProto) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let other_storage = _args.1
if _storage._descriptor != other_storage._descriptor {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ThirdParty_Tensorflow_Tools_Api_TFAPIObject: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".TFAPIObject"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "path"),
2: .standard(proto: "tf_module"),
3: .standard(proto: "tf_class"),
4: .standard(proto: "tf_proto"),
]
fileprivate class _StorageClass {
var _path: String? = nil
var _tfModule: ThirdParty_Tensorflow_Tools_Api_TFAPIModule? = nil
var _tfClass: ThirdParty_Tensorflow_Tools_Api_TFAPIClass? = nil
var _tfProto: ThirdParty_Tensorflow_Tools_Api_TFAPIProto? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_path = source._path
_tfModule = source._tfModule
_tfClass = source._tfClass
_tfProto = source._tfProto
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._tfProto, !v.isInitialized {return false}
return true
}
}
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &_storage._path)
case 2: try decoder.decodeSingularMessageField(value: &_storage._tfModule)
case 3: try decoder.decodeSingularMessageField(value: &_storage._tfClass)
case 4: try decoder.decodeSingularMessageField(value: &_storage._tfProto)
default: break
}
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._path {
try visitor.visitSingularStringField(value: v, fieldNumber: 1)
}
if let v = _storage._tfModule {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
if let v = _storage._tfClass {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
}
if let v = _storage._tfProto {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: ThirdParty_Tensorflow_Tools_Api_TFAPIObject) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let other_storage = _args.1
if _storage._path != other_storage._path {return false}
if _storage._tfModule != other_storage._tfModule {return false}
if _storage._tfClass != other_storage._tfClass {return false}
if _storage._tfProto != other_storage._tfProto {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
| gpl-3.0 |
liuxuan30/SwiftCharts | SwiftCharts/Layers/ChartGuideLinesLayer.swift | 7 | 8152 | //
// ChartGuideLinesLayer.swift
// SwiftCharts
//
// Created by ischuetz on 26/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartGuideLinesLayerSettings {
let linesColor: UIColor
let linesWidth: CGFloat
public init(linesColor: UIColor = UIColor.grayColor(), linesWidth: CGFloat = 0.3) {
self.linesColor = linesColor
self.linesWidth = linesWidth
}
}
public class ChartGuideLinesDottedLayerSettings: ChartGuideLinesLayerSettings {
let dotWidth: CGFloat
let dotSpacing: CGFloat
public init(linesColor: UIColor, linesWidth: CGFloat, dotWidth: CGFloat = 2, dotSpacing: CGFloat = 2) {
self.dotWidth = dotWidth
self.dotSpacing = dotSpacing
super.init(linesColor: linesColor, linesWidth: linesWidth)
}
}
public enum ChartGuideLinesLayerAxis {
case X, Y, XAndY
}
public class ChartGuideLinesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer {
private let settings: T
private let onlyVisibleX: Bool
private let onlyVisibleY: Bool
private let axis: ChartGuideLinesLayerAxis
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: T, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
self.settings = settings
self.onlyVisibleX = onlyVisibleX
self.onlyVisibleY = onlyVisibleY
self.axis = axis
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
fatalError("override")
}
override public func chartViewDrawing(#context: CGContextRef, chart: Chart) {
let originScreenLoc = self.innerFrame.origin
let xScreenLocs = onlyVisibleX ? self.xAxis.visibleAxisValuesScreenLocs : self.xAxis.axisValuesScreenLocs
let yScreenLocs = onlyVisibleY ? self.yAxis.visibleAxisValuesScreenLocs : self.yAxis.axisValuesScreenLocs
if self.axis == .X || self.axis == .XAndY {
for xScreenLoc in xScreenLocs {
let x1 = xScreenLoc
let y1 = originScreenLoc.y
let x2 = x1
let y2 = originScreenLoc.y + self.innerFrame.height
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
if self.axis == .Y || self.axis == .XAndY {
for yScreenLoc in yScreenLocs {
let x1 = originScreenLoc.x
let y1 = yScreenLoc
let x2 = originScreenLoc.x + self.innerFrame.width
let y2 = y1
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
}
}
public typealias ChartGuideLinesLayer = ChartGuideLinesLayer_<Any>
public class ChartGuideLinesLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesLayerSettings> {
override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: ChartGuideLinesLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor)
}
}
public typealias ChartGuideLinesDottedLayer = ChartGuideLinesDottedLayer_<Any>
public class ChartGuideLinesDottedLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesDottedLayerSettings> {
override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .XAndY, settings: ChartGuideLinesDottedLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing)
}
}
public class ChartGuideLinesForValuesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer {
private let settings: T
private let axisValuesX: [ChartAxisValue]
private let axisValuesY: [ChartAxisValue]
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: T, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
self.settings = settings
self.axisValuesX = axisValuesX
self.axisValuesY = axisValuesY
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
private func drawGuideline(context: CGContextRef, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint, dotWidth: CGFloat, dotSpacing: CGFloat) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: width, color: color, dotWidth: dotWidth, dotSpacing: dotSpacing)
}
private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
fatalError("override")
}
override public func chartViewDrawing(#context: CGContextRef, chart: Chart) {
let originScreenLoc = self.innerFrame.origin
for axisValue in self.axisValuesX {
let screenLoc = self.xAxis.screenLocForScalar(axisValue.scalar)
let x1 = screenLoc
let y1 = originScreenLoc.y
let x2 = x1
let y2 = originScreenLoc.y + self.innerFrame.height
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
for axisValue in self.axisValuesY {
let screenLoc = self.yAxis.screenLocForScalar(axisValue.scalar)
let x1 = originScreenLoc.x
let y1 = screenLoc
let x2 = originScreenLoc.x + self.innerFrame.width
let y2 = y1
self.drawGuideline(context, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
}
public typealias ChartGuideLinesForValuesLayer = ChartGuideLinesForValuesLayer_<Any>
public class ChartGuideLinesForValuesLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesLayerSettings> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor)
}
}
public typealias ChartGuideLinesForValuesDottedLayer = ChartGuideLinesForValuesDottedLayer_<Any>
public class ChartGuideLinesForValuesDottedLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesDottedLayerSettings> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesDottedLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY)
}
override private func drawGuideline(context: CGContextRef, p1: CGPoint, p2: CGPoint) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing)
}
}
| apache-2.0 |
altyus/clubhouse-ios-api | Pod/Classes/ClubhouseAPI.swift | 1 | 1762 | //
// ClubhouseAPI.swift
// Pods
//
// Created by Al Tyus on 3/13/16.
//
//
import Foundation
import Alamofire
import SwiftyJSON
public class ClubhouseAPI {
// MARK: - Types
public typealias SuccessList = ([AnyObject]) -> Void
public typealias SuccessObject = (JSON) -> Void
public typealias Failure = (ErrorType?) -> Void
// MARK: - Properties
public static let sharedInstance: ClubhouseAPI = ClubhouseAPI()
internal let baseURLString = "https://api.clubhouse.io/api/v1/"
public var apiToken: String?
// MARK: - Initializers
public class func configure(apiToken: String) {
ClubhouseAPI.sharedInstance.apiToken = apiToken
}
//MARK: - Functions
public static func URLRequest(method: Alamofire.Method, path: String) -> NSMutableURLRequest {
guard let apiToken = ClubhouseAPI.sharedInstance.apiToken, baseURL = NSURL(string: ClubhouseAPI.sharedInstance.baseURLString) else {
fatalError("Token must be set")
}
let URL = baseURL.URLByAppendingPathComponent(path).URLByAppendingQueryParameters(["token": apiToken])
let mutableURLReuqest = NSMutableURLRequest(URL: URL)
mutableURLReuqest.HTTPMethod = method.rawValue
return mutableURLReuqest
}
internal func request(request: URLRequestConvertible, success: (AnyObject) -> Void, failure: Failure) {
Alamofire.request(request)
.validate()
.responseJSON { response in
switch response.result {
case .Success(let value):
success(value)
case .Failure(let error):
failure(error)
}
}
}
}
| mit |
tiehuaz/iOS-Application-for-AURIN | AurinProject/SidebarMenu/HTTPGetJSON.swift | 1 | 1876 | import Foundation
/*these functions are used ot send HTTP request and parse returned JSON data*/
func JSONParseDict(jsonString:String) -> Dictionary<String, AnyObject> {
if let data: NSData = jsonString.dataUsingEncoding(
NSUTF8StringEncoding){
do{
if let jsonObj = try NSJSONSerialization.JSONObjectWithData(
data,
options: NSJSONReadingOptions(rawValue: 0)) as? Dictionary<String, AnyObject>{
return jsonObj
}
}catch{
print("Error")
}
}
return [String: AnyObject]()
}
func HTTPsendRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(
request, completionHandler :
{
data, response, error in
if error != nil {
callback("", (error!.localizedDescription) as String)
} else {
callback(
NSString(data: data!, encoding: NSUTF8StringEncoding) as! String,
nil
)
}
})
task.resume()
}
func HTTPGetJSON(
url: String,
callback: (Dictionary<String, AnyObject>, String?) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.setValue("application/json", forHTTPHeaderField: "Accept")
HTTPsendRequest(request) {
(data: String, error: String?) -> Void in
if error != nil {
callback(Dictionary<String, AnyObject>(), error)
} else {
let jsonObj = JSONParseDict(data)
callback(jsonObj, nil)
}
}
}
| apache-2.0 |
DonMag/CellTest2 | CellTest2/CellTest2/TestTableViewController.swift | 1 | 4395 | //
// TestTableViewController.swift
// CellTest2
//
// Created by DonMag on 7/4/17.
// Copyright © 2017 DonMag. All rights reserved.
//
import UIKit
class TestBCell: UITableViewCell {
@IBOutlet weak var leftLabel1: UILabel!
@IBOutlet weak var leftLabel2: UILabel!
@IBOutlet weak var rightLabel: UILabel!
}
class TestTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 80
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UILabel(frame: CGRect.zero)
v.numberOfLines = 0
v.text = "Section \(section)\nA really really long string"
v.backgroundColor = UIColor.lightGray
return v
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 8
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// cell with "testB" identifier (red background) has NO width limit on Left Labels
// cell with "testC" identifier (blue background) has Left Labels width constrained to <= 200 (just arbirary number for demonstration)
let cell = tableView.dequeueReusableCell(withIdentifier: "testB", for: indexPath) as! TestBCell
// let cell = tableView.dequeueReusableCell(withIdentifier: "testC", for: indexPath) as! TestBCell
switch indexPath.section {
case 0:
cell.leftLabel1?.text = "Label1 aabbccdd"
cell.leftLabel2?.text = "Label2 aabbccdd"
cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
break
case 3:
cell.leftLabel1?.text = "Shorter"
cell.leftLabel2?.text = "Label2 aabbccdd"
cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
break
case 1:
cell.leftLabel1?.text = "Label1 aabbccdd"
cell.leftLabel2?.text = "Label2 aabbccdd"
cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
break
case 4:
cell.leftLabel1?.text = "Label1 aabbccdd"
cell.leftLabel2?.text = "Shorter"
cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
break
case 2:
cell.leftLabel1?.text = "Label1 aabbccdd"
cell.leftLabel2?.text = "Label2 aabbccdd"
cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really really really really really really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
break
case 5:
cell.leftLabel1?.text = "Label1 aabbccdd"
cell.leftLabel2?.text = "Label2 aabbccdd"
cell.rightLabel?.text = "Only 1 line on right"
break
case 6:
cell.leftLabel1?.text = "Short"
cell.leftLabel2?.text = "Shorter"
cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
break
case 7:
cell.leftLabel1?.text = "The text for this Label takes up too much room!"
cell.leftLabel2?.text = "Label2 aabbccdd"
cell.rightLabel?.text = "That might be a problem, unless you have length limits on the left."
break
default:
cell.leftLabel1?.text = "Left 1"
cell.leftLabel2?.text = "Left 2"
cell.rightLabel?.text = "Right"
break
}
return cell
}
}
| mit |
alpascual/DigitalWil | NotificationScheduler.swift | 1 | 5586 | //
// NotificationScheduler.swift
// FrostedSidebar
//
// Created by Al Pascual on 8/29/14.
// Copyright (c) 2014 Evan Dekhayser. All rights reserved.
//
import UIKit
class NotificationScheduler: NSObject {
override init() {
}
func ChangesOnNotification()
{
let configuration = Configuration()
var defaults = NSUserDefaults()
var isThere: AnyObject? = defaults.objectForKey(configuration.Code)
var isThereHowOften : AnyObject? = defaults.objectForKey(configuration.HowLongBetweenRequests)
var isThereRepeat : AnyObject? = defaults.objectForKey(configuration.NumberOfTries)
if ( isThere != nil && isThereHowOften != nil && isThereRepeat != nil) {
UIApplication.sharedApplication().cancelAllLocalNotifications()
self.ScheduleAll()
//HUDController.sharedController.contentView = HUDContentView.TextView(text: "Alerts have been scheduled")
}
else
{
// Display a message that you need all the info and code to be setup
HUDController.sharedController.contentView = HUDContentView.TextView(text: "Need to set up a code to schedule alerts")
}
HUDController.sharedController.show()
HUDController.sharedController.hide(afterDelay: 2.0)
}
func ScheduleAll()
{
var defaults = NSUserDefaults()
let notification = UILocalNotification()
let configuration = Configuration()
// Schedule first one
var betweenRequests = defaults.objectForKey(configuration.HowLongBetweenRequests) as Int
var seconds : Double = Double(betweenRequests)
var days = self.convertSecondsToDays(seconds)
notification.fireDate = self.insidePreferedWindow(NSDate(timeIntervalSinceNow: days))
notification.applicationIconBadgeNumber=notification.applicationIconBadgeNumber+1
notification.alertBody = "Confirm you are still alive and well by clicking the notification"
notification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(notification)
// Schedule number of tries
var lastday = days
var numberOfTries = defaults.objectForKey(configuration.NumberOfTries) as Int
for var i = 0; i < numberOfTries; i++ {
let tempNotification = UILocalNotification()
// increasing one day
lastday = lastday + self.convertSecondsToDays(Double(i))
tempNotification.fireDate = self.insidePreferedWindow(NSDate(timeIntervalSinceNow: lastday))
tempNotification.alertBody = "Remaining " + String(configuration.getNumberOfTriesValue()-i) + " days before showing the password"
tempNotification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(tempNotification)
}
// Last notification showing the password
let lastNotification = UILocalNotification()
lastday = lastday + self.convertSecondsToDays(1)
lastNotification.fireDate = self.insidePreferedWindow(NSDate(timeIntervalSinceNow: lastday))
lastNotification.alertBody = "The owner of the phone is gone, unlock it, this is the password: " + configuration.getCodeValue()
lastNotification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(lastNotification)
// One last one in case
let lastNotification2 = UILocalNotification()
lastday = lastday + self.convertSecondsToDays(1)
lastNotification2.fireDate = self.insidePreferedWindow(NSDate(timeIntervalSinceNow: lastday))
lastNotification2.alertBody = "The owner of the phone is gone, unlock it, this is the password: " + configuration.getCodeValue() + " last communication"
lastNotification2.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(lastNotification2)
}
func convertSecondsToDays(seconds: Double) -> Double
{
var days = (((seconds * 60) * 60) * 24)
return days
}
func insidePreferedWindow(date : NSDate) -> NSDate
{
println("-------Original-----")
println(date)
//Make sure the timer is on their selected window
var hour = self.getHour(date)
let configuration = Configuration()
var timeOfDay = configuration.getTimeOfTheDayValue()
var max = 24
var min = 19
if ( timeOfDay == "Morning")
{
max = 11
min = 8
}
else if ( timeOfDay == "Afternoon")
{
max = 18
min = 12
}
var newDate : NSDate = date
while ( hour < min || hour > max)
{
newDate = NSDate(timeInterval: NSTimeInterval(1500), sinceDate: newDate)
println("-------Changed-----")
println(newDate)
hour = self.getHour(newDate)
println(hour)
}
return newDate
}
func getHour(date : NSDate) -> Int
{
//Make sure the timer is on their selected window
let calendar = NSCalendar.currentCalendar()
var conponents : NSDateComponents = calendar.components(NSCalendarUnit.HourCalendarUnit, fromDate: date)
//println(conponents)
return conponents.hour
}
}
| mit |
CalebeEmerick/Checkout | Source/Checkout/ViewExtension.swift | 1 | 695 | //
// ViewExtension.swift
// Checkout
//
// Created by Calebe Emerick on 06/12/16.
// Copyright © 2016 CalebeEmerick. All rights reserved.
//
import UIKit
protocol ViewCreatable { }
extension ViewCreatable where Self : UIView {
static func makeXib() -> Self {
let identifier = String(describing: Self.self)
guard let view = Bundle.main.loadNibNamed(identifier, owner: self, options: nil)?.first as? Self else {
fatalError("It was not possible create Xib with identifier: \(identifier). The '.xib' and '.swift' files must have the same name.")
}
return view
}
}
extension UIView : ViewCreatable { }
| mit |
noppoMan/aws-sdk-swift | Tests/SotoTests/Services/Glacier/GlacierTests.swift | 1 | 3489 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import NIO
import XCTest
@testable import SotoGlacier
class GlacierTests: XCTestCase {
static var client: AWSClient!
static var glacier: Glacier!
override class func setUp() {
Self.client = AWSClient(credentialProvider: TestEnvironment.credentialProvider, middlewares: TestEnvironment.middlewares, httpClientProvider: .createNew)
Self.glacier = Glacier(
client: GlacierTests.client,
region: .euwest1,
endpoint: TestEnvironment.getEndPoint(environment: "LOCALSTACK_ENDPOINT")
)
if TestEnvironment.isUsingLocalstack {
print("Connecting to Localstack")
} else {
print("Connecting to AWS")
}
}
override class func tearDown() {
XCTAssertNoThrow(try self.client.syncShutdown())
}
// create a buffer of random values. Will always create the same given you supply the same z and w values
// Random number generator from https://www.codeproject.com/Articles/25172/Simple-Random-Number-Generation
func createRandomBuffer(_ w: UInt, _ z: UInt, size: Int) -> [UInt8] {
var z = z
var w = w
func getUInt8() -> UInt8 {
z = 36969 * (z & 65535) + (z >> 16)
w = 18000 * (w & 65535) + (w >> 16)
return UInt8(((z << 16) + w) & 0xFF)
}
var data = [UInt8](repeating: 0, count: size)
for i in 0..<size {
data[i] = getUInt8()
}
return data
}
func testComputeTreeHash() throws {
// create buffer full of random data, use the same seeds to ensure we get the same buffer everytime
let data = self.createRandomBuffer(23, 4, size: 7 * 1024 * 1024 + 258)
// create byte buffer
var byteBuffer = ByteBufferAllocator().buffer(capacity: data.count)
byteBuffer.writeBytes(data)
let middleware = GlacierRequestMiddleware(apiVersion: "2012-06-01")
let treeHash = try middleware.computeTreeHash(byteBuffer)
XCTAssertEqual(
treeHash,
[210, 50, 5, 126, 16, 6, 59, 6, 21, 40, 186, 74, 192, 56, 39, 85, 210, 25, 238, 54, 4, 252, 221, 238, 107, 127, 76, 118, 245, 76, 22, 45]
)
}
func testError() {
// This doesnt work with LocalStack
guard !TestEnvironment.isUsingLocalstack else { return }
let job = Glacier.JobParameters(description: "Inventory", format: "CSV", type: "inventory-retrieval")
let inventoryJobInput = Glacier.InitiateJobInput(accountId: "-", jobParameters: job, vaultName: "aws-test-vault-doesnt-exist")
let response = Self.glacier.initiateJob(inventoryJobInput)
XCTAssertThrowsError(try response.wait()) { error in
switch error {
case let error as GlacierErrorType where error == .resourceNotFoundException:
XCTAssertNotNil(error.message)
default:
XCTFail("Wrong error: \(error)")
}
}
}
}
| apache-2.0 |
jisudong555/swift | weibo/weibo/AppDelegate.swift | 1 | 2213 | //
// AppDelegate.swift
// weibo
//
// Created by jisudong on 16/4/7.
// Copyright © 2016年 jisudong. All rights reserved.
//
import UIKit
let SwitchRootViewControllerNotification = "SwitchRootViewControllerNotification"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(switchRootViewController(_:)), name: SwitchRootViewControllerNotification, object: nil)
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = defaultController()
window?.makeKeyAndVisible()
return true
}
func switchRootViewController(notify: NSNotification)
{
if notify.object as! Bool
{
window?.rootViewController = TabBarController()
} else
{
window?.rootViewController = WelcomeViewController()
}
}
func defaultController() -> UIViewController
{
if UserAccount.userLogin()
{
return isNewVersion() ? NewfeatureCollectionViewController() : WelcomeViewController()
}
return TabBarController()
}
func isNewVersion() -> Bool
{
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
let sanboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
if currentVersion?.compare(sanboxVersion) == NSComparisonResult.OrderedDescending
{
NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
return true
}
return false
}
}
| mit |
radex/swift-compiler-crashes | crashes-duplicates/04005-swift-sourcemanager-getmessage.swift | 11 | 321 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init<T: b {
protocol a {
}
func g<h: P {
protocol a {
struct d<h: P {
let a {
let f = compose() {
class a {
var _ = 1)?
enum b : b<h: P {
class
case c,
| mit |
swift-mtl/WTM-Montreal | WTM-CodeLab/AppDelegate.swift | 1 | 2148 | //
// AppDelegate.swift
// WTM-CodeLab
//
// Created by Fatih Nayebi on 2016-03-10.
// Copyright © 2016 Swift-Mtl. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
qualaroo/QualarooSDKiOS | QualarooTests/Managers/AutotrackingManagerSpec.swift | 1 | 1478 | //
// AutotrackingManagerSpec.swift
// QualarooTests
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class MethodSwizzlerMock: MethodSwizzler {
var swizzledCount: Int = 0
override func swizzle(_ firstSelector: Selector,
with secondSelector: Selector,
aClass: AnyClass) { swizzledCount += 1 }
}
class AutotrackingManagerSpec: QuickSpec {
override func spec() {
super.spec()
describe("AutotrackingManager") {
var manager: AutotrackingManager!
var swizzler: MethodSwizzlerMock!
beforeEach {
swizzler = MethodSwizzlerMock()
manager = AutotrackingManager(swizzler: swizzler)
}
context("autotracking") {
it("is disabled by default it is changing implementation if needed") {
expect(swizzler.swizzledCount).to(equal(0))
manager.enableAutotracking()
expect(swizzler.swizzledCount).to(equal(1))
manager.enableAutotracking()
expect(swizzler.swizzledCount).to(equal(1))
manager.disableAutotracking()
expect(swizzler.swizzledCount).to(equal(2))
manager.disableAutotracking()
expect(swizzler.swizzledCount).to(equal(2))
}
}
}
}
}
| mit |
iSapozhnik/LoadingViewController | Example/Tests/Tests.swift | 1 | 771 | import UIKit
import XCTest
import LoadingViewController
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
iJudson/RxBasicInterface | RxBasicInterface/RxBasicInterface/Business/Profile/ProfileViewController.swift | 1 | 594 | //
// ProfileViewController.swift
// RxBasicInterface
//
// Created by 陈恩湖 on 2017/9/9.
// Copyright © 2017年 Judson. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
initializeTopBarControls()
}
fileprivate func initializeTopBarControls() {
let barStyle = NavigationBarStyle(center: (image: nil, title: "我的"))
let navigationBar = NavigationBar(themeStyle: barStyle)
self.view.addSubview(navigationBar)
}
}
| mit |
radex/swift-compiler-crashes | crashes-duplicates/13790-swift-constraints-solution-solution.swift | 11 | 245 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g<T {
struct c
{
{
}
init( ) {
let f = c
enum A {
{
}
let start = c( )
| mit |
jkolb/Shkadov | Shkadov/engine/input/RawInputListener.swift | 1 | 1187 | /*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public protocol RawInputListener : class {
func received(input: RawInput)
}
| mit |
naokits/my-programming-marathon | RxSwiftDemo/Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/Driver+Test.swift | 2 | 39109 | //
// Driver+Test.swift
// RxTests
//
// Created by Krunoslav Zaher on 10/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import XCTest
import RxTests
class DriverTest : RxTest {
var backgroundScheduler = SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .Default)
override func tearDown() {
super.tearDown()
}
}
// test helpers that make sure that resulting driver operator honors definition
// * only one subscription is made and shared - shareReplay(1)
// * subscription is made on main thread - subscribeOn(ConcurrentMainScheduler.instance)
// * events are observed on main thread - observeOn(MainScheduler.instance)
// * it can't error out - it needs to have catch somewhere
extension DriverTest {
func subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription<R: Equatable>(driver: Driver<R>, subscribedOnBackground: () -> ()) -> [R] {
var firstElements = [R]()
var secondElements = [R]()
let subscribeFinished = self.expectationWithDescription("subscribeFinished")
var expectation1: XCTestExpectation!
var expectation2: XCTestExpectation!
backgroundScheduler.schedule(()) { _ in
var subscribing1 = true
let currentThread = NSThread.currentThread()
_ = driver.asObservable().subscribe { e in
if !subscribing1 {
XCTAssertTrue(isMainThread())
}
else {
XCTAssertEqual(currentThread, NSThread.currentThread())
}
switch e {
case .Next(let element):
firstElements.append(element)
case .Error(let error):
XCTFail("Error passed \(error)")
case .Completed:
expectation1.fulfill()
}
}
subscribing1 = false
var subscribing = true
_ = driver.asDriver().asObservable().subscribe { e in
if !subscribing {
XCTAssertTrue(isMainThread())
}
else {
XCTAssertEqual(currentThread, NSThread.currentThread())
}
switch e {
case .Next(let element):
secondElements.append(element)
case .Error(let error):
XCTFail("Error passed \(error)")
case .Completed:
expectation2.fulfill()
}
}
subscribing = false
// Subscription should be made on main scheduler
// so this will make sure execution is continued after
// subscription because of serial nature of main scheduler.
MainScheduler.instance.schedule(()) { _ in
subscribeFinished.fulfill()
return NopDisposable.instance
}
return NopDisposable.instance
}
waitForExpectationsWithTimeout(1.0) { error in
XCTAssertTrue(error == nil)
}
expectation1 = self.expectationWithDescription("finished1")
expectation2 = self.expectationWithDescription("finished2")
subscribedOnBackground()
waitForExpectationsWithTimeout(1.0) { error in
XCTAssertTrue(error == nil)
}
XCTAssertTrue(firstElements == secondElements)
return firstElements
}
}
// MARK: properties
extension DriverTest {
func testDriverSharing_WhenErroring() {
let scheduler = TestScheduler(initialClock: 0)
let observer1 = scheduler.createObserver(Int)
let observer2 = scheduler.createObserver(Int)
let observer3 = scheduler.createObserver(Int)
var disposable1: Disposable!
var disposable2: Disposable!
var disposable3: Disposable!
let coldObservable = scheduler.createColdObservable([
next(10, 0),
next(20, 1),
next(30, 2),
next(40, 3),
error(50, testError)
])
let driver = coldObservable.asDriver(onErrorJustReturn: -1)
scheduler.scheduleAt(200) {
disposable1 = driver.asObservable().subscribe(observer1)
}
scheduler.scheduleAt(225) {
disposable2 = driver.asObservable().subscribe(observer2)
}
scheduler.scheduleAt(235) {
disposable1.dispose()
}
scheduler.scheduleAt(260) {
disposable2.dispose()
}
// resubscription
scheduler.scheduleAt(260) {
disposable3 = driver.asObservable().subscribe(observer3)
}
scheduler.scheduleAt(285) {
disposable3.dispose()
}
scheduler.start()
XCTAssertEqual(observer1.events, [
next(210, 0),
next(220, 1),
next(230, 2)
])
XCTAssertEqual(observer2.events, [
next(225, 1),
next(230, 2),
next(240, 3),
next(250, -1),
completed(250)
])
XCTAssertEqual(observer3.events, [
next(270, 0),
next(280, 1),
])
XCTAssertEqual(coldObservable.subscriptions, [
Subscription(200, 250),
Subscription(260, 285),
])
}
func testDriverSharing_WhenCompleted() {
let scheduler = TestScheduler(initialClock: 0)
let observer1 = scheduler.createObserver(Int)
let observer2 = scheduler.createObserver(Int)
let observer3 = scheduler.createObserver(Int)
var disposable1: Disposable!
var disposable2: Disposable!
var disposable3: Disposable!
let coldObservable = scheduler.createColdObservable([
next(10, 0),
next(20, 1),
next(30, 2),
next(40, 3),
error(50, testError)
])
let driver = coldObservable.asDriver(onErrorJustReturn: -1)
scheduler.scheduleAt(200) {
disposable1 = driver.asObservable().subscribe(observer1)
}
scheduler.scheduleAt(225) {
disposable2 = driver.asObservable().subscribe(observer2)
}
scheduler.scheduleAt(235) {
disposable1.dispose()
}
scheduler.scheduleAt(260) {
disposable2.dispose()
}
// resubscription
scheduler.scheduleAt(260) {
disposable3 = driver.asObservable().subscribe(observer3)
}
scheduler.scheduleAt(285) {
disposable3.dispose()
}
scheduler.start()
XCTAssertEqual(observer1.events, [
next(210, 0),
next(220, 1),
next(230, 2)
])
XCTAssertEqual(observer2.events, [
next(225, 1),
next(230, 2),
next(240, 3),
next(250, -1),
completed(250)
])
XCTAssertEqual(observer3.events, [
next(270, 0),
next(280, 1),
])
XCTAssertEqual(coldObservable.subscriptions, [
Subscription(200, 250),
Subscription(260, 285),
])
}
}
// MARK: conversions
extension DriverTest {
func testVariableAsDriver() {
let hotObservable = Variable(1)
let driver = Driver.zip(hotObservable.asDriver(), Driver.of(0, 0)) { all in
return all.0
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
hotObservable.value = 1
hotObservable.value = 2
}
XCTAssertEqual(results, [1, 1])
}
func testAsDriver_onErrorJustReturn() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
func testAsDriver_onErrorDriveWith() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorDriveWith: Driver.just(-1))
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
func testAsDriver_onErrorRecover() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver { e in
return Driver.empty()
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2])
}
}
// MARK: deferred
extension DriverTest {
func testAsDriver_deferred() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = Driver.deferred { hotObservable.asDriver(onErrorJustReturn: -1) }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
}
// MARK: map
extension DriverTest {
func testAsDriver_map() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).map { (n: Int) -> Int in
XCTAssertTrue(isMainThread())
return n + 1
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [2, 3, 0])
}
}
// MARK: filter
extension DriverTest {
func testAsDriver_filter() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).filter { n in
XCTAssertTrue(isMainThread())
return n % 2 == 0
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [2])
}
}
// MARK: switch latest
extension DriverTest {
func testAsDriver_switchLatest() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Driver<Int>>()
let hotObservable1 = MainThreadPrimitiveHotObservable<Int>()
let hotObservable2 = MainThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: hotObservable1.asDriver(onErrorJustReturn: -1)).switchLatest()
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(hotObservable1.asDriver(onErrorJustReturn: -2)))
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
hotObservable.on(.Next(hotObservable2.asDriver(onErrorJustReturn: -3)))
hotObservable2.on(.Next(10))
hotObservable2.on(.Next(11))
hotObservable2.on(.Error(testError))
hotObservable.on(.Error(testError))
hotObservable1.on(.Completed)
hotObservable.on(.Completed)
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [
1, 2, -2,
10, 11, -3
])
}
}
// MARK: flatMapLatest
extension DriverTest {
func testAsDriver_flatMapLatest() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable1 = MainThreadPrimitiveHotObservable<Int>()
let hotObservable2 = MainThreadPrimitiveHotObservable<Int>()
let errorHotObservable = MainThreadPrimitiveHotObservable<Int>()
let drivers: [Driver<Int>] = [
hotObservable1.asDriver(onErrorJustReturn: -2),
hotObservable2.asDriver(onErrorJustReturn: -3),
errorHotObservable.asDriver(onErrorJustReturn: -4),
]
let driver = hotObservable.asDriver(onErrorJustReturn: 2).flatMapLatest { drivers[$0] }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(0))
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
hotObservable.on(.Next(1))
hotObservable2.on(.Next(10))
hotObservable2.on(.Next(11))
hotObservable2.on(.Error(testError))
hotObservable.on(.Error(testError))
errorHotObservable.on(.Completed)
hotObservable.on(.Completed)
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [
1, 2, -2,
10, 11, -3
])
}
}
// MARK: flatMapFirst
extension DriverTest {
func testAsDriver_flatMapFirst() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable1 = MainThreadPrimitiveHotObservable<Int>()
let hotObservable2 = MainThreadPrimitiveHotObservable<Int>()
let errorHotObservable = MainThreadPrimitiveHotObservable<Int>()
let drivers: [Driver<Int>] = [
hotObservable1.asDriver(onErrorJustReturn: -2),
hotObservable2.asDriver(onErrorJustReturn: -3),
errorHotObservable.asDriver(onErrorJustReturn: -4),
]
let driver = hotObservable.asDriver(onErrorJustReturn: 2).flatMapFirst { drivers[$0] }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(0))
hotObservable.on(.Next(1))
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Next(10))
hotObservable2.on(.Next(11))
hotObservable2.on(.Error(testError))
hotObservable.on(.Error(testError))
errorHotObservable.on(.Completed)
hotObservable.on(.Completed)
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [
1, 2, -2,
])
}
}
// MARK: doOn
extension DriverTest {
func testAsDriver_doOn() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
var events = [Event<Int>]()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).doOn { e in
XCTAssertTrue(isMainThread())
events.append(e)
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
let expectedEvents = [.Next(1), .Next(2), .Next(-1), .Completed] as [Event<Int>]
XCTAssertEqual(events, expectedEvents)
}
func testAsDriver_doOnNext() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
var events = [Int]()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).doOnNext { e in
XCTAssertTrue(isMainThread())
events.append(e)
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
let expectedEvents = [1, 2, -1]
XCTAssertEqual(events, expectedEvents)
}
func testAsDriver_doOnCompleted() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
var completed = false
let driver = hotObservable.asDriver(onErrorJustReturn: -1).doOnCompleted { e in
XCTAssertTrue(isMainThread())
completed = true
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
XCTAssertEqual(completed, true)
}
}
// MARK: distinct until change
extension DriverTest {
func testAsDriver_distinctUntilChanged1() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged()
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
func testAsDriver_distinctUntilChanged2() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged({ $0 })
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
func testAsDriver_distinctUntilChanged3() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged({ $0 == $1 })
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
func testAsDriver_distinctUntilChanged4() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).distinctUntilChanged({ $0 }) { $0 == $1 }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1])
}
}
// MARK: flat map
extension DriverTest {
func testAsDriver_flatMap() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).flatMap { (n: Int) -> Driver<Int> in
XCTAssertTrue(isMainThread())
return Driver.just(n + 1)
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [2, 3, 0])
}
}
// MARK: merge
extension DriverTest {
func testAsDriver_merge() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).map { (n: Int) -> Driver<Int> in
XCTAssertTrue(isMainThread())
return Driver.just(n + 1)
}.merge()
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [2, 3, 0])
}
func testAsDriver_merge2() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).map { (n: Int) -> Driver<Int> in
XCTAssertTrue(isMainThread())
return Driver.just(n + 1)
}.merge(maxConcurrent: 1)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [2, 3, 0])
}
}
// MARK: debounce
extension DriverTest {
func testAsDriver_debounce() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).debounce(0.0)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [-1])
}
func testAsDriver_throttle() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).throttle(0.0)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [-1])
}
}
// MARK: scan
extension DriverTest {
func testAsDriver_scan() {
let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable.asDriver(onErrorJustReturn: -1).scan(0) { (a: Int, n: Int) -> Int in
XCTAssertTrue(isMainThread())
return a + n
}
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable])
hotObservable.on(.Next(1))
hotObservable.on(.Next(2))
hotObservable.on(.Error(testError))
XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 3, 2])
}
}
// MARK: concat
extension DriverTest {
func testAsDriver_concat_sequenceType() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = MainThreadPrimitiveHotObservable<Int>()
let driver = AnySequence([hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)]).concat()
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable2.on(.Next(4))
hotObservable2.on(.Next(5))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1, 4, 5, -2])
}
func testAsDriver_concat() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = MainThreadPrimitiveHotObservable<Int>()
let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].concat()
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable2.on(.Next(4))
hotObservable2.on(.Next(5))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [1, 2, -1, 4, 5, -2])
}
}
// MARK: combine latest
extension DriverTest {
func testAsDriver_combineLatest_array() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].combineLatest { a in a.reduce(0, combine: +) }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable2.on(.Next(4))
hotObservable1.on(.Next(2))
hotObservable2.on(.Next(5))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [5, 6, 7, 4, -3])
}
func testAsDriver_combineLatest() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = Driver.combineLatest(hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2), resultSelector: +)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable2.on(.Next(4))
hotObservable1.on(.Next(2))
hotObservable2.on(.Next(5))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [5, 6, 7, 4, -3])
}
}
// MARK: zip
extension DriverTest {
func testAsDriver_zip_array() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].zip { a in a.reduce(0, combine: +) }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable2.on(.Next(4))
hotObservable1.on(.Next(2))
hotObservable2.on(.Next(5))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [5, 7, -3])
}
func testAsDriver_zip() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = Driver.zip(hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2), resultSelector: +)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable2.on(.Next(4))
hotObservable1.on(.Next(2))
hotObservable2.on(.Next(5))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [5, 7, -3])
}
}
// MARK: withLatestFrom
extension DriverTest {
func testAsDriver_withLatestFrom() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable1.asDriver(onErrorJustReturn: -1).withLatestFrom(hotObservable2.asDriver(onErrorJustReturn: -2)) { f, s in "\(f)\(s)" }
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable2.on(.Next(4))
hotObservable1.on(.Next(2))
hotObservable2.on(.Next(5))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, ["24", "-15"])
}
func testAsDriver_withLatestFromDefaultOverload() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let hotObservable2 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable1.asDriver(onErrorJustReturn: -1).withLatestFrom(hotObservable2.asDriver(onErrorJustReturn: -2))
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable2.on(.Next(4))
hotObservable1.on(.Next(2))
hotObservable2.on(.Next(5))
hotObservable1.on(.Error(testError))
hotObservable2.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
XCTAssertTrue(hotObservable2.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [4, 5])
}
}
// MARK: skip
extension DriverTest {
func testAsDriver_skip() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable1.asDriver(onErrorJustReturn: -1).skip(1)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [2, -1])
}
}
// MARK: startWith
extension DriverTest {
func testAsDriver_startWith() {
let hotObservable1 = BackgroundThreadPrimitiveHotObservable<Int>()
let driver = hotObservable1.asDriver(onErrorJustReturn: -1).startWith(0)
let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) {
XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable])
hotObservable1.on(.Next(1))
hotObservable1.on(.Next(2))
hotObservable1.on(.Error(testError))
XCTAssertTrue(hotObservable1.subscriptions == [UnsunscribedFromHotObservable])
}
XCTAssertEqual(results, [0, 1, 2, -1])
}
}
//MARK: interval
extension DriverTest {
func testAsDriver_interval() {
let testScheduler = TestScheduler(initialClock: 0)
let firstObserver = testScheduler.createObserver(Int)
let secondObserver = testScheduler.createObserver(Int)
var disposable1: Disposable!
var disposable2: Disposable!
driveOnScheduler(testScheduler) {
let interval = Driver<Int>.interval(100)
testScheduler.scheduleAt(20) {
disposable1 = interval.asObservable().subscribe(firstObserver)
}
testScheduler.scheduleAt(170) {
disposable2 = interval.asObservable().subscribe(secondObserver)
}
testScheduler.scheduleAt(230) {
disposable1.dispose()
disposable2.dispose()
}
testScheduler.start()
}
XCTAssertEqual(firstObserver.events, [
next(120, 0),
next(220, 1)
])
XCTAssertEqual(secondObserver.events, [
next(170, 0),
next(220, 1)
])
}
}
//MARK: timer
extension DriverTest {
func testAsDriver_timer() {
let testScheduler = TestScheduler(initialClock: 0)
let firstObserver = testScheduler.createObserver(Int)
let secondObserver = testScheduler.createObserver(Int)
var disposable1: Disposable!
var disposable2: Disposable!
driveOnScheduler(testScheduler) {
let interval = Driver<Int>.timer(100, period: 105)
testScheduler.scheduleAt(20) {
disposable1 = interval.asObservable().subscribe(firstObserver)
}
testScheduler.scheduleAt(170) {
disposable2 = interval.asObservable().subscribe(secondObserver)
}
testScheduler.scheduleAt(230) {
disposable1.dispose()
disposable2.dispose()
}
testScheduler.start()
}
XCTAssertEqual(firstObserver.events, [
next(120, 0),
next(225, 1)
])
XCTAssertEqual(secondObserver.events, [
next(170, 0),
next(225, 1)
])
}
} | mit |
ihomway/RayWenderlichCourses | Advanced Swift 3/Advanced Swift 3.playground/Pages/Ranges Challenge.xcplaygroundpage/Contents.swift | 1 | 1538 | //: [Previous](@previous)
import Foundation
import CoreGraphics
// Background:
// If you create a range with floating point Bounds,
// the result is a Range or ClosedRange that is not
// countable. It is useful for telling if a value
// is contained in a range.
let range = 1.0 ..< 2.0
let closedRange = 1.0 ... 2.0
closedRange.contains(1.5)
// Challenge
// Given the following extension on FloatingPoint for generating
// quasi-uniform random numbers create your own random property.
// (Note: Generating true uniform floating point randoms is
// actually very difficult and beyond the scope of this challenge.
// See https://mumble.net/~campbell/2014/04/28/uniform-random-float )
extension FloatingPoint {
// Doesn't include the upperbound.
static func unitRandom() -> Self {
return Self(arc4random())/(Self(UInt32.max)+Self(1))
}
// Includes the upper bound
static func closedUnitRandom() -> Self {
return Self(arc4random())/Self(UInt32.max)
}
}
// HINT: Use two extensions, one for ClosedRange and one for Range.
// Closed ranges want to include the upperBound so they use Double.closedUnitRandom()
extension ClosedRange where Bound: FloatingPoint {
var random: Bound {
return lowerBound + (upperBound - lowerBound) * Bound.closedUnitRandom()
}
}
// Half open ranges should not include the upperBound.
extension Range where Bound: FloatingPoint {
var random: Bound {
return lowerBound + (upperBound - lowerBound) * Bound.unitRandom()
}
}
// Test Code
range.random
closedRange.random
//: [Next](@next)
| mit |
rokuz/omim | iphone/Maps/UI/Appearance/ThemeManager.swift | 1 | 1916 | @objc(MWMThemeManager)
final class ThemeManager: NSObject {
private static let autoUpdatesInterval: TimeInterval = 30 * 60 // 30 minutes in seconds
private static let instance = ThemeManager()
private weak var timer: Timer?
private override init() { super.init() }
private func update(theme: MWMTheme) {
let actualTheme: MWMTheme = { theme in
let isVehicleRouting = MWMRouter.isRoutingActive() && (MWMRouter.type() == .vehicle)
switch theme {
case .day: fallthrough
case .vehicleDay: return isVehicleRouting ? .vehicleDay : .day
case .night: fallthrough
case .vehicleNight: return isVehicleRouting ? .vehicleNight : .night
case .auto:
guard isVehicleRouting else { return .day }
switch FrameworkHelper.daytime(at: MWMLocationManager.lastLocation()) {
case .day: return .vehicleDay
case .night: return .vehicleNight
}
}
}(theme)
let nightMode = UIColor.isNightMode()
let newNightMode: Bool = { theme in
switch theme {
case .day: fallthrough
case .vehicleDay: return false
case .night: fallthrough
case .vehicleNight: return true
case .auto: assert(false); return false
}
}(actualTheme)
FrameworkHelper.setTheme(actualTheme)
if nightMode != newNightMode {
UIColor.setNightMode(newNightMode)
(UIViewController.topViewController() as! MWMController).mwm_refreshUI()
}
}
@objc static func invalidate() {
instance.update(theme: MWMSettings.theme())
}
@objc static var autoUpdates: Bool {
get {
return instance.timer != nil
}
set {
if newValue {
instance.timer = Timer.scheduledTimer(timeInterval: autoUpdatesInterval, target: self, selector: #selector(invalidate), userInfo: nil, repeats: true)
} else {
instance.timer?.invalidate()
}
invalidate()
}
}
}
| apache-2.0 |
IBM-MIL/IBM-Ready-App-for-Banking | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/SettingsViewController.swift | 1 | 3962 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* Custom UIViewController for Settings page.
*/
class SettingsViewController: HatchUIViewController{
/// Table view that contains all cells for Settings page
@IBOutlet weak var tableView: UITableView!
/// Button that opens the menu
@IBOutlet weak var menuButton: UIButton!
/// Label displaying the title of the Settings page
@IBOutlet weak var titleLabel: UILabel!
var cellTitles: [String] = [NSLocalizedString("ACCOUNTS", comment: ""),
NSLocalizedString("TOUCH ID", comment: ""),
NSLocalizedString("NOTIFICATIONS", comment: ""),
NSLocalizedString("PROFILE PICTURE", comment: "")]
/**
Method that sets up the UI style and sets up button action receivers.
*/
override func viewDidLoad() {
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.menuButton.addTarget(self.navigationController,
action: "menuButtonTapped:",
forControlEvents: .TouchUpInside)
self.titleLabel.setKernAttribute(4.0)
}
}
extension SettingsViewController: UITableViewDataSource, UITableViewDelegate{
/**
Delegate method to create individual settings cells
- parameter tableView:
- parameter indexPath:
- returns:
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Disclosure Indicator Cell
if (indexPath.row == 0 || indexPath.row == 3){
var disclosureCell = self.tableView.dequeueReusableCellWithIdentifier("disclosureCell", forIndexPath: indexPath) as? SettingsDisclosureIndicatorCell
if disclosureCell == nil {
disclosureCell = SettingsDisclosureIndicatorCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "disclosureCell")
}
disclosureCell?.configCell(cellTitles[indexPath.row])
return disclosureCell!
} else {
// UISwitch Cell
var switchCell = self.tableView.dequeueReusableCellWithIdentifier("switchCell", forIndexPath: indexPath) as? SettingsUISwitchCell
if switchCell == nil {
switchCell = SettingsUISwitchCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "switchCell")
}
switchCell?.configCell(indexPath.row, title: cellTitles[indexPath.row])
return switchCell!
}
}
/**
Delegate method that returns the height for rows in the tableview.
- parameter tableView:
- parameter indexPath:
- returns: Height for specified row.
*/
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
/**
Delegate method that returns the number of rows in a specified section
- parameter tableView:
- parameter section:
- returns:
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellTitles.count
}
/**
Delegate method to handle event of cell being tapped
- parameter tableView:
- parameter indexPath:
*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0 || indexPath.row == 3){
// Animates title label as if it were button to give user feedback
let disclosureCell = self.tableView.cellForRowAtIndexPath(indexPath) as! SettingsDisclosureIndicatorCell
disclosureCell.animateLabelColorChange()
}
}
}
| epl-1.0 |
tdginternet/TGCameraViewController | ExampleSwift/TGInitialViewController.swift | 1 | 2525 | //
// ViewController.swift
// ExampleSwift
//
// Created by Mario Cecchi on 7/20/16.
// Copyright © 2016 Tudo Gostoso Internet. All rights reserved.
//
import UIKit
class TGInitialViewController: UIViewController, TGCameraDelegate {
@IBOutlet weak var photoView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// set custom tint color
//TGCameraColor.setTint(.green)
// save image to album
TGCamera.setOption(kTGCameraOptionSaveImageToAlbum, value: true)
// use the original image aspect instead of square
//TGCamera.setOption(kTGCameraOptionUseOriginalAspect, value: true)
// hide switch camera button
//TGCamera.setOption(kTGCameraOptionHiddenToggleButton, value: true)
// hide album button
//TGCamera.setOption(kTGCameraOptionHiddenAlbumButton, value: true)
// hide filter button
//TGCamera.setOption(kTGCameraOptionHiddenFilterButton, value: true)
photoView.clipsToBounds = true
let clearButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action:#selector(clearTapped))
navigationItem.rightBarButtonItem = clearButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: TGCameraDelegate - Required methods
func cameraDidCancel() {
dismiss(animated: true, completion: nil)
}
func cameraDidTakePhoto(_ image: UIImage!) {
photoView.image = image
dismiss(animated: true, completion: nil)
}
func cameraDidSelectAlbumPhoto(_ image: UIImage!) {
photoView.image = image
dismiss(animated: true, completion: nil)
}
// MARK: TGCameraDelegate - Optional methods
func cameraWillTakePhoto() {
print("cameraWillTakePhoto")
}
func cameraDidSavePhoto(atPath assetURL: URL!) {
print("cameraDidSavePhotoAtPath: \(assetURL)")
}
func cameraDidSavePhotoWithError(_ error: Error!) {
print("cameraDidSavePhotoWithError \(error)")
}
// MARK: Actions
@IBAction func takePhotoTapped() {
let navigationController = TGCameraNavigationController.new(with: self)
present(navigationController!, animated: true, completion: nil)
}
// MARK: Private methods
func clearTapped() {
photoView.image = nil
}
}
| mit |
mmrmmlrr/HandyText | HandyText/Font.swift | 1 | 1526 | //
// Font.swift
// HandyText
//
// Copyright © 2016 aleksey chernish. All rights reserved.
//
public struct Font {
public enum Thickness {
case extralight, light, regular, medium, bold, heavy, extraheavy
}
public let extralight: String
public let extralightItalic: String
public let light: String
public let lightItalic: String
public let regular: String
public let italic: String
public let medium: String
public let mediumItalic: String
public let bold: String
public let boldItalic: String
public let heavy: String
public let heavyItalic: String
public let extraheavy: String
public let extraheavyItalic: String
public init(
extralight: String = "",
extralightItalic: String = "",
light: String = "",
lightItalic: String = "",
regular: String = "",
italic: String = "",
medium: String = "",
mediumItalic: String = "",
bold: String = "",
boldItalic: String = "",
heavy: String = "",
heavyItalic: String = "",
extraheavy: String = "",
extraheavyItalic: String = ""
) {
self.extralight = extralight
self.extralightItalic = extralightItalic
self.light = light
self.lightItalic = lightItalic
self.regular = regular
self.italic = italic
self.medium = medium
self.mediumItalic = mediumItalic
self.bold = bold
self.boldItalic = boldItalic
self.heavy = heavy
self.heavyItalic = heavyItalic
self.extraheavy = extraheavy
self.extraheavyItalic = extraheavyItalic
}
}
| mit |
jacobwhite/firefox-ios | UITests/EarlGrey.swift | 13 | 6535 | //
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import EarlGrey
import Foundation
public func GREYAssert(_ expression: @autoclosure () -> Bool, reason: String) {
GREYAssert(expression, reason, details: "Expected expression to be true")
}
public func GREYAssertTrue(_ expression: @autoclosure () -> Bool, reason: String) {
GREYAssert(expression(), reason, details: "Expected the boolean expression to be true")
}
public func GREYAssertFalse(_ expression: @autoclosure () -> Bool, reason: String) {
GREYAssert(!expression(), reason, details: "Expected the boolean expression to be false")
}
public func GREYAssertNotNil(_ expression: @autoclosure ()-> Any?, reason: String) {
GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil")
}
public func GREYAssertNil(_ expression: @autoclosure () -> Any?, reason: String) {
GREYAssert(expression() == nil, reason, details: "Expected expression to be nil")
}
public func GREYAssertEqual(_ left: @autoclosure () -> AnyObject?,
_ right: @autoclosure () -> AnyObject?, reason: String) {
GREYAssert(left() === right(), reason, details: "Expected left term to be equal to right term")
}
public func GREYAssertNotEqual(_ left: @autoclosure () -> AnyObject?,
_ right: @autoclosure () -> AnyObject?, reason: String) {
GREYAssert(left() !== right(), reason, details: "Expected left term to not equal the right term")
}
public func GREYAssertEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?, _ right: @autoclosure () -> T?, reason: String) {
GREYAssert(left() == right(), reason, details: "Expected object of the left term to be equal" +
" to the object of the right term")
}
public func GREYAssertNotEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?, _ right: @autoclosure () -> T?, reason: String) {
GREYAssert(left() != right(), reason, details: "Expected object of the left term to not" +
" equal the object of the right term")
}
public func GREYFail(_ reason: String) {
EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: "")
}
public func GREYFailWithDetails(_ reason: String, details: String) {
EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
private func GREYAssert(_ expression: @autoclosure () -> Bool,
_ reason: String, details: String) {
GREYSetCurrentAsFailable()
if !expression() {
EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
}
private func GREYSetCurrentAsFailable() {
let greyFailureHandlerSelector =
#selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:))
let greyFailureHandler =
Thread.current.threadDictionary.value(forKey: kGREYFailureHandlerKey) as! GREYFailureHandler
if greyFailureHandler.responds(to: greyFailureHandlerSelector) {
greyFailureHandler.setInvocationFile!(#file, andInvocationLine:#line)
}
}
open class EarlGrey: NSObject {
open class func select(elementWithMatcher matcher: GREYMatcher,
file: StaticString = #file,
line: UInt = #line) -> GREYElementInteraction {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.selectElement(with: matcher)
}
open class func setFailureHandler(handler: GREYFailureHandler,
file: StaticString = #file,
line: UInt = #line) {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.setFailureHandler(handler)
}
open class func handle(exception: GREYFrameworkException,
details: String,
file: StaticString = #file,
line: UInt = #line) {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.handle(exception, details: details)
}
@discardableResult open class func rotateDeviceTo(orientation: UIDeviceOrientation,
errorOrNil: UnsafeMutablePointer<NSError?>!,
file: StaticString = #file,
line: UInt = #line)
-> Bool {
return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
.rotateDevice(to: orientation,
errorOrNil: errorOrNil)
}
}
extension GREYInteraction {
@discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher) -> Self {
return self.assert(with:matcher())
}
@discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher,
error: UnsafeMutablePointer<NSError?>!) -> Self {
return self.assert(with: matcher(), error: error)
}
@discardableResult public func using(searchAction: GREYAction,
onElementWithMatcher matcher: GREYMatcher) -> Self {
return self.usingSearch(searchAction, onElementWith: matcher)
}
}
extension GREYCondition {
open func waitWithTimeout(seconds: CFTimeInterval) -> Bool {
return self.wait(withTimeout: seconds)
}
open func waitWithTimeout(seconds: CFTimeInterval, pollInterval: CFTimeInterval)
-> Bool {
return self.wait(withTimeout: seconds, pollInterval: pollInterval)
}
}
| mpl-2.0 |
notbenoit/tvOS-Twitch | Code/iOS/Controllers/Home/Cells/GameCell.swift | 1 | 2024 | // Copyright (c) 2015 Benoit Layer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import ReactiveSwift
import WebImage
import DataSource
final class GameCell: CollectionViewCell {
static let identifier: String = "cellIdentifierGame"
static let nib: UINib = UINib(nibName: "GameCell", bundle: nil)
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var labelName: UILabel!
fileprivate let disposable = CompositeDisposable()
override func prepareForReuse() {
imageView.image = nil
labelName.text = nil
}
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.twitchLightColor()
disposable += self.cellModel.producer
.map { $0 as? GameCellViewModel }
.skipNil()
.startWithValues { [weak self] in self?.configure(with: $0) }
}
private func configure(with item: GameCellViewModel) {
labelName.text = item.gameName
if let url = URL(string: item.gameImageURL) {
imageView.sd_setImage(with: url)
}
}
}
| bsd-3-clause |
mark-randall/Core-Data-Extensions | Pod/Classes/NSManagedObject+Fetching.swift | 1 | 2952 | //
// NSManagedObject+Fetching.swift
// CoreData2
//
// Created by mrandall on 10/12/15.
// Copyright © 2015 mrandall. All rights reserved.
//
import Foundation
import CoreData
//MARK: - Creating
public extension NSManagedObject {
/// Create Self entity name in NSManagedObjectContext
///
/// parameter moc: NSManagedObjectContext
/// returns String
public class func entityNameInContext(_ moc: NSManagedObjectContext) -> String {
let classString = NSStringFromClass(self)
let components = NSStringFromClass(self).components(separatedBy: ".")
return components.last ?? classString
}
/// Create Self in NSManagedObjectContext
///
/// parameter: moc NSManagedObjectContext
public class func createInContext(_ moc: NSManagedObjectContext) -> Self {
return _createInContext(moc, type: self)
}
/// Create Self in NSManagedObjectContext
///
/// parameter moc: NSManagedObjectContext
/// parameter type: Class
/// return type
fileprivate class func _createInContext<T>(_ moc: NSManagedObjectContext, type: T.Type) -> T {
let entityName = entityNameInContext(moc)
let entity = NSEntityDescription.insertNewObject(forEntityName: entityName, into: moc)
return entity as! T
}
}
//MARK: - Fetching
public extension NSManagedObject {
/// Fetch all entities of type T
///
/// parameter sort: [NSSortDescriptor]
/// parameter moc: NSManagedObjectContext
public class func fetchAll<T: NSFetchRequestResult>(sortOn sort: [NSSortDescriptor]? = nil, moc: NSManagedObjectContext) -> [T] {
return self.fetchWithPredicate(nil, sort: sort, prefetchRelationships: nil, moc: moc)
}
/// Fetch entities of type T
///
/// NOTE: Current the return type must be specified where method is called to satisfy T.
/// Hopefully there is a better way in the future of Swift. [Self] is not allowed outside protocol definition
///
/// parameter predicate: NSPredicate
/// parameter sort: [NSSortDescriptor]
/// parameter prefetchRelationships: [String] relationshipKeyPathsForPrefetching value
/// parameter moc: NSManagedObjectContext
public class func fetchWithPredicate<T: NSFetchRequestResult>(
_ predicate: NSPredicate?,
sort: [NSSortDescriptor]? = [],
prefetchRelationships: [String]? = nil,
moc: NSManagedObjectContext
) -> [T] {
//create fetchRequest
let entityName = self.entityNameInContext(moc)
let request = NSFetchRequest<T>(entityName: entityName)
request.predicate = predicate
request.sortDescriptors = sort
request.relationshipKeyPathsForPrefetching = prefetchRelationships
//execute fetch
do {
return try moc.fetch(request).map { return $0 as! T }
} catch {
return []
}
}
}
| mit |
sschiau/swift-package-manager | Tests/PackageGraphTests/PackageGraphTests.swift | 1 | 28155 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import PackageGraph
import PackageModel
import TestSupport
class PackageGraphTests: XCTestCase {
func testBasic() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/source.swift",
"/Foo/Sources/FooDep/source.swift",
"/Foo/Tests/FooTests/source.swift",
"/Bar/source.swift",
"/Baz/Sources/Baz/source.swift",
"/Baz/Tests/BazTests/source.swift"
)
let diagnostics = DiagnosticsEngine()
let g = loadPackageGraph(root: "/Baz", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
products: [
ProductDescription(name: "Foo", targets: ["Foo"])
],
targets: [
TargetDescription(name: "Foo", dependencies: ["FooDep"]),
TargetDescription(name: "FooDep", dependencies: []),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
dependencies: [
PackageDependencyDescription(url: "/Foo", requirement: .upToNextMajor(from: "1.0.0"))
],
products: [
ProductDescription(name: "Bar", targets: ["Bar"])
],
targets: [
TargetDescription(name: "Bar", dependencies: ["Foo"], path: "./")
]),
Manifest.createV4Manifest(
name: "Baz",
path: "/Baz",
url: "/Baz",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Baz", dependencies: ["Bar"]),
TargetDescription(name: "BazTests", dependencies: ["Baz"], type: .test),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(g) { result in
result.check(packages: "Bar", "Foo", "Baz")
result.check(targets: "Bar", "Foo", "Baz", "FooDep")
result.check(testModules: "BazTests")
result.check(dependencies: "FooDep", target: "Foo")
result.check(dependencies: "Foo", target: "Bar")
result.check(dependencies: "Bar", target: "Baz")
}
}
func testProductDependencies() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/source.swift",
"/Bar/Source/Bar/source.swift",
"/Bar/Source/CBar/module.modulemap"
)
let diagnostics = DiagnosticsEngine()
let g = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Foo", dependencies: ["Bar", "CBar"]),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
products: [
ProductDescription(name: "Bar", targets: ["Bar"]),
ProductDescription(name: "CBar", targets: ["CBar"]),
],
targets: [
TargetDescription(name: "Bar", dependencies: ["CBar"]),
TargetDescription(name: "CBar", type: .system),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(g) { result in
result.check(packages: "Bar", "Foo")
result.check(targets: "Bar", "CBar", "Foo")
result.check(dependencies: "Bar", "CBar", target: "Foo")
result.check(dependencies: "CBar", target: "Bar")
}
}
func testCycle() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/source.swift",
"/Bar/Sources/Bar/source.swift",
"/Baz/Sources/Baz/source.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Foo"),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
dependencies: [
PackageDependencyDescription(url: "/Baz", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Baz",
path: "/Baz",
url: "/Baz",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Baz"),
]),
]
)
XCTAssertEqual(diagnostics.diagnostics[0].localizedDescription, "cyclic dependency declaration found: Foo -> Bar -> Baz -> Bar")
}
func testCycle2() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/source.swift",
"/Bar/Sources/Bar/source.swift",
"/Baz/Sources/Baz/source.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Foo", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Foo"),
]),
]
)
XCTAssertEqual(diagnostics.diagnostics[0].localizedDescription, "cyclic dependency declaration found: Foo -> Foo")
}
// Make sure there is no error when we reference Test targets in a package and then
// use it as a dependency to another package. SR-2353
func testTestTargetDeclInExternalPackage() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/source.swift",
"/Foo/Tests/FooTests/source.swift",
"/Bar/Sources/Bar/source.swift",
"/Bar/Tests/BarTests/source.swift"
)
let diagnostics = DiagnosticsEngine()
let g = loadPackageGraph(root: "/Bar", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
dependencies: [
PackageDependencyDescription(url: "/Foo", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Bar", dependencies: ["Foo"]),
TargetDescription(name: "BarTests", dependencies: ["Bar"], type: .test),
]),
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
products: [
ProductDescription(name: "Foo", targets: ["Foo"]),
],
targets: [
TargetDescription(name: "Foo", dependencies: []),
TargetDescription(name: "FooTests", dependencies: ["Foo"], type: .test),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
PackageGraphTester(g) { result in
result.check(packages: "Bar", "Foo")
result.check(targets: "Bar", "Foo")
result.check(testModules: "BarTests")
}
}
func testDuplicateModules() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Bar/source.swift",
"/Bar/Sources/Bar/source.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
targets: [
TargetDescription(name: "Bar"),
]),
]
)
XCTAssertEqual(diagnostics.diagnostics[0].localizedDescription, "multiple targets named 'Bar' in: Bar, Foo")
}
func testMultipleDuplicateModules() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Fourth/Sources/First/source.swift",
"/Third/Sources/First/source.swift",
"/Second/Sources/First/source.swift",
"/First/Sources/First/source.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/First", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Fourth",
path: "/Fourth",
url: "/Fourth",
products: [
ProductDescription(name: "Fourth", targets: ["First"])
],
targets: [
TargetDescription(name: "First"),
]),
Manifest.createV4Manifest(
name: "Third",
path: "/Third",
url: "/Third",
products: [
ProductDescription(name: "Third", targets: ["First"])
],
targets: [
TargetDescription(name: "First"),
]),
Manifest.createV4Manifest(
name: "Second",
path: "/Second",
url: "/Second",
products: [
ProductDescription(name: "Second", targets: ["First"])
],
targets: [
TargetDescription(name: "First"),
]),
Manifest.createV4Manifest(
name: "First",
path: "/First",
url: "/First",
dependencies: [
PackageDependencyDescription(url: "/Second", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Third", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Fourth", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "First", dependencies: ["Second", "Third", "Fourth"]),
]),
]
)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "multiple targets named 'First' in: First, Fourth, Second, Third", behavior: .error)
}
}
func testSeveralDuplicateModules() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Fourth/Sources/Bar/source.swift",
"/Third/Sources/Bar/source.swift",
"/Second/Sources/Foo/source.swift",
"/First/Sources/Foo/source.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/First", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Fourth",
path: "/Fourth",
url: "/Fourth",
products: [
ProductDescription(name: "Fourth", targets: ["Bar"])
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Third",
path: "/Third",
url: "/Third",
products: [
ProductDescription(name: "Third", targets: ["Bar"])
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Second",
path: "/Second",
url: "/Second",
products: [
ProductDescription(name: "Second", targets: ["Foo"])
],
targets: [
TargetDescription(name: "Foo"),
]),
Manifest.createV4Manifest(
name: "First",
path: "/First",
url: "/First",
dependencies: [
PackageDependencyDescription(url: "/Second", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Third", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Fourth", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Foo", dependencies: ["Second", "Third", "Fourth"]),
]),
]
)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "multiple targets named 'Bar' in: Fourth, Third", behavior: .error)
result.check(diagnostic: "multiple targets named 'Foo' in: First, Second", behavior: .error)
}
}
func testNestedDuplicateModules() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Fourth/Sources/First/source.swift",
"/Third/Sources/Third/source.swift",
"/Second/Sources/Second/source.swift",
"/First/Sources/First/source.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/First", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Fourth",
path: "/Fourth",
url: "/Fourth",
products: [
ProductDescription(name: "Fourth", targets: ["First"])
],
targets: [
TargetDescription(name: "First"),
]),
Manifest.createV4Manifest(
name: "Third",
path: "/Third",
url: "/Third",
dependencies: [
PackageDependencyDescription(url: "/Fourth", requirement: .upToNextMajor(from: "1.0.0")),
],
products: [
ProductDescription(name: "Third", targets: ["Third"])
],
targets: [
TargetDescription(name: "Third", dependencies: ["Fourth"]),
]),
Manifest.createV4Manifest(
name: "Second",
path: "/Second",
url: "/Second",
dependencies: [
PackageDependencyDescription(url: "/Third", requirement: .upToNextMajor(from: "1.0.0")),
],
products: [
ProductDescription(name: "Second", targets: ["Second"])
],
targets: [
TargetDescription(name: "Second", dependencies: ["Third"]),
]),
Manifest.createV4Manifest(
name: "First",
path: "/First",
url: "/First",
dependencies: [
PackageDependencyDescription(url: "/Second", requirement: .upToNextMajor(from: "1.0.0")),
],
products: [
ProductDescription(name: "First", targets: ["First"])
],
targets: [
TargetDescription(name: "First", dependencies: ["Second"]),
]),
]
)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "multiple targets named 'First' in: First, Fourth", behavior: .error)
}
}
func testEmptyDependency() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/foo.swift",
"/Bar/Sources/Bar/source.txt"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Foo", dependencies: ["Bar"]),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
products: [
ProductDescription(name: "Bar", targets: ["Bar"])
],
targets: [
TargetDescription(name: "Bar"),
]),
]
)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "target 'Bar' in package 'Bar' contains no valid source files", behavior: .warning)
result.check(diagnostic: "target 'Bar' referenced in product 'Bar' could not be found", behavior: .error, location: "'Bar' /Bar")
result.check(diagnostic: "product dependency 'Bar' not found", behavior: .error, location: "'Foo' /Foo")
}
}
func testUnusedDependency() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/foo.swift",
"/Bar/Sources/Bar/bar.swift",
"/Baz/Sources/Baz/baz.swift",
"/Biz/Sources/Biz/main.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Baz", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Biz", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Foo", dependencies: ["BarLibrary"]),
]),
Manifest.createV4Manifest(
name: "Biz",
path: "/Biz",
url: "/Biz",
products: [
ProductDescription(name: "biz", type: .executable, targets: ["Biz"])
],
targets: [
TargetDescription(name: "Biz"),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
products: [
ProductDescription(name: "BarLibrary", targets: ["Bar"])
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Baz",
path: "/Baz",
url: "/Baz",
products: [
ProductDescription(name: "BazLibrary", targets: ["Baz"])
],
targets: [
TargetDescription(name: "Baz"),
]),
]
)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "dependency 'Baz' is not used by any target", behavior: .warning)
}
}
func testUnusedDependency2() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/module.modulemap",
"/Bar/Sources/Bar/main.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Bar", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
dependencies: [
PackageDependencyDescription(url: "/Foo", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo"),
]
)
// We don't expect any unused dependency diagnostics from a system module package.
DiagnosticsEngineTester(diagnostics) { _ in }
}
func testDuplicateInterPackageTargetNames() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Start/Sources/Foo/foo.swift",
"/Start/Sources/Bar/bar.swift",
"/Dep1/Sources/Baz/baz.swift",
"/Dep2/Sources/Foo/foo.swift",
"/Dep2/Sources/Bam/bam.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Start", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Start",
path: "/Start",
url: "/Start",
dependencies: [
PackageDependencyDescription(url: "/Dep1", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Foo", dependencies: ["BazLibrary"]),
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Dep1",
path: "/Dep1",
url: "/Dep1",
dependencies: [
PackageDependencyDescription(url: "/Dep2", requirement: .upToNextMajor(from: "1.0.0")),
],
products: [
ProductDescription(name: "BazLibrary", targets: ["Baz"])
],
targets: [
TargetDescription(name: "Baz", dependencies: ["FooLibrary"]),
]),
Manifest.createV4Manifest(
name: "Dep2",
path: "/Dep2",
url: "/Dep2",
products: [
ProductDescription(name: "FooLibrary", targets: ["Foo"]),
ProductDescription(name: "BamLibrary", targets: ["Bam"]),
],
targets: [
TargetDescription(name: "Foo"),
TargetDescription(name: "Bam"),
]),
]
)
DiagnosticsEngineTester(diagnostics) { result in
result.check(diagnostic: "multiple targets named 'Foo' in: Dep2, Start", behavior: .error)
}
}
func testDuplicateProducts() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/foo.swift",
"/Bar/Sources/Bar/bar.swift",
"/Baz/Sources/Baz/baz.swift"
)
let diagnostics = DiagnosticsEngine()
_ = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/Baz", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Foo", dependencies: ["Bar"]),
]),
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
products: [
ProductDescription(name: "Bar", targets: ["Bar"])
],
targets: [
TargetDescription(name: "Bar"),
]),
Manifest.createV4Manifest(
name: "Baz",
path: "/Baz",
url: "/Baz",
products: [
ProductDescription(name: "Bar", targets: ["Baz"])
],
targets: [
TargetDescription(name: "Baz"),
]),
]
)
XCTAssertTrue(diagnostics.diagnostics.contains(where: { $0.localizedDescription.contains("multiple products named 'Bar' in: Bar, Baz") }), "\(diagnostics.diagnostics)")
}
}
| apache-2.0 |
victorpimentel/SwiftLint | Tests/SwiftLintFrameworkTests/TrailingCommaRuleTests.swift | 2 | 3732 | //
// TrailingCommaRuleTests.swift
// SwiftLint
//
// Created by Matt Rubin on 12/22/16.
// Copyright © 2016 Realm. All rights reserved.
//
import SwiftLintFramework
import XCTest
class TrailingCommaRuleTests: XCTestCase {
func testTrailingCommaRuleWithDefaultConfiguration() {
// Verify TrailingCommaRule with test values for when mandatory_comma is false (default).
verifyRule(TrailingCommaRule.description)
// Ensure the rule produces the correct reason string.
let failingCase = "let array = [\n\t1,\n\t2,\n]\n"
XCTAssertEqual(trailingCommaViolations(failingCase), [
StyleViolation(
ruleDescription: TrailingCommaRule.description,
location: Location(file: nil, line: 3, character: 3),
reason: "Collection literals should not have trailing commas."
)]
)
}
private static let triggeringExamples = [
"let foo = [1, 2,\n 3↓]\n",
"let foo = [1: 2,\n 2: 3↓]\n",
"let foo = [1: 2,\n 2: 3↓ ]\n",
"struct Bar {\n let foo = [1: 2,\n 2: 3↓]\n}\n",
"let foo = [1, 2,\n 3↓] + [4,\n 5, 6↓]\n",
"let foo = [\"אבג\", \"αβγ\",\n\"🇺🇸\"↓]\n"
]
private static let corrections: [String: String] = {
let fixed = triggeringExamples.map { $0.replacingOccurrences(of: "↓", with: ",") }
var result: [String: String] = [:]
for (triggering, correction) in zip(triggeringExamples, fixed) {
result[triggering] = correction
}
return result
}()
private let mandatoryCommaRuleDescription = RuleDescription(
identifier: TrailingCommaRule.description.identifier,
name: TrailingCommaRule.description.name,
description: TrailingCommaRule.description.description,
nonTriggeringExamples: [
"let foo = []\n",
"let foo = [:]\n",
"let foo = [1, 2, 3,]\n",
"let foo = [1, 2, 3, ]\n",
"let foo = [1, 2, 3 ,]\n",
"let foo = [1: 2, 2: 3, ]\n",
"struct Bar {\n let foo = [1: 2, 2: 3,]\n}\n",
"let foo = [Void]()\n",
"let foo = [(Void, Void)]()\n",
"let foo = [1, 2, 3]\n",
"let foo = [1: 2, 2: 3]\n",
"let foo = [1: 2, 2: 3 ]\n",
"struct Bar {\n let foo = [1: 2, 2: 3]\n}\n",
"let foo = [1, 2, 3] + [4, 5, 6]\n"
],
triggeringExamples: TrailingCommaRuleTests.triggeringExamples,
corrections: TrailingCommaRuleTests.corrections
)
func testTrailingCommaRuleWithMandatoryComma() {
// Verify TrailingCommaRule with test values for when mandatory_comma is true.
let ruleDescription = mandatoryCommaRuleDescription
let ruleConfiguration = ["mandatory_comma": true]
verifyRule(ruleDescription, ruleConfiguration: ruleConfiguration)
// Ensure the rule produces the correct reason string.
let failingCase = "let array = [\n\t1,\n\t2\n]\n"
XCTAssertEqual(trailingCommaViolations(failingCase, ruleConfiguration: ruleConfiguration), [
StyleViolation(
ruleDescription: TrailingCommaRule.description,
location: Location(file: nil, line: 3, character: 3),
reason: "Multi-line collection literals should have trailing commas."
)]
)
}
private func trailingCommaViolations(_ string: String, ruleConfiguration: Any? = nil) -> [StyleViolation] {
let config = makeConfig(ruleConfiguration, TrailingCommaRule.description.identifier)!
return SwiftLintFrameworkTests.violations(string, config: config)
}
}
| mit |
dvor/Antidote | Antidote/OCTManagerMock.swift | 1 | 8424 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
import MobileCoreServices
private enum Gender {
case male
case female
}
class OCTManagerMock: NSObject, OCTManager {
var bootstrap: OCTSubmanagerBootstrap
var calls: OCTSubmanagerCalls
var chats: OCTSubmanagerChats
var dns: OCTSubmanagerDNS
var files: OCTSubmanagerFiles
var friends: OCTSubmanagerFriends
var objects: OCTSubmanagerObjects
var user: OCTSubmanagerUser
var realm: RLMRealm
override init() {
let configuration = RLMRealmConfiguration.default()
configuration.inMemoryIdentifier = "test realm"
realm = try! RLMRealm(configuration: configuration)
bootstrap = OCTSubmanagerBootstrapMock()
calls = OCTSubmanagerCallsMock()
chats = OCTSubmanagerChatsMock()
dns = OCTSubmanagerDNSMock()
files = OCTSubmanagerFilesMock()
friends = OCTSubmanagerFriendsMock()
objects = OCTSubmanagerObjectsMock(realm: realm)
user = OCTSubmanagerUserMock()
super.init()
populateRealm()
}
func configuration() -> OCTManagerConfiguration {
return OCTManagerConfiguration()
}
func exportToxSaveFile() throws -> String {
return "123"
}
func changeEncryptPassword(_ newPassword: String, oldPassword: String) -> Bool {
return true
}
func isManagerEncrypted(withPassword password: String) -> Bool {
return true
}
}
private extension OCTManagerMock {
func populateRealm() {
realm.beginWriteTransaction()
let f1 = addFriend(gender: .female, number: 1, connectionStatus: .TCP, status: .none)
let f2 = addFriend(gender: .male, number: 1, connectionStatus: .TCP, status: .busy)
let f3 = addFriend(gender: .female, number: 2, connectionStatus: .none, status: .none)
let f4 = addFriend(gender: .male, number: 2, connectionStatus: .TCP, status: .away)
let f5 = addFriend(gender: .male, number: 3, connectionStatus: .TCP, status: .none)
let f6 = addFriend(gender: .female, number: 3, connectionStatus: .TCP, status: .away)
let f7 = addFriend(gender: .male, number: 4, connectionStatus: .TCP, status: .away)
let f8 = addFriend(gender: .female, number: 4, connectionStatus: .none, status: .none)
let f9 = addFriend(gender: .female, number: 5, connectionStatus: .TCP, status: .none)
let f10 = addFriend(gender: .male, number: 5, connectionStatus: .none, status: .none)
let c1 = addChat(friend: f1)
let c2 = addChat(friend: f2)
let c3 = addChat(friend: f3)
let c4 = addChat(friend: f4)
let c5 = addChat(friend: f5)
let c6 = addChat(friend: f6)
let c7 = addChat(friend: f7)
let c8 = addChat(friend: f8)
let c9 = addChat(friend: f9)
let c10 = addChat(friend: f10)
addDemoConversationToChat(c1)
addCallMessage(chat: c2, outgoing: false, answered: false, duration: 0.0)
addTextMessage(chat: c3, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_1"))
addCallMessage(chat: c4, outgoing: true, answered: true, duration: 1473.0)
addTextMessage(chat: c5, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_2"))
addFileMessage(chat: c6, outgoing: false, fileName: "party.png")
addTextMessage(chat: c7, outgoing: true, text: String(localized: "app_store_screenshot_chat_message_3"))
addTextMessage(chat: c8, outgoing: true, text: String(localized: "app_store_screenshot_chat_message_4"))
addFileMessage(chat: c9, outgoing: true, fileName: "presentation_2016.pdf")
addTextMessage(chat: c10, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_5"))
c1.lastReadDateInterval = Date().timeIntervalSince1970
// unread message
// c2.lastReadDateInterval = NSDate().timeIntervalSince1970
c3.lastReadDateInterval = Date().timeIntervalSince1970
c4.lastReadDateInterval = Date().timeIntervalSince1970
c5.lastReadDateInterval = Date().timeIntervalSince1970
c6.lastReadDateInterval = Date().timeIntervalSince1970
c7.lastReadDateInterval = Date().timeIntervalSince1970
c8.lastReadDateInterval = Date().timeIntervalSince1970
c9.lastReadDateInterval = Date().timeIntervalSince1970
c10.lastReadDateInterval = Date().timeIntervalSince1970
try! realm.commitWriteTransaction()
}
func addFriend(gender: Gender,
number: Int,
connectionStatus: OCTToxConnectionStatus,
status: OCTToxUserStatus) -> OCTFriend {
let friend = OCTFriend()
friend.publicKey = "123"
friend.connectionStatus = connectionStatus
friend.isConnected = connectionStatus != .none
friend.status = status
switch gender {
case .male:
friend.nickname = String(localized: "app_store_screenshot_friend_male_\(number)")
friend.avatarData = UIImagePNGRepresentation(UIImage(named: "male-\(number)")!)
case .female:
friend.nickname = String(localized: "app_store_screenshot_friend_female_\(number)")
friend.avatarData = UIImagePNGRepresentation(UIImage(named: "female-\(number)")!)
}
realm.add(friend)
return friend
}
func addChat(friend: OCTFriend) -> OCTChat {
let chat = OCTChat()
realm.add(chat)
chat.friends.add(friend)
return chat
}
func addDemoConversationToChat(_ chat: OCTChat) {
addFileMessage(chat: chat, outgoing: false, fileName: "party.png")
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_1"))
addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_2"))
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_3"))
addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_4"))
addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_5"))
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_6"))
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_7"))
}
func addTextMessage(chat: OCTChat, outgoing: Bool, text: String) {
let messageText = OCTMessageText()
messageText.text = text
messageText.isDelivered = outgoing
let message = addMessageAbstract(chat: chat, outgoing: outgoing)
message.messageText = messageText
}
func addFileMessage(chat: OCTChat, outgoing: Bool, fileName: String) {
let messageFile = OCTMessageFile()
messageFile.fileName = fileName
messageFile.internalFilePath = Bundle.main.path(forResource: "dummy-photo", ofType: "jpg")
messageFile.fileType = .ready
messageFile.fileUTI = kUTTypeImage as String
let message = addMessageAbstract(chat: chat, outgoing: outgoing)
message.messageFile = messageFile
}
func addCallMessage(chat: OCTChat, outgoing: Bool, answered: Bool, duration: TimeInterval) {
let messageCall = OCTMessageCall()
messageCall.callDuration = duration
messageCall.callEvent = answered ? .answered : .unanswered
let message = addMessageAbstract(chat: chat, outgoing: outgoing)
message.messageCall = messageCall
}
func addMessageAbstract(chat: OCTChat, outgoing: Bool) -> OCTMessageAbstract {
let message = OCTMessageAbstract()
if !outgoing {
let friend = chat.friends.firstObject() as! OCTFriend
message.senderUniqueIdentifier = friend.uniqueIdentifier
}
message.chatUniqueIdentifier = chat.uniqueIdentifier
message.dateInterval = Date().timeIntervalSince1970
realm.add(message)
chat.lastMessage = message
return message
}
}
| mit |
chetca/Android_to_iOs | memuDemo/CurrentHistoryController.swift | 1 | 1207 | //
// CurrentHistoryController.swift
// memuDemo
//
// Created by Dugar Badagarov on 26/08/2017.
// Copyright © 2017 Parth Changela. All rights reserved.
//
import UIKit
class CurrentHistoryController: UIViewController {
@IBOutlet var dateTime: UILabel!
@IBOutlet var text: UILabel!
@IBOutlet var img: UIImageView!
@IBOutlet var titleText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
dateTime.text=StringDataField
text.text = StringText
titleText.text = StringLblText
img.image = JSONTaker.shared.loadImg(url: StringUrlImg)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/About/Settings/Sections/Language/LanagageCell.swift | 1 | 2643 | //
// LanagageCell.swift
// EclipseSoundscapes
//
// Created by Arlindo on 12/26/20.
// Copyright © 2020 Eclipse Soundscapes. All rights reserved.
//
import RxSwift
class LanguageCell: RxTableViewCell, SettingCell {
private let infoLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true
label.numberOfLines = 0
return label
}()
private let settingsButton: RoundedButton = {
let button = RoundedButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body)
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.addSqueeze()
button.backgroundColor = SoundscapesColor.eclipseOrange
return button
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
selectionStyle = .none
contentView.addSubviews(infoLabel, settingsButton)
[infoLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
infoLabel.bottomAnchor.constraint(equalTo: settingsButton.topAnchor, constant: -16),
infoLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16),
infoLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16),
settingsButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
settingsButton.leftAnchor.constraint(equalTo: infoLabel.leftAnchor),
settingsButton.rightAnchor.constraint(equalTo: infoLabel.rightAnchor),
settingsButton.heightAnchor.constraint(greaterThanOrEqualToConstant: 50)
].forEach { $0.isActive = true }
}
func configure(with settingItem: SettingItem) {
guard let languageSettingItem = settingItem as? LanguageSettingItem else { return }
infoLabel.text = languageSettingItem.info
settingsButton.setTitle(languageSettingItem.setingsButtonTitle, for: .normal)
settingsButton.rx.tap
.map { Action.openDeviceSettings }
.bind(to: languageSettingItem.rx.react)
.disposed(by: disposeBag)
}
}
| gpl-3.0 |
glessard/swift-channels | ChannelsTests/SelectTests.swift | 1 | 7293 | //
// SelectTests.swift
// Channels
//
// Created by Guillaume Lessard on 2015-01-15.
// Copyright (c) 2015 Guillaume Lessard. All rights reserved.
//
import Darwin
import Foundation
import XCTest
@testable import Channels
class SelectUnbufferedTests: XCTestCase
{
var selectableCount: Int { return 10 }
func MakeChannels() -> [Chan<Int>]
{
return (0..<selectableCount).map { _ in Chan<Int>.Make() }
}
func getIterations(_ sleepInterval: TimeInterval) -> Int
{
return sleepInterval < 0 ? ChannelsTests.performanceTestIterations : 100
}
func SelectReceiverTest(sleepInterval: TimeInterval = -1)
{
let iterations = getIterations(sleepInterval)
let channels = MakeChannels()
let senders = channels.map { Sender($0) }
let receivers = channels.map { Receiver($0) }
async {
if sleepInterval > 0
{
for i in 0..<iterations
{
Foundation.Thread.sleep(forTimeInterval: sleepInterval)
let index = Int(arc4random_uniform(UInt32(senders.count)))
senders[index] <- i
}
Foundation.Thread.sleep(forTimeInterval: sleepInterval > 0 ? sleepInterval : 1e-6)
for sender in senders { sender.close() }
}
else
{
for i in 0..<senders.count
{
let sender = senders[i]
let messages = iterations/senders.count + ((i < iterations%senders.count) ? 1:0)
DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!).async {
for m in 0..<messages
{
sender.send(m)
}
sender.close()
}
}
}
}
var i = 0
// Currently required to avoid a runtime crash:
let selectables = receivers.map { $0 as Selectable }
while let selection = select_chan(selectables)
{
if let receiver = selection.id as? Receiver<Int>
{
if let _ = receiver.extract(selection) { i += 1 }
}
}
XCTAssert(i == iterations, "Received \(i) messages; expected \(iterations)")
}
func testPerformanceSelectReceiver()
{
self.measure {
self.SelectReceiverTest()
}
}
func testSelectReceiverWithSleep()
{
SelectReceiverTest(sleepInterval: 0.01)
}
func SelectSenderTest(sleepInterval: TimeInterval = -1)
{
let iterations = getIterations(sleepInterval)
let channels = MakeChannels()
let senders = channels.map { Sender($0) }
let receivers = channels.map { Receiver($0) }
async {
var i = 0
// Currently required to avoid a runtime crash:
let selectables = senders.map { $0 as Selectable }
while i < iterations, let selection = select_chan(selectables)
{
if let sender = selection.id as? Sender<Int>
{
if sender.insert(selection, newElement: i) { i += 1 }
}
}
for sender in senders { sender.close() }
}
var m = 0
if sleepInterval > 0
{
let receiver = merge(receivers)
while let _ = receiver.receive()
{
m += 1
Foundation.Thread.sleep(forTimeInterval: sleepInterval)
}
}
else
{
let result = Channel<Int>.Make(channels.count)
let g = DispatchGroup()
let q = DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!)
for i in 0..<channels.count
{
let receiver = receivers[i]
q.async(group: g) {
var i = 0
while let _ = receiver.receive() { i += 1 }
result.tx <- i
}
}
g.notify(queue: q) { result.tx.close() }
while let count = <-result.rx { m += count }
}
XCTAssert(m == iterations, "Received \(m) messages; expected \(iterations)")
}
func testPerformanceSelectSender()
{
self.measure {
self.SelectSenderTest()
}
}
func testSelectSenderWithSleep()
{
SelectSenderTest(sleepInterval: 0.01)
}
fileprivate enum Sleeper { case receiver; case sender; case none }
fileprivate func DoubleSelectTest(sleeper: Sleeper)
{
let sleepInterval = (sleeper == .none) ? -1.0 : 0.01
let iterations = getIterations(sleepInterval)
let channels = MakeChannels()
let senders = channels.map { Sender($0) }
let receivers = channels.map { Receiver($0) }
async {
var i = 0
// Currently required to avoid a runtime crash:
let selectables = senders.map { $0 as Selectable }
while let selection = select_chan(selectables)
{
if let sender = selection.id as? Sender<Int>
{
if sender.insert(selection, newElement: i)
{
i += 1
if sleeper == .sender { Foundation.Thread.sleep(forTimeInterval: sleepInterval) }
if i >= iterations { break }
}
}
}
for sender in senders { sender.close() }
}
var i = 0
// Currently required to avoid a runtime crash:
let selectables = receivers.map { $0 as Selectable }
while let selection = select_chan(selectables)
{
if let receiver = selection.id as? Receiver<Int>
{
if let _ = receiver.extract(selection)
{
i += 1
if sleeper == .receiver { Foundation.Thread.sleep(forTimeInterval: sleepInterval) }
}
}
}
XCTAssert(i == iterations, "Received \(i) messages; expected \(iterations)")
}
func testPerformanceDoubleSelect()
{
self.measure {
self.DoubleSelectTest(sleeper: .none)
}
}
func testDoubleSelectSlowGet()
{
DoubleSelectTest(sleeper: .receiver)
}
func testDoubleSelectSlowPut()
{
DoubleSelectTest(sleeper: .sender)
}
func testSelectAndCloseReceivers()
{
let channels = MakeChannels()
let senders = channels.map { Sender(channelType: $0) }
let receivers = channels.map { Receiver(channelType: $0) }
let q = DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!)
q.asyncAfter(deadline: DispatchTime.now() + Double(10_000_000) / Double(NSEC_PER_SEC)) {
for sender in senders { sender.close() }
}
let selectables = receivers.map { $0 as Selectable }
while let selection = select_chan(selectables)
{
if selection.id is Receiver<Int>
{
XCTFail("Should not return one of our Receivers")
}
}
}
func testSelectAndCloseSenders()
{
let channels = MakeChannels()
let senders = channels.map { Sender(channelType: $0) }
let q = DispatchQueue.global(qos: DispatchQoS.QoSClass(rawValue: qos_class_self())!)
q.asyncAfter(deadline: DispatchTime.now() + Double(10_000_000) / Double(NSEC_PER_SEC)) {
for sender in senders { sender.close() }
}
for sender in senders
{ // fill up the buffers so that the select_chan() below will block
while sender.isFull == false { sender <- 0 }
}
let selectables = senders.map { $0 as Selectable }
while let selection = select_chan(selectables)
{
if selection.id is Sender<Int>
{
XCTFail("Should not return one of our Senders")
}
}
}
}
class SelectBufferedTests: SelectUnbufferedTests
{
override func MakeChannels() -> [Chan<Int>]
{
return (0..<selectableCount).map { _ in Chan<Int>.Make(1) }
}
}
| mit |
Aioria1314/WeiBo | WeiBo/WeiBo/Classes/Views/Home/ZXCHomeController.swift | 1 | 5759 | //
// ZXCHomeController.swift
// WeiBo
//
// Created by Aioria on 2017/3/26.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
import YYModel
class ZXCHomeController: ZXCVistorViewController {
// lazy var statusList: [ZXCStatus] = [ZXCStatus]()
fileprivate lazy var pullUpView: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
indicatorView.color = UIColor.red
return indicatorView
}()
// fileprivate lazy var pullDownView: UIRefreshControl = {
//
// let refresh = UIRefreshControl()
//
// refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged)
//
// return refresh
// }()
fileprivate lazy var pullDownView: ZXCRefreshControl = {
let refresh = ZXCRefreshControl()
refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged)
return refresh
}()
fileprivate lazy var labTip: UILabel = {
let lab = UILabel()
lab.text = "没有加载到最新数据"
lab.isHidden = true
lab.textColor = UIColor.white
lab.backgroundColor = UIColor.orange
lab.font = UIFont.systemFont(ofSize: 15)
lab.textAlignment = .center
return lab
}()
fileprivate lazy var homeViewModel: ZXCHomeViewModel = ZXCHomeViewModel()
override func viewDidLoad()
{
super.viewDidLoad()
if !isLogin {
visitorView?.updateVisitorInfo(imgName: nil, message: nil)
}
else {
loadData()
setupUI()
}
}
fileprivate func setupUI() {
setupTableView()
if let nav = self.navigationController {
nav.view.insertSubview(labTip, belowSubview: nav.navigationBar)
labTip.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.width, height: 35)
}
}
fileprivate func setupTableView() {
tableView.register(ZXCHomeTableViewCell.self, forCellReuseIdentifier: homeReuseID)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
tableView.separatorStyle = .none
tableView.tableFooterView = pullUpView
// self.refreshControl = pullDownView
tableView.addSubview(pullDownView)
}
fileprivate func loadData() {
// ZXCNetworkTools.sharedTools.requestHomeData(accessToken: ZXCUserAccountViewModel.sharedViewModel.accessToken!) { (response, error) in
//
// if error != nil {
// }
//
// guard let dict = response as? [String: Any] else {
// return
// }
//
// let statusDic = dict["statuses"] as? [[String: Any]]
//
// let statusArray = NSArray.yy_modelArray(with: ZXCStatus.self, json: statusDic!) as! [ZXCStatus]
//
// self.statusList = statusArray
//
// self.tableView.reloadData()
// }
homeViewModel.requestHomeData(isPullup: pullUpView.isAnimating) { (isSuccess, message) in
if self.pullUpView.isAnimating == false {
if self.labTip.isHidden == false {
return
}
self.tipAnimation(message: message)
}
self.endRefreshing()
if isSuccess {
self.tableView.reloadData()
}
}
}
fileprivate func endRefreshing() {
pullUpView.stopAnimating()
pullDownView.endRefreshing()
}
// MARK: DataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.homeViewModel.statusList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ZXCHomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: homeReuseID, for: indexPath) as! ZXCHomeTableViewCell
cell.statusViewModel = homeViewModel.statusList[indexPath.row]
// cell.textLabel?.text = homeViewModel.statusList[indexPath.row].user?.screen_name
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == homeViewModel.statusList.count - 1 && !pullUpView.isAnimating{
pullUpView.startAnimating()
loadData()
}
}
@objc fileprivate func pullDownrefreshAction () {
loadData()
}
fileprivate func tipAnimation(message: String) {
labTip.text = message
labTip.isHidden = false
UIView.animate(withDuration: 1, animations: {
self.labTip.transform = CGAffineTransform(translationX: 0, y: self.labTip.height)
}) { (_) in
UIView.animate(withDuration: 1, animations: {
self.labTip.transform = CGAffineTransform.identity
}, completion: { (_) in
self.labTip.isHidden = true
})
}
}
}
| mit |
solszl/Shrimp500px | Shrimp500px/ViewControllers/Discover/UserView/UserViewModel.swift | 1 | 501 | //
// UserViewModel.swift
// Shrimp500px
//
// Created by 振亮 孙 on 16/3/12.
// Copyright © 2016年 papa.studio. All rights reserved.
//
import Foundation
class UserViewModel {
var data: [RecommendUserInfo] = []
let bizz: BizzUser = BizzUser()
init() {
}
func fetchNewUser(callback:(()->Void)? = nil) {
bizz.fatchRecommendUser { (userList, error) -> Void in
self.data = userList!
callback!()
}
}
} | mit |
drinkapoint/DrinkPoint-iOS | DrinkPoint/Pods/FacebookShare/Sources/Share/Views/LikeButton.swift | 1 | 4045 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import FBSDKShareKit
/**
A button to like an object.
Tapping the receiver will invoke an API call to the Facebook app through a fast-app-switch that allows
the object to be liked. Upon return to the calling app, the view will update with the new state. If the
currentAccessToken has "publish_actions" permission and the object is an Open Graph object, then the like can happen
seamlessly without the fast-app-switch.
*/
public class LikeButton: UIView {
private var sdkLikeButton: FBSDKLikeButton
/// If `true`, a sound is played when the reciever is toggled.
public var isSoundEnabled: Bool {
get {
return sdkLikeButton.soundEnabled
}
set {
sdkLikeButton.soundEnabled = newValue
}
}
/// The object to like
public var object: LikableObject {
get {
return LikableObject(sdkObjectType: sdkLikeButton.objectType, sdkObjectId: sdkLikeButton.objectID)
}
set {
let sdkRepresentation = newValue.sdkObjectRepresntation
sdkLikeButton.objectType = sdkRepresentation.objectType
sdkLikeButton.objectID = sdkRepresentation.objectId
}
}
/**
Create a new LikeButton with a given frame and object.
- parameter frame: The frame to initialize with.
- parameter object: The object to like.
*/
public init(frame: CGRect? = nil, object: LikableObject) {
let sdkLikeButton = FBSDKLikeButton()
let frame = frame ?? sdkLikeButton.bounds
self.sdkLikeButton = sdkLikeButton
super.init(frame: frame)
self.object = object
self.addSubview(sdkLikeButton)
}
/**
Create a new LikeButton from an encoded interface file.
- parameter aDecoder: The coder to initialize from.
*/
public required init?(coder aDecoder: NSCoder) {
sdkLikeButton = FBSDKLikeButton()
super.init(coder: aDecoder)
addSubview(sdkLikeButton)
}
/**
Performs logic for laying out subviews.
*/
public override func layoutSubviews() {
super.layoutSubviews()
sdkLikeButton.frame = CGRect(origin: .zero, size: bounds.size)
}
/**
Resizes and moves the receiver view so it just encloses its subviews.
*/
public override func sizeToFit() {
bounds.size = sizeThatFits(CGSize(width: CGFloat.max, height: CGFloat.max))
}
/**
Asks the view to calculate and return the size that best fits the specified size.
- parameter size: A new size that fits the receiver’s subviews.
- returns: A new size that fits the receiver’s subviews.
*/
public override func sizeThatFits(size: CGSize) -> CGSize {
return sdkLikeButton.sizeThatFits(size)
}
/**
Returns the natural size for the receiving view, considering only properties of the view itself.
- returns: A size indicating the natural size for the receiving view based on its intrinsic properties.
*/
public override func intrinsicContentSize() -> CGSize {
return sdkLikeButton.intrinsicContentSize()
}
}
| mit |
googleprojectzero/fuzzilli | Tests/FuzzilliTests/AnalyzerTest.swift | 1 | 8690 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import Fuzzilli
class AnalyzerTests: XCTestCase {
func testContextAnalyzer() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
for _ in 0..<10 {
b.build(n: 100, by: .runningGenerators)
let program = b.finalize()
var contextAnalyzer = ContextAnalyzer()
for instr in program.code {
contextAnalyzer.analyze(instr)
}
XCTAssertEqual(contextAnalyzer.context, .javascript)
}
}
func testNestedLoops() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertEqual(b.context, .javascript)
let _ = b.buildPlainFunction(with: .parameters(n: 3)) { args in
XCTAssertEqual(b.context, [.javascript, .subroutine])
let loopVar1 = b.loadInt(0)
b.buildDoWhileLoop(loopVar1, .lessThan, b.loadInt(42)) {
XCTAssertEqual(b.context, [.javascript, .subroutine, .loop])
b.buildPlainFunction(with: .parameters(n: 2)) { args in
XCTAssertEqual(b.context, [.javascript, .subroutine])
let v1 = b.loadInt(0)
let v2 = b.loadInt(10)
let v3 = b.loadInt(20)
b.buildForLoop(v1, .lessThan, v2, .Add, v3) { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine, .loop])
}
}
XCTAssertEqual(b.context, [.javascript, .subroutine, .loop])
}
}
let _ = b.finalize()
}
func testNestedFunctions() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertEqual(b.context, .javascript)
b.buildAsyncFunction(with: .parameters(n: 2)) { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine, .asyncFunction])
let v3 = b.loadInt(0)
b.buildPlainFunction(with: .parameters(n: 3)) { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine])
}
XCTAssertEqual(b.context, [.javascript, .subroutine, .asyncFunction])
b.await(v3)
b.buildAsyncGeneratorFunction(with: .parameters(n: 2)) { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine, .asyncFunction, .generatorFunction])
}
XCTAssertEqual(b.context, [.javascript, .subroutine, .asyncFunction])
}
let _ = b.finalize()
}
func testNestedWithStatements() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertEqual(b.context, .javascript)
let obj = b.loadString("HelloWorld")
b.buildWith(obj) {
XCTAssertEqual(b.context, [.javascript, .with])
b.buildPlainFunction(with: .parameters(n: 3)) { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine])
b.buildWith(obj) {
XCTAssertEqual(b.context, [.javascript, .subroutine, .with])
}
}
XCTAssertEqual(b.context, [.javascript, .with])
b.loadFromScope(id: b.genPropertyNameForRead())
}
let _ = b.finalize()
}
func testClassDefinitions() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertEqual(b.context, .javascript)
let superclass = b.buildClass() { cls in
cls.defineConstructor(with: .parameters(n: 1)) { params in
XCTAssertEqual(b.context, [.javascript, .classDefinition, .subroutine])
let loopVar1 = b.loadInt(0)
b.buildDoWhileLoop(loopVar1, .lessThan, b.loadInt(42)) {
XCTAssertEqual(b.context, [.javascript, .classDefinition, .subroutine, .loop])
}
XCTAssertEqual(b.context, [.javascript, .classDefinition, .subroutine])
}
}
XCTAssertEqual(b.context, .javascript)
b.buildClass(withSuperclass: superclass) { cls in
cls.defineConstructor(with: .parameters(n: 1)) { _ in
XCTAssertEqual(b.context, [.javascript, .classDefinition, .subroutine])
let v0 = b.loadInt(42)
let v1 = b.createObject(with: ["foo": v0])
b.callSuperConstructor(withArgs: [v1])
}
cls.defineMethod("classMethod", with: .parameters(n: 2)) { _ in
XCTAssertEqual(b.context, [.javascript, .classDefinition, .subroutine])
b.buildAsyncFunction(with: .parameters(n: 2)) { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine, .asyncFunction])
}
XCTAssertEqual(b.context, [.javascript, .classDefinition, .subroutine])
}
}
XCTAssertEqual(b.context, .javascript)
let _ = b.finalize()
}
func testCodeStrings() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertEqual(b.context, .javascript)
let _ = b.buildCodeString() {
XCTAssertEqual(b.context, .javascript)
let v11 = b.loadInt(0)
let v12 = b.loadInt(2)
let v13 = b.loadInt(1)
b.buildForLoop(v11, .lessThan, v12, .Add, v13) { _ in
b.loadInt(1337)
XCTAssertEqual(b.context, [.javascript, .loop])
let _ = b.buildCodeString() {
b.loadString("hello world")
XCTAssertEqual(b.context, [.javascript])
}
}
}
XCTAssertEqual(b.context, .javascript)
let _ = b.finalize()
}
func testContextPropagatingBlocks() {
let fuzzer = makeMockFuzzer()
let b = fuzzer.makeBuilder()
XCTAssertEqual(b.context, .javascript)
let _ = b.buildPlainFunction(with: .parameters(n: 3)) { args in
XCTAssertEqual(b.context, [.javascript, .subroutine])
let loopVar1 = b.loadInt(0)
b.buildDoWhileLoop(loopVar1, .lessThan, b.loadInt(42)) {
XCTAssertEqual(b.context, [.javascript, .subroutine, .loop])
b.buildIfElse(args[0], ifBody: {
XCTAssertEqual(b.context, [.javascript, .subroutine, .loop])
let v = b.binary(args[0], args[1], with: .Mul)
b.doReturn(v)
}, elseBody: {
XCTAssertEqual(b.context, [.javascript, .subroutine, .loop])
b.doReturn(args[2])
})
}
b.blockStatement {
XCTAssertEqual(b.context, [.javascript, .subroutine])
b.buildTryCatchFinally(tryBody: {
XCTAssertEqual(b.context, [.javascript, .subroutine])
let v = b.binary(args[0], args[1], with: .Mul)
b.doReturn(v)
}, catchBody: { _ in
XCTAssertEqual(b.context, [.javascript, .subroutine])
let v4 = b.createObject(with: ["a" : b.loadInt(1337)])
b.reassign(args[0], to: v4)
}, finallyBody: {
XCTAssertEqual(b.context, [.javascript, .subroutine])
let v = b.binary(args[0], args[1], with: .Add)
b.doReturn(v)
})
}
}
XCTAssertEqual(b.context, .javascript)
let _ = b.finalize()
}
}
extension AnalyzerTests {
static var allTests : [(String, (AnalyzerTests) -> () throws -> Void)] {
return [
("testContextAnalyzer", testContextAnalyzer),
("testNestedLoops", testNestedLoops),
("testNestedFunctions", testNestedFunctions),
("testNestedWithStatements", testNestedWithStatements),
("testClassDefinitions", testClassDefinitions),
("testCodeStrings", testCodeStrings),
("testContextPropagatingBlocks", testContextPropagatingBlocks)
]
}
}
| apache-2.0 |
LibraryLoupe/PhotosPlus | PhotosPlus/Cameras/Nikon/NikonE8700.swift | 3 | 485 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Nikon {
public struct E8700: CameraModel {
public init() {}
public let name = "Nikon E8700"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Nikon.self
}
}
public typealias NikonE8700 = Cameras.Manufacturers.Nikon.E8700
| mit |
ziligy/JGScrollerController | JGScrollerController/JGTapButton.swift | 1 | 8144 | //
// JGTapButton.swift
//
// Created by Jeff on 8/20/15.
// Copyright © 2015 Jeff Greenberg. All rights reserved.
//
import UIKit
enum TapButtonShape {
case Round
case Rectangle
}
enum TapButtonStyle {
case Raised
case Flat
}
@IBDesignable
public class JGTapButton: UIButton {
// MARK: Inspectables
// select round or rectangle button shape
@IBInspectable public var round: Bool = true {
didSet {
buttonShape = (round ? .Round : .Rectangle)
}
}
// select raised or flat style
@IBInspectable public var raised: Bool = true {
didSet {
buttonStyle = (raised ? .Raised : .Flat)
}
}
// set title caption for button
@IBInspectable public var title: String = "JGTapButton" {
didSet {
buttonTitle = title
}
}
// optional button image
@IBInspectable public var image: UIImage=UIImage() {
didSet {
setButtonImage()
}
}
@IBInspectable public var imageInset: CGFloat = 0 {
didSet {
setButtonImage()
}
}
// main background button color
@IBInspectable public var mainColor: UIColor = UIColor.redColor() {
didSet {
buttonColor = mainColor
}
}
// title font size
@IBInspectable public var fontsize: CGFloat = 22.0 {
didSet {
titleFontSize = fontsize
}
}
@IBInspectable public var fontColor: UIColor = UIColor.whiteColor()
// MARK: Private variables
private var buttonShape = TapButtonShape.Round
private var buttonStyle = TapButtonStyle.Flat
private var buttonTitle = ""
private var buttonColor = UIColor.redColor()
private var titleFontSize: CGFloat = 22.0
private var tapButtonFrame = CGRectMake(0, 0, 100, 100)
// outline shape of button from draw
private var outlinePath = UIBezierPath()
// variables for glow animation
private let tapGlowView = UIView()
private let tapGlowBackgroundView = UIView()
private var tapGlowColor = UIColor(white: 0.9, alpha: 1)
private var tapGlowBackgroundColor = UIColor(white: 0.95, alpha: 1)
private var tapGlowMask: CAShapeLayer? {
get {
let maskLayer = CAShapeLayer()
maskLayer.path = outlinePath.CGPath
return maskLayer
}
}
// optional image for
private var iconImageView = UIImageView(frame: CGRectMake(0, 0, 40, 40))
// MARK: Initialize
func initMaster() {
self.backgroundColor = UIColor.clearColor()
self.addSubview(iconImageView)
}
override init(frame: CGRect) {
super.init(frame: frame)
initMaster()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initMaster()
}
convenience init(sideSize: CGFloat) {
self.init(frame: CGRect(x: 0, y: 0, width: sideSize, height: sideSize))
}
override public func prepareForInterfaceBuilder() {
invalidateIntrinsicContentSize()
self.backgroundColor = UIColor.clearColor()
}
// MARK: Layout
override public func layoutSubviews() {
super.layoutSubviews()
iconImageView.layer.mask = tapGlowMask
tapGlowBackgroundView.layer.mask = tapGlowMask
}
// override intrinsic size for uibutton
public override func intrinsicContentSize() -> CGSize {
return bounds.size
}
// MARK: draw
override public func drawRect(rect: CGRect) {
outlinePath = drawTapButton(buttonShape, buttonTitle: buttonTitle, fontsize: titleFontSize)
tapGlowSetup()
}
private func tapGlowSetup() {
tapGlowBackgroundView.backgroundColor = tapGlowBackgroundColor
tapGlowBackgroundView.frame = bounds
layer.addSublayer(tapGlowBackgroundView.layer)
tapGlowBackgroundView.layer.addSublayer(tapGlowView.layer)
tapGlowBackgroundView.alpha = 0
}
private func drawTapButton(buttonShape: TapButtonShape, buttonTitle: String, fontsize: CGFloat) -> UIBezierPath {
var bezierPath: UIBezierPath!
if buttonStyle == .Raised {
tapButtonFrame = CGRectMake(1, 1, CGRectGetWidth(self.bounds) - 2, CGRectGetHeight(self.bounds) - 2)
} else {
tapButtonFrame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))
}
let context = UIGraphicsGetCurrentContext()
if buttonShape == .Round {
bezierPath = UIBezierPath(ovalInRect: tapButtonFrame)
} else {
bezierPath = UIBezierPath(rect: tapButtonFrame)
}
buttonColor.setFill()
bezierPath.fill()
let shadow = UIColor.blackColor().CGColor
let shadowOffset = CGSizeMake(3.1, 3.1)
let shadowBlurRadius: CGFloat = 7
if buttonStyle == .Raised {
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow)
fontColor.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
CGContextRestoreGState(context)
}
// MARK: Title Text
if image == "" || iconImageView.image == nil {
let buttonTitleTextContent = NSString(string: buttonTitle)
CGContextSaveGState(context)
if buttonStyle == .Raised {
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow)
}
let buttonTitleStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
buttonTitleStyle.alignment = NSTextAlignment.Center
let buttonTitleFontAttributes = [NSFontAttributeName: UIFont(name: "AppleSDGothicNeo-Regular", size: fontsize)!, NSForegroundColorAttributeName: fontColor, NSParagraphStyleAttributeName: buttonTitleStyle]
let buttonTitleTextHeight: CGFloat = buttonTitleTextContent.boundingRectWithSize(CGSizeMake(tapButtonFrame.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: buttonTitleFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, tapButtonFrame);
buttonTitleTextContent.drawInRect(CGRectMake(tapButtonFrame.minX, tapButtonFrame.minY + (tapButtonFrame.height - buttonTitleTextHeight) / 2, tapButtonFrame.width, buttonTitleTextHeight), withAttributes: buttonTitleFontAttributes)
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
return bezierPath
}
private func setButtonImage() {
iconImageView.frame = CGRectMake(imageInset, imageInset, CGRectGetWidth(self.frame) - imageInset*2, CGRectGetHeight(self.frame) - imageInset*2)
iconImageView.image = self.image
}
// MARK: Tap events
override public func beginTrackingWithTouch(touch: UITouch,
withEvent event: UIEvent?) -> Bool {
UIView.animateWithDuration(0.1, animations: {
self.tapGlowBackgroundView.alpha = 1
}, completion: nil)
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override public func endTrackingWithTouch(touch: UITouch?,
withEvent event: UIEvent?) {
super.endTrackingWithTouch(touch, withEvent: event)
UIView.animateWithDuration(0.1, animations: {
self.tapGlowBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animateWithDuration(0.6 , animations: {
self.tapGlowBackgroundView.alpha = 0
}, completion: nil)
})
}
}
| mit |
Webtrekk/webtrekk-ios-sdk | Source/Public/Events/Protocols/TrackingEventWithSessionDetails.swift | 1 | 130 | public protocol TrackingEventWithSessionDetails: TrackingEvent {
var sessionDetails: [Int: TrackingValue] { get mutating set }
}
| mit |
dfortuna/theCraic3 | theCraic3/Main/Common/InputTagsTableViewCell.swift | 1 | 1679 | //
// InputTagsTableViewCell.swift
// theCraic3
//
// Created by Denis Fortuna on 23/5/18.
// Copyright © 2018 Denis. All rights reserved.
//
import UIKit
protocol TagsProtocol: class {
func emitAlertSpecialCharacters(sender: InputTagsTableViewCell)
func tagAdded(sender: InputTagsTableViewCell)
}
class InputTagsTableViewCell: UITableViewCell {
weak var delegate: TagsProtocol?
var tagAdded = String()
@IBOutlet weak var displayTagsScrollView: DisplayTagsScrollView!
@IBOutlet weak var tagsTextField: UITextField!
@IBAction func okButton(_ sender: UIButton) {
if let tag = tagsTextField.text {
if testStringForBallon(forString: tag) {
self.tagAdded = tag
self.delegate?.tagAdded(sender: self)
displayTagsScrollView.setupUI(forTag: tag, isClickable: true)
} else {
self.delegate?.emitAlertSpecialCharacters(sender: self)
}
}
tagsTextField.text = ""
}
func updateUI(tags: [String], withTitle: Bool) {
displayTagsScrollView.layer.borderWidth = 0.3
displayTagsScrollView.layer.borderColor = UIColor.lightGray.cgColor
if !tags.isEmpty {
for tag in tags {
displayTagsScrollView.setupUI(forTag: tag, isClickable: true)
}
}
}
func testStringForBallon(forString tag: String) -> Bool {
let charctersNotAllowed = [".","$","[","]","#","/"]
for character in charctersNotAllowed {
if tag.range(of: character) != nil {
return false
}
}
return true
}
}
| apache-2.0 |
eamosov/thrift | lib/swift/Sources/TSSLSocketTransport.swift | 14 | 8028 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
import CoreFoundation
#if !swift(>=4.2)
// Swift 3/4 compatibility
fileprivate extension RunLoopMode {
static let `default` = defaultRunLoopMode
}
#endif
#if os(Linux)
public class TSSLSocketTransport {
init(hostname: String, port: UInt16) {
// FIXME!
assert(false, "Security not available in Linux, TSSLSocketTransport Unavilable for now")
}
}
#else
let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian
let htons = isLittleEndian ? _OSSwapInt16 : { $0 }
let htonl = isLittleEndian ? _OSSwapInt32 : { $0 }
public class TSSLSocketTransport: TStreamTransport {
var sslHostname: String
var sd: Int32 = 0
public init(hostname: String, port: UInt16) throws {
sslHostname = hostname
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
/* create a socket structure */
var pin: sockaddr_in = sockaddr_in()
var hp: UnsafeMutablePointer<hostent>? = nil
for i in 0..<10 {
hp = gethostbyname(hostname.cString(using: String.Encoding.utf8)!)
if hp == nil {
print("failed to resolve hostname \(hostname)")
herror("resolv")
if i == 9 {
super.init(inputStream: nil, outputStream: nil) // have to init before throwing
throw TSSLSocketTransportError(error: .hostanameResolution(hostname: hostname))
}
Thread.sleep(forTimeInterval: 0.2)
} else {
break
}
}
pin.sin_family = UInt8(AF_INET)
pin.sin_addr = in_addr(s_addr: UInt32((hp?.pointee.h_addr_list.pointee?.pointee)!)) // Is there a better way to get this???
pin.sin_port = htons(port)
/* create the socket */
sd = socket(Int32(AF_INET), Int32(SOCK_STREAM), Int32(IPPROTO_TCP))
if sd == -1 {
super.init(inputStream: nil, outputStream: nil) // have to init before throwing
throw TSSLSocketTransportError(error: .socketCreate(port: Int(port)))
}
/* open a connection */
// need a non-self ref to sd, otherwise the j complains
let sd_local = sd
let connectResult = withUnsafePointer(to: &pin) {
connect(sd_local, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size))
}
if connectResult == -1 {
super.init(inputStream: nil, outputStream: nil) // have to init before throwing
throw TSSLSocketTransportError(error: .connect)
}
CFStreamCreatePairWithSocket(kCFAllocatorDefault, sd, &readStream, &writeStream)
CFReadStreamSetProperty(readStream?.takeRetainedValue(), .socketNativeHandle, kCFBooleanTrue)
CFWriteStreamSetProperty(writeStream?.takeRetainedValue(), .socketNativeHandle, kCFBooleanTrue)
var inputStream: InputStream? = nil
var outputStream: OutputStream? = nil
if readStream != nil && writeStream != nil {
CFReadStreamSetProperty(readStream?.takeRetainedValue(),
.socketSecurityLevel,
kCFStreamSocketSecurityLevelTLSv1)
let settings: [String: Bool] = [kCFStreamSSLValidatesCertificateChain as String: true]
CFReadStreamSetProperty(readStream?.takeRetainedValue(),
.SSLSettings,
settings as CFTypeRef)
CFWriteStreamSetProperty(writeStream?.takeRetainedValue(),
.SSLSettings,
settings as CFTypeRef)
inputStream = readStream!.takeRetainedValue()
inputStream?.schedule(in: .current, forMode: .default)
inputStream?.open()
outputStream = writeStream!.takeRetainedValue()
outputStream?.schedule(in: .current, forMode: .default)
outputStream?.open()
readStream?.release()
writeStream?.release()
}
super.init(inputStream: inputStream, outputStream: outputStream)
self.input?.delegate = self
self.output?.delegate = self
}
func recoverFromTrustFailure(_ myTrust: SecTrust, lastTrustResult: SecTrustResultType) -> Bool {
let trustTime = SecTrustGetVerifyTime(myTrust)
let currentTime = CFAbsoluteTimeGetCurrent()
let timeIncrement = 31536000 // from TSSLSocketTransport.m
let newTime = currentTime - Double(timeIncrement)
if trustTime - newTime != 0 {
let newDate = CFDateCreate(nil, newTime)
SecTrustSetVerifyDate(myTrust, newDate!)
var tr = lastTrustResult
let success = withUnsafeMutablePointer(to: &tr) { trPtr -> Bool in
if SecTrustEvaluate(myTrust, trPtr) != errSecSuccess {
return false
}
return true
}
if !success { return false }
}
if lastTrustResult == .proceed || lastTrustResult == .unspecified {
return false
}
print("TSSLSocketTransport: Unable to recover certificate trust failure")
return true
}
public func isOpen() -> Bool {
return sd > 0
}
}
extension TSSLSocketTransport: StreamDelegate {
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event(): break
case Stream.Event.hasBytesAvailable: break
case Stream.Event.openCompleted: break
case Stream.Event.hasSpaceAvailable:
var proceed = false
var trustResult: SecTrustResultType = .invalid
var newPolicies: CFMutableArray?
repeat {
let trust: SecTrust = aStream.property(forKey: .SSLPeerTrust) as! SecTrust
// Add new policy to current list of policies
let policy = SecPolicyCreateSSL(false, sslHostname as CFString?)
var ppolicy = policy // mutable for pointer
let policies: UnsafeMutablePointer<CFArray?>? = nil
if SecTrustCopyPolicies(trust, policies!) != errSecSuccess {
break
}
withUnsafeMutablePointer(to: &ppolicy) { ptr in
newPolicies = CFArrayCreateMutableCopy(nil, 0, policies?.pointee)
CFArrayAppendValue(newPolicies, ptr)
}
// update trust policies
if SecTrustSetPolicies(trust, newPolicies!) != errSecSuccess {
break
}
// Evaluate the trust chain
let success = withUnsafeMutablePointer(to: &trustResult) { trustPtr -> Bool in
if SecTrustEvaluate(trust, trustPtr) != errSecSuccess {
return false
}
return true
}
if !success {
break
}
switch trustResult {
case .proceed: proceed = true
case .unspecified: proceed = true
case .recoverableTrustFailure:
proceed = self.recoverFromTrustFailure(trust, lastTrustResult: trustResult)
case .deny: break
case .fatalTrustFailure: break
case .otherError: break
case .invalid: break
default: break
}
} while false
if !proceed {
print("TSSLSocketTransport: Cannot trust certificate. Result: \(trustResult)")
aStream.close()
}
case Stream.Event.errorOccurred: break
case Stream.Event.endEncountered: break
default: break
}
}
}
#endif
| apache-2.0 |
Wrenbjor/RetroCalc | RetroCalc/AppDelegate.swift | 1 | 2146 | //
// AppDelegate.swift
// RetroCalc
//
// Created by Wayne Renbjor on 10/23/15.
// Copyright © 2015 WCRStudios. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
OlenaPianykh/Garage48KAPU | KAPU/KapuDescriptionCell.swift | 1 | 613 | //
// KapuDescriptionCell.swift
// KAPU
//
// Created by Oleksii Pelekh on 3/4/17.
// Copyright © 2017 Vasyl Khmil. All rights reserved.
//
import UIKit
class KapuDescriptionCell: UITableViewCell {
@IBOutlet weak var descriptionTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
self.frame = CGRect.init(x: 0, y: 0, width: self.frame.width, height: 150.0)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
xedin/swift | test/Driver/Dependencies/whole-module-build-record.swift | 11 | 895 | /// other ==> main
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/one-way/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/fake-build-whole-module.py" -output-file-map %t/output.json -whole-module-optimization ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Produced main.o
// CHECK-RECORD-DAG: "./main.swift": [
// CHECK-RECORD-DAG: "./other.swift": [
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/../Inputs/fail.py" -output-file-map %t/output.json -whole-module-optimization ./main.swift ./other.swift -module-name main -j1 -v 2>&1
// Just don't crash.
| apache-2.0 |
superk589/DereGuide | DereGuide/Model/CoreDataHelper/Migration.swift | 2 | 1777 | //
// Migration.swift
// Migrations
//
// Created by Florian on 06/10/15.
// Copyright © 2015 objc.io. All rights reserved.
//
import CoreData
public func migrateStore<Version: ModelVersion>(from sourceURL: URL, to targetURL: URL, targetVersion: Version, deleteSource: Bool = false, progress: Progress? = nil) {
guard let sourceVersion = Version(storeURL: sourceURL as URL) else { fatalError("unknown store version at URL \(sourceURL)") }
var currentURL = sourceURL
let migrationSteps = sourceVersion.migrationSteps(to: targetVersion)
var migrationProgress: Progress?
if let p = progress {
migrationProgress = Progress(totalUnitCount: Int64(migrationSteps.count), parent: p, pendingUnitCount: p.totalUnitCount)
}
for step in migrationSteps {
migrationProgress?.becomeCurrent(withPendingUnitCount: 1)
let manager = NSMigrationManager(sourceModel: step.source, destinationModel: step.destination)
migrationProgress?.resignCurrent()
let destinationURL = URL.temporary
for mapping in step.mappings {
try! manager.migrateStore(from: currentURL, sourceType: NSSQLiteStoreType, options: nil, with: mapping, toDestinationURL: destinationURL, destinationType: NSSQLiteStoreType, destinationOptions: nil)
}
if currentURL != sourceURL {
NSPersistentStoreCoordinator.destroyStore(at: currentURL)
}
currentURL = destinationURL
}
try! NSPersistentStoreCoordinator.replaceStore(at: targetURL, withStoreAt: currentURL)
if currentURL != sourceURL {
NSPersistentStoreCoordinator.destroyStore(at: currentURL)
}
if targetURL != sourceURL && deleteSource {
NSPersistentStoreCoordinator.destroyStore(at: sourceURL)
}
}
| mit |
tad-iizuka/swift-sdk | Source/DiscoveryV1/Models/Document.swift | 2 | 2923 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** A document to upload to a collection. */
public struct Document: JSONDecodable {
/// Unique identifier of the ingested document.
public let documentID: String
/// The unique identifier of the collection's configuration.
public let configurationID: String?
/// The creation date of the document in the format yyyy-MM-dd'T'HH:mm
/// :ss.SSS'Z'.
public let created: String?
/// The timestamp of when the document was last updated in the format
/// yyyy-MM-dd'T'HH:mm:ss.SSS'Z'.
public let updated: String?
/// The status of the document in ingestion process.
public let status: DocumentStatus
/// The description of the document status.
public let statusDescription: String?
/// The array of notices produced by the document-ingestion process.
public let notices: [Notice]?
/// The raw JSON object used to construct this model.
public let json: [String: Any]
/// Used internally to initialize a `Document` model from JSON.
public init(json: JSON) throws {
documentID = try json.getString(at: "document_id")
configurationID = try? json.getString(at: "configuration_id")
created = try? json.getString(at: "created")
updated = try? json.getString(at: "updated")
guard let documentStatus = DocumentStatus(rawValue: try json.getString(at: "status")) else {
throw JSON.Error.valueNotConvertible(value: json, to: DocumentStatus.self)
}
status = documentStatus
statusDescription = try? json.getString(at: "status_description")
notices = try? json.decodedArray(at: "notices", type: Notice.self)
self.json = try json.getDictionaryObject()
}
/// Used internally to serialize a 'Document' model to JSON.
public func toJSONObject() -> Any {
return json
}
}
/** Status of a document uploaded to a collection. */
public enum DocumentStatus: String {
/// Available
case available = "available"
/// Availabe with notices
case availableWithNotices = "available with notices"
/// Deleted
case deleted = "deleted"
/// Failed
case failed = "failed"
/// Processing
case processing = "processing"
}
| apache-2.0 |
boqian2000/swift-algorithm-club | Trie/Trie/TrieTests/TrieTests.swift | 1 | 5284 | //
// TrieTests.swift
// TrieTests
//
// Created by Rick Zaccone on 2016-12-12.
// Copyright © 2016 Rick Zaccone. All rights reserved.
//
import XCTest
@testable import Trie
class TrieTests: XCTestCase {
var wordArray: [String]?
var trie = Trie()
/// Makes sure that the wordArray and trie are initialized before each test.
override func setUp() {
super.setUp()
createWordArray()
insertWordsIntoTrie()
}
/// Don't need to do anything here because the wordArray and trie should
/// stay around.
override func tearDown() {
super.tearDown()
}
/// Reads words from the dictionary file and inserts them into an array. If
/// the word array already has words, do nothing. This allows running all
/// tests without repeatedly filling the array with the same values.
func createWordArray() {
guard wordArray == nil else {
return
}
let resourcePath = Bundle.main.resourcePath! as NSString
let fileName = "dictionary.txt"
let filePath = resourcePath.appendingPathComponent(fileName)
var data: String?
do {
data = try String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
} catch let error as NSError {
XCTAssertNil(error)
}
XCTAssertNotNil(data)
let dictionarySize = 162825
wordArray = data!.components(separatedBy: "\n")
XCTAssertEqual(wordArray!.count, dictionarySize)
}
/// Inserts words into a trie. If the trie is non-empty, don't do anything.
func insertWordsIntoTrie() {
guard let wordArray = wordArray, trie.count == 0 else { return }
for word in wordArray {
trie.insert(word: word)
}
}
/// Tests that a newly created trie has zero words.
func testCreate() {
let trie = Trie()
XCTAssertEqual(trie.count, 0)
}
/// Tests the insert method
func testInsert() {
let trie = Trie()
trie.insert(word: "cute")
trie.insert(word: "cutie")
trie.insert(word: "fred")
XCTAssertTrue(trie.contains(word: "cute"))
XCTAssertFalse(trie.contains(word: "cut"))
trie.insert(word: "cut")
XCTAssertTrue(trie.contains(word: "cut"))
XCTAssertEqual(trie.count, 4)
}
/// Tests the remove method
func testRemove() {
let trie = Trie()
trie.insert(word: "cute")
trie.insert(word: "cut")
XCTAssertEqual(trie.count, 2)
trie.remove(word: "cute")
XCTAssertTrue(trie.contains(word: "cut"))
XCTAssertFalse(trie.contains(word: "cute"))
XCTAssertEqual(trie.count, 1)
}
/// Tests the words property
func testWords() {
let trie = Trie()
var words = trie.words
XCTAssertEqual(words.count, 0)
trie.insert(word: "foobar")
words = trie.words
XCTAssertEqual(words[0], "foobar")
XCTAssertEqual(words.count, 1)
}
/// Tests the performance of the insert method.
func testInsertPerformance() {
self.measure() {
let trie = Trie()
for word in self.wordArray! {
trie.insert(word: word)
}
}
XCTAssertGreaterThan(trie.count, 0)
XCTAssertEqual(trie.count, wordArray?.count)
}
/// Tests the performance of the insert method when the words are already
/// present.
func testInsertAgainPerformance() {
self.measure() {
for word in self.wordArray! {
self.trie.insert(word: word)
}
}
}
/// Tests the performance of the contains method.
func testContainsPerformance() {
self.measure() {
for word in self.wordArray! {
XCTAssertTrue(self.trie.contains(word: word))
}
}
}
/// Tests the performance of the remove method. Since setup has already put
/// words into the trie, remove them before measuring performance.
func testRemovePerformance() {
for word in self.wordArray! {
self.trie.remove(word: word)
}
self.measure() {
self.insertWordsIntoTrie()
for word in self.wordArray! {
self.trie.remove(word: word)
}
}
XCTAssertEqual(trie.count, 0)
}
/// Tests the performance of the words computed property. Also tests to see
/// if it worked properly.
func testWordsPerformance() {
var words: [String]?
self.measure {
words = self.trie.words
}
XCTAssertEqual(words?.count, trie.count)
for word in words! {
XCTAssertTrue(self.trie.contains(word: word))
}
}
/// Tests the archiving and unarchiving of the trie.
func testArchiveAndUnarchive() {
let resourcePath = Bundle.main.resourcePath! as NSString
let fileName = "dictionary-archive"
let filePath = resourcePath.appendingPathComponent(fileName)
NSKeyedArchiver.archiveRootObject(trie, toFile: filePath)
let trieCopy = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Trie
XCTAssertEqual(trieCopy.count, trie.count)
}
}
| mit |
SwiftGen/SwiftGen | Sources/TestUtils/Fixtures/Generated/Strings/flat-swift5/localizable.swift | 2 | 5333 | // swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable superfluous_disable_command file_length implicit_return prefer_self_in_static_references
// MARK: - Strings
// swiftlint:disable function_parameter_count identifier_name line_length type_body_length
internal enum L10n {
/// Some /*alert body there
internal static let alertMessage = L10n.tr("Localizable", "alert__message", fallback: "Some /*alert body there")
/// Title for an alert 1️⃣
internal static let alertTitle = L10n.tr("Localizable", "alert__title", fallback: "Title of the alert")
/// value1 value
internal static let key1 = L10n.tr("Localizable", "key1", fallback: "value1\tvalue")
/// These are %3$@'s %1$d %2$@.
internal static func objectOwnership(_ p1: Int, _ p2: Any, _ p3: Any) -> String {
return L10n.tr("Localizable", "ObjectOwnership", p1, String(describing: p2), String(describing: p3), fallback: "These are %3$@'s %1$d %2$@.")
}
/// This is a %% character.
internal static let percent = L10n.tr("Localizable", "percent", fallback: "This is a %% character.")
/// Hello, my name is "%@" and I'm %d
internal static func `private`(_ p1: Any, _ p2: Int) -> String {
return L10n.tr("Localizable", "private", String(describing: p1), p2, fallback: "Hello, my name is \"%@\" and I'm %d")
}
/// Object: '%@', Character: '%c', Integer: '%d', Float: '%f', CString: '%s', Pointer: '%p'
internal static func types(_ p1: Any, _ p2: CChar, _ p3: Int, _ p4: Float, _ p5: UnsafePointer<CChar>, _ p6: UnsafeRawPointer) -> String {
return L10n.tr("Localizable", "types", String(describing: p1), p2, p3, p4, p5, Int(bitPattern: p6), fallback: "Object: '%@', Character: '%c', Integer: '%d', Float: '%f', CString: '%s', Pointer: '%p'")
}
/// You have %d apples
internal static func applesCount(_ p1: Int) -> String {
return L10n.tr("Localizable", "apples.count", p1, fallback: "You have %d apples")
}
/// A comment with no space above it
internal static func bananasOwner(_ p1: Int, _ p2: Any) -> String {
return L10n.tr("Localizable", "bananas.owner", p1, String(describing: p2), fallback: "Those %d bananas belong to %@.")
}
/// Same as "key1" = "value1"; but in the context of user not logged in
internal static let key1Anonymous = L10n.tr("Localizable", "key1.anonymous", fallback: "value2")
/// %@ %d %f %5$d %04$f %6$d %007$@ %8$3.2f %11$1.2f %9$@ %10$d
internal static func manyPlaceholdersBase(_ p1: Any, _ p2: Int, _ p3: Float, _ p4: Float, _ p5: Int, _ p6: Int, _ p7: Any, _ p8: Float, _ p9: Any, _ p10: Int, _ p11: Float) -> String {
return L10n.tr("Localizable", "many.placeholders.base", String(describing: p1), p2, p3, p4, p5, p6, String(describing: p7), p8, String(describing: p9), p10, p11, fallback: "%@ %d %f %5$d %04$f %6$d %007$@ %8$3.2f %11$1.2f %9$@ %10$d")
}
/// %@ %d %0$@ %f %5$d %04$f %6$d %007$@ %8$3.2f %11$1.2f %9$@ %10$d
internal static func manyPlaceholdersZero(_ p1: Any, _ p2: Int, _ p3: Float, _ p4: Float, _ p5: Int, _ p6: Int, _ p7: Any, _ p8: Float, _ p9: Any, _ p10: Int, _ p11: Float) -> String {
return L10n.tr("Localizable", "many.placeholders.zero", String(describing: p1), p2, p3, p4, p5, p6, String(describing: p7), p8, String(describing: p9), p10, p11, fallback: "%@ %d %0$@ %f %5$d %04$f %6$d %007$@ %8$3.2f %11$1.2f %9$@ %10$d")
}
/// Some Reserved Keyword there👍🏽
internal static let settingsNavigationBarSelf_️ = L10n.tr("Localizable", "settings.navigation-bar.self♦️", fallback: "Some Reserved Keyword there👍🏽")
/// DeepSettings
internal static let settingsNavigationBarTitleDeeperThanWeCanHandleNoReallyThisIsDeep = L10n.tr("Localizable", "settings.navigation-bar.title.deeper.than.we.can.handle.no.really.this.is.deep", fallback: "DeepSettings")
/// Settings
internal static let settingsNavigationBarTitleEvenDeeper = L10n.tr("Localizable", "settings.navigation-bar.title.even.deeper", fallback: "Settings")
/// Here you can change some user profile settings.
internal static let settingsUserProfileSectionFooterText = L10n.tr("Localizable", "settings.user__profile_section.footer_text", fallback: "Here you can change some user profile settings.")
/// User Profile Settings
internal static let settingsUserProfileSectionHEADERTITLE = L10n.tr("Localizable", "settings.user__profile_section.HEADER_TITLE", fallback: "User Profile Settings")
/// some comment 👨👩👧👦
internal static let whatHappensHere = L10n.tr("Localizable", "what./*happens*/.here", fallback: "hello world! /* still in string */")
}
// swiftlint:enable function_parameter_count identifier_name line_length type_body_length
// MARK: - Implementation Details
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg..., fallback value: String) -> String {
let format = BundleToken.bundle.localizedString(forKey: key, value: value, table: table)
return String(format: format, locale: Locale.current, arguments: args)
}
}
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: BundleToken.self)
#endif
}()
}
// swiftlint:enable convenience_type
| mit |
eonil/toolbox.swift | EonilToolbox/OSXOnly/AppKitExtensions.swift | 1 | 160 | //
// AppKitExtensions.swift
// EonilToolbox
//
// Created by Hoon H. on 2016/04/27.
// Copyright © 2016 Eonil. All rights reserved.
//
import Foundation
| mit |
haawa799/WaniKani-Kanji-Strokes | Pods/WaniKit/Pod/Classes/WaniKit operations/UserInfo/ParseUserInfoOperation.swift | 1 | 746 | //
// ParseUserInfoOperation.swift
// Pods
//
// Created by Andriy K. on 12/14/15.
//
//
import UIKit
public typealias UserInfoResponse = (UserInfo?)
public typealias UserInfoResponseHandler = (Result<UserInfoResponse, NSError>) -> Void
public class ParseUserInfoOperation: ParseOperation<UserInfoResponse> {
override init(cacheFile: NSURL, handler: ResponseHandler) {
super.init(cacheFile: cacheFile, handler: handler)
name = "Parse User info"
}
override func parsedValue(rootDictionary: NSDictionary?) -> UserInfoResponse? {
var user: UserInfo?
if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary {
user = UserInfo(dict: userInfo)
}
return user
}
} | mit |
TrustWallet/trust-wallet-ios | Trust/UI/Size.swift | 1 | 258 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
struct Size {
static func scale(size: CGFloat) -> CGFloat {
if UIScreen.main.scale == 3 {
return size
}
return size * 0.90
}
}
| gpl-3.0 |
naoto0822/transient-watch-ios | TransientWatch/Domain/Entity/AstroObj.swift | 1 | 1108 | //
// AstroObj.swift
// TransientWatch
//
// Created by naoto yamaguchi on 2015/04/12.
// Copyright (c) 2015年 naoto yamaguchi. All rights reserved.
//
import UIKit
class AstroObj: NSObject {
// MARK: - Property
var id: Int?
var name: String?
var ra: Float?
var dec: Float?
var astroClassId: Int?
var fluxRate: Int?
var link: String?
// MARK: - LifeCycle
init(response: [String: AnyObject?]) {
super.init()
let fluxRate = response["flux_rate"] as? Int
let astroObj = response["astroObj"] as [String: AnyObject]
let id = astroObj["id"] as? Int
let name = astroObj["name"] as? String
let ra = astroObj["ra"] as? Float
let dec = astroObj["dec"] as? Float
let astroClassId = astroObj["astro_class_id"] as? Int
let link = astroObj["link"] as? String
self.id = id
self.name = name
self.ra = ra
self.dec = dec
self.astroClassId = astroClassId
self.fluxRate = fluxRate
self.link = link
}
}
| gpl-3.0 |
TotalDigital/People-iOS | People at Total/OAuth2RetryHandler.swift | 1 | 2355 | //
// OAuth2RetryHandler.swift
// People at Total
//
// Created by Florian Letellier on 14/03/2017.
// Copyright © 2017 Florian Letellier. All rights reserved.
//
import Foundation
import p2_OAuth2
import Alamofire
/**
An adapter for Alamofire. Set up your OAuth2 instance as usual, without forgetting to implement `handleRedirectURL()`, instantiate **one**
`SessionManager` and use this class as the manager's `adapter` and `retrier`, like so:
let oauth2 = OAuth2CodeGrant(settings: [...])
oauth2.authConfig.authorizeEmbedded = true // if you want embedded
oauth2.authConfig.authorizeContext = <# your UIViewController / NSWindow #>
let sessionManager = SessionManager()
let retrier = OAuth2RetryHandler(oauth2: oauth2)
sessionManager.adapter = retrier
sessionManager.retrier = retrier
self.alamofireManager = sessionManager
sessionManager.request("https://api.github.com/user").validate().responseJSON { response in
debugPrint(response)
}
*/
class OAuth2RetryHandler: RequestRetrier, RequestAdapter {
let loader: OAuth2DataLoader
init(oauth2: OAuth2) {
loader = OAuth2DataLoader(oauth2: oauth2)
}
/// Intercept 401 and do an OAuth2 authorization.
public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
if let response = request.task?.response as? HTTPURLResponse, 401 == response.statusCode, let req = request.request {
var dataRequest = OAuth2DataRequest(request: req, callback: { _ in })
dataRequest.context = completion
loader.enqueue(request: dataRequest)
loader.attemptToAuthorize() { authParams, error in
self.loader.dequeueAndApply() { req in
if let comp = req.context as? RequestRetryCompletion {
comp(nil != authParams, 0.0)
}
}
}
}
else {
completion(false, 0.0) // not a 401, not our problem
}
}
/// Sign the request with the access token.
public func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
guard nil != loader.oauth2.accessToken else {
return urlRequest
}
return try urlRequest.signed(with: loader.oauth2)
}
}
| apache-2.0 |
cornerAnt/PilesSugar | PilesSugar/PilesSugar/Module/Club/ClubClub/Controller/ClubClubController.swift | 1 | 3585 | //
// ClubClubController.swift
// PilesSugar
//
// Created by SoloKM on 16/1/21.
// Copyright © 2016年 SoloKM. All rights reserved.
//
import UIKit
private let ClubClubCellID = "ClubClubCell"
class ClubClubController: UITableViewController {
var models = [ClubClubModel]()
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
init(){
super.init(style: UITableViewStyle.Grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTableView() {
tableView!.registerNib(UINib(nibName: ClubClubCellID, bundle: nil), forCellReuseIdentifier: ClubClubCellID)
tableView!.tableFooterView = UIView()
tableView!.rowHeight = 50
tableView!.contentInset.top = 29
tableView!.sectionHeaderHeight = 0
tableView!.sectionFooterHeight = 10
loadNewData()
// tableView!.mj_header = RefreshHeader.init(refreshingBlock: { () -> Void in
//
// self.loadNewData()
// })
// tableView!.mj_header.beginRefreshing()
}
private func loadNewData(){
let url = "http://www.duitang.com/napi/club/list/by_user_id/?app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=Unknown%20iPhone&device_platform=iPhone6%2C1&include_fields=check_in&limit=0&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2.1&screen_height=568&screen_width=320&start=0&user_id=11189659"
NetWorkTool.sharedInstance.get(url, parameters: nil, success: { (response) -> () in
self.models = ClubClubModel.loadClubClubModels(response!)
self.tableView.reloadData()
// self.tableView!.mj_header.endRefreshing()
}) { (error) -> () in
DEBUGLOG(error)
// self.tableView!.mj_header.endRefreshing()
}
}
}
// MARK: - TableviewDataSource
extension ClubClubController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? models.count : 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ClubClubCellID, forIndexPath: indexPath) as! ClubClubCell
if indexPath.section == 0 {
cell.clubClubModel = models[indexPath.row]
cell.nameLabel.textColor = UIColor.blackColor()
}else {
cell.photoImageView.image = UIImage(named: "more_club")
cell.nameLabel.text = "浏览更多Club"
cell.nameLabel.textColor = UIColor.grayColor()
cell.unreadLabel.text = ">"
}
return cell
}
}
// MARK: - TableviewDelegate
extension ClubClubController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
let vc = ClubMoreController()
navigationController?.pushViewController(vc, animated: true)
}
}
}
| apache-2.0 |
jameszaghini/bonjour-demo-osx-to-ios | bonjour-demo-mac/BonjourServer.swift | 1 | 6091 | //
// BonjourServer.swift
// bonjour-demo-mac
//
// Created by James Zaghini on 14/05/2015.
// Copyright (c) 2015 James Zaghini. All rights reserved.
//
import Cocoa
enum PacketTag: Int {
case header = 1
case body = 2
}
protocol BonjourServerDelegate {
func connected()
func disconnected()
func handleBody(_ body: NSString?)
func didChangeServices()
}
class BonjourServer: NSObject, NetServiceBrowserDelegate, NetServiceDelegate, GCDAsyncSocketDelegate {
var delegate: BonjourServerDelegate!
var coServiceBrowser: NetServiceBrowser!
var devices: Array<NetService>!
var connectedService: NetService!
var sockets: [String : GCDAsyncSocket]!
override init() {
super.init()
self.devices = []
self.sockets = [:]
self.startService()
}
func parseHeader(_ data: Data) -> UInt {
var out: UInt = 0
(data as NSData).getBytes(&out, length: MemoryLayout<UInt>.size)
return out
}
func handleResponseBody(_ data: Data) {
if let message = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
self.delegate.handleBody(message)
}
}
func connectTo(_ service: NetService) {
service.delegate = self
service.resolve(withTimeout: 15)
}
// MARK: NSNetServiceBrowser helpers
func stopBrowsing() {
if self.coServiceBrowser != nil {
self.coServiceBrowser.stop()
self.coServiceBrowser.delegate = nil
self.coServiceBrowser = nil
}
}
func startService() {
if self.devices != nil {
self.devices.removeAll(keepingCapacity: true)
}
self.coServiceBrowser = NetServiceBrowser()
self.coServiceBrowser.delegate = self
self.coServiceBrowser.searchForServices(ofType: "_probonjore._tcp.", inDomain: "local.")
}
func send(_ data: Data) {
print("send data")
if let socket = self.getSelectedSocket() {
var header = data.count
let headerData = Data(bytes: &header, count: MemoryLayout<UInt>.size)
socket.write(headerData, withTimeout: -1.0, tag: PacketTag.header.rawValue)
socket.write(data, withTimeout: -1.0, tag: PacketTag.body.rawValue)
}
}
func connectToServer(_ service: NetService) -> Bool {
var connected = false
let addresses: Array = service.addresses!
var socket = self.sockets[service.name]
if !(socket?.isConnected != nil) {
socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
while !connected && !addresses.isEmpty {
let address: Data = addresses[0]
do {
if (try socket?.connect(toAddress: address) != nil) {
self.sockets.updateValue(socket!, forKey: service.name)
self.connectedService = service
connected = true
}
} catch {
print(error);
}
}
}
return true
}
// MARK: NSNetService Delegates
func netServiceDidResolveAddress(_ sender: NetService) {
print("did resolve address \(sender.name)")
if self.connectToServer(sender) {
print("connected to \(sender.name)")
}
}
func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) {
print("net service did no resolve. errorDict: \(errorDict)")
}
// MARK: GCDAsyncSocket Delegates
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
print("connected to host \(String(describing: host)), on port \(port)")
sock.readData(toLength: UInt(MemoryLayout<UInt64>.size), withTimeout: -1.0, tag: 0)
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
print("socket did disconnect \(String(describing: sock)), error: \(String(describing: err?._userInfo))")
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
print("socket did read data. tag: \(tag)")
if self.getSelectedSocket() == sock {
if data.count == MemoryLayout<UInt>.size {
let bodyLength: UInt = self.parseHeader(data)
sock.readData(toLength: bodyLength, withTimeout: -1, tag: PacketTag.body.rawValue)
} else {
self.handleResponseBody(data)
sock.readData(toLength: UInt(MemoryLayout<UInt>.size), withTimeout: -1, tag: PacketTag.header.rawValue)
}
}
}
func socketDidCloseReadStream(_ sock: GCDAsyncSocket) {
print("socket did close read stream")
}
// MARK: NSNetServiceBrowser Delegates
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didFind aNetService: NetService, moreComing: Bool) {
self.devices.append(aNetService)
if !moreComing {
self.delegate.didChangeServices()
}
}
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didRemove aNetService: NetService, moreComing: Bool) {
self.devices.removeObject(aNetService)
if !moreComing {
self.delegate.didChangeServices()
}
}
func netServiceBrowserDidStopSearch(_ aNetServiceBrowser: NetServiceBrowser) {
self.stopBrowsing()
}
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
self.stopBrowsing()
}
// MARK: helpers
func getSelectedSocket() -> GCDAsyncSocket? {
var sock: GCDAsyncSocket?
if self.connectedService != nil {
sock = self.sockets[self.connectedService.name]!
}
return sock
}
}
| mit |
gowansg/firefox-ios | Utils/DeferredUtils.swift | 3 | 2082 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Haskell, baby.
// Monadic bind/flatMap operator for Deferred.
infix operator >>== { associativity left precedence 160 }
public func >>== <T, U>(x: Deferred<Result<T>>, f: T -> Deferred<Result<U>>) -> Deferred<Result<U>> {
return chainDeferred(x, f)
}
// A termination case.
public func >>== <T, U>(x: Deferred<Result<T>>, f: T -> ()) {
return x.upon { result in
if let v = result.successValue {
f(v)
}
}
}
// Monadic `do` for Deferred.
infix operator >>> { associativity left precedence 150 }
public func >>> <T, U>(x: Deferred<Result<T>>, f: () -> Deferred<Result<U>>) -> Deferred<Result<U>> {
return x.bind { res in
if res.isSuccess {
return f();
}
return deferResult(res.failureValue!)
}
}
/**
* Returns a thunk that return a Deferred that resolves to the provided value.
*/
public func always<T>(t: T) -> () -> Deferred<Result<T>> {
return { deferResult(t) }
}
public func deferResult<T>(s: T) -> Deferred<Result<T>> {
return Deferred(value: Result(success: s))
}
public func deferResult<T>(e: ErrorType) -> Deferred<Result<T>> {
return Deferred(value: Result(failure: e))
}
public func chainDeferred<T, U>(a: Deferred<Result<T>>, f: T -> Deferred<Result<U>>) -> Deferred<Result<U>> {
return a.bind { res in
if let v = res.successValue {
return f(v)
}
return Deferred(value: Result<U>(failure: res.failureValue!))
}
}
public func chainResult<T, U>(a: Deferred<Result<T>>, f: T -> Result<U>) -> Deferred<Result<U>> {
return a.map { res in
if let v = res.successValue {
return f(v)
}
return Result<U>(failure: res.failureValue!)
}
}
public func chain<T, U>(a: Deferred<Result<T>>, f: T -> U) -> Deferred<Result<U>> {
return chainResult(a, { Result<U>(success: f($0)) })
}
| mpl-2.0 |
guillermo-ag-95/App-Development-with-Swift-for-Students | 2 - Introduction to UIKit/10 - Auto Layout and Stack Views/lab/Calculator/Calculator/ViewController.swift | 1 | 384 | //
// ViewController.swift
// Calculator
//
// Created by Guillermo Alcalá Gamero on 20/12/2018.
// Copyright © 2018 Guillermo Alcalá Gamero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| mit |
ingresse/ios-sdk | IngresseSDK/Services/User/ApiUserService.swift | 1 | 2564 | //
// Copyright © 2022 Ingresse. All rights reserved.
//
import Foundation
public class ApiUserService: BaseService {
public typealias CustomApiResult<U: Decodable> = ApiResult<U, ResponseError, ResponseError>
public typealias UserTransactionsResponse = PagedResponse<UserTransactionResponse>
public func getTransactions(request: UserTransactionsRequest,
queue: DispatchQueue,
completion: @escaping (CustomApiResult<UserTransactionsResponse>) -> Void) {
let urlRequest = ApiUserURLRequest.GetTransactions(request: request,
environment: client.environment,
userAgent: client.userAgent,
apiKey: client.apiKey,
authToken: client.authToken)
Network.apiRequest(queue: queue, networkURLRequest: urlRequest, completion: completion)
}
public func refundTransaction(request: RefundTransactionRequest,
queue: DispatchQueue,
completion: @escaping (CustomApiResult<TransactionRefundedResponse>) -> Void) {
let urlRequest = ApiUserURLRequest.RefundTransaction(request: request,
environment: client.environment,
userAgent: client.userAgent,
apiKey: client.apiKey,
authToken: client.authToken)
Network.apiRequest(queue: queue, networkURLRequest: urlRequest, completion: completion)
}
public func deleteUser(request: DeleteUserRequest,
queue: DispatchQueue,
completion: @escaping (CustomApiResult<DeleteUserResponse>) -> Void) {
let urlRequest = ApiUserURLRequest.DeleteUser(request: request,
environment: client.environment,
userAgent: client.userAgent,
apiKey: client.apiKey,
authToken: client.authToken)
Network.apiRequest(queue: queue, networkURLRequest: urlRequest, completion: completion)
}
}
| mit |
sajeel/AutoScout | AutoScout/View & Controllers/MainViewController.swift | 1 | 4406 | //
// MainViewController.swift
// AutoScout
//
// Created by Sajjeel Khilji on 5/19/17.
// Copyright © 2017 Saj. All rights reserved.
//
import UIKit
import Foundation
import MXParallaxHeader
class MainViewController: MXSegmentedPagerController {
let segmentedNames = ["Cars", "Fav"]
private var carsDataSource: CustomTableViewDataSource!
private var favsDataSource: CustomTableViewDataSource!
private var carsViewModel: CarsViewModel?
private var favsViewModel: FavViewModel?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configurePager()
}
public func setViewModels(carsViewModel: ViewsModelData, favsViewModel: ViewsModelData) -> Void
{
self.carsViewModel = carsViewModel as? CarsViewModel
self.favsViewModel = favsViewModel as? FavViewModel
self.carsDataSource = CustomTableViewDataSource(viewModel: carsViewModel)
self.favsDataSource = CustomTableViewDataSource(viewModel: favsViewModel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
configureViewControllersAndModels()
}
func configureViewControllersAndModels() {
for index in 0...segmentedNames.count {
let indexKey = NSNumber.init(value: index)
let viewController = self.pageViewControllers.object(forKey: indexKey)
if viewController is CarsViewController{
let carsViewController = viewController as! CarsViewController
carsViewController.tableView.dataSource = self.carsDataSource
carsViewController.viewModel = self.carsViewModel
self.carsViewModel?.delegate = carsViewController
}else if viewController is FavViewController{
let favsViewController = viewController as! FavViewController
favsViewController.tableView.dataSource = self.favsDataSource
favsViewController.viewModel = self.favsViewModel
self.favsViewModel?.delegate = favsViewController
}
}
}
func configurePager() {
segmentedPager.backgroundColor = .white
// Segmented Control customization
segmentedPager.segmentedControl.selectionIndicatorLocation = .down
segmentedPager.segmentedControl.backgroundColor = .white
segmentedPager.segmentedControl.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.black]
segmentedPager.segmentedControl.selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.orange]
segmentedPager.segmentedControl.selectionStyle = .fullWidthStripe
segmentedPager.segmentedControl.selectionIndicatorColor = .orange
segmentedPager.bounces = true
}
func adjustTableView() {
edgesForExtendedLayout = []
extendedLayoutIncludesOpaqueBars = false
automaticallyAdjustsScrollViewInsets = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func segmentedPager(_ segmentedPager: MXSegmentedPager, titleForSectionAt index: Int) -> String {
return segmentedNames[index]
}
override func segmentedPager(_ segmentedPager: MXSegmentedPager, didScrollWith parallaxHeader: MXParallaxHeader) {
print("progress \(parallaxHeader.progress)")
}
}
/*
override func segmentedPager(_ segmentedPager: MXSegmentedPager, viewControllerForPageAt index: Int) -> UIViewController {
let pageViewController: UIViewController = super.segmentedPager(segmentedPager, viewControllerForPageAt: index)
if pageViewController is CarsViewController {
(pageViewController as! CarsViewController).delegate = self.carsDataSource.viewModel as! CarsViewModelInput
(pageViewController as! CarsViewController).tableView.dataSource = self.carsDataSource
}else if pageViewController is FavViewController{
(pageViewController as! FavViewController).delegate = self.favsDataSource.viewModel as! FavViewModelInput
(pageViewController as! FavViewController).tableView.dataSource = self.favsDataSource
}
return pageViewController;
}*/
| gpl-3.0 |
pdcgomes/RendezVous | RendezVous/StringColorizer.swift | 1 | 12514 | //
// StringColorizer.swift
// RendezVous
//
// Created by Pedro Gomes on 11/09/2015.
// Copyright © 2015 Pedro Gomes. All rights reserved.
//
import Foundation
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public enum AnsiColorCode : UInt, CustomStringConvertible {
case Black = 0
case Red = 1
case Green = 2
case Yellow = 3
case Blue = 4
case Magenta = 5
case Cyan = 6
case White = 7
case Default = 9
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public init?(rawValue: UInt) {
var value: UInt
switch rawValue {
case 30...39: value = rawValue - 30; break
case 40...49: value = rawValue - 40; break
case 60...69: value = rawValue - 60; break
default: value = rawValue
}
switch value {
case 0: self = .Black; break
case 1: self = .Red; break
case 2: self = .Green; break
case 3: self = .Yellow; break
case 4: self = .Blue; break
case 5: self = .Magenta; break
case 6: self = .Cyan; break
case 7: self = .White; break
case 9: self = .Default; break
default: return nil
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static func values() -> [AnsiColorCode] {
var values = [AnsiColorCode]()
for v: UInt in 0...7 {
if let enumValue = AnsiColorCode(rawValue: v) {
values.append(enumValue)
}
}
return values
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func lightColor() -> UInt {
switch self.rawValue {
case 0...7: return self.rawValue + 60
default: return self.rawValue
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func foregroundColor() -> UInt {
return self.rawValue + 30
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func backgroundColor() -> UInt {
return self.rawValue + 40
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public var description: String {
switch self {
case Black: return "Black"
case Red: return "Red"
case Green: return "Green"
case Yellow: return "Yellow"
case Blue: return "Blue"
case Magenta: return "Magenta"
case Cyan: return "Cyan"
case White: return "White"
case Default: return ""
}
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public enum AnsiModeCode : UInt, CustomStringConvertible {
case Default = 0
case Bold = 1
case Italic = 3
case Underline = 4
case Inverse = 7
case Hide = 8
case Strike = 9
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static func values() -> [AnsiModeCode] {
var values = [AnsiModeCode]()
for v: UInt in 0...9 {
if let enumValue = AnsiModeCode(rawValue: v) {
values.append(enumValue)
}
}
return values
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public var description: String {
switch self {
case Bold: return "Bold"
case Italic: return "Italic"
case Underline: return "Underline"
case Inverse: return "Inverse"
case Hide: return "Hide"
case Strike: return "Strikethrough"
case Default: return ""
}
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
struct ANSISequence: CustomStringConvertible {
var modeCode: UInt
var foregroundCode: UInt
var backgroundCode: UInt
var string: String
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
init(foreground: AnsiColorCode = .Default, background: AnsiColorCode = .Default, mode: AnsiModeCode = .Default, string: String) {
self.foregroundCode = foreground.foregroundColor()
self.backgroundCode = background.backgroundColor()
self.modeCode = mode.rawValue
self.string = string
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
var description: String {
let codeSequence = [modeCode, foregroundCode, backgroundCode]
.map({ String($0) })
.joinWithSeparator(";")
return "\u{001b}[\(codeSequence)m" + string + "\u{001b}[0m"
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public extension String {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public func colorize(text: AnsiColorCode = .Default, background: AnsiColorCode = .Default, mode: AnsiModeCode = .Default) -> String {
let (hasSequence, sequence) = extractANSISequence()
if hasSequence {
let seq = sequence!
return ANSISequence(
foreground: (text == .Default ? AnsiColorCode(rawValue: seq.foregroundCode)! : text),
background: (background == .Default ? AnsiColorCode(rawValue: seq.backgroundCode)! : background),
mode: (mode == .Default ? AnsiModeCode(rawValue: seq.modeCode)! : mode),
string: seq.string).description
}
return ANSISequence(
foreground: text,
background: background,
mode: mode,
string: self).description
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public static func printColorSamples() -> Void {
let colorCodes = AnsiColorCode.values().map { $0 }
let maxLen = Int(colorCodes.reduce(0) {
return $1.description.characters.count > $0 ? $1.description.characters.count : $0 })
for f in colorCodes {
for b in colorCodes {
let foreground = f.description.leftJustify(maxLen + 1)
let background = b.description.leftJustify(maxLen + 1)
print("\(foreground) on \(background)".colorize(f, background: b))
}
}
}
////////////////////////////////////////////////////////////////////////////////
// If we already have existing ANSI sequences, return them
////////////////////////////////////////////////////////////////////////////////
private func extractANSISequence() -> (Bool, ANSISequence?) {
let result = self =~ "\\u001B\\[([^m]*)m(.+?)\\u001B\\[0m"
guard result else { return (false, nil) }
let codes = result[1].componentsSeparatedByString(";").map({ UInt($0)! })
let mode = AnsiModeCode(rawValue: UInt(codes[0]))!
let foreground = AnsiColorCode(rawValue: UInt(codes[1]))!
let background = AnsiColorCode(rawValue: UInt(codes[2]))!
return (true, ANSISequence(
foreground: foreground,
background: background,
mode: mode,
string: result[2]))
}
}
////////////////////////////////////////////////////////////////////////////////
// Convenience methods and properties
////////////////////////////////////////////////////////////////////////////////
public extension String {
////////////////////////////////////////////////////////////////////////////////
// Convenince text colorizer properties
////////////////////////////////////////////////////////////////////////////////
var black: String { return self.colorize(.Black) }
var red: String { return self.colorize(.Red) }
var green: String { return self.colorize(.Green) }
var yellow: String { return self.colorize(.Yellow) }
var blue: String { return self.colorize(.Blue) }
var magenta: String { return self.colorize(.Magenta)}
var cyan: String { return self.colorize(.Cyan) }
var white: String { return self.colorize(.White) }
////////////////////////////////////////////////////////////////////////////////
// Convenience background colorizer properties
////////////////////////////////////////////////////////////////////////////////
var on_black: String { return self.colorize(background: .Black) }
var on_red: String { return self.colorize(background: .Red) }
var on_green: String { return self.colorize(background: .Green) }
var on_yellow: String { return self.colorize(background: .Yellow) }
var on_blue: String { return self.colorize(background: .Blue) }
var on_magenta: String { return self.colorize(background: .Magenta)}
var on_cyan: String { return self.colorize(background: .Cyan) }
var on_white: String { return self.colorize(background: .White) }
////////////////////////////////////////////////////////////////////////////////
// Convenience mode setting properties
////////////////////////////////////////////////////////////////////////////////
var bold: String { return self.colorize(mode: .Bold) }
var underline: String { return self.colorize(mode: .Underline)}
var italic: String { return self.colorize(mode: .Italic) }
var inverse: String { return self.colorize(mode: .Inverse) }
var strike: String { return self.colorize(mode: .Strike) }
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public extension String {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func leftJustify(padding: Int) -> String {
if self.characters.count >= padding {
return self
}
var justifiedStr = self
for _ in 0..<(padding - self.characters.count) {
justifiedStr.appendContentsOf(" ")
}
return justifiedStr
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
func rightJustify(padding: Int) -> String {
if self.characters.count >= padding {
return self
}
var justifiedStr = ""
for _ in 0..<(padding - self.characters.count) {
justifiedStr.appendContentsOf(" ")
}
justifiedStr.appendContentsOf(self)
return justifiedStr
}
}
| mit |
WE-St0r/SwiftyVK | Library/Sources/Sessions/Management/SessionsStorage.swift | 2 | 2402 | import Foundation
protocol SessionsStorage {
func save(sessions: [EncodedSession]) throws
func restore() throws -> [EncodedSession]
}
final class SessionsStorageImpl: SessionsStorage {
private let fileManager: VKFileManager
private let gateQueue = DispatchQueue(label: "SwiftyVK.sessionStorageQueue")
private let bundleName: String
private let configName: String
init(
fileManager: VKFileManager,
bundleName: String,
configName: String
) {
self.fileManager = fileManager
self.bundleName = bundleName
self.configName = configName
}
func save(sessions: [EncodedSession]) throws {
try gateQueue.sync {
let fileUrl = try configurationUrl()
try createFileIfNotExists(at: fileUrl)
let data = try PropertyListEncoder().encode(sessions)
try data.write(to: fileUrl, options: .atomicWrite)
}
}
func restore() throws -> [EncodedSession] {
return try gateQueue.sync {
let fileUrl = try configurationUrl()
guard fileManager.fileExists(atPath: fileUrl.path) else {
print("SwiftyVK: Session not restored because file not exists yet")
return []
}
let rawData = try Data(contentsOf: fileUrl)
let sessions = try PropertyListDecoder().decode([EncodedSession].self, from: rawData)
return sessions
}
}
func configurationUrl() throws -> URL {
if configName.starts(with: "/") {
return URL(fileURLWithPath: configName)
}
return try fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
.appendingPathComponent(bundleName)
.appendingPathComponent("\(configName).plist")
}
func createFileIfNotExists(at url: URL) throws {
guard !fileManager.fileExists(atPath: url.path) else {
return
}
try fileManager.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
_ = fileManager.createFile(atPath: url.path, contents: nil, attributes: nil)
}
}
| mit |
Azurelus/Swift-Useful-Files | Sources/Extensions/UIFont+Extension.swift | 1 | 1224 | //
// UIFont+Extension.swift
// Swift-Useful-Files
//
// Created by Maksym Husar on 9/7/17.
// Copyright © 2017 Husar Maksym. All rights reserved.
//
import UIKit
extension UIFont {
enum FontFamily: String {
case sanFrancisco = ".SFUIText"
//case someOther = "OTHER"
}
enum FontWeight {
case light
case regular
case medium
case bold
case semibold
func string(for family: FontFamily) -> String? {
switch self {
case .light: return "Light"
case .regular: return nil
case .medium: return "Medium"
case .bold: return "Bold"
case .semibold: return "Semibold"
}
}
}
class func font(ofSize size: CGFloat, weight: FontWeight = .regular, family: FontFamily = .sanFrancisco) -> UIFont {
var fontName = family.rawValue
if let weightString = weight.string(for: family) {
fontName += "-\(weightString)"
}
guard let selectedFont = UIFont(name: fontName, size: size) else {
preconditionFailure("Error! Custom font doesn't found")
}
return selectedFont
}
}
| mit |
phimage/Phiole | PhioleColor.swift | 1 | 11524 | //
// PhioleColor.swift
// Phiole
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
// Check if property XcodeColors set for plugin https://github.com/robbiehanson/XcodeColors
let XCODE_COLORS: Bool = {
let dict = NSProcessInfo.processInfo().environment
if let env = dict["XcodeColors"] where env == "YES" {
return true
}
return false
}()
public extension Phiole {
private struct key {
static let colorize = UnsafePointer<Void>(bitPattern: Selector("colorize").hashValue)
static let outputColor = UnsafePointer<Void>(bitPattern: Selector("outputColor").hashValue)
static let errorColor = UnsafePointer<Void>(bitPattern: Selector("errorColor").hashValue)
}
// Bool to deactivate default colorization
public var colorize: Bool {
get {
if let o = objc_getAssociatedObject(self, key.colorize) as? Bool {
return o
}
else {
let obj = true
objc_setAssociatedObject(self, key.colorize, obj, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return obj
}
}
set {
objc_setAssociatedObject(self, key.colorize, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var outputColor: Color {
get {
if let o = objc_getAssociatedObject(self, key.outputColor) as? Int {
return Color(rawValue: o)!
}
else {
let obj = Color.None
objc_setAssociatedObject(self, key.outputColor, obj.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return obj
}
}
set {
objc_setAssociatedObject(self, key.outputColor, newValue.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
colorize = true
}
}
public var errorColor: Color {
get {
if let o = objc_getAssociatedObject(self, key.errorColor) as? Int {
return Color(rawValue: o)!
}
else {
let obj = Color.None
objc_setAssociatedObject(self, key.errorColor, obj.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return obj
}
}
set {
objc_setAssociatedObject(self, key.errorColor, newValue.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
colorize = true
}
}
// MARK: coloration and font enhancement
private struct PhioleColor {
var red, green, blue: UInt8
}
public enum Color: Int, StringDecorator {
case Black, Red, Green, Yellow, Blue, Cyan, Purple, Gray,
DarkGray,BrightRed,BrightGreen,BrightYellow,BrightBlue,BrightMagenta,BrightCyan,White,
None
public static let allValues = [Black,Red,Green,Yellow,Blue,Cyan,Purple,Gray,
DarkGray,BrightRed,BrightGreen,BrightYellow,BrightBlue,BrightMagenta,BrightCyan,White,None]
public static let ESCAPE_SEQUENCE = "\u{001b}["
public static let TERMINAL_COLORS_RESET = "\u{0030}\u{006d}"
public static let XCODE_COLORS_FG = "fg"
public static let XCODE_COLORS_RESET_FG = "fg;"
public static let XCODE_COLORS_BG = "bg"
public static let XCODE_COLORS_RESET_BG = "bg;"
public static let XCODE_COLORS_RESET = ";"
public static let COLORS_RESET = XCODE_COLORS ? XCODE_COLORS_RESET : TERMINAL_COLORS_RESET
public var foregroundCode: String? {
if XCODE_COLORS {
if let c = self.xcodeColor {
return "\(Color.XCODE_COLORS_FG)\(c.red),\(c.green),\(c.blue);"
}
return nil
}
switch self {
case Black : return "30m"
case Red : return "31m"
case Green : return "32m"
case Yellow : return "33m"
case Blue : return "34m"
case Purple : return "35m"
case Cyan : return "36m"
case Gray : return "37m"
// bold
case DarkGray : return "1;30m"
case BrightRed : return "1;31m"
case BrightGreen : return "1;32m"
case BrightYellow : return "1;33m"
case BrightBlue : return "1;34m"
case BrightMagenta : return "1;35m"
case BrightCyan : return "1;36m"
case White : return "1;37m"
case None : return nil
}
}
public var backgroundCode: String? {
if XCODE_COLORS {
if let c = self.xcodeColor {
return "\(Color.XCODE_COLORS_BG)\(c.red),\(c.green),\(c.blue);"
}
return nil
}
switch self {
case Black : return "40m"
case Red : return "41m"
case Green : return "42m"
case Yellow : return "43m"
case Blue : return "44m"
case Purple : return "45m"
case Cyan : return "46m"
case Gray : return "47m"
case DarkGray : return "1;40m"
case BrightRed : return "1;41m"
case BrightGreen : return "1;42m"
case BrightYellow : return "1;43m"
case BrightBlue : return "1;44m"
case BrightMagenta : return "1;45m"
case BrightCyan : return "1;46m"
case White : return "1;47m"
case None : return nil
}
}
/*private var terminalColor: PhioleColor? {
switch self {
case Black : return PhioleColor(red: 0, green: 0, blue: 0)
case Red : return PhioleColor(red:194, green: 54, blue: 33)
case Green : return PhioleColor(red: 37, green: 188, blue: 36)
case Yellow : return PhioleColor(red:173, green: 173, blue: 39)
case Blue : return PhioleColor(red: 73, green: 46, blue: 225)
case Purple : return PhioleColor(red:211, green: 56, blue: 211)
case Cyan : return PhioleColor(red: 51, green: 187, blue: 200)
case Gray : return PhioleColor(red:203, green: 204, blue: 205)
case DarkGray : return PhioleColor(red:129, green: 131, blue: 131)
case BrightRed : return PhioleColor(red:252, green: 57, blue: 31)
case BrightGreen : return PhioleColor(red: 49, green: 231, blue: 34)
case BrightYellow : return PhioleColor(red:234, green: 236, blue: 35)
case BrightBlue : return PhioleColor(red: 88, green: 51, blue: 255)
case BrightMagenta : return PhioleColor(red:249, green: 53, blue: 248)
case BrightCyan : return PhioleColor(red: 20, green: 240, blue: 240)
case White : return PhioleColor(red:233, green: 235, blue: 235)
case None : return nil
}
}*/
private var xcodeColor: PhioleColor? {
switch self {
case Black : return PhioleColor(red: 0, green: 0, blue: 0)
case Red : return PhioleColor(red:205, green: 0, blue: 0)
case Green : return PhioleColor(red: 0, green: 205, blue: 0)
case Yellow : return PhioleColor(red:205, green: 205, blue: 0)
case Blue : return PhioleColor(red: 0, green: 0, blue: 238)
case Purple : return PhioleColor(red:205, green: 0, blue: 205)
case Cyan : return PhioleColor(red: 0, green: 205, blue: 205)
case Gray : return PhioleColor(red:229, green: 229, blue: 229)
case DarkGray : return PhioleColor(red:127, green: 127, blue: 127)
case BrightRed : return PhioleColor(red:255, green: 0, blue: 0)
case BrightGreen : return PhioleColor(red: 0, green: 255, blue: 0)
case BrightYellow : return PhioleColor(red:255, green: 255, blue: 0)
case BrightBlue : return PhioleColor(red: 92, green: 92, blue: 255)
case BrightMagenta : return PhioleColor(red:255, green: 0, blue: 255)
case BrightCyan : return PhioleColor(red: 0, green: 255, blue: 255)
case White : return PhioleColor(red:255, green: 255, blue: 255)
case None : return nil
}
}
// MARK: functions
public func fg(string: String) -> String {
if let code = self.foregroundCode {
return Color.ESCAPE_SEQUENCE + code + string + Color.ESCAPE_SEQUENCE + Color.COLORS_RESET
}
return string
}
public func bg(string: String) -> String {
if let code = self.backgroundCode {
return Color.ESCAPE_SEQUENCE + code + string + Color.ESCAPE_SEQUENCE + Color.COLORS_RESET
}
return string
}
public func decorate(string: String) -> String {
return fg(string)
}
public static func decorate(string: String, fg: Color, bg: Color) -> String {
if let fcode = fg.foregroundCode, bcode = bg.backgroundCode {
return Color.ESCAPE_SEQUENCE + fcode + ESCAPE_SEQUENCE + bcode + string + Color.ESCAPE_SEQUENCE + Color.COLORS_RESET
}
if fg.foregroundCode != nil {
return fg.fg(string)
}
if bg.backgroundCode != nil {
return bg.bg(string)
}
return string
}
}
/*public enum FontStyle {
case Bold
case Italic
case Underline
case Reverse
public var on: String {
switch self {
case Bold : return "1m"
case Italic : return "3m"
case Underline : return "4m"
case Reverse : return "7m"
}
}
public var off: String {
switch self {
case Bold : return "22m"
case Italic : return "23m"
case Underline : return "24m"
case Reverse : return "27m"
}
}
public func decorate(string: String) -> String {
return self.on + string + self.off
}
}*/
}
| mit |
fiveagency/ios-five-ui-components | Example/Classes/UserInterface/Home/ExamplesViewModel.swift | 1 | 1294 | //
// ExamplesViewModel.swift
// Example
//
// Created by Denis Mendica on 2/14/17.
// Copyright © 2017 Five Agency. All rights reserved.
//
import Foundation
enum Example {
case gradientView
case delayedCellLoadingAnimator
case sectionedLayout
case snappingCollectionView
case smoothPageControl
case pageViewControllers
case pageViewController(Int)
static var homeScreenExamples: [Example] {
return [.gradientView, .delayedCellLoadingAnimator, .sectionedLayout, .snappingCollectionView, .smoothPageControl, .pageViewControllers]
}
static var pageViewControllerExamples: [Example] {
return [.pageViewController(1), .pageViewController(2), .pageViewController(3)]
}
}
class ExamplesViewModel {
private let examples: [Example]
private let navigationService: NavigationService
init(navigationService: NavigationService, examples: [Example]) {
self.navigationService = navigationService
self.examples = examples
}
var numberOfExamples: Int {
return examples.count
}
func cellViewModel(at index: Int) -> ExampleCellViewModel {
return ExampleCellViewModel(navigationService: navigationService, example: examples[index], index: index)
}
}
| mit |
the-grid/Portal | Portal/Models/SiteConfig.swift | 1 | 1635 | import Argo
import Curry
import Foundation
import Ogra
/// A site configuration.
public struct SiteConfig {
public var color: ColorConfig?
public var favicon: NSURL?
public var layout: Float?
public var logo: NSURL?
public var typography: Float?
public init(
color: ColorConfig? = .None,
favicon: NSURL? = .None,
layout: Float? = .None,
logo: NSURL? = .None,
typography: Float? = .None
) {
self.color = color
self.favicon = favicon
self.layout = layout
self.logo = logo
self.typography = typography
}
}
// MARK: - Decodable
extension SiteConfig: Decodable {
public static func decode(json: JSON) -> Decoded<SiteConfig> {
return curry(self.init)
<^> json <|? "color"
<*> json <|? "favicon"
<*> json <|? "layout_spectrum"
<*> json <|? "logo"
<*> json <|? "typography_spectrum"
}
}
// MARK: - Encodable
extension SiteConfig: Encodable {
public func encode() -> JSON {
return .Object([
"color": color.encode(),
"favicon": favicon.encode(),
"layout_spectrum": layout.encode(),
"logo": logo.encode(),
"typography_spectrum": typography.encode()
])
}
}
// MARK: - Equatable
extension SiteConfig: Equatable {}
public func == (lhs: SiteConfig, rhs: SiteConfig) -> Bool {
return lhs.color == rhs.color
&& lhs.favicon == rhs.favicon
&& lhs.layout == rhs.layout
&& lhs.logo == rhs.logo
&& lhs.typography == rhs.typography
}
| mit |
zmian/xcore.swift | Sources/Xcore/SwiftUI/Extensions/View+PrivacyScreen.swift | 1 | 2676 | //
// Xcore
// Copyright © 2021 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
extension View {
/// The content view is automatically displayed when scene transitions to
/// non-active state.
///
/// Privacy screen behavior is suitable to be used on any view that displays
/// private content that should be masked when when scene transition to
/// non-active state.
///
/// **Usage**
///
/// ```swift
/// @main
/// struct MyApp: App {
/// var body: some Scene {
/// WindowGroup {
/// ContentView()
/// .privacyScreen {
/// Color.black
/// }
/// }
/// }
/// }
/// ```
/// - Parameter content: The privacy screen content view.
public func privacyScreen<Content: View>(@ViewBuilder content: @escaping () -> Content) -> some View {
modifier(PrivacyScreenViewModifier(screen: content))
}
/// The content view is automatically displayed when scene transitions to
/// non-active state.
///
/// Privacy screen behavior is suitable to be used on any view that displays
/// private content that should be masked when when scene transition to
/// non-active state.
///
/// **Usage**
///
/// ```swift
/// @main
/// struct MyApp: App {
/// var body: some Scene {
/// WindowGroup {
/// ContentView()
/// .privacyScreen(Color.black)
/// }
/// }
/// }
/// ```
/// - Parameter content: The privacy screen content view.
public func privacyScreen<Content: View>(_ content: @autoclosure @escaping () -> Content) -> some View {
privacyScreen { content() }
}
}
// MARK: - ViewModifier
private struct PrivacyScreenViewModifier<Screen: View>: ViewModifier {
@Environment(\.scenePhase) private var scenePhase
@State private var isPrivacyScreenActive = false
private let screen: () -> Screen
init(@ViewBuilder screen: @escaping () -> Screen) {
self.screen = screen
}
func body(content: Content) -> some View {
content
.window(isPresented: $isPrivacyScreenActive) {
ZStack {
if isPrivacyScreenActive {
screen()
.transition(.opacity)
}
}
.animation(.easeInOut, value: isPrivacyScreenActive)
}
.onChange(of: scenePhase) { phase in
isPrivacyScreenActive = phase != .active
}
}
}
| mit |
ustwo/US2MapperKit | US2MapperKit/Shared Test Cases/Classes/TestObjectEleven.swift | 1 | 66 | import Foundation
class TestObjectEleven : _TestObjectEleven {
} | mit |
Jnosh/swift | validation-test/compiler_crashers_fixed/00457-swift-declcontext-lookupqualified.swift | 65 | 503 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let g = c> S<T
let t: NSObject {
class B<H : d where A: AnyObject) {
let c>: String {
}
var f: Int = ""\
| apache-2.0 |
StYaphet/firefox-ios | Client/Frontend/Browser/TabPeekViewController.swift | 7 | 9575 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import WebKit
protocol TabPeekDelegate: AnyObject {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks")
fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard")
fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab")
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var fxaDevicePicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
fileprivate var webView: WKWebView?
// Preview action items.
override var previewActionItems: [UIPreviewActionItem] {
get {
return previewActions
}
}
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isBookmarked {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: Strings.SendToDeviceTitle, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return }
wself.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) {[weak self] previewAction, viewController in
guard let wself = self, let url = wself.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view)
})
}
}
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
@available(iOS 13, *)
func contextActions(defaultActions: [UIMenuElement]) -> UIMenu {
var actions = [UIAction]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isBookmarked {
actions.append(UIAction(title: TabPeekViewController.PreviewActionAddToBookmarks, image: UIImage.templateImageNamed("menu-Bookmark"), identifier: nil) { [weak self] _ in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIAction(title: Strings.SendToDeviceTitle, image: UIImage.templateImageNamed("menu-Send"), identifier: nil) { [weak self] _ in
guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return }
wself.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
actions.append(UIAction(title: TabPeekViewController.PreviewActionCopyURL, image: UIImage.templateImageNamed("menu-Copy-Link"), identifier: nil) {[weak self] _ in
guard let wself = self, let url = wself.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view)
})
}
actions.append(UIAction(title: TabPeekViewController.PreviewActionCloseTab, image: UIImage.templateImageNamed("menu-CloseTabs"), identifier: nil) { [weak self] _ in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidCloseTab(tab)
})
return UIMenu(title: "", children: actions)
}
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
webView?.navigationDelegate = nil
self.webView = nil
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
setupWebView(tab?.webView)
guard let screenshot = tab?.screenshot else { return }
setupWithScreenshot(screenshot)
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
clonedWebView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
self.webView = clonedWebView
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: DevicePickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else {
return
}
guard let displayURL = tab.url?.absoluteString, !displayURL.isEmpty else {
return
}
browserProfile.places.isBookmarked(url: displayURL) >>== { isBookmarked in
self.isBookmarked = isBookmarked
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(.main) {
guard let clientGUIDs = $0.successValue else {
return
}
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = DevicePickerViewController()
clientPickerController.pickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
clientPickerController.profileNeedsShutdown = false
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.fxaDevicePicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList.getRecordWithURL(displayURL).value.successValue
self.isInReadingList = !(result?.url.isEmpty ?? true)
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
| mpl-2.0 |
griotspeak/Rational | Carthage/Checkouts/SwiftCheck/Tests/ReplaySpec.swift | 1 | 818 | //
// ReplaySpec.swift
// SwiftCheck
//
// Created by Robert Widmann on 11/18/15.
// Copyright © 2015 Robert Widmann. All rights reserved.
//
import SwiftCheck
import XCTest
class ReplaySpec : XCTestCase {
func testProperties() {
property("Test is replayed at specific args") <- forAll { (seedl : Int, seedr : Int, size : Int) in
let replayArgs = CheckerArguments(replay: .Some(StdGen(seedl, seedr), size))
var foundArgs : [Int] = []
property("Replay at \(seedl), \(seedr)", arguments: replayArgs) <- forAll { (x : Int) in
foundArgs.append(x)
return true
}
var foundArgs2 : [Int] = []
property("Replay at \(seedl), \(seedr)", arguments: replayArgs) <- forAll { (x : Int) in
foundArgs2.append(x)
return foundArgs.contains(x)
}
return foundArgs == foundArgs2
}
}
}
| mit |
ldt25290/MyInstaMap | ThirdParty/Alamofire/Source/Request.swift | 1 | 24233 | //
// Request.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
public protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
open class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
open var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
open let session: URLSession
/// The request sent or to be sent to the server.
open var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
open internal(set) var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
open func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
open func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
open func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
open func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
open var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
open var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -v"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(
host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = delegate.credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
#if swift(>=3.2)
components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
#else
components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
#endif
}
}
var headers: [AnyHashable: Any] = [:]
if let additionalHeaders = session.configuration.httpAdditionalHeaders {
for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
headers[field] = value
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields where field != "Cookie" {
headers[field] = value
}
}
for (field, value) in headers {
components.append("-H \"\(field): \(value)\"")
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
open class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.sync { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let requestable = originalTask as? Requestable { return requestable.urlRequest }
return nil
}
/// The progress of fetching the response data from the server for the request.
open var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
open func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
open class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
public struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
public let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.sync { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
return urlRequest
}
return nil
}
/// The resume data of the underlying download task if available after a failure.
open var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
open var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
open override func cancel() {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
open class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
guard let uploadable = originalTask as? Uploadable else { return nil }
switch uploadable {
case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
return urlRequest
}
}
/// The progress of uploading the payload to the server for the upload request.
open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.sync { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
| mit |
juliangrosshauser/ConvenienceKit | ConvenienceKit/Source/UIColor+Hexadecimal.swift | 1 | 592 | //
// UIColor+Hexadecimal.swift
// ConvenienceKit
//
// Created by Julian Grosshauser on 14/11/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
public extension UIColor {
public convenience init(hexadecimalColor: UInt32) {
let red = CGFloat(hexadecimalColor >> 24 & 0xFF) / 255
let green = CGFloat(hexadecimalColor >> 16 & 0xFF) / 255
let blue = CGFloat(hexadecimalColor >> 8 & 0xFF) / 255
let alpha = CGFloat(hexadecimalColor & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
| mit |
sunfei/realm-cocoa | Realm/Tests/Swift2.0/SwiftLinkTests.swift | 3 | 7906 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
class SwiftLinkTests: RLMTestCase {
// Swift models
func testBasicLink() {
let realm = realmWithTestPath()
let owner = SwiftOwnerObject()
owner.name = "Tim"
owner.dog = SwiftDogObject()
owner.dog!.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
let owners = SwiftOwnerObject.allObjectsInRealm(realm)
let dogs = SwiftDogObject.allObjectsInRealm(realm)
XCTAssertEqual(owners.count, UInt(1), "Expecting 1 owner")
XCTAssertEqual(dogs.count, UInt(1), "Expecting 1 dog")
XCTAssertEqual((owners[0] as! SwiftOwnerObject).name, "Tim", "Tim is named Tim")
XCTAssertEqual((dogs[0] as! SwiftDogObject).dogName, "Harvie", "Harvie is named Harvie")
let tim = owners[0] as! SwiftOwnerObject
XCTAssertEqual(tim.dog!.dogName, "Harvie", "Tim's dog should be Harvie")
}
func testMultipleOwnerLink() {
let realm = realmWithTestPath()
let owner = SwiftOwnerObject()
owner.name = "Tim"
owner.dog = SwiftDogObject()
owner.dog!.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog")
realm.beginWriteTransaction()
let fiel = SwiftOwnerObject.createInRealm(realm, withValue: ["Fiel", NSNull()])
fiel.dog = owner.dog
realm.commitWriteTransaction()
XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, UInt(2), "Expecting 2 owners")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog")
}
func testLinkRemoval() {
let realm = realmWithTestPath()
let owner = SwiftOwnerObject()
owner.name = "Tim"
owner.dog = SwiftDogObject()
owner.dog!.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog")
realm.beginWriteTransaction()
realm.deleteObject(owner.dog!)
realm.commitWriteTransaction()
XCTAssertNil(owner.dog, "Dog should be nullified when deleted")
// refresh owner and check
let owner2 = SwiftOwnerObject.allObjectsInRealm(realm).firstObject() as! SwiftOwnerObject
XCTAssertNotNil(owner2, "Should have 1 owner")
XCTAssertNil(owner2.dog, "Dog should be nullified when deleted")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, UInt(0), "Expecting 0 dogs")
}
// FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects
// func testCircularLinks() {
// let realm = realmWithTestPath()
//
// let obj = SwiftCircleObject()
// obj.data = "a"
// obj.next = obj
//
// realm.beginWriteTransaction()
// realm.addObject(obj)
// obj.next.data = "b"
// realm.commitWriteTransaction()
//
// let obj2 = SwiftCircleObject.allObjectsInRealm(realm).firstObject() as SwiftCircleObject
// XCTAssertEqual(obj2.data, "b", "data should be 'b'")
// XCTAssertEqual(obj2.data, obj2.next.data, "objects should be equal")
// }
// Objective-C models
func testBasicLink_objc() {
let realm = realmWithTestPath()
let owner = OwnerObject()
owner.name = "Tim"
owner.dog = DogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
let owners = OwnerObject.allObjectsInRealm(realm)
let dogs = DogObject.allObjectsInRealm(realm)
XCTAssertEqual(owners.count, UInt(1), "Expecting 1 owner")
XCTAssertEqual(dogs.count, UInt(1), "Expecting 1 dog")
XCTAssertEqual((owners[0] as! OwnerObject).name!, "Tim", "Tim is named Tim")
XCTAssertEqual((dogs[0] as! DogObject).dogName!, "Harvie", "Harvie is named Harvie")
let tim = owners[0] as! OwnerObject
XCTAssertEqual(tim.dog.dogName!, "Harvie", "Tim's dog should be Harvie")
}
func testMultipleOwnerLink_objc() {
let realm = realmWithTestPath()
let owner = OwnerObject()
owner.name = "Tim"
owner.dog = DogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog")
realm.beginWriteTransaction()
let fiel = OwnerObject.createInRealm(realm, withValue: ["Fiel", NSNull()])
fiel.dog = owner.dog
realm.commitWriteTransaction()
XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, UInt(2), "Expecting 2 owners")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog")
}
func testLinkRemoval_objc() {
let realm = realmWithTestPath()
let owner = OwnerObject()
owner.name = "Tim"
owner.dog = DogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 owner")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(1), "Expecting 1 dog")
realm.beginWriteTransaction()
realm.deleteObject(owner.dog)
realm.commitWriteTransaction()
XCTAssertNil(owner.dog, "Dog should be nullified when deleted")
// refresh owner and check
let owner2 = OwnerObject.allObjectsInRealm(realm).firstObject() as! OwnerObject
XCTAssertNotNil(owner2, "Should have 1 owner")
XCTAssertNil(owner2.dog, "Dog should be nullified when deleted")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, UInt(0), "Expecting 0 dogs")
}
// FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects
// func testCircularLinks_objc() {
// let realm = realmWithTestPath()
//
// let obj = CircleObject()
// obj.data = "a"
// obj.next = obj
//
// realm.beginWriteTransaction()
// realm.addObject(obj)
// obj.next.data = "b"
// realm.commitWriteTransaction()
//
// let obj2 = CircleObject.allObjectsInRealm(realm).firstObject() as CircleObject
// XCTAssertEqual(obj2.data, "b", "data should be 'b'")
// XCTAssertEqual(obj2.data, obj2.next.data, "objects should be equal")
// }
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.