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 |
---|---|---|---|---|---|
OatmealCode/Oatmeal | Example/Pods/Carlos/Carlos/ExpensiveObject.swift | 2 | 1175 | import Foundation
/// Abstracts objects that have a cost (useful for the MemoryCacheLevel)
public protocol ExpensiveObject {
/// The cost of the object
var cost: Int { get }
}
extension NSData: ExpensiveObject {
/// The number of bytes of the data block
public var cost: Int {
return self.length
}
}
extension String: ExpensiveObject {
/// The number of characters of the string
public var cost: Int {
return self.characters.count
}
}
extension NSString: ExpensiveObject {
/// The number of characters of the NSString
public var cost: Int {
return self.length
}
}
extension NSURL: ExpensiveObject {
/// The size of the URL
public var cost: Int {
return absoluteString.cost
}
}
extension Int: ExpensiveObject {
/// Integers have a unit cost
public var cost: Int {
return 1
}
}
extension Float: ExpensiveObject {
/// Floats have a unit cost
public var cost: Int {
return 1
}
}
extension Double: ExpensiveObject {
/// Doubles have a unit cost
public var cost: Int {
return 1
}
}
extension Character: ExpensiveObject {
/// Characters have a unit cost
public var cost: Int {
return 1
}
} | mit |
MA806P/SwiftDemo | SwiftTips/SwiftTips/OCToSwift/main.swift | 1 | 54586 | //
// main.swift
// OCToSwift
//
// Created by MA806P on 2018/12/1.
// Copyright © 2018 myz. All rights reserved.
//
import Foundation
print("Hello, World!")
// -----------------------------
// Toll-Free Bridging 和 Unmanaged
/*
在 Swift 中对于 Core Foundation 在内存管理进行了一系列简化,大大降低了与这些 CF api 打交道的复杂程度。
对于 Cocoa 中 Toll-Free Bridging 的处理。
NS 开头的类其实在 CF 中都有对应的类型存在,NS 只是对 CF 在更高层的一个封装。
如 NSURL 在 CF 中的 CFURLRef 内存结构是同样的,NSString 对应着 CFStringRef
在 OC 中 ARC 负责的只是 NSObject 的自动引用计数,对 CF 无法进行内存管理,在 NS 和 CF 之间进行转换时,
需要向编译器说明是否需要转移内存的管理权。对于不涉及到内存管理的情况,在 OC 中直接在转换时加上 __bridge 来进行说明
表示内存管理权不变。
NSURL *fileURL = [NSURL URLWithString:@"SomeURL"];
SystemSoundID theSoundID;
//OSStatus AudioServicesCreateSystemSoundID(CFURLRef inFileURL,
// SystemSoundID *outSystemSoundID);
OSStatus error = AudioServicesCreateSystemSoundID(
(__bridge CFURLRef)fileURL,
&theSoundID);
而在 Swift 中,这样的转换可以直接省掉了,上面的代码可以写为下面的形式,简单了许多:
import AudioToolbox
let fileURL = NSURL(string: "SomeURL")
var theSoundID: SystemSoundID = 0
//AudioServicesCreateSystemSoundID(inFileURL: CFURL,
// _ outSystemSoundID: UnsafeMutablePointer<SystemSoundID>) -> OSStatus
AudioServicesCreateSystemSoundID(fileURL!, &theSoundID)
CFURLRef 在Swift中是被 typealias 到 CFURL 上的,其他各类 CF 类都进行了类似的处理,主要是为了减少 API 的迷惑。
OC ARC 不能处理的一个问题是 CF 类型的创建和释放:对于 CF 系的 API,如果 API 的名字中含有 Create,Copy 或者 Retain
在使用完成后需要调用 CFRelease 来进行释放。
Swift 中不在需要显示去释放带有这些关键字的内容了。只是在合适的地方加上了像 CF_RETURNS_RETAINED 和 CF_RETURNS_NOT_RETAINED 这样的标注。
对于非系统的 CF API,自己写的或者第三方的,因为没有强制机制要求一定遵照 Cocoa 的命名规范,贸然进行自动内存管理是不可行的
如没有明确使用上面的标注来指明内存管理的方式的话,这些返回 CF 对象的 API 导入 Swift 时,他们得类型会被对应为 “Unmanaged<T>。
这意味着在使用时我们需要手动进行内存管理,一般来说会使用得到的 Unmanaged 对象的 takeUnretainedValue 或者 takeRetainedValue 从中取出需要的 CF 对象,并同时处理引用计数。
takeUnretainedValue 将保持原来的引用计数不变,在你明白你没有义务去释放原来的内存时,应该使用这个方法。
而如果你需要释放得到的 CF 的对象的内存时,应该使用 takeRetainedValue 来让引用计数加一,然后在使用完后对原来的 Unmanaged 进行手动释放。
为了能手动操作 Unmanaged 的引用计数,Unmanaged 中还提供了 retain,release 和 autorelease 供我们使用。
// CFGetSomething() -> Unmanaged<Something>
// CFCreateSomething() -> Unmanaged<Something>
// 两者都没有进行标注,Create 中进行了创建
let unmanaged = CFGetSomething()
let something = unmanaged.takeUnretainedValue()
// something 的类型是 Something,直接使用就可以了
let unmanaged = CFCreateSomething()
let something = unmanaged.takeRetainedValue()
// 使用 something
// 因为在取值时 retain 了,使用完成后进行 release
unmanaged.release()
切记,这些只有在没有标注的极少数情况下才会用到,如果你只是调用系统的 CF API,而不会去写自己的 CF API 的话,是没有必要关心这些的。
*/
// -----------------------------
/*
//Lock
/*
Cocoa 和 OC 中加锁的方式很多,最常用的是 @synchronized
可用来修饰一个变量,并为其自动加上和解除互斥锁
- (void)myMethod:(id)anObj { @synchronized(anObj){ //...} }
加锁解锁都是要消耗一定性能的,不太可能为所有的方法加上锁。
过多的锁不仅没有意义,而且对于多线程编程来说,可能会产生死锁这样的陷阱,难以调试。
Swift 中加锁
*/
func myMethod(anObj: AnyObject!) {
objc_sync_enter(anObj)
//中间持有 anObj 锁
objc_sync_exit(anObj)
}
func synchronized(_ lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
func myMethodLocked(anObj: AnyObject!) {
synchronized(anObj) {
// 在括号内持有 anObj 锁
}
}
//使用例子
class Obj {
var _str = "123"
var str: String {
get {
return _str
}
set {
synchronized(self) {
_str = newValue
}
}
}
}
*/
// -----------------------------
/*
//Associated Object
/*
得益于 OC 的运行时和 Key-Value Coding 的特性,可以在运行时向一个对象添加值存储
而在使用 Category 扩展现有的类的功能的时候,直接添加实例变量是不被允许的,这是一般使用 property 配合 Associated Object
的方式,将一个对象 关联 到已有的扩展对象上
Swift 中这样的方法依旧有效
func objc_getAssociatedObject(object: AnyObject!, key: UnsafePointer<Void> ) -> AnyObject!
func objc_setAssociatedObject(object: AnyObject!, key: UnsafePointer<Void>, value: AnyObject!, policy: objc_AssociationPolicy)
*/
func printTitle(_ input: MyClass) {
if let title = input.title {
print("Title: \(title)")
} else {
print("没有配置")
}
}
let a = MyClass()
printTitle(a) //没有配置
a.title = "swift"
printTitle(a) //Title: swift
*/
// -----------------------------
// delegate
/*
Cocoa 开发,在 ARC 中,对于一般的 delegate,我们会在声明中将其指定为 weak,
在这个 delegate 实际的对象被释放的时候,会被重置回 nil。这可以保证即使 delegate 已经不存在时,
我们也不会由于访问到已被回收的内存而导致崩溃。ARC 的这个特性杜绝了 Cocoa 开发中一种非常常见的崩溃错误
Swift 的 protocol 是可以被除了 class 以外的其他类型遵守的,而对于像 struct 或是 enum 这样的类型,
本身就不通过引用计数来管理内存,所以也不可能用 weak 这样的 ARC 的概念来进行修饰。
想要在 Swift 中使用 weak delegate,我们就需要将 protocol 限制在 class 内。
一种做法是将 protocol 声明为 Objective-C 的,这可以通过在 protocol 前面加上 @objc 关键字来达到,
Objective-C 的 protocol 都只有类能实现,因此使用 weak 来修饰就合理了
@objc protocol MyClassDelegate { func method() }
另一种可能更好的办法是在 protocol 声明的名字后面加上 class,这可以为编译器显式地指明这个 protocol 只能由 class 来实现。
protocol MyClassDelegate: class { func method() }
后一种方法更能表现出问题的实质,同时也避免了过多的不必要的 Objective-C 兼容,可以说是一种更好的解决方式
例子见 SwiftAppTest
*/
// -----------------------------
//C 代码调用 和 @asmname
/*
导入了 import Darwin 我们就可以在 Swift 中无缝使用 Darwin 中定义的 C 函数了,涵盖了绝大多数 C 标准库中的内容
Foundation 框架中包含了 Drawin ,在 app 开发中使用 UIKit 或者 Cocoa 这样的框架,它们又导入了 Foundation
所以平时开发并不需要特别做什么,就可以使用这些标准的 C 函数了。
Swift 在导入时为我们将 Darwin 也进行了类型的自动转换对应,例如函数返回 Swift 类型,而非 C 的类型
func sin(_ x: Double) -> Double
对于第三方的 C 代码,想要调用非标准库的 C 代码的话,将 C代码的头文件在桥接的头文件中进行导入
详情见 target SwiftToOCExample
print(sin(Double.pi/2)) //1.0
*/
// -----------------------------
/*
//类型编码 @encode
/*
OC 中有一些冷僻但是如果知道的话在特定情况下会很有用的关键字,比如 @encode
通过传入一个类型,可获得代表这个类型的编码 C 字符串
char *typeChar1 = @encode(int32_t);
char *typeChar2 = @encode(NSArray);
// typeChar1 = "i", typeChar2 = "{NSArray=#}
常用的地方是在 OC 运行时的消息发送机制中,由于类型信息的缺失,需要类型编码进行辅助保证类型信息也能够被传递。
Swift使用了自己的Metatype来处理类型,并且在运行时保留了这些类型的信息。但是在 Cocoa 中我们还是可以通过
NSValue 的 objcType 属性来获取对应值的类型指针:
class NSValue: NSObject, NSCopying, NSSecureCoding, NSCoding {
var objcType: UnsafePointer<Int8> {get}
}
*/
let int: Int = 0
let float: Float = 0.0
let double: Double = 0.0
let intNumber: NSNumber = int as NSNumber
let floatNumber: NSNumber = float as NSNumber
let doubleNumber: NSNumber = double as NSNumber
print(String(validatingUTF8: intNumber.objCType))
print(String(validatingUTF8: floatNumber.objCType))
print(String(validatingUTF8: doubleNumber.objCType))
//Optional("q")
//Optional("f")
//Optional("d")
// 注意,validatingUTF8 返回的是 `String?`”
/*
对于像其他一些可以转换为 NSValue 的类型,可以用同样方式获取类型编码,这些类型会是某些 struct,
因为 NSValue 设计的初衷就是被作为那些不能直接放入 NSArray 的值的容器来使用的:
let p = NSValue(cgPoint: CGPoint(x: 3, y: 3))
String(validatingUTF8: p.objcType)
// {Some "{CGPoint=dd}"}
let t = NSValue(cgAffineTransform: .identity)
String(validatingUTF8: t.objCType)
// {Some "{CGAffineTransform=dddddd}"}
有了这些信息之后,就能够在这种类型信息可能损失的时候构建准确的类型转换和还原。
*/
*/
// -----------------------------
// 数组 enumerate
/*
使用常见的需求是在枚举数组内元素的同时也想使用对应的下标索引
*/
/*
let arr: NSArray = [1,2,3,4,5]
var result = 0
arr.enumerateObjects({(num, idx, stop) -> Void in
result += num as! Int
if idx == 2 {
stop.pointee = true
}
})
print(result) //6
arr.enumerateObjects { (num, idx, stop) in
result += num as! Int
if idx == 3 {
stop.pointee = true
}
}
print(result) //16
/*
“虽然说使用 enumerateObjectsUsingBlock: 非常方便,但是其实从性能上来说这个方法并不理想
另外这个方法要求作用在 NSArray 上,这显然已经不符合 Swift 的编码方式了。
在 Swift 中,我们在遇到这样的需求的时候,有一个效率,安全性和可读性都很好的替代,
那就是快速枚举某个数组的 EnumerateGenerator,它的元素是同时包含了元素下标索引以及元素本身的多元组:”
*/
var result2 = 0
for (idx, num) in [1,2,3,4,5].enumerated() {
result2 += num
if idx == 2 {
break
}
}
print(result2)//6
*/
// -----------------------------
// Options
/*
在 OC 中,很多需要提供某些选项的 API ,一般用来控制 API 的具体的行为配置等。可以使用 | & 按位逻辑符对这些选项进行操作。
[UIView animateWithDuration:0.3 delay:0.0
options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
animations:^{} completion:nil];
在 Swift 中,对于原来的枚举类型 NS_ENUM 我们有新的 enum 类型来对应。
但是原来的 NS_OPTIONS 在 Swift 里显然没有枚举类型那样重要,并没有直接的原生类型来进行定义。
原来的 Option 值现在被映射为了满足 OptionSetType 协议的 struct 类型,以及一组静态的 get 属性:
public struct UIViewAnimationOptions : OptionSetType {
public init(rawValue: UInt)
static var layoutSubviews: UIViewAnimationOptions { get }
static var allowUserInteraction: UIViewAnimationOptions { get }
//...
static var transitionFlipFromBottom: UIViewAnimationOptions { get }
}
OptionSetType 是实现了 SetAlgebraType 的,因此我们可以对两个集合进行各种集合运算,包括并集、交集
对于不需要选项输入的情况,可直接使用空集合 [] 来表示。
UIView.animate(withDuration: 0.3, delay: 0.0,
options: [.curveEaseIn, .allowUserInteraction],
animations: {},
completion: nil)
要实现一个 Options 的 struct 的话,可以参照已有的写法建立类并实现 OptionSetType。
因为基本上所有的 Options 都是很相似的,所以最好是准备一个 snippet 以快速重用:
struct YourOption: OptionSet {
let rawValue: UInt
static let none = YourOption(rawValue: 0)
static let option1 = YourOption(rawValue: 1)
static let option2 = YourOption(rawValue: 1 << 1)
//...
}
*/
// -----------------------------
//输出格式化
/*
在 Swift 里,我们在输出时一般使用的 print 中是支持字符串插值的,
而字符串插值时将直接使用类型的 Streamable,Printable 或者 DebugPrintable 协议
(按照先后次序,前面的没有实现的话则使用后面的) 中的方法返回的字符串并进行打印。
这样就可以不借助于占位符,也不用再去记忆类型所对应的字符表示,就能很简单地输出各种类型的字符串描述了。
C 的字符串格式化,在需要以一定格式输出的时候,传统的方式就显得很有用。例如打算只输出小数后两位
*/
/*
let a = 3
let b = 1.23456
let c = "abc"
print("int:\(a) double:\(b) string:\(c)")
//int:3 double:1.23456 string:abc
let format = String(format: "%.2lf", b)
print("double:\(format)") //1.23
extension Double {
func format(_ f: String) -> String {
return String(format: "%\(f)f", self)
}
}
let f = ".4"
print("double:\(b.format(f))") //1.2346
*/
// -----------------------------
//调用 C 动态库
/*
OC 是 C 的超级,可以无缝访问 C 的内容,只需要指定依赖并且导入头文件就可以了。
Swift 不能直接使用 C 代码,之前计算某个字符串的 MD5 以前直接使用 CommonCrypto 中的 CC_MD5 就可以了,
但是现在因为我们在 Swift 中无法直接写 #import <CommonCrypto/CommonCrypto.h> 这样的代码,
这些动态库暂时也没有 module 化,因此快捷的方法就只有借助于通过 Objective-C 来进行调用了
暂时建议尽量使用现有的经过时间考验的 C 库,一方面 Swift 还年轻,三方库的引入和依赖机制不很成熟,另外使用动态库至少可以减少APP大小
*/
// -----------------------------
//类族
/*
类族就是使用一个统一的公共类来定制单一的接口,然后在表面之下对应若干个私有类进行实现的方式。
避免公开很多子类造成混乱,典型的例子 NSNumber
类族在 OC 中实现起来也很自然,在所谓的 初始化方法 中将 self 进行替换,根据调用的方式或者输入的类型,返回合适的私有子类对象就可以了。
Swift 中有所不同,Swift 有真正的初始化方法,初始化的时候只能得到当前类的实例,并且要完成所有的配置。
对于公共类,是不可能在初始化方法中返回其子类的信息。Swift中使用工厂方法
*/
/*
class Drinking {
typealias LiquidColor = Int
var color: LiquidColor {
return 0
}
class func drinking (name: String) -> Drinking {
var drinking: Drinking
switch name {
case "Coke":
drinking = Coke()
case "Beer":
drinking = Beer()
default:
drinking = Drinking()
}
return drinking
}
}
class Coke: Drinking {
override var color: LiquidColor {
return 1
}
}
class Beer: Drinking {
override var color: LiquidColor {
return 2
}
}
let coke = Drinking.drinking(name: "Coke")
print(coke.color) //1
let beer = Drinking.drinking(name: "Beer")
print(beer.color) //22
print(NSStringFromClass(type(of: coke))) //OCToSwift.Coke
print(NSStringFromClass(type(of: beer))) //OCToSwift.Beer
*/
// -----------------------------
//哈希
/*
我需要为判等结果为相同的对象提供相同的哈希值,以保证在被用作字典的 key 是的确定性和性能。
Swift 中对 NSObject 子类对象使用 == 时要是该子类没有实现这个操作符重载的话将回滚到 -isEqual: 方法。
对于哈希计算,Swift 也采用了类似的策略,提供了 Hashable 的协议,实现这个协议即可为该类型提供哈希支持:
protocol Hashable: Equatable { var hashValue: Int { get } }
Swift 的原生 Dictionary 中,key 一定是要实现了的 Hashable 协议的类型。
像 Int 或者 String 这些 Swift 基础类型,已经实现了这个协议,因此可以用来作为 key 来使用。比如 Int 的 hashValue 就是它本身:
let num = 19
print(num.hashValue) // 19
OC 中当对 NSObject 的子类 -isEqual 进行重写的时候,一般也需要将 -hash 方法重写,以提供一个判等为真时返回同样的哈希值的方法
“在 Swift 中,NSObject 也默认就实现了 Hashable,而且和判等的时候情况类似,
NSObject 对象的 hashValue 属性的访问将返回其对应的 -hash 的值”
“在 Objective-C 中,对于 NSObject 的子类来说,其实 NSDictionary 的安全性是通过人为来保障的。
对于那些重写了判等但是没有重写对应的哈希方法的子类,编译器并不能给出实质性的帮助。
而在 Swift 中,如果你使用非 NSObject 的类型和原生的 Dictionary,并试图将这个类型作为字典的 key 的话,编译器将直接抛出错误。
从这方面来说,如果我们尽量使用 Swift 的话,安全性将得到大大增加。
关于哈希值,另一个特别需要提出的是,除非我们正在开发一个哈希散列的数据结构,否则我们不应该直接依赖系统所实现的哈希值来做其他操作。
首先哈希的定义是单向的,对于相等的对象或值,我们可以期待它们拥有相同的哈希,但是反过来并不一定成立。
其次,某些对象的哈希值有可能随着系统环境或者时间的变化而改变。
因此你也不应该依赖于哈希值来构建一些需要确定对象唯一性的功能,在绝大部分情况下,你将会得到错误的结果。”
*/
// -----------------------------
/*
//判等
/*
OC 中使用 isEqualToString 进行字符串判等。Swift 使用 ==
OC 中 == 这个符号意思是判断两个对象是否指向同一块内存地址,更关心的是对象的内容相同,OC 中通常对 isEqual 进行重写
否则在调用这个方法时会直接使用 == 进行判断
Swift 里的 == 是一个操作符的声明
protocol Equatable {
func ==(lhs: Self, rhs: Self) -> Bool
}
实现这个协议类型需要定义适合自己类型的 == 操作符,如果认为相等 返回 true
*/
let str1 = "abc"
let str2 = "abc"
let str3 = "def"
print(str1 == str2) // true
print(str2 == str3) // false
class TodoItem {
let uuid: String
var title: String
init(uuid: String, title: String) {
self.uuid = uuid
self.title = title
}
}
extension TodoItem: Equatable {
}
//==的实现没有放在对应的 extension 里,而是放在全局的 scope 中,因为你应该需要在全局范围内都能使用 ==
//事实上 Swift 的操作符都是全局的
func ==(lhs: TodoItem, rhs: TodoItem) -> Bool {
return lhs.uuid == rhs.uuid
}
/*
对于 NSObject 子类的判等你有两种选择,要么重载 ==,要么重写 -isEqual:。
如果你只在 Swift 中使用你的类的话,两种方式是等效的;
但是如果你还需要在 OC 中使用这个类的话,OC 不接受操作符重载,只能使用 -isEqual:,这时你应该考虑使用第二种方式。
对于原来 OC 中使用 == 进行的对象指针的判定,在 Swift 中提供的是另一个操作符 ===。在 Swift 中 === 只有一种重载:
func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool
它用来判断两个 AnyObject 是否是同一个引用。
对于判等,和它紧密相关的一个话题就是哈希。
重载了判等的话,我们还需要提供一个可靠的哈希算法使得判等的对象在字典中作为 key 时不会发生奇怪的事情。
*/
*/
// -----------------------------
// 局部 Scope
/*
C 系语言方法内部可以任意添加成对 {} 来限定代码的作用范围。
超过作用域后里面的临时变量就将失效,可使方法内部的命名更加容易,那些不需要的引用的回收提前进行了
也利于方法的梳理
-(void)loadView {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
{
UILabel *titleLabel = [[UILabel alloc]
initWithFrame:CGRectMake(150, 30, 200, 40)];
titleLabel.textColor = [UIColor redColor];
titleLabel.text = @"Title";
[view addSubview:titleLabel];
}
{
UILabel *textLabel = [[UILabel alloc]
initWithFrame:CGRectMake(150, 80, 200, 40)];
textLabel.textColor = [UIColor redColor];
textLabel.text = @"Text";
[view addSubview:textLabel];
}
self.view = view;
}
“推荐使用局部 scope 将它们分隔开来。比如上面的代码建议加上括号重写为以下形式,
这样至少编译器会提醒我们一些低级错误,我们也可能更专注于每个代码块”
在 Swift 直接使用大括号的写法是不支持的,这和闭包的定义产生了冲突。想类似的使用局部 scope 来分隔代码的话,
定义一个接受 ()->() 作为函数的全局方法,然后执行
func local(_ closure: ()->()) { closure() }
可以利用尾随闭包的特性模拟局部 scope
“override func loadView() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
view.backgroundColor = .white
local {
let titleLabel = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40))
titleLabel.textColor = .red
titleLabel.text = "Title"
view.addSubview(titleLabel)
}
local {
let textLabel = UILabel(frame: CGRect(x: 150, y: 80, width: 200, height: 40))
textLabel.textColor = .red
textLabel.text = "Text"
view.addSubview(textLabel)
}
self.view = view
}
Swift 2.0 中,为了处理异常,Apple 加入了 do 这个关键字来作为捕获异常的作用域。这一功能恰好为我们提供了一个完美的局部作用域
do { let textLabel = ... }
OC 中可使用 GNU 时候C 的声明扩展来限制局部作用域的时候同时进行复制,运用得当的话,可使代码更加紧凑和整洁。
self.titleLabel = ({
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(150, 30, 20, 40)];
label.text = @"Title";
[view addSubview:label];
label;
});
swift 中可使用匿名的闭包,写出类似的代码:
let titleLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40))
label.text = "Title"
return label
}()
*/
// -----------------------------
/*
// KeyPath 和 KVO
/*
“KVO 的目的并不是为当前类的属性提供一个钩子方法,而是为了其他不同实例对当前的某个属性 (严格来说是 keypath)
进行监听时使用的。其他实例可以充当一个订阅者的角色,当被监听的属性发生变化时,订阅者将得到通知。”
“像通过监听 model 的值来自动更新 UI 的绑定这样的工作,基本都是基于 KVO 来完成的。”
“在 Swift 中我们也是可以使用 KVO 的,不过 KVO 仅限于在 NSObject 的子类中,因为 KVO 是基于 KVC (Key-Value Coding)
以及动态派发技术实现的,而这些东西都是 OC 运行时的概念。另外由于 Swift 为了效率,默认禁用了动态派发,
因此想用 Swift 来实现 KVO,我们还需要做额外的工作,那就是将想要观测的对象标记为 dynamic 和 @objc。”
*/
class MyClass: NSObject {
@objc dynamic var date = Date()
}
private var myContext = 0
class AnotherClass: NSObject {
var myObject: MyClass!
var observation: NSKeyValueObservation?
override init() {
super.init()
myObject = MyClass()
print("初始化 AnotherClass,当前日期: \(myObject.date)")
observation = myObject.observe(\MyClass.date, options: [.new]) { (_, change) in
if let newDate = change.newValue {
print("AnotherClass 日期发生变化 \(newDate)")
}
}
delayBling(1) { self.myObject.date = Date() }
}
}
let obj = Class()
//初始化 MyClass,当前日期: 2018-12-29 03:09:13 +0000
//MyClass 日期发生变化 2018-12-29 03:09:17 +0000
*/
// -----------------------------
/*
//自省
/*
向一个对象发出询问以确定是不是属于某个类,这种操作称为自省。
OC 中
[obj1 isKindOfClass:[ClassA class]];
[obj2 isMemberOfClass:[ClassB class]];
isKindOfClass: 判断 obj1 是否是 ClassA 或者其子类的实例对象;
isMemberOfClass: 则对 obj2 做出判断,当且仅当 obj2 的类型为 ClassB 时返回为真。”
这两个是 NSObject 的方法,在 Swift 中如是 NSObject 的子类的话,可直接使用这两个方法
“首先需要明确的一点是,我们为什么需要在运行时去确定类型。因为有泛型支持,Swift 对类型的推断和记录是完备的。
因此在绝大多数情况下,我们使用的 Swift 类型都应该是在编译期间就确定的。
如果在你写的代码中经常需要检查和确定 AnyObject 到底是什么类的话,几乎就意味着你的代码设计出了问题”
*/
class ClassA: NSObject { }
class ClassB: ClassA { }
let obj1: NSObject = ClassB()
let obj2: NSObject = ClassB()
print(obj1.isKind(of: ClassA.self)) // true
print(obj2.isMember(of: ClassA.self)) // false
//对于不是 NSObject 的类,怎么确定其类型
class ClassC: NSObject { }
class ClassD: ClassC { }
let obj3: AnyObject = ClassD()
let obj4: AnyObject = ClassD()
print(obj3.isKind(of: ClassC.self)) // true
print(obj4.isMember(of: ClassC.self)) // false
//Swift 提供了一个简洁的写法,可以使用 is 来判断,is 相当于 isKindOfClass
// is 不仅可用于 class 类型上,也可以对 Swift 的其他 struct enum 类型进行判断
if (obj4 is ClassC) {
print("is ClassC")
}
// 如果编译器能够唯一确定类型,那么 is 的判断就没有必要
//let string = "abc"
//if string is String { print("is string") } // 警告:'is' test is always true
*/
// -----------------------------
/*
//获取对象类型
/*
“如果遵循规则的话,Swift 会是一门相当安全的语言:不会存在类型的疑惑,绝大多数的内容应该能在编译期间就唯一确定。”
object_getClass 是一个定义在 OC 的 runtime 中的方法
*/
let date = NSDate()
let name: AnyClass! = object_getClass(date)
print(name) //some(__NSDate)
let name2 = type(of: date)
print(name2) //__NSDate
let string = "Hello"
let name3 = type(of: string)
print(name3) //String
*/
// -----------------------------
/*
// GCD 和延时调用
/*
Swift 中抛弃了传统的基于 C 的GCD API,采用了更为先进的书写方式。
*/
//创建目标队列
let workingQueue = DispatchQueue(label: "my_queue")
//派发到刚创建的队列中,GCD进行线程调度
workingQueue.async {
//在 workingQueue 中异步进行
print("working")
Thread.sleep(forTimeInterval: 2) //模拟2s执行时间
DispatchQueue.main.async {
//返回主线程更新 UI
print("refresh UI")
}
}
// GCD 延时调用
let time: TimeInterval = 2.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
print("2 秒后输出")
}
//这里直接程序结束了,参考 SwiftAppTest 例子。封装对象,加上可以取消的功能
*/
// -----------------------------
/*
“在 C 中有一类指针,你在头文件中无法找到具体的定义,只能拿到类型的名字,而所有的实现细节都是隐藏的。
这类指针在 C 或 C++ 中被叫做不透明指针 (Opaque Pointer),顾名思义,它的实现和表意对使用者来说是不透明的。”
swift 中对应这类不透明指针的类型是 COpaquePointer 用来表示那些在 Swift 中无法进行类型描述的 C 指针,其他的用
更准确的 UnsafePointer<T> 来存储
“COpaquePointer 在 Swift 中扮演的是指针转换的中间人的角色,我们可以通过这个类型在不同指针类型间进行转换,除非有十足的把握
知道自己在干什么,否则不要这么做。
另外一种重要指针指向函数的指针,
在 C 中的函数
int cFunction(int (callBack)(int x, int y)) { return callBack(1, 2); }
如果想要在 Swift 中使用这个函数
let callback: @convention(c) (Int32, Int32) -> Int32 = {
(x, y) -> Int32 in
return x + y }
let result = cFunction(callback)
print(result) // 3”
let result = cFunction {
(x, y) -> Int32 in return x + y
}
*/
// -----------------------------
/*
//UnsafePointer
/*
Swift 是一门非常安全的语言,所有的引用或者变量的类型都是确定并且正确对应他们得实际类型的,
应当无法进行任意的类型转换,也不能直接通过指针作出一些出格的事。有助于避免不必要的bug,迅速稳定的
找出代码错误。在高安全的同时,也丧失了部分的灵活性。
为了与 C 系帝国进行合作,Swift 定义了一套对 C 语言指针的访问和转换方法 UnsafePointer
“对于使用 C API 时如果遇到接受内存地址作为参数,或者返回是内存地址的情况,在 Swift 里会将它们转为 UnsafePointer<Type> 的类型”
“UnsafePointer,就是 Swift 中专门针对指针的转换。对于其他的 C 中基础类型,在 Swift 中对应的类型都遵循统一的命名规则:
在前面加上一个字母 C 并将原来的第一个字母大写:比如 int,bool 和 char 的对应类型分别是 CInt,CBool 和 CChar。
在下面的 C 方法中,我们接受一个 int 的指针,转换到 Swift 里所对应的就是一个 CInt 的 UnsafePointer 类型。
这里原来的 C API 中已经指明了输入的 num 指针的不可变的 (const),因此在 Swift 中我们与之对应的是 UnsafePointer 这个不可变版本。
如果只是一个普通的可变指针的话,我们可以使用 UnsafeMutablePointer 来对应:
C API Swift API
const Type * UnsafePointer
Type * UnsafeMutablePointer”
如何在指针的内容和实际的值之间进行转换
*/
//C 语言
//void method(const int *num) { printf("%d", *num); }
// int a = 123; method(&a);
//对应的 Swift 方法应该是:
func method(_ num: UnsafePointer<CInt>) {
print(num.pointee)
}
var a: CInt = 123
method(&a) //123
//func CFArrayGetValueAtIndex(theArray: CFArray!, idx: CFIndex) -> UnsafePointer<Any> { }
//“CFArray 中是可以存放任意对象的,所以这里的返回是一个任意对象的指针,相当于 C 中的 void *。
//这显然不是我们想要的东西。Swift 中为我们提供了一个强制转换的方法 unsafeBitCast,
//通过下面的代码,我们可以看到应当如何使用类似这样的 API,将一个指针强制按位转成所需类型的对象:
let arr = NSArray(object: "meow")
let str = unsafeBitCast(CFArrayGetValueAtIndex(arr, 0), to: CFString.self)
// str = "meow”
//“unsafeBitCast 会将第一个参数的内容按照第二个参数的类型进行转换,而不去关心实际是不是可行,
//这也正是 UnsafePointer 的不安全所在,因为我们不必遵守类型转换的检查,而拥有了在指针层面直接操作内存的机会。”
//“Apple 将直接的指针访问冠以 Unsafe 的前缀,就是提醒我们:这些东西不安全,亲们能不用就别用了吧”
//C 指针内存管理
/*
C 指针在 Swift 被冠名 unsafe 的另一个原因是无法对其2进行自动的内存管理,需要手动来申请释放内存
*/
class MyClass {
var a = 1
deinit {
print("deinit")
}
}
var pointer: UnsafeMutablePointer<MyClass>!
pointer = UnsafeMutablePointer<MyClass>.allocate(capacity: 1)
pointer.initialize(to: MyClass())
print(pointer.pointee.a) //1
//pointer = nil //UnsafeMutablePointer 不会自动内存管理,指向的内存没有释放回收,没有调用 deinit
pointer.deinitialize(count: 1)//释放指针指向的内存的对象以及指针自己本身
pointer = nil // deinit
//“手动处理这类指针的内存管理时,我们需要遵循的一个基本原则就是谁创建谁释放。
//deallocate 与 deinitialize 应该要和 allocate 与 initialize 成对出现”
//“如果我们是通过调用了某个方法得到的指针,那么除非文档或者负责这个方法的开发者明确告诉你应该由使用者进行释放,否则都不应该去试图管理它的内存状态:
var x:UnsafeMutablePointer<tm>!
var t = time_t()
time(&t)
x = localtime(&t)
x = nil
//指针的内存申请也可以使用 malloc 或者 calloc 来完成,这种情况下在释放时我们需要对应使用 free 而不是 deallocate。
*/
// -----------------------------
/*
//String 还是 NSString
/*
像 string 这样的 Swift 类型和 Foundation 的对应的类是可以无缝转换的,使用时怎么选择
尽可能的使用原生的 string 类型。
1、虽然有良好的互相转换的特性,但现在 Cocoa所有的API都接受和返回string类型,不必给自己凭空添加麻烦把框架返回的
字符串做一遍转换
2、在Swift中String是struct,相比NSString类来说更切合字符串的”不变“这一特性。配合常量赋值let,
这种不变性在多线程编程就非常重要了。在不触及NSString特有操作和动态特性的时候使用String的方法,在性能上也有所提升。
3、String 实现了 collection 这样的协议,因此有些 Swift 语法只有 String 才能使用
使用 String 唯一一个比较麻烦的地方是 它和 Range 的配合
*/
let levels = "ABCDEF"
for i in levels {
print(i)
}
var a = levels.contains("CD")
print(a)
//报错:Argument type 'NSRange' (aka '_NSRange') does not conform to expected type 'RangeExpression'
//let nsRange = NSMakeRange(1, 4)
//levels.replacingCharacters(in: nsRange, with: "XXXX")
let indexPositionOne = levels.index(levels.startIndex, offsetBy: 1)
let swiftRange = indexPositionOne ..< levels.index(levels.startIndex, offsetBy: 5)
let replaceString = levels.replacingCharacters(in: swiftRange, with: "XXXX")
print(replaceString) //AXXXXF
//可能更愿意和基于 Int 的 Range 一起工作,而不喜欢用麻烦的 Range<String.Index>
let nsRange = NSMakeRange(1, 4)
let nsReplaceString = (levels as NSString).replacingCharacters(in: nsRange, with: "ZZZZ")
print(nsReplaceString) // AZZZZF
*/
// -----------------------------
/*
//值类型和引用类型
/*
Swift 的类型分为值类型和引用类型,值类型在传递和赋值时将进行赋值,引用类型则只会使用引用对象的一个”指向“。
struct enum 定义的类型是值类型,使用 class 定义的为引用类型。
Swift 中所有的内建类型都是值类型,Int String Array Dictionary 都是值类型
值类型的好处,减少了堆上内存分配和回收的次数。值类型的一个特点是在传递和赋值时进行复制,
每次复制肯定会产生额外开销,但是在 Swift 中这个消耗被控制在了最小范围内,
在没有必要复制的时候,值类型的复制都是不会发生的。也就是说,简单的赋值,参数的传递等等普通操作,
虽然我们可能用不同的名字来回设置和传递值类型,但是在内存上它们都是同一块内容。”
将数组字典设计为值类型最大的考虑是为了线程安全,在数目较少时,非常高效
在数目较多时 Swift 内建的值类型的容器类型在每次操作时都需要复制一遍,
即使是存储的都是引用类型,在复制时我们还是需要存储大量的引用
“在需要处理大量数据并且频繁操作 (增减) 其中元素时,选择 NSMutableArray 和 NSMutableDictionary 会更好,
而对于容器内条目小而容器本身数目多的情况,应该使用 Swift 语言内建的 Array 和 Dictionary。”
*/
func test(_ arr:[Int]) {
print(arr)
for i in arr {
print(i)
}
}
var a = [1,2,3]
var b = a
test(a)
//在物理内存上都是用一个东西,而且 a 还只在栈空间上,只是发生了指针移动,完全没有堆内存的分配和释放问题,效率高
//当对值进行改变时,值复制就是必须的了
b.append(4) //b 和 a 内存地址不再相同。将其中的值类型进行复制,对于引用类型的话,只复制一份引用
class MyObject {
var num = 0
}
var myObject = MyObject()
var arr1 = [myObject]
var arr2 = arr1
arr2.append(myObject)
myObject.num = 123
print(arr1[0].num) //123
print(arr2[0].num) //123
*/
// -----------------------------
// @autoreleasepool
/*
swift 在内存管理上使用 ARC 的一套方法,不需要手动的调用 retain, release, autorelease 来管理引用计数
编译器在编译时在合适的地方帮我们加入。
autorelease 会将接收改消息的对象放到 auto release pool 中,当 autoreleasepool 收到 drain 消息时,将这些对象引用计数-1
然后从池子中移除。
“在 app 中,整个主线程其实是跑在一个自动释放池里的,并且在每个主 Runloop 结束时进行 drain 操作”
“因为我们有时候需要确保在方法内部初始化的生成的对象在被返回后别人还能使用,而不是立即被释放掉。”
OC 中使用 @autoreleasepool 就行了,其实 @autoreleasepool 在编译时会被展开为 NSAutoreleasePool 并附带 drain 方法的调用。
Swift 中我们也是能使用 autoreleasepool 的 -- 虽然语法上略有不同。
相比于原来在 Objective-C 中的关键字,现在它变成了一个接受闭包的方法:
func autoreleasepool(code: () -> ())
利用尾随闭包的写法,很容易就能在 Swift 中加入一个类似的自动释放池了:
func loadBigData() {
if let path = NSBundle.mainBundle()
.pathForResource("big", ofType: "jpg") {
for i in 1...10000 {
autoreleasepool {
let data = NSData.dataWithContentsOfFile(
path, options: nil, error: nil)
NSThread.sleepForTimeInterval(0.5)
}
}
}
}
上面的代码是 Swift 1.0 的,NSData.dataWithContentsOfFile 仅供参考
*/
// -----------------------------
/*
//内存管理 weak 和 unowned
//Swift 是自动管理内存的,遵循自动引用计数 ARC
/*
1、循环引用
防止循环引用,不希望互相持有, weak 向编译器说明不希望持有
除了 weak 还有 unowned。类比 OC unowned 更像是 unsafe_unretained
unowned 设置后即使他引用的内容已经被释放了,他仍会保持对被已经释放了的对象的一个无效引用,他不能是 Optional 值
也不会指向 nil,当调用这个引用的方法时,程序崩溃。weak 则友好一点,在引用的内容被释放后,会自动变为nil,因此标记为 weak 的变量
一定需要是 Optional 值。
“Apple 给我们的建议是如果能够确定在访问时不会已被释放的话,尽量使用 unowned,如果存在被释放的可能,那就选择用 weak
“日常工作中一般使用弱引用的最常见的场景有两个:
设置 delegate 时
在 self 属性存储为闭包时,其中拥有对 self 引用时”
闭包和循环引用
“闭包中对任何其他元素的引用都是会被闭包自动持有的。如果我们在闭包中写了 self 这样的东西的话,那我们其实也就在闭包内持有了当前的对象。
如果当前的实例直接或者间接地对这个闭包又有引用的话,就形成了一个 self -> 闭包 -> self 的循环引用”
*/
class A: NSObject {
let b: B
override init() {
b = B()
super.init()
b.a = self
}
deinit {
print("A deinit")
}
}
class B: NSObject {
weak var a: A? = nil
deinit {
print("B deinit")
}
}
var obj: A? = A()
obj = nil //内存没有释放
//闭包
class Person {
let name: String
lazy var printName: ()->() = {
//如可以确定在整个过程中self不会被释放,weak 可以改为 unowned 就不需要 strongSelf 的判断
[weak self] in
if let strongSelf = self {
print("The name is \(strongSelf.name)")
}
//如果需要标注的元素有多个
// { [unowned self, weak someObject] (number: Int) -> Bool in .. return true}
}
init(personName: String) {
name = personName
}
deinit {
print("Person deinit \(self.name)")
}
}
var xiaoMing : Person? = Person(personName: "XiaoMing")
xiaoMing!.printName() //The name is XiaoMing
xiaoMing = nil //Person deinit XiaoMing
*/
// -----------------------------
/*
//可扩展协议和协议扩展
/*
OC 中 protocol @optional 修饰的方法,并非必须要实现
原生的 Swift protocol 里没有可选项,所有定义的方法都是必须实现的,要想实现需要将协议本身可选方法都定义为 OC 的
“使用 @objc 修饰的 protocol 就只能被 class 实现了,
对于 struct 和 enum 类型,我们是无法令它们所实现的协议中含有可选方法或者属性的”
“在 Swift 2.0 中,可使用 protocol extension。
我们可以在声明一个 protocol 之后再用 extension 的方式给出部分方法默认的实现。这样这些方法在实际的类中就是可选实现的了”
*/
@objc protocol OptionalProtocol {
@objc optional func optionalMethod()
func protocolMethod()
@objc optional func anotherOptionalMethod()
}
protocol NormalProtocol {
func optionalNormalProtocolMethod()
func necessaryNormalProtocolMethod()
}
extension NormalProtocol {
func optionalNormalProtocolMethod() {
print("optionalNormalProtocolMethod")
}
}
//报错:Non-class type 'MyStruct' cannot conform to class protocol 'OptionalProtocol'
//struct MyStruct: OptionalProtocol {}
class MyClass: OptionalProtocol, NormalProtocol {
func necessaryNormalProtocolMethod() {
print("MyClass optionalNormalProtocolMethod")
}
func protocolMethod() {
print("MyClass protocolMethod")
}
}
let myClass = MyClass()
myClass.optionalNormalProtocolMethod() //optionalNormalProtocolMethod
*/
// -----------------------------
// @objc 和 dynamic
/*
最初的 Swift 版本中,不得不考虑与 OC 的兼容,允许同一个项目中使用 Swift 和 OC 进行开发
其实文件是处于两个不同世界中,为了能互相联通,需要添加一些桥梁。
“首先通过添加 {product-module-name}-Bridging-Header.h 文件,并在其中填写想要使用的头文件名称,
我们就可以很容易地在 Swift 中使用 Objective-C 代码了”
“如果想要在 Objective-C 中使用 Swift 的类型的时候,事情就复杂一些。如果是来自外部的框架,
那么这个框架与 Objective-C 项目肯定不是处在同一个 target 中的,我们需要对外部的 Swift module 进行导入。
这个其实和使用 Objective-C 的原来的 Framework 是一样的,对于一个项目来说,外界框架是由 Swift 写的还是 Objective-C 写的,
两者并没有太大区别。我们通过使用 2013 年新引入的 @import 来引入 module:
@import MySwiftKit;
之后就可以正常使用这个 Swift 写的框架了。”
“如果想要在 Objective-C 里使用的是同一个项目中的 Swift 的源文件的话,可以直接导入自动生成的头文件
{product-module-name}-Swift.h 来完成。比如项目的 target 叫做 MyApp 的话,我们就需要在 Objective-C 文件中写
#import "MyApp-Swift.h”
“Objective-C 和 Swift 在底层使用的是两套完全不同的机制,Cocoa 中的 Objective-C 对象是基于运行时的,
它从骨子里遵循了 KVC (Key-Value Coding,通过类似字典的方式存储对象信息) 以及动态派发 (Dynamic Dispatch,
在运行调用时再决定实际调用的具体实现)。而 Swift 为了追求性能,如果没有特殊需要的话,
是不会在运行时再来决定这些的。也就是说,Swift 类型的成员或者方法在编译时就已经决定,而运行时便不再需要经过一次查找,而可以直接使用。”
“这带来的问题是如果我们要使用 Objective-C 的代码或者特性来调用纯 Swift 的类型时候,我们会因为找不到所需要的这些运行时信息,而导致失败。
解决起来也很简单,在 Swift 类型文件中,我们可以将需要暴露给 Objective-C 使用的任何地方 (包括类,属性和方法等) 的声明前面加上 @objc 修饰符。
注意这个步骤只需要对那些不是继承自 NSObject 的类型进行,如果你用 Swift 写的 class 是继承自 NSObject 的话,
Swift 会默认自动为所有的非 private 的类和成员加上 @objc。这就是说,对一个 NSObject 的子类,
你只需要导入相应的头文件就可以在 Objective-C 里使用这个类了。”
“@objc 修饰符的另一个作用是为 Objective-C 侧重新声明方法或者变量的名字。虽然绝大部分时候自动转换的方法名已经足够好用
(比如会将 Swift 中类似 init(name: String) 的方法转换成 -initWithName:(NSString *)name 这样)”
*/
// -----------------------------
//UIApplicationMain
//Cocoa开发环境已经在新建一个项目时帮助我们进行很多配置,导致很多人无法说清一个App启动的流程
/*
C系语言中程序的入口都是main函数
int main(int argc, char * argv[]) {
@autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
UIApplicationMain 根据第三个参数初始化一个 UIAppliction 或者其子类对象 传nil就是用默认的UIAppliction,然后开始接收事件
AppDelegate 作为应用委托,用来接收与应用生命周期相关的委托方法。
“虽然这个方法标明为返回一个 int,但是其实它并不会真正返回。它会一直存在于内存中,直到用户或者系统将其强制终止。”
Swift 项目中在默认的 AppDelegate 只有一个 @UIApplicationMain 的标签,这个标签做的事情就是将被标注的类作为委托,
去创建一个 UIApplication 并启动整个程序。在编译的时候,编译器将寻找这个标记的类,并自动插入像 main 函数这样的模板代码。
和 C 系语言的 main.c 或者 main.m 文件一样,Swift 项目也可以有一个名为 main.swift 特殊的文件。
在这个文件中,我们不需要定义作用域,而可以直接书写代码。这个文件中的代码将作为 main 函数来执行。
比如我们在删除 @UIApplicationMain 后,在项目中添加一个 main.swift 文件,然后加上这样的代码:
UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))
现在编译运行,就不会再出现错误了。
我们还可以通过将第三个参数替换成自己的 UIApplication 子类,这样我们就可以轻易地做一些控制整个应用行为的事情了。
比如将 main.swift 的内容换成:
import UIKit
class MyApplication: UIApplication {
override func sendEvent(event: UIEvent!) {
super.sendEvent(event)
print("Event sent: \(event)");
}
}
UIApplicationMain(Process.argc, Process.unsafeArgv, NSStringFromClass(MyApplication), NSStringFromClass(AppDelegate))
这样每次发送事件 (比如点击按钮) 时,我们都可以监听到这个事件了。
*/
// -----------------------------
//编译标记
//在 OC 中在代码中插入 #pragma 来标记代码区间,方便代码定位
//在 Swift 中使用 // MARK:-
// TODO: 123
// FIXME: 455
//上面两个用来提示还未完成的工作或者需要修正的地方。
// MARK: - 123
// -----------------------------
/*
//条件编译
/*
C系语言中,使用 #if #ifdef 编译条件分支来控制哪些代码需要编译。
Swift 中 #if 这套编译标记还是存在的,使用的语法也和原来没有区别
#if <condition>
#elseif <condition>
#else
#endif
condition 并不是任意的,Swift 内建了几种平台和架构的组合,来帮助我们为不同的平台编译不同的代码。
*/
//os(macOS) iOS tvOS watchOS Linux
//arch() arm(32位CPU真机) arm64(64位CPU真机) i386(32为模拟器) x86_64(64位22CPU模拟器)
//swift() >=某个版本
#if os(macOS)
#else
#endif
//另一种方式是对自定义的符号进行条件编译,比如我们需要使用同一个 target 完成同一个 app 的收费版和免费版两个版本,
//并且希望在点击某个按钮时收费版本执行功能,而免费版本弹出提示的话,可以使用类似下面的方法:
@IBAction func someButtonPressed(sender: AnyObject!) {
#if FREE_VERSION
// 弹出购买提示,导航至商店等
#else
// 实际功能
#endif
}
//在这里我们用 FREE_VERSION 这个编译符号来代表免费版本。
//为了使之有效,我们需要在项目的编译选项中进行设置,在项目的 Build Settings 中,
//找到 Swift Compiler - Custom Flags,并在其中的 Other Swift Flags 加上 -D FREE_VERSION 就可以了。”
*/
// -----------------------------
/*
//单例
/*
OC中公认的单列写法
+ (id)sharedManager {
static MyManager * staticInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
staticInstance = [[self alloc] init];
});
return staticInstance;
}
在 Swift 3 中 Apple 移除了 dispatch_once
Swift 中使用 let 简单的方法来保证线程安全
在 Swift 1.2 后,可以使用类变量
*/
class MyManager {
class var shared: MyManager {
struct Static {
static let shareInstance : MyManager = MyManager()
}
return Static.shareInstance
}
}
/*
//由于 Swift 1.2 之前 class 不支持存储式的 property,我们想要使用一个只存在一份的属性时,
//就只能将其定义在全局的 scope 中。值得庆幸的是,在 Swift 中是有访问级别的控制的,
//我们可以在变量定义前面加上 private 关键字,使这个变量只在当前文件中可以被访问。”
private let sharedInstance = MyManager()
class MyManager {
class shared: MyManager {
return sharedInstance
}
}
*/
//在 Swift 1.2 以及之后,如没有特别需求,推荐使用
class MyManager1 {
static let shared = MyManager1()
private init() {
}
}
/*
“这种写法不仅简洁,而且保证了单例的独一无二。在初始化类变量的时候,Apple 将会把这个初始化包装在一次 swift_once_block_invoke 中,
以保证它的唯一性。不仅如此,对于所有的全局变量,Apple 都会在底层使用这个类似 dispatch_once 的方式来确保只以 lazy 的方式初始化一次。”
“我们在这个类型中加入了一个私有的初始化方法,来覆盖默认的公开初始化方法,
这让项目中的其他地方不能够通过 init 来生成自己的 MyManager 实例,也保证了类型单例的唯一性。
如果你需要的是类似 default 的形式的单例 (也就是说这个类的使用者可以创建自己的实例) 的话,可以去掉这个私有的 init 方法。”
*/
*/
// -----------------------------
//实例方法的动态调用
/*
/*
可以让我们不直接使用实例来调用这个实例上的方法,通过类型取出这个类型的实例方法的签名
然后再通过传递实例来拿到实际需要调用的方法。
这种方法只适用于实例方法,对于属性的 getter setter 是不能用类似的写法
*/
class MyClass {
func method(number: Int) -> Int {
return number + 1
}
class func method(number: Int) -> Int {
return number + 1
}
}
let f = MyClass.method //let f: (MyClass) -> (Int) -> Int // let f = { (obj: MyClass) in obj.method}
let object = MyClass()
//let result = f(object)(1)
//如果遇到有类型方法的名字冲突时,如不改动 MyClass.method 将取到的是类型方法
//“如果我们想要取实例方法的话,可以显式地加上类型声明加以区别
let f1 = MyClass.method // class func method 的版本
let f2: (Int) -> Int = MyClass.method // 和 f1 相同
let f3: (MyClass) -> (Int) -> Int = MyClass.method // func method 的柯里化版本”
*/
// -----------------------------
//Selector
/*
@selector 是 OC 时代的一个关键字 可以将一个方法转换并赋值给一个 SEL 类型,类似一个动态的函数指针。
-(void) callMeWithParam:(id)obj { }
SEL anotherMethod = @selector(callMeWithParam:);
// 或者也可以使用 NSSelectorFromString
// SEL anotherMethod = NSSelectorFromString(@"callMeWithParam:");”
在 Swift 中没有 @selector 了,取而代之,从 Swift 2.2 开始我们使用 #selector 来从暴露给 Objective-C 的代码中获取一个 selector。
类似地,在 Swift 里对应原来 SEL 的类型是一个叫做 Selector 的结构体。像上面的两个例子在 Swift 中等效的写法是:
@objc func callMeWithParam(obj: AnyObject!) { }
let anotherMethod = #selector(callMeWithParam(obj:))
“在 Swift 4 中,默认情况下所有的 Swift 方法在 Objective-C 中都是不可见的,
所以你需要在这类方法前面加上 @objc 关键字,将这个方法暴露给 Objective-C,才能进行使用。”
“如果想让整个类型在 Objective-C 可用,可以在类型前添加 @objcMembers。”
*/
| apache-2.0 |
NoryCao/zhuishushenqi | zhuishushenqi/Root/ViewModel/ZSMyViewModel.swift | 1 | 5116 | //
// ZSMyViewModel.swift
// zhuishushenqi
//
// Created by yung on 2018/10/20.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
import AdSupport
import ZSAPI
import RxSwift
class ZSMyViewModel: NSObject, ZSRefreshProtocol {
var refreshStatus: Variable<ZSRefreshStatus> = Variable(.none)
let webService = ZSMyService()
let loginService = ZSLoginService()
var account:ZSAccount?
var coin:ZSCoin?
var detail:ZSUserDetail?
var bind:ZSUserBind?
var useableVoucher:[ZSVoucher] = []
var unuseableVoucher:[ZSVoucher] = []
var expiredVoucher:[ZSVoucher] = []
func fetchAccount(token:String ,completion:@escaping ZSBaseCallback<ZSAccount>) {
webService.fetchAccount(token: token) { [weak self](account) in
guard let sSelf = self else { return }
sSelf.account = account
completion(account)
}
}
func fetchCoin(token:String, completion:@escaping ZSBaseCallback<ZSCoin>) {
webService.fetchCoin(token: token) { [weak self](coin) in
guard let sSelf = self else { return }
sSelf.coin = coin
completion(coin)
}
}
func fetchDetail(token:String, completion:@escaping ZSBaseCallback<ZSUserDetail>) {
webService.fetchDetail(token: token) { [weak self](detail) in
guard let sSelf = self else { return }
sSelf.detail = detail
completion(detail)
}
}
func fetchUserBind (token:String, completion:@escaping ZSBaseCallback<ZSUserBind>) {
webService.fetchUserBind(token: token) { [weak self](bind) in
guard let sSelf = self else { return }
sSelf.bind = bind
completion(bind)
}
}
func fetchLogout(token:String, completion:@escaping ZSBaseCallback<[String:Any]>) {
webService.fetchLogout(token: token) { (json) in
completion(json)
}
}
func fetchSMSCode(param:[String:String]?, completion:@escaping ZSBaseCallback<[String:Any]>) {
let mobile = param?["mobile"] ?? ""
let randstr = param?["Randstr"] ?? ""
let ticket = param?["Ticket"] ?? ""
let captchaType = param?["captchaType"] ?? ""
let type = param?["type"] ?? ""
let api = ZSAPI.SMSCode(mobile: mobile, Randstr: randstr, Ticket: ticket, captchaType: captchaType, type: type)
loginService.fetchSMSCode(url: api.path, parameter: api.parameters) { (json) in
completion(json)
}
}
func mobileLogin(mobile:String, smsCode:String, completion:@escaping ZSBaseCallback<ZSQQLoginResponse>) {
let version = "2"
let platform_code = "mobile"
let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
let api = ZSAPI.mobileLogin(mobile: mobile, idfa: idfa, platform_code: platform_code, smsCode: smsCode, version: version)
loginService.mobileLgin(urlString: api.path, param: api.parameters) { (json) in
completion(json)
}
}
func fetchNicknameChange(nickname:String, token:String, completion:@escaping ZSBaseCallback<[String:Any]>) {
let api = ZSAPI.nicknameChange(nickname: nickname, token: token)
webService.fetchNicknameChange(url: api.path, param: api.parameters) { (json) in
completion(json)
}
}
// https://api.zhuishushenqi.com/voucher?token=xAk9Ac8k3Jj9Faf11q8mBVPQ&type=useable&start=0&limit=20
func fetchVoucher(token:String, type:String, start:Int, limit:Int, completion:@escaping ZSBaseCallback<[ZSVoucher]>) {
let api = QSAPI.voucherList(token: token, type: type, start: start, limit: limit)
webService.fetchVoucherList(url: api.path, param: api.parameters) { [weak self](vouchers) in
guard let sSelf = self else { return }
if type == "useable" {
sSelf.useableVoucher = vouchers ?? []
} else if type == "unuseable" {
sSelf.unuseableVoucher = vouchers ?? []
} else {
sSelf.expiredVoucher = vouchers ?? []
}
sSelf.refreshStatus.value = .headerRefreshEnd
completion(vouchers)
}
}
func fetchMoreVoucher(token:String, type:String, start:Int, limit:Int, completion:@escaping ZSBaseCallback<[ZSVoucher]>) {
let api = QSAPI.voucherList(token: token, type: type, start: start, limit: limit)
webService.fetchVoucherList(url: api.path, param: api.parameters) { [weak self](vouchers) in
guard let sSelf = self else { return }
if type == "useable" {
sSelf.useableVoucher.append(contentsOf: vouchers ?? [])
} else if type == "unuseable" {
sSelf.unuseableVoucher.append(contentsOf: vouchers ?? [])
} else {
sSelf.expiredVoucher.append(contentsOf: vouchers ?? [])
}
sSelf.refreshStatus.value = .footerRefreshEnd
completion(vouchers)
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/18984-getselftypeforcontainer.swift | 11 | 274 | // 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 A {
struct A {
class a {
class A {
typealias f = F
deinit {
protocol B : f.c {
typealias f
func f
| mit |
kiliankoe/catchmybus | catchmybus/NotificationController.swift | 1 | 1724 | //
// NotificationController.swift
// catchmybus
//
// Created by Kilian Költzsch on 11/05/15.
// Copyright (c) 2015 Kilian Koeltzsch. All rights reserved.
//
import Foundation
private let _NotificationControllerSharedInstance = NotificationController()
class NotificationController {
// NotificationController is a singleton, accessible via NotificationController.shared()
static func shared() -> NotificationController {
return _NotificationControllerSharedInstance
}
// MARK: -
var notification: NSUserNotification
var notificationTime: NSDate
var shouldDisplayNotifications: Bool
// MARK: -
init () {
notification = NSUserNotification()
notificationTime = NSDate()
shouldDisplayNotifications = NSUserDefaults.standardUserDefaults().boolForKey(kShouldDisplayNotifications)
// TODO: Check if it might be better to send the bool state as the notification object instead of using it as a note to load from NSUserDefaults
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateShouldDisplayNotification", name: kUpdatedShouldDisplayUserNotificationNotification, object: nil)
}
private func updateShouldDisplayNotification() {
shouldDisplayNotifications = NSUserDefaults.standardUserDefaults().boolForKey(kShouldDisplayNotifications)
}
// MARK: - Handle user notifications
internal func scheduleNotification(notificationDate: NSDate) {
// TODO: Adjust notification date
if shouldDisplayNotifications {
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(notification)
}
}
internal func removeScheduledNotification() {
NSUserNotificationCenter.defaultUserNotificationCenter().removeScheduledNotification(notification)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03537-swift-sourcemanager-getmessage.swift | 11 | 283 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
(([Void{
case c,
([Void{
if true {
func b
{
struct B<j : c,
{
enum B : a<f : e)
{
let t: a {
class
case c,
(_ = [
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/23777-llvm-foldingset-swift-classtype-nodeequals.swift | 10 | 225 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class b{var _=[B}
class B<T where H:a
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/06004-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 291 | // 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 B<T: C {
func f: d where H.e where g: d: String = T]()
class d<h : d where H.e where f: d: d where T>: a {
func a
l
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19878-getselftypeforcontainer.swift | 11 | 233 | // 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 < {
func c<T> (a )
protocol a {
typealias B : B
var a: Any
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03953-swift-sourcemanager-getmessage.swift | 11 | 296 | // 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 d<T {
class c : j { func a
var e: NSObject {
if true {
func a(Any) {
var e(v: A? {
protocol A : S<b: A? {
class
case c,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/12480-no-stacktrace.swift | 11 | 283 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
{
{
{
}
{
}
protocol a {
enum A {
{
}
{
{
}
}
{
}
var b {
{
{
}
{
deinit {
{
}
{
{
{
return m( [ {
class
case ,
| mit |
sebastianvarela/iOS-Swift-Helpers | Helpers/Helpers/OptionalExtensions.swift | 2 | 111 | import Foundation
public extension Optional {
public var isNil: Bool {
return self == nil
}
}
| mit |
clayellis/StringScanner | Sources/StringScanner/CharacterSet.swift | 1 | 2417 | //
// CharactersSet.swift
// StringScanner
//
// Created by Omar Abdelhafith on 26/10/2016.
//
//
/// Range Set
public enum CharactersSet: Containable {
/// All english letters set
case allLetters
/// Small english letters set
case smallLetters
/// Capital english letters set
case capitalLetters
/// Numbers set
case numbers
/// Spaces set
case space
/// Alpha Numeric set
case alphaNumeric
/// Characters in the string
case string(String)
/// Containable Array
case containables([Containable])
/// Range (and closed range)
case range(Containable)
/// Join with another containable
public func join(characterSet: CharactersSet) -> CharactersSet {
let array = [characterSet.containable, self.containable]
return .containables(array)
}
public func contains(character element: Character) -> Bool {
return self.containable.contains(character: element)
}
var containable: Containable {
switch self {
case .smallLetters:
return RangeContainable(ranges: "a"..."z")
case .capitalLetters:
return RangeContainable(ranges: "A"..."Z")
case .allLetters:
return RangeContainable(
ranges: CharactersSet.smallLetters.containable, CharactersSet.capitalLetters.containable)
case .numbers:
return RangeContainable(ranges: "0"..."9")
case .space:
return RangeContainable(ranges: " "..." ")
case .alphaNumeric:
return RangeContainable(ranges:
CharactersSet.allLetters.containable, CharactersSet.numbers.containable)
case .string(let string):
return ContainableString(stringOfCharacters: string)
case .containables(let array):
return RangeContainable(array: array)
case .range(let range):
return RangeContainable(ranges: range)
}
}
}
private struct ContainableString: Containable {
let stringOfCharacters: String
func contains(character element: Character) -> Bool {
return stringOfCharacters.find(string: String(element)) != nil
}
}
private struct RangeContainable: Containable {
let ranges: [Containable]
init(ranges: Containable...) {
self.ranges = ranges
}
init(array: [Containable]) {
self.ranges = array
}
func contains(character element: Character) -> Bool {
let filtered = ranges.filter { $0.contains(character: element) }
return filtered.count > 0
}
}
| mit |
carabina/SwiftStore | Example/SwiftStoreExample/SwiftStoreExample/DB.swift | 2 | 354 | //
// DB.swift
// SwiftStoreExample
//
// Created by Hemanta Sapkota on 12/05/2015.
// Copyright (c) 2015 Hemanta Sapkota. All rights reserved.
//
import Foundation
import SwiftStore
class DB : SwiftStore {
class var store:DB {
struct Singleton {
static let instance = DB(storeName: "db")
}
return Singleton.instance
}
} | mit |
bcattle/AudioLogger-iOS | AudioLogger-iOS/FileListViewController.swift | 1 | 7865 | //
// FileListViewController.swift
// AudioLogger-iOS
//
// Created by Bryan on 1/8/17.
// Copyright © 2017 bcattle. All rights reserved.
//
import UIKit
import AVFoundation
//import EZAudioiOS
class FileListViewController: UIViewController {
@IBOutlet weak var tableView:UITableView!
@IBOutlet weak var deleteButton:UIButton!
@IBOutlet weak var shareButton:UIButton!
@IBOutlet weak var selectButton:UIButton!
var files:[URL]?
var sizes:[UInt64]?
var allSelected = false
var player:AVAudioPlayer?
var playingIndexPath:IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
tableView.setEditing(true, animated: false)
updateFileList()
}
func updateFileList() {
let fs = getFiles()
files = fs.urls
sizes = fs.sizes
tableView.reloadData()
updateButtonVisibility()
}
func getFiles() -> (urls:[URL], sizes:[UInt64]) {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
var sizes = [UInt64]()
for url in directoryContents {
do {
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
sizes.append(attributes[FileAttributeKey.size] as! UInt64)
} catch let error {
print("Error getting file size: \(error)")
sizes.append(0)
}
}
return (urls:directoryContents, sizes:sizes)
} catch let error as NSError {
print(error.localizedDescription)
return ([], [])
}
}
func getSelectedURLs() -> [URL] {
if let selected = tableView.indexPathsForSelectedRows {
return selected.map { files![$0.row] }
} else {
return []
}
}
func deleteFiles(at urls:[URL]) {
for url in urls {
do {
try FileManager.default.removeItem(at: url)
} catch let error {
print("Error deleting <\(url)>: \(error)")
}
}
// Done!
updateFileList()
}
func getHumanReadableByteCount(bytes:UInt64, si:Bool = true) -> String {
let unit:UInt64 = si ? 1000 : 1024;
if bytes < unit { return "\(bytes) B" }
let exp = Int(round(log(Double(bytes)) / log(Double(unit))))
let pre = (si ? "kMGTPE" : "KMGTPE")[exp - 1] + (si ? "" : "i");
let val = Double(bytes) / pow(Double(unit), Double(exp))
return "\(String(format:"%.1f", val)) \(pre)B"
}
@IBAction func backButtonTapped(sender:UIButton) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
@IBAction func shareButtonTapped(sender:UIButton) {
let shareVC = UIActivityViewController(activityItems: getSelectedURLs(), applicationActivities: nil)
present(shareVC, animated: false)
}
@IBAction func deleteButtonTapped(sender:UIButton) {
let selected = getSelectedURLs()
let alert = UIAlertController(title: "Are you sure?", message: "Do you want to delete \(selected.count) files?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (action) in
self.deleteFiles(at: selected)
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { (action) in
}))
present(alert, animated: true)
}
@IBAction func selectButtonTapped(sender:UIButton) {
let totalRows = tableView.numberOfRows(inSection: 0)
for row in 0..<totalRows {
if allSelected {
tableView.deselectRow(at:IndexPath(row: row, section: 0), animated: false)
UIView.performWithoutAnimation {
selectButton.setTitle("Select All", for: .normal)
selectButton.layoutIfNeeded()
}
} else {
tableView.selectRow(at: IndexPath(row: row, section: 0), animated: false, scrollPosition: .none)
UIView.performWithoutAnimation {
selectButton.setTitle("Select None", for: .normal)
selectButton.layoutIfNeeded()
}
}
}
allSelected = !allSelected
updateButtonVisibility()
}
}
extension FileListViewController:UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let files = files {
return files.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell", for: indexPath) as! FileCell
cell.backgroundColor = UIColor.clear
cell.label.text = files![indexPath.row].lastPathComponent
cell.sizeLabel.text = getHumanReadableByteCount(bytes: sizes![indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
updateButtonVisibility()
updatePlaybackForIndexPath(indexPath: indexPath)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
updateButtonVisibility()
updatePlaybackForIndexPath(indexPath: indexPath)
}
func updateButtonVisibility() {
if let selectedRows = tableView.indexPathsForSelectedRows {
UIView.performWithoutAnimation {
deleteButton.setTitle("Delete (\(selectedRows.count))", for: .normal)
shareButton.setTitle("Share (\(selectedRows.count))", for: .normal)
deleteButton.layoutIfNeeded()
shareButton.layoutIfNeeded()
}
UIView.animate(withDuration: 0.3, animations: {
self.deleteButton.alpha = 1
self.shareButton.alpha = 1
})
} else {
UIView.animate(withDuration: 0.3, animations: {
self.deleteButton.alpha = 0
self.shareButton.alpha = 0
})
}
}
func updatePlaybackForIndexPath(indexPath:IndexPath) {
player?.pause()
if indexPath != playingIndexPath {
// player?.pause()
// } else {
if let files = files {
do {
try player = AVAudioPlayer(contentsOf: files[indexPath.row])
player!.play()
} catch let error {
print("Error trying to play: \(error)")
}
// player.
// let file = EZAudioFile(url: files[indexPath.row])
// player?.playAudioFile(file)
// playingIndexPath = indexPath
}
}
}
// func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// return []
// }
}
extension String {
subscript (i: Int) -> Character {
return self[index(self.startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
// subscript (r: Range<Int>) -> String {
// let start = startIndex.advancedBy(r.startIndex)
// let end = start.advancedBy(r.endIndex - r.startIndex)
// return self[Range(start ..< end)]
// }
}
| mit |
paulz/PerspectiveTransform | Example/PerspectiveTransform/AppDelegate.swift | 1 | 275 | //
// AppDelegate.swift
// PerspectiveTransform
//
// Created by Paul Zabelin on 02/18/2016.
// Copyright (c) 2016 Paul Zabelin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| mit |
rsmoz/swift-corelibs-foundation | TestFoundation/TestNSBundle.swift | 1 | 5495 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSBundle : XCTestCase {
var allTests : [(String, () throws -> Void)] {
return [
("test_paths", test_paths),
("test_resources", test_resources),
("test_infoPlist", test_infoPlist),
("test_localizations", test_localizations),
("test_URLsForResourcesWithExtension", test_URLsForResourcesWithExtension),
]
}
func test_paths() {
let bundle = NSBundle.mainBundle()
// bundlePath
XCTAssert(!bundle.bundlePath.isEmpty)
XCTAssertEqual(bundle.bundleURL.path, bundle.bundlePath)
let path = bundle.bundlePath
// etc
#if os(OSX)
XCTAssertEqual("\(path)/Contents/Resources", bundle.resourcePath)
XCTAssertEqual("\(path)/Contents/MacOS/TestFoundation", bundle.executablePath)
XCTAssertEqual("\(path)/Contents/Frameworks", bundle.privateFrameworksPath)
XCTAssertEqual("\(path)/Contents/SharedFrameworks", bundle.sharedFrameworksPath)
XCTAssertEqual("\(path)/Contents/SharedSupport", bundle.sharedSupportPath)
#endif
XCTAssertNil(bundle.pathForAuxiliaryExecutable("no_such_file"))
XCTAssertNil(bundle.appStoreReceiptURL)
}
func test_resources() {
let bundle = NSBundle.mainBundle()
// bad resources
XCTAssertNil(bundle.URLForResource(nil, withExtension: nil, subdirectory: nil))
XCTAssertNil(bundle.URLForResource("", withExtension: "", subdirectory: nil))
XCTAssertNil(bundle.URLForResource("no_such_file", withExtension: nil, subdirectory: nil))
// test file
let testPlist = bundle.URLForResource("Test", withExtension: "plist")
XCTAssertNotNil(testPlist)
XCTAssertEqual("Test.plist", testPlist!.lastPathComponent)
XCTAssert(NSFileManager.defaultManager().fileExistsAtPath(testPlist!.path!))
// aliases, paths
XCTAssertEqual(testPlist!.path, bundle.URLForResource("Test", withExtension: "plist", subdirectory: nil)!.path)
XCTAssertEqual(testPlist!.path, bundle.pathForResource("Test", ofType: "plist"))
XCTAssertEqual(testPlist!.path, bundle.pathForResource("Test", ofType: "plist", inDirectory: nil))
}
func test_infoPlist() {
let bundle = NSBundle.mainBundle()
// bundleIdentifier
XCTAssertEqual("org.swift.TestFoundation", bundle.bundleIdentifier)
// infoDictionary
let info = bundle.infoDictionary
XCTAssertNotNil(info)
XCTAssert("org.swift.TestFoundation" == info!["CFBundleIdentifier"] as! String)
XCTAssert("TestFoundation" == info!["CFBundleName"] as! String)
// localizedInfoDictionary
XCTAssertNil(bundle.localizedInfoDictionary) // FIXME: Add a localized Info.plist for testing
}
func test_localizations() {
let bundle = NSBundle.mainBundle()
XCTAssertEqual(["en"], bundle.localizations)
XCTAssertEqual(["en"], bundle.preferredLocalizations)
XCTAssertEqual(["en"], NSBundle.preferredLocalizationsFromArray(["en", "pl", "es"]))
}
private let _bundleName = "MyBundle.bundle"
private let _bundleResourceNames = ["hello.world", "goodbye.world", "swift.org"]
private func _setupPlayground() -> String? {
// Make sure the directory is uniquely named
let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().UUIDString + "/"
do {
try NSFileManager.defaultManager().createDirectoryAtPath(tempDir, withIntermediateDirectories: false, attributes: nil)
// Make a flat bundle in the playground
let bundlePath = tempDir + _bundleName
try NSFileManager.defaultManager().createDirectoryAtPath(bundlePath, withIntermediateDirectories: false, attributes: nil)
// Put some resources in the bundle
for n in _bundleResourceNames {
NSFileManager.defaultManager().createFileAtPath(bundlePath + "/" + n, contents: nil, attributes: nil)
}
} catch _ {
return nil
}
return tempDir
}
private func _cleanupPlayground(location: String) {
do {
try NSFileManager.defaultManager().removeItemAtPath(location)
} catch _ {
// Oh well
}
}
func test_URLsForResourcesWithExtension() {
guard let playground = _setupPlayground() else { XCTFail("Unable to create playground"); return }
let bundle = NSBundle(path: playground + _bundleName)
XCTAssertNotNil(bundle)
let worldResources = bundle?.URLsForResourcesWithExtension("world", subdirectory: nil)
XCTAssertNotNil(worldResources)
XCTAssertEqual(worldResources?.count, 2)
_cleanupPlayground(playground)
}
}
| apache-2.0 |
modnovolyk/MAVLinkSwift | Sources/MAVDataStreamCommonEnum.swift | 1 | 2483 | //
// MAVDataStreamCommonEnum.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
/// THIS INTERFACE IS DEPRECATED AS OF JULY 2015. Please use MESSAGE_INTERVAL instead. A data stream is not a fixed set of messages, but rather a recommendation to the autopilot software. Individual autopilots may or may not obey the recommended messages.
public enum MAVDataStream: Int {
/// Enable all data streams
case all = 0
/// Enable IMU_RAW, GPS_RAW, GPS_STATUS packets.
case rawSensors = 1
/// Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS
case extendedStatus = 2
/// Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW
case rcChannels = 3
/// Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT.
case rawController = 4
/// Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages.
case position = 6
/// Dependent on the autopilot
case extra1 = 10
/// Dependent on the autopilot
case extra2 = 11
/// Dependent on the autopilot
case extra3 = 12
}
extension MAVDataStream: Enumeration {
public static var typeName = "MAV_DATA_STREAM"
public static var typeDescription = "THIS INTERFACE IS DEPRECATED AS OF JULY 2015. Please use MESSAGE_INTERVAL instead. A data stream is not a fixed set of messages, but rather a recommendation to the autopilot software. Individual autopilots may or may not obey the recommended messages."
public static var allMembers = [all, rawSensors, extendedStatus, rcChannels, rawController, position, extra1, extra2, extra3]
public static var membersDescriptions = [("MAV_DATA_STREAM_ALL", "Enable all data streams"), ("MAV_DATA_STREAM_RAW_SENSORS", "Enable IMU_RAW, GPS_RAW, GPS_STATUS packets."), ("MAV_DATA_STREAM_EXTENDED_STATUS", "Enable GPS_STATUS, CONTROL_STATUS, AUX_STATUS"), ("MAV_DATA_STREAM_RC_CHANNELS", "Enable RC_CHANNELS_SCALED, RC_CHANNELS_RAW, SERVO_OUTPUT_RAW"), ("MAV_DATA_STREAM_RAW_CONTROLLER", "Enable ATTITUDE_CONTROLLER_OUTPUT, POSITION_CONTROLLER_OUTPUT, NAV_CONTROLLER_OUTPUT."), ("MAV_DATA_STREAM_POSITION", "Enable LOCAL_POSITION, GLOBAL_POSITION/GLOBAL_POSITION_INT messages."), ("MAV_DATA_STREAM_EXTRA1", "Dependent on the autopilot"), ("MAV_DATA_STREAM_EXTRA2", "Dependent on the autopilot"), ("MAV_DATA_STREAM_EXTRA3", "Dependent on the autopilot")]
public static var enumEnd = UInt(13)
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/25803-swift-constructordecl-setbodyparams.swift | 1 | 458 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See 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
func a{class a<c{class a{class A:a{class a{struct B{let g:b
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/27073-swift-constraints-constraint-create.swift | 1 | 439 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See 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 t{
enum b{case
enum b{struct B<T:T.c
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/15901-swift-typechecker-checksubstitutions.swift | 11 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
class A : a
protocol a {
struct S<b: S<Int>
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/04006-swift-sourcemanager-getmessage.swift | 11 | 232 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum A {
protocol A {
deinit {
typealias e : A {
class
case c,
| mit |
githubxiangdong/DouYuZB | DouYuZB/DouYuZB/Classes/Home/View/AdsCollectionViewCell.swift | 1 | 786 | //
// AdsCollectionViewCell.swift
// DouYuZB
//
// Created by new on 2017/5/8.
// Copyright © 2017年 9-kylins. All rights reserved.
//
import UIKit
class AdsCollectionViewCell: UICollectionViewCell {
//MARK:- 控件属性
@IBOutlet var iconImageView: UIImageView!
@IBOutlet var titleLabel: UILabel!
//MARK:- 定义模型属性
var model : AdsModel? {
didSet {
// 0, 校验模型是否有值
guard let model = model else { return }
// 1, 显示文字
titleLabel.text = model.title
// 2,显示图片
let iconUrl = URL(string: model.pic_url)
iconImageView.kf.setImage(with: iconUrl, placeholder: UIImage(named: "Img_default"))
}
}
}
| mit |
googlearchive/cannonball-ios | Cannonball/ThemeCell.swift | 1 | 1659 | //
// Copyright (C) 2018 Google, Inc. and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class ThemeCell: UITableViewCell {
// MARK: Properties
@IBOutlet fileprivate weak var nameLabel: UILabel!
@IBOutlet fileprivate weak var pictureImageView: UIImageView!
fileprivate var gradient: CAGradientLayer!
override func awakeFromNib() {
// Add the gradient to the picture image view.
gradient = CAGradientLayer()
let colors: [AnyObject] = [UIColor.clear.cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
gradient.colors = colors
gradient.startPoint = CGPoint(x: 0.0, y: 0.4)
gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
pictureImageView.layer.addSublayer(gradient)
}
override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = bounds
}
func configureWithTheme(_ theme: Theme) {
// Add category name.
nameLabel.text = "#\(theme.name)"
// Add background picture.
pictureImageView.image = UIImage(named: theme.getRandomPicture()!)
}
}
| apache-2.0 |
glock45/swifter | Sources/Swifter/App.swift | 1 | 1555 | //
// App.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public class App {
private let server = HttpServer()
public init() { }
@available(OSX 10.10, *)
public func run(_ port: in_port_t = 9080, _ databasePath: String) throws -> Void {
// Open database connection.
DatabaseReflection.sharedDatabase = try SQLite.open(databasePath)
defer {
DatabaseReflection.sharedDatabase?.close()
}
// Watch process signals.
Process.watchSignals { switch $0 {
case SIGTERM, SIGINT:
self.server.stop()
DatabaseReflection.sharedDatabase?.close()
exit(EXIT_SUCCESS)
case SIGHUP:
print("//TODO - Reload config.")
default:
print("Unknown signal received: \(signal).")
}
}
// Add simple logging.
self.server.middleware.append({ r in
print("\(r.method) - \(r.path)")
return nil
})
// Boot the server.
print("Starting Swifter (\(HttpServer.VERSION)) at port \(try server.port()) with PID \(Process.tid)...")
try self.server.start(port)
print("Server started. Waiting for requests....")
#if os(Linux)
while true { }
#else
RunLoop.current.run()
#endif
}
}
| bsd-3-clause |
poolmyride/DataStoreKit | Pod/Classes/FileDeserializer.swift | 1 | 1708 | //
// FileDeserializer.swift
//
//
// Created by Rohit Talwar on 11/06/15.
// Copyright (c) 2015 Rajat Talwar. All rights reserved.
//
import Foundation
open class FileDeserializer<T> where T:AnyObject,T:ObjectCoder {
fileprivate func isPList(_ fileName:String) -> Bool{
return fileName.hasSuffix("plist")
}
fileprivate func getJsonArray(_ fileName:String) -> NSArray? {
let url = Bundle.main.url(forResource: fileName, withExtension: "");
var jsonarray:NSArray? = nil
do {
try jsonarray = JSONSerialization.jsonObject(with: Data(contentsOf: url!), options: []) as? NSArray
} catch _ as NSError {
}
return jsonarray
}
fileprivate func getPlistArray(_ fileName:String) -> NSArray? {
let url = Bundle.main.url(forResource: fileName, withExtension: "");
let array:NSArray? = (url != nil) ? NSArray(contentsOf: url!) : nil
return array
}
open func getObjectArrayFrom(fielName fileName:String,callback: @escaping (NSError?,NSArray?)->Void) {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.high).async(execute: { () -> Void in
let array = (self.isPList(fileName) ? self.getPlistArray(fileName) : self.getJsonArray(fileName)) ?? []
let objectDeserializer = ObjectDeserializer<T>();
let results:NSArray = objectDeserializer.deSerializeArray(array)
DispatchQueue.main.async(execute: { () -> Void in
callback(nil,results)
});
});
}
}
| mit |
mansoor92/MaksabComponents | Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Helper/MaksabTheme.swift | 1 | 923 | //
// MaksabTheme.swift
// ActionCableClient
//
// Created by Mansoor Ali on 30/03/2018.
//
import UIKit
public enum MaksabThemeType{
case lightContent
case darkContent
}
public struct MaksabTheme {
static public func set(navigationBar: UINavigationBar, theme: MaksabThemeType){
switch theme {
case .lightContent:
setStatusBar(style: .lightContent)
setNavBar(navigationBar: navigationBar, tintColor: UIColor.appColor(color: .Light))
case .darkContent:
setStatusBar(style: .default)
setNavBar(navigationBar: navigationBar, tintColor: UIColor.appColor(color: .Dark))
}
}
private static func setNavBar(navigationBar: UINavigationBar, tintColor: UIColor){
navigationBar.tintColor = tintColor
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: tintColor]
}
private static func setStatusBar(style: UIStatusBarStyle){
UIApplication.shared.statusBarStyle = style
}
}
| mit |
wibosco/CoalescingOperations-Example | CoalescingOperations-Example/Coalescing/CoalescingExampleManager.swift | 1 | 1605 | //
// CoalescingExampleManager.swift
// CoalescingOperations-Example
//
// Created by Boles on 28/02/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
/**
An example manager that handles queuing operations.
It exists as we don't really want our VCs to know anything about coalescing or the queue.
*/
class CoalescingExampleManager: NSObject {
// MARK: - Add
class func addExampleCoalescingOperation(queueManager: QueueManager = QueueManager.sharedInstance, completion: (QueueManager.CompletionClosure)?) {
let coalescingOperationExampleIdentifier = "coalescingOperationExampleIdentifier"
if let completion = completion {
queueManager.addNewCompletionClosure(completion, identifier: coalescingOperationExampleIdentifier)
}
if !queueManager.operationIdentifierExistsOnQueue(coalescingOperationExampleIdentifier) {
let operation = CoalescingExampleOperation()
operation.identifier = coalescingOperationExampleIdentifier
operation.completion = {(successful) in
let closures = queueManager.completionClosures(coalescingOperationExampleIdentifier)
if let closures = closures {
for closure in closures {
closure(successful: successful)
}
queueManager.clearClosures(coalescingOperationExampleIdentifier)
}
}
queueManager.enqueue(operation)
}
}
}
| mit |
damonthecricket/my-json | MYJSON/JSON+Extensions.swift | 1 | 3976 | //
// ModelTypes.swift
// InstaCollage
//
// Created by Optimus Prime on 11.02.17.
// Copyright © 2017 Tren Lab. All rights reserved.
//
import Foundation
// MARK: - JSON Extensions
public extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
// MARK: - Is
/**
Returns `true` if instance has сorresponding `JSON` value for key.
Otherwise, returns empty `false`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func isJSON(forKey key: Key) -> Bool {
return isValue(forKey: key) && self[key] is MYJSON
}
/**
Returns `true` if instance has сorresponding `dictionary array` value for key.
Otherwise, returns empty `false`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func isJSONArray(forKey key: Key) -> Bool {
return isValue(forKey: key) && self[key] is [MYJSON]
}
/**
Returns `true` if instance has a `value` for сorresponding key.
Otherwise, returns empty `false`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func isValue(forKey key: Key) -> Bool {
return self[key] != nil
}
// MARK: - JSON
/**
Returns `JSON` for key if instance has сorresponding `JSON` value for key.
Otherwise, returns empty `dictionary`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func json(forKey key: Key) -> MYJSONType {
guard isJSON(forKey: key) else {
return [:]
}
return self[key] as! MYJSONType
}
/**
Returns JSON `array` if instance has сorresponding JSON `array` value for key.
Otherwise, returns empty `array`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func jsonArray(forKey key: Key) -> MYJSONArrayType {
guard isJSONArray(forKey: key) else {
return []
}
return self[key] as! MYJSONArrayType
}
// MARK: - Number
/**
Returns `number` if instance has сorresponding `number` value for key.
Otherwise, returns empty `number`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func number(forKey key: Key) -> NSNumber {
guard isValue(forKey: key) else {
return NSNumber()
}
guard let number = self[key] as? NSNumber else {
return NSNumber()
}
return number
}
// MARK: - String
/**
Returns `string` if instance has сorresponding `string` value for key.
Otherwise, returns empty `string`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func string(forKey key: Key) -> String {
guard isValue(forKey: key), let str = self[key] as? String else {
return ""
}
return str
}
// MARK: - Array
/**
Returns `array` if instance has сorresponding `array` value for key.
Otherwise, returns empty `array`.
- Parameters:
- key: A key to find in the dictionary.
*/
public func array<T>(forKey key: Key) -> [T] {
guard isValue(forKey: key), let array = self[key] as? [T] else {
return []
}
return array
}
}
// MARK: - JSON Equality
/**
Returns `true` if lhs and rhs are equal.
Otherwise, returns `false`.
- Parameters:
- lhs: Left operand.
- rhs: Right operand.
*/
public func == (lhs: MYJSONType, rhs: MYJSONType) -> Bool {
return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
/**
Returns `true` if lhs and rhs are equal.
Otherwise, returns `false`.
- Parameters:
- lhs: Left operand.
- rhs: Right operand.
*/
public func == (lhs: MYJSONArrayType, rhs: MYJSONArrayType) -> Bool {
return NSArray(array: lhs).isEqual(to: rhs)
}
| mit |
kzaher/RxSwift | RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift | 1 | 25518 | //
// SharedSequence+Operators.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
// MARK: map
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence into a new form.
- parameter selector: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ selector: @escaping (Element) -> Result) -> SharedSequence<SharingStrategy, Result> {
let source = self
.asObservable()
.map(selector)
return SharedSequence<SharingStrategy, Result>(source)
}
}
// MARK: compactMap
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence into an optional form and filters all optional results.
- parameter transform: A transform function to apply to each source element and which returns an element or nil.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ selector: @escaping (Element) -> Result?) -> SharedSequence<SharingStrategy, Result> {
let source = self
.asObservable()
.compactMap(selector)
return SharedSequence<SharingStrategy, Result>(source)
}
}
// MARK: filter
extension SharedSequenceConvertibleType {
/**
Filters the elements of an observable sequence based on a predicate.
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (Element) -> Bool) -> SharedSequence<SharingStrategy, Element> {
let source = self
.asObservable()
.filter(predicate)
return SharedSequence(source)
}
}
// MARK: switchLatest
extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType {
/**
Transforms an observable sequence of observable sequences into an observable sequence
producing values only from the most recent observable sequence.
Each time a new inner observable sequence is received, unsubscribe from the
previous inner observable sequence.
- returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func switchLatest() -> SharedSequence<Element.SharingStrategy, Element.Element> {
let source: Observable<Element.Element> = self
.asObservable()
.map { $0.asSharedSequence() }
.switchLatest()
return SharedSequence<Element.SharingStrategy, Element.Element>(source)
}
}
// MARK: flatMapLatest
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence into a new sequence of observable sequences and then
transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
It is a combination of `map` + `switchLatest` operator
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an
Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func flatMapLatest<Sharing, Result>(_ selector: @escaping (Element) -> SharedSequence<Sharing, Result>)
-> SharedSequence<Sharing, Result> {
let source: Observable<Result> = self
.asObservable()
.flatMapLatest(selector)
return SharedSequence<Sharing, Result>(source)
}
}
// MARK: flatMapFirst
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
public func flatMapFirst<Sharing, Result>(_ selector: @escaping (Element) -> SharedSequence<Sharing, Result>)
-> SharedSequence<Sharing, Result> {
let source: Observable<Result> = self
.asObservable()
.flatMapFirst(selector)
return SharedSequence<Sharing, Result>(source)
}
}
// MARK: do
extension SharedSequenceConvertibleType {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter afterCompleted: Action to invoke after graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((Element) -> Void)? = nil, afterNext: ((Element) -> Void)? = nil, onCompleted: (() -> Void)? = nil, afterCompleted: (() -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil)
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose)
return SharedSequence(source)
}
}
// MARK: debug
extension SharedSequenceConvertibleType {
/**
Prints received events for all observers on standard output.
- parameter identifier: Identifier that is printed together with event description to standard output.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) -> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function)
return SharedSequence(source)
}
}
// MARK: distinctUntilChanged
extension SharedSequenceConvertibleType where Element: Equatable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinctUntilChanged()
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) })
return SharedSequence(source)
}
}
extension SharedSequenceConvertibleType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) -> Key) -> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.distinctUntilChanged(keySelector, comparer: { $0 == $1 })
return SharedSequence(source)
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
public func distinctUntilChanged(_ comparer: @escaping (Element, Element) -> Bool) -> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.distinctUntilChanged({ $0 }, comparer: comparer)
return SharedSequence<SharingStrategy, Element>(source)
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) -> K, comparer: @escaping (K, K) -> Bool) -> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.distinctUntilChanged(keySelector, comparer: comparer)
return SharedSequence<SharingStrategy, Element>(source)
}
}
// MARK: flatMap
extension SharedSequenceConvertibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Sharing, Result>(_ selector: @escaping (Element) -> SharedSequence<Sharing, Result>) -> SharedSequence<Sharing, Result> {
let source = self.asObservable()
.flatMap(selector)
return SharedSequence(source)
}
}
// MARK: merge
extension SharedSequenceConvertibleType {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> SharedSequence<SharingStrategy, Element>
where Collection.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.merge(sources.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
/**
Merges elements from all observable sequences from array into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: [SharedSequence<SharingStrategy, Element>]) -> SharedSequence<SharingStrategy, Element> {
let source = Observable.merge(sources.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
/**
Merges elements from all observable sequences into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: SharedSequence<SharingStrategy, Element>...) -> SharedSequence<SharingStrategy, Element> {
let source = Observable.merge(sources.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
}
// MARK: merge
extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType {
/**
Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public func merge() -> SharedSequence<Element.SharingStrategy, Element.Element> {
let source = self.asObservable()
.map { $0.asSharedSequence() }
.merge()
return SharedSequence<Element.SharingStrategy, Element.Element>(source)
}
/**
Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences.
- parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently.
- returns: The observable sequence that merges the elements of the inner sequences.
*/
public func merge(maxConcurrent: Int)
-> SharedSequence<Element.SharingStrategy, Element.Element> {
let source = self.asObservable()
.map { $0.asSharedSequence() }
.merge(maxConcurrent: maxConcurrent)
return SharedSequence<Element.SharingStrategy, Element.Element>(source)
}
}
// MARK: throttle
extension SharedSequenceConvertibleType {
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- returns: The throttled sequence.
*/
public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true)
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.throttle(dueTime, latest: latest, scheduler: SharingStrategy.scheduler)
return SharedSequence(source)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- parameter dueTime: Throttling duration for each element.
- returns: The throttled sequence.
*/
public func debounce(_ dueTime: RxTimeInterval)
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.debounce(dueTime, scheduler: SharingStrategy.scheduler)
return SharedSequence(source)
}
}
// MARK: scan
extension SharedSequenceConvertibleType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<A>(_ seed: A, accumulator: @escaping (A, Element) -> A)
-> SharedSequence<SharingStrategy, A> {
let source = self.asObservable()
.scan(seed, accumulator: accumulator)
return SharedSequence<SharingStrategy, A>(source)
}
}
// MARK: concat
extension SharedSequence {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> SharedSequence<SharingStrategy, Element>
where Sequence.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.concat(sequence.lazy.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> SharedSequence<SharingStrategy, Element>
where Collection.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.concat(collection.map { $0.asObservable() })
return SharedSequence<SharingStrategy, Element>(source)
}
}
// MARK: zip
extension SharedSequence {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<Collection: Swift.Collection, Result>(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence<SharingStrategy, Result>
where Collection.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }, resultSelector: resultSelector)
return SharedSequence<SharingStrategy, Result>(source)
}
/**
Merges the specified observable sequences into one observable sequence all of the observable sequences have produced an element at a corresponding index.
- returns: An observable sequence containing the result of combining elements of the sources.
*/
public static func zip<Collection: Swift.Collection>(_ collection: Collection) -> SharedSequence<SharingStrategy, [Element]>
where Collection.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() })
return SharedSequence<SharingStrategy, [Element]>(source)
}
}
// MARK: combineLatest
extension SharedSequence {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func combineLatest<Collection: Swift.Collection, Result>(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence<SharingStrategy, Result>
where Collection.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.combineLatest(collection.map { $0.asObservable() }, resultSelector: resultSelector)
return SharedSequence<SharingStrategy, Result>(source)
}
/**
Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element.
- returns: An observable sequence containing the result of combining elements of the sources.
*/
public static func combineLatest<Collection: Swift.Collection>(_ collection: Collection) -> SharedSequence<SharingStrategy, [Element]>
where Collection.Element == SharedSequence<SharingStrategy, Element> {
let source = Observable.combineLatest(collection.map { $0.asObservable() })
return SharedSequence<SharingStrategy, [Element]>(source)
}
}
// MARK: withLatestFrom
extension SharedSequenceConvertibleType {
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: SharedSequenceConvertibleType, ResultType>(_ second: SecondO, resultSelector: @escaping (Element, SecondO.Element) -> ResultType) -> SharedSequence<SharingStrategy, ResultType> where SecondO.SharingStrategy == SharingStrategy {
let source = self.asObservable()
.withLatestFrom(second.asSharedSequence(), resultSelector: resultSelector)
return SharedSequence<SharingStrategy, ResultType>(source)
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element.
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: SharedSequenceConvertibleType>(_ second: SecondO) -> SharedSequence<SharingStrategy, SecondO.Element> {
let source = self.asObservable()
.withLatestFrom(second.asSharedSequence())
return SharedSequence<SharingStrategy, SecondO.Element>(source)
}
}
// MARK: skip
extension SharedSequenceConvertibleType {
/**
Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter count: The number of elements to skip before returning the remaining elements.
- returns: An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
public func skip(_ count: Int)
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.skip(count)
return SharedSequence(source)
}
}
// MARK: startWith
extension SharedSequenceConvertibleType {
/**
Prepends a value to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter element: Element to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
public func startWith(_ element: Element)
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.startWith(element)
return SharedSequence(source)
}
}
// MARK: delay
extension SharedSequenceConvertibleType {
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
public func delay(_ dueTime: RxTimeInterval)
-> SharedSequence<SharingStrategy, Element> {
let source = self.asObservable()
.delay(dueTime, scheduler: SharingStrategy.scheduler)
return SharedSequence(source)
}
}
| mit |
chaoyang805/DoubanMovie | DoubanMovie/HomeViewController.swift | 1 | 10185 | /*
* Copyright 2016 chaoyang805 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import SDWebImage
import ObjectMapper
class HomeViewController: UIViewController{
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var pageControl: LoadingPageControl!
@IBOutlet weak var refreshBarButtonItem: UIBarButtonItem!
private(set) var movieDialogView: MovieDialogView!
fileprivate var animator: UIDynamicAnimator!
fileprivate var attachmentBehavior: UIAttachmentBehavior!
fileprivate var gravityBehavior: UIGravityBehavior!
fileprivate var snapBehavior: UISnapBehavior!
fileprivate var imagePrefetcher = SDWebImagePrefetcher()
fileprivate var doubanService: DoubanService {
return DoubanService.sharedService
}
fileprivate lazy var realm: RealmHelper = {
return RealmHelper()
}()
fileprivate lazy var placeHolderImage: UIImage = {
return UIImage(named: "placeholder")!
}()
fileprivate var movieCount: Int {
return resultsSet != nil ? resultsSet.subjects.count : 0
}
fileprivate var resultsSet: DoubanResultsSet! {
didSet {
self.pageControl.numberOfPages = movieCount
showCurrentMovie(animated: false)
}
}
fileprivate var currentPage: Int = 0
private var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
private var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
override func viewDidLoad() {
super.viewDidLoad()
setupMovieDialogView()
self.fetchData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.imagePrefetcher.cancelPrefetching()
}
private func setupMovieDialogView() {
let dialogWidth = screenWidth * 280 / 375
let dialogHeight = dialogWidth / 280 * 373
let x = (screenWidth - dialogWidth) / 2
let y = (screenHeight - dialogHeight + 44) / 2
movieDialogView = MovieDialogView(frame: CGRect(x: x, y: y, width: dialogWidth, height: dialogHeight))
movieDialogView.addTarget(target: self, action: #selector(HomeViewController.movieDialogViewDidTouch(_:)), for: .touchUpInside)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(HomeViewController.handleGestures(_:)))
self.movieDialogView.addGestureRecognizer(panGesture)
self.view.addSubview(movieDialogView)
animator = UIDynamicAnimator(referenceView: self.view)
}
func movieDialogViewDidTouch(_ sender: AnyObject) {
self.performSegue(withIdentifier: "ShowDetailSegue", sender: self)
}
// MAKR: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDetailSegue" {
guard let toVC = segue.destination as? MovieDetailViewController else { return }
toVC.detailMovie = resultsSet.subjects[currentPage]
}
if segue.identifier == "MenuSegue" {
if let toVC = segue.destination as? MenuViewController {
if toVC.delegate == nil {
toVC.delegate = self
}
}
}
}
}
// MARK: - refresh home view controller
extension HomeViewController {
@IBAction func refreshButtonDidTouch(_ sender: UIBarButtonItem) {
self.fetchData(force: true)
}
/**
refresh home screen data
- parameter force: force reload from internet or load local cache data
*/
fileprivate func fetchData(force: Bool = false) {
doubanService.getInTheaterMovies(at: 0, resultCount:5,forceReload: force) { [weak self](responseJSON, error) in
guard let `self` = self else { return }
self.endLoading()
if error != nil {
Snackbar.make(text: "刷新失败,请稍后重试", duration: .Short).show()
}
if responseJSON != nil {
self.resultsSet = Mapper<DoubanResultsSet>().map(JSON: responseJSON!)
self.prefetchImages()
}
}
self.beginLoading()
}
private func prefetchImages() {
let urls = self.resultsSet.subjects.map { URL(string: $0.images?.mediumImageURL ?? "") }.flatMap { $0 }
self.imagePrefetcher.prefetchURLs(urls)
}
private func beginLoading() {
UIView.animate(withDuration: 0.2) { [weak self] in
guard let `self` = self else { return }
self.backgroundImageView.alpha = 0
}
self.refreshBarButtonItem.isEnabled = false
self.movieDialogView.beginLoading()
self.pageControl.beginLoading()
}
private func endLoading() {
UIView.animate(withDuration: 0.2) { [weak self] in
guard let `self` = self else { return }
self.backgroundImageView.alpha = 1
}
self.refreshBarButtonItem.isEnabled = true
self.movieDialogView.endLoading()
self.pageControl.endLoading()
}
// test method
private func performFetch(completion: @escaping () -> Void) {
DispatchQueue(label: "network", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent).async {
NSLog("perform loading start...")
Thread.sleep(forTimeInterval: 5)
DispatchQueue.main.sync {
completion()
NSLog("perform loading completed")
}
}
}
}
// MARK: - Pages
extension HomeViewController {
@IBAction func handleGestures(_ sender: UIPanGestureRecognizer) {
let location = sender.location(in: view)
guard let myView = movieDialogView else { return }
let boxLocation = sender.location(in: myView)
switch sender.state {
case .began:
if let snap = snapBehavior{
animator.removeBehavior(snap)
}
let centerOffset = UIOffset(horizontal: boxLocation.x - myView.bounds.midX, vertical: boxLocation.y - myView.bounds.midY)
attachmentBehavior = UIAttachmentBehavior(item: myView, offsetFromCenter: centerOffset, attachedToAnchor: location)
attachmentBehavior.frequency = 0
animator.addBehavior(attachmentBehavior)
case .changed:
attachmentBehavior.anchorPoint = location
case .ended:
animator.removeBehavior(attachmentBehavior)
snapBehavior = UISnapBehavior(item: myView, snapTo: CGPoint(x: view.center.x, y: view.center.y + 22))
animator.addBehavior(snapBehavior)
let translation = sender.translation(in: view)
if abs(translation.x) < 150 {
return
}
animator.removeAllBehaviors()
if gravityBehavior == nil {
gravityBehavior = UIGravityBehavior(items: [myView])
}
if translation.x < -150 {
// 左
gravityBehavior.gravityDirection = CGVector(dx: -20.0, dy: 0)
} else if translation.x > 150 {
// 右
gravityBehavior.gravityDirection = CGVector(dx: 20.0, dy: 0)
}
animator.addBehavior(gravityBehavior)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(300), execute: {
self.refreshData()
})
default:
break
}
}
private func refreshData() {
animator.removeAllBehaviors()
snapBehavior = UISnapBehavior(item: movieDialogView, snapTo: view.center)
movieDialogView.center = CGPoint(x: view.center.x, y: view.center.y + 20)
attachmentBehavior.anchorPoint = CGPoint(x: view.center.x, y: view.center.y + 20)
let scale = CGAffineTransform(scaleX: 0.5, y: 0.5)
let offsetX = gravityBehavior.gravityDirection.dx < 0 ? self.view.frame.width + 200 : -200
let translation = CGAffineTransform(translationX:offsetX, y: 0)
movieDialogView.transform = scale.concatenating(translation)
if gravityBehavior.gravityDirection.dx < 0 {
currentPage = (currentPage + 1) % movieCount
} else {
currentPage = currentPage <= 0 ? movieCount - 1 : currentPage - 1
}
showCurrentMovie(animated: true)
}
fileprivate func showCurrentMovie(animated: Bool) {
guard movieCount > 0 && currentPage < movieCount else { return }
pageControl.currentPage = currentPage
let currentMovie = resultsSet.subjects[currentPage]
movieDialogView.movie = currentMovie
backgroundImageView.sd_setImage(with: URL(string: currentMovie.images!.mediumImageURL), placeholderImage: placeHolderImage)
if animated {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.movieDialogView.transform = CGAffineTransform.identity
}, completion: nil)
}
}
}
| apache-2.0 |
CoderGuoJiGang/DouYuZB | DYZB/DYZB/Classes/Main/ViewController/MainViewController.swift | 1 | 1218 | //
// MainViewController.swift
// DYZB
//
// Created by 郭吉刚 on 16/9/21.
// Copyright © 2016年 郭吉刚. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVc("Home")
addChildVc("Live")
addChildVc("Fellow")
addChildVc("Profile")
}
fileprivate func addChildVc(_ storyBoradName:String){
// 创建控制器
let childVc = UIStoryboard(name: storyBoradName, bundle: nil).instantiateInitialViewController()!
// 添加到自控制器
addChildViewController(childVc)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
LeoMobileDeveloper/MDTable | MDTableExample/DynamicHeightRow.swift | 1 | 1245 | //
// DynamicHeightRow.swift
// MDTableExample
//
// Created by Leo on 2017/6/16.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import Foundation
import MDTable
class DynamicHeightRow: RowConvertable{
//Protocol
var rowHeight: CGFloat{
get{
let attributes = [NSFontAttributeName: DynamicHeightCellConst.font]
let size = CGSize(width: DynamicHeightCellConst.cellWidth, height: .greatestFiniteMagnitude)
let height = (self.title as NSString).boundingRect(with: size,
options: [.usesLineFragmentOrigin],
attributes: attributes,
context: nil).size.height
return height + 8.0
}
}
var reuseIdentifier: String = "DynamicHeightRow"
var initalType: RowConvertableInitalType = RowConvertableInitalType.code(className: DynamicHeightCell.self)
//Optional evnet
var didSelectRowAt: (UITableView, IndexPath) -> Void
//Data
var title:String
init(title:String) {
self.title = title
self.didSelectRowAt = {_,_ in}
}
}
| mit |
svedm/SweetyViperDemo | SweetyViperDemo/SweetyViperDemo/Classes/PresentationLayer/Common/ModuleTransitionHandler.swift | 1 | 334 | //
// ModuleTransitionHandler.swift
// SweetyViperDemo
//
// Created by Svetoslav on 13.02.17.
// Copyright © 2017 Svedm. All rights reserved.
//
import Foundation
protocol ModuleTransitionHandler: class {
func openModule(segueIdentifier: String, configurationClosure: ModuleConfigurationClosure?)
func closeModule()
}
| mit |
robrix/Hammer.swift | Hammer/Generator.swift | 1 | 347 | // Copyright (c) 2014 Rob Rix. All rights reserved.
/// Concatenation of Generators.
func ++ <A : Generator, B : Generator, Element where Element == A.Element, Element == B.Element>(var a: A, var b: B) -> GeneratorOf<Element> {
return GeneratorOf {
switch a.next() {
case .None:
return b.next()
case let .Some(x):
return x
}
}
}
| mit |
ndleon09/SwiftSample500px | pictures/Modules/Detail/DetailInteractor.swift | 1 | 1375 | //
// DetailInteractor.swift
// pictures
//
// Created by Nelson on 05/11/15.
// Copyright © 2015 Nelson Dominguez. All rights reserved.
//
import Foundation
class DetailInteractor: DetailInteractorInputProtocol {
var output : DetailInteractorOutputProtocol?
var dataManager : DetailDataManagerProtocol?
func findDetailPhoto(identifier: Double) {
dataManager?.findDetailPhoto(identifier: identifier, completion: { picture in
let detailModel = self.detailModelFromPictureModel(picture)
self.output?.foundDetailPhoto(detailModel: detailModel)
})
}
fileprivate func detailModelFromPictureModel(_ pictureModel: PictureModel?) -> DetailModel? {
if let picture = pictureModel {
let detailModel = DetailModel()
detailModel.name = picture.name
detailModel.camera = picture.camera
detailModel.descriptionText = picture.detailText
detailModel.latitude = picture.latitude
detailModel.longitude = picture.longitude
detailModel.userName = picture.user?.name
if let image = picture.user?.image {
detailModel.userImage = URL(string: image)
}
return detailModel
}
return nil
}
}
| mit |
botherbox/JSONtoModel | JSONtoModel/EasyNetwork/EasyNetwork.swift | 2 | 3594 | //
// EasyNetwork.swift
// EasyNetwork
//
// Created by BotherBox on 15/3/3.
// Copyright (c) 2015年 sz. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
}
public class EasyNetwork {
public typealias Completion = (data: AnyObject?, error: NSError?) -> Void
public func requestJSONWithURL(urlString: String, method: HTTPMethod, params: [String: String]?, completion:Completion) {
// 根据请求方法和请求参数字符串生成NSURLRequest
if let request = creatRequest(urlString, method: method, params: params) {
//
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in
// 如果有错误直接返回
if error != nil {
completion(data: nil, error: error)
return
}
var jsonError: NSError?
let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
// 如果反序列化失败
if result == nil {
let error = NSError(domain: EasyNetwork.errorDomain, code: 1, userInfo: ["error": "反序列化失败", "error_json": jsonError!])
completion(data: nil, error: error)
} else {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
completion(data: result, error: nil)
})
}
}).resume()
// 请求成功,不继续往下走
return
}
// 请求失败
let error = NSError(domain: EasyNetwork.errorDomain, code: -1, userInfo: ["errorMsg": "请求失败"])
completion(data: nil, error: error)
}
/// 生成请求对象
func creatRequest(urlString: String, method: HTTPMethod, params: [String: String]?) -> NSURLRequest? {
if urlString.isEmpty {
return nil
}
var request: NSURLRequest?
var urlStrM = urlString
if method == HTTPMethod.GET {
// var url = NSURL(string: urlString + "?" + parseParams(params)!)
if let queryStr = parseParams(params) {
urlStrM += "?" + queryStr
}
request = NSURLRequest(URL: NSURL(string: urlStrM)!)
} else if method == HTTPMethod.POST { // POST请求
// 如果请求参数不为空
if let queryStr = parseParams(params) {
let requestM = NSMutableURLRequest(URL: NSURL(string: urlString)!)
requestM.HTTPMethod = method.rawValue
requestM.HTTPBody = queryStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request = requestM
}
}
return request
}
// 解析参数
func parseParams(params: [String: String]?) -> String? {
if params == nil || params!.isEmpty {
return nil
}
var tmpArr = [String]()
for (k, v) in params! {
tmpArr.append("\(k)=\(v)")
}
return join("&", tmpArr)
}
static let errorDomain = "com.botherbox.EasyNetwork"
/// Construction Method
public init() {}
} | mit |
vermont42/Conjugar | Conjugar/TestGameCenter.swift | 1 | 699 | //
// TestGameCenter.swift
// Conjugar
//
// Created by Joshua Adams on 11/27/18.
// Copyright © 2018 Josh Adams. All rights reserved.
//
import UIKit
class TestGameCenter: GameCenterable {
var isAuthenticated: Bool
init(isAuthenticated: Bool = false) {
self.isAuthenticated = isAuthenticated
}
func authenticate(onViewController: UIViewController, completion: ((Bool) -> Void)?) {
if !isAuthenticated {
isAuthenticated = true
completion?(true)
} else {
completion?(false)
}
}
func reportScore(_ score: Int) {
print("Pretending to report score \(score).")
}
func showLeaderboard() {
print("Pretending to show leaderboard.")
}
}
| agpl-3.0 |
jonnyleeharris/ento | Ento/ento/core/Entity.swift | 1 | 3164 | //
// Created by Jonathan Harris on 29/06/2015.
// Copyright © 2015 Jonathan Harris. All rights reserved.
//
import Foundation
struct EntityComponentAddedOrRemoved {
var componentClass:Any.Type;
var entity:Entity;
}
struct EntityNameChanged {
var name:String;
var entity:Entity;
}
public class Entity : Hashable {
private static var nameCount:Int = 0;
private static var hashCount:Int = 0;
private var hashNumber:Int;
public var numComponents:Int {
get {
return components.count;
}
}
/**
* All entities have a name. If no name is set, a default name is used. Names are used to
* fetch specific entities from the engine, and can also help to identify an entity when debugging.
*/
var name : String {
didSet {
self.nameChanged.fire( EntityNameChanged(name: oldValue, entity: self) );
}
}
public var hashValue:Int {
get {
return self.hashNumber;
}
}
/**
* This signal is dispatched when a component is added to the entity.
*/
private (set) var componentAdded:Signal<EntityComponentAddedOrRemoved>;
/**
* This signal is dispatched when a component is removed from the entity.
*/
private (set) var componentRemoved:Signal<EntityComponentAddedOrRemoved>;
/**
* Dispatched when the name of the entity changes. Used internally by the engine to track entities based on their names.
*/
internal var nameChanged:Signal<EntityNameChanged>;
internal var previous:Entity?;
internal var next:Entity?;
internal var components:Dictionary<String, Any>;
public init(name:String) {
self.componentAdded = Signal<EntityComponentAddedOrRemoved>()
self.componentRemoved = Signal<EntityComponentAddedOrRemoved>()
self.nameChanged = Signal<EntityNameChanged>();
self.name = name;
self.hashNumber = Entity.hashCount++
self.components = [String: Any]();
}
public convenience init() {
let name:String = "entity\(++Entity.nameCount)";
self.init(name: name);
}
public func add(component:Any) {
let key:String = String(component.dynamicType);
if let existing = self.components[key] {
remove(existing.dynamicType);
}
self.components[key] = component;
self.componentAdded.fire( EntityComponentAddedOrRemoved(componentClass: component.dynamicType, entity: self) );
}
public func remove(componentClass:Any.Type) -> Any? {
let key:String = String(componentClass);
if let existing:Any = self.components.removeValueForKey(key) {
self.componentRemoved.fire( EntityComponentAddedOrRemoved(componentClass: existing.dynamicType, entity: self) );
return existing;
} else {
return nil;
}
}
public func get<T>(componentType:T.Type) -> T? {
let key:String = String(componentType);
return self.components[key] as? T;
}
// public func getAll() -> Array<Any> {
// return [Any](self.components.values)
// }
public func has(componentType:AnyClass) -> Bool {
let key:String = String(componentType);
return self.components.keys.contains(key)
// if let _ = self.components[key] {
// return true;
// } else {
// return false;
// }
}
}
public func == (lhs:Entity, rhs:Entity) -> Bool {
return lhs.hashValue == rhs.hashValue;
}
| mit |
lojals/QRGen | Pods/QRCodeReader.swift/QRCodeReader/QRCodeReaderResult.swift | 2 | 1508 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
/**
The result of the scan with its content value and the corresponding metadata type.
*/
public struct QRCodeReaderResult {
/**
The error corrected data decoded into a human-readable string.
*/
public let value: String
/**
The type of the metadata.
*/
public let metadataType: String
} | mit |
rplankenhorn/BowieUtilityKnife | Pods/BrightFutures/BrightFutures/NSOperationQueue+BrightFutures.swift | 3 | 383 | //
// NSOperationQueue+BrightFutures.swift
// BrightFutures
//
// Created by Thomas Visser on 18/09/15.
// Copyright © 2015 Thomas Visser. All rights reserved.
//
import Foundation
public extension NSOperationQueue {
public var context: ExecutionContext {
return { [weak self] task in
self?.addOperation(NSBlockOperation(block: task))
}
}
} | mit |
christiankm/FinanceKit | Tests/FinanceKitTests/CurrencyPairTests.swift | 1 | 997 | //
// FinanceKit
// Copyright © 2022 Christian Mitteldorf. All rights reserved.
// MIT license, see LICENSE file for details.
//
import FinanceKit
import XCTest
class CurrencyPairTests: XCTestCase {
func testInit() {
let pair = CurrencyPair(
baseCurrency: .usDollars,
secondaryCurrency: .danishKroner,
rate: 0.64
)
XCTAssertNotEqual(pair.baseCurrency, pair.secondaryCurrency)
XCTAssertEqual(pair.baseCurrency.code.rawValue, "USD")
XCTAssertEqual(pair.secondaryCurrency.code.rawValue, "DKK")
XCTAssertEqual(pair.rate, 0.64)
}
func testInitWithSameCurrency() {
let pair = CurrencyPair(
baseCurrency: .danishKroner,
secondaryCurrency: .danishKroner,
rate: 1.00
)
XCTAssertEqual(pair.baseCurrency.code.rawValue, "DKK")
XCTAssertEqual(pair.secondaryCurrency.code.rawValue, "DKK")
XCTAssertEqual(pair.rate, 1.00)
}
}
| mit |
larrynatalicio/15DaysofAnimationsinSwift | Animation 10 - SecretTextAnimation/SecretTextAnimation/CharacterLabel.swift | 1 | 6461 | //
// CharacterLabel.swift
// SecretTextAnimation
//
// Created by Larry Natalicio on 4/27/16.
// Copyright © 2016 Larry Natalicio. All rights reserved.
//
import UIKit
import QuartzCore
import CoreText
class CharacterLabel: UILabel, NSLayoutManagerDelegate {
// MARK: - Properties
let textStorage = NSTextStorage(string: " ")
let textContainer = NSTextContainer()
let layoutManager = NSLayoutManager()
var oldCharacterTextLayers = [CATextLayer]()
var characterTextLayers = [CATextLayer]()
override var lineBreakMode: NSLineBreakMode {
get {
return super.lineBreakMode
}
set {
textContainer.lineBreakMode = newValue
super.lineBreakMode = newValue
}
}
override var numberOfLines: Int {
get {
return super.numberOfLines
}
set {
textContainer.maximumNumberOfLines = newValue
super.numberOfLines = newValue
}
}
override var bounds: CGRect {
get {
return super.bounds
}
set {
textContainer.size = newValue.size
super.bounds = newValue
}
}
override var text: String! {
get {
return super.text
}
set {
let wordRange = NSMakeRange(0, newValue.characters.count)
let attributedText = NSMutableAttributedString(string: newValue)
attributedText.addAttribute(NSForegroundColorAttributeName , value:self.textColor, range:wordRange)
attributedText.addAttribute(NSFontAttributeName , value:self.font, range:wordRange)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = self.textAlignment
attributedText.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range: wordRange)
self.attributedText = attributedText
}
}
override var attributedText: NSAttributedString? {
get {
return super.attributedText
}
set {
if textStorage.string == newValue!.string {
return
}
cleanOutOldCharacterTextLayers()
oldCharacterTextLayers = [CATextLayer](characterTextLayers)
textStorage.setAttributedString(newValue!)
}
}
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
setupLayoutManager()
}
// MARK: - NSCoding
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayoutManager()
}
// MARK: - View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
setupLayoutManager()
}
// MARK: - NSLayoutManagerDelegate
func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
calculateTextLayers()
}
// MARK: - Convenience
func calculateTextLayers() {
characterTextLayers.removeAll(keepingCapacity: false)
let attributedText = textStorage.string
let wordRange = NSMakeRange(0, attributedText.characters.count)
let attributedString = self.internalAttributedText()
let layoutRect = layoutManager.usedRect(for: textContainer)
var index = wordRange.location
while index < wordRange.length + wordRange.location {
let glyphRange = NSMakeRange(index, 1)
let characterRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange:nil)
let textContainer = layoutManager.textContainer(forGlyphAt: index, effectiveRange: nil)
var glyphRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!)
let location = layoutManager.location(forGlyphAt: index)
let kerningRange = layoutManager.range(ofNominallySpacedGlyphsContaining: index)
if kerningRange.length > 1 && kerningRange.location == index {
if characterTextLayers.count > 0 {
let previousLayer = characterTextLayers[characterTextLayers.endIndex-1]
var frame = previousLayer.frame
frame.size.width += glyphRect.maxX-frame.maxX
previousLayer.frame = frame
}
}
glyphRect.origin.y += location.y-(glyphRect.height/2)+(self.bounds.size.height/2)-(layoutRect.size.height/2)
let textLayer = CATextLayer(frame: glyphRect, string: (attributedString?.attributedSubstring(from: characterRange))!)
initialTextLayerAttributes(textLayer)
layer.addSublayer(textLayer)
characterTextLayers.append(textLayer)
index += characterRange.length
}
}
func setupLayoutManager() {
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.size = bounds.size
textContainer.maximumNumberOfLines = numberOfLines
textContainer.lineBreakMode = lineBreakMode
layoutManager.delegate = self
}
func initialTextLayerAttributes(_ textLayer: CATextLayer) {
}
func internalAttributedText() -> NSMutableAttributedString! {
let wordRange = NSMakeRange(0, textStorage.string.characters.count)
let attributedText = NSMutableAttributedString(string: textStorage.string)
attributedText.addAttribute(NSForegroundColorAttributeName , value: self.textColor.cgColor, range:wordRange)
attributedText.addAttribute(NSFontAttributeName , value: self.font, range:wordRange)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = self.textAlignment
attributedText.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range: wordRange)
return attributedText
}
func cleanOutOldCharacterTextLayers() {
for textLayer in oldCharacterTextLayers {
textLayer.removeFromSuperlayer()
}
oldCharacterTextLayers.removeAll(keepingCapacity: false)
}
}
| mit |
AxziplinNet/AxziplinNet | Package.swift | 1 | 1334 | //
// Package.swift
// AxziplinNet
//
// Created by devedbox on 2017/4/19.
// Copyright © 2017年 devedbox. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import PackageDescription
let package = Package(name: "AxziplinNet", dependencies : [], exclude: ["Tests"])
| mit |
onmyway133/Github.swift | Carthage/Checkouts/Sugar/Tests/Shared/TestTruncate.swift | 1 | 475 | import Foundation
import XCTest
@testable import Sugar
class StringTruncateTests: XCTestCase {
let testString = "John Hyperseed"
func testTruncate() {
XCTAssertEqual(testString.truncate(4), "John...")
XCTAssertNotEqual(testString.truncate(5), "John...")
}
func testTruncateSuffix() {
XCTAssertEqual(testString.truncate(4, suffix: "-"), "John-")
}
func testTruncateWithShortString() {
XCTAssertEqual(testString.truncate(20), testString)
}
}
| mit |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift | 1 | 1967 | /**
* Copyright IBM Corporation 2018
*
* 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
/** SpeechRecognitionAlternative. */
public struct SpeechRecognitionAlternative: Decodable {
/// A transcription of the audio.
public var transcript: String
/// A score that indicates the service's confidence in the transcript in the range of 0 to 1. Returned only for the best alternative and only with results marked as final.
public var confidence: Double?
/// Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds. Example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Returned only for the best alternative.
public var timestamps: [WordTimestamp]?
/// A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0 to 1. Example: `[["hello",0.95],["world",0.866]]`. Returned only for the best alternative and only with results marked as final.
public var wordConfidence: [WordConfidence]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case transcript = "transcript"
case confidence = "confidence"
case timestamps = "timestamps"
case wordConfidence = "word_confidence"
}
}
| mit |
karstengresch/rw_studies | CoreData/HitList/HitList/ViewController.swift | 1 | 2802 | //
// ViewController.swift
// HitList
//
// Created by Karsten Gresch on 31.05.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "The List"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
@IBOutlet weak var tableView: UITableView!
// var names: [String] = []
var people: [NSManagedObject] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
do {
people =
try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Coud not fetch. \(error), \(error.userInfo)")
}
}
@IBAction func addName(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "New Name", message: "Please add a new name", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
guard let textField = alert.textFields?.first , let nameToSave = textField.text else {
return
}
self.save(name: nameToSave)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alert.addTextField()
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
func save(name: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
let person = NSManagedObject(entity: entity, insertInto: managedContext)
person.setValue(name, forKeyPath: "name")
do {
try managedContext.save()
people.append(person)
} catch let error as NSError {
print("Coud not save. \(error), \(error.userInfo)")
}
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let person = people[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = person.value(forKeyPath: "name") as? String
return cell
}
}
| unlicense |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Common Models/Errors.swift | 1 | 1342 | //
// Errors.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/26/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
/// Represents the different types of error returned by this Framework
public enum Error: ErrorType {
/// This is an error existing on ther server side. It will most likely be
/// something unexpected and not the client's fault.
///
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451659
case ServerError(message: String)
/// This is most likely the result of the client passing an invalid argument in a request.
///
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451659
case ArgumentError(message: String)
/// A result of failure to map the response received with the rules provided.
case MappingError
/// Invalid credentials were provider when making a request that requires valid login
case InvalidLoginError
/// An error on the client's system. Most likely a networking error.
case SystemError(code: Int, domain: String)
/// An error from the lol API
case LolError(message: String)
/// An error returned if more than 10,000 events have occurred since your specified lastEventId
case TooManyEvents
/// Catch all for errors that can't be matched to one of the other categories.
case UnkownError
}
| mit |
Ellusioists/TimingRemind | TimingRemind/Utils/SQliteRepository.swift | 1 | 4671 | //
// SQliteRepository.swift
// PasswordKeeper-swift
//
// Created by Channing on 2017/1/3.
// Copyright © 2017年 Channing Kuo. All rights reserved.
//
import Foundation
// SQlite数据库操作类
class SQliteRepository {
public static let PASSWORDINFOTABLE: String = "dataInfoTable"
private static var db: SQLiteDB! = SQLiteDB.sharedInstance
// 创建表
class func createTable(tableName: String, columns: [ColumnType]) {
var sql = "create table if not exists \(tableName)(\(tableName)Id varchar(100) not null primary key, "
for column in columns {
sql += "\(column.colName) \(column.colType!), "
}
// 最后有一个空格字符所以取 长度 - 2
sql = sql.subString(start: 0, length: sql.characters.count - 2) + ")"
_ = SQliteRepository.db.execute(sql: sql)
}
// 存入数据
class func syncInsert(tableName: String, rowValue: [[ColumnType]]) -> CInt {
var iterator: CInt = 0
for row in rowValue {
iterator += addOrUpdate(tableName: tableName, colValue: row)
}
return iterator
}
// 插入数据或更新数据 新增主键值用guid自动生成
class func addOrUpdate(tableName: String, colValue: [ColumnType]) -> CInt {
// 1、从colValue中获取主键对应的值
var parimaryKeyValue = ""
for col in colValue {
if col.colName == tableName + "Id" {
parimaryKeyValue = col.colValue as! String
break
}
}
// 2、根据主键和表名查询对应的数据
//let id = checkExist(tableName: tableName, key: parimaryKeyValue)
var id = ""
let sql = "select \(tableName)Id from \(tableName) where \(tableName)Id = '\(parimaryKeyValue)'"
let data = SQliteRepository.db.query(sql: sql)
if(data.count > 0){
let info = data[data.count - 1]
id = info["\(tableName)Id"] as! String
}
// 3、根据查询结果决定新增或是更新
if id.isEmpty {
// Add
var sqlAdd = "insert into \(tableName)("
for col in colValue {
if col.colName == "\(tableName)Id" {
continue
}
sqlAdd += "\(col.colName), "
}
sqlAdd += "\(tableName)Id) values("
for col in colValue {
if col.colName == "\(tableName)Id" {
continue
}
sqlAdd += "'\(col.colValue!)', "
}
let parimaryKey = id.isEmpty ? UUID().uuidString : id
sqlAdd += "'" + parimaryKey + "')"
return SQliteRepository.db.execute(sql: sqlAdd)
}
else {
// Update
var sqlUpdate = "update \(tableName) set "
for col in colValue {
if col.colName == "\(tableName)Id" {
continue
}
sqlUpdate += "\(col.colName) = '\(col.colValue!)', "
}
sqlUpdate = sqlUpdate.subString(start: 0, length: sqlUpdate.characters.count - 2)
// 添加where条件
sqlUpdate += " where \(tableName)Id = '\(id)'"
return SQliteRepository.db.execute(sql: sqlUpdate)
}
}
// 删除数据
class func delete(tableName: String, columns: [ColumnType]) -> CInt {
var sql = "delete from \(tableName) where "
for (index,col) in columns.enumerated() {
if index != columns.count - 1 {
sql += "\(col.colName) = '\(col.colValue!)' and "
}
else{
sql += "\(col.colName) = '\(col.colValue!)'"
}
}
return SQliteRepository.db.execute(sql: sql)
}
// 删除数据
class func deleteAll(tableName: String) -> CInt {
let sql = "delete from \(tableName) "
return SQliteRepository.db.execute(sql: sql)
}
// 查询表数据
class func getData(tableName: String) -> [[String: Any]] {
let sql = "select * from \(tableName)"
return SQliteRepository.db.query(sql: sql)
}
// 用SQL自定义查询表数据
class func sqlExcute(sql: String) -> [[String: Any]] {
return SQliteRepository.db.query(sql: sql)
}
}
public struct ColumnType {
var colName: String
var colType: String?
var colValue: Any?
init(colName: String, colType: String?, colValue: Any?) {
self.colName = colName
self.colType = colType
self.colValue = colValue
}
}
| mit |
LYM-mg/DemoTest | indexView/Extesion/Category(扩展)/NSObject+Extension.swift | 1 | 7382 | //
// NSObject+Extension.swift
// chart2
//
// Created by i-Techsys.com on 16/12/3.
// Copyright © 2016年 i-Techsys. All rights reserved.
//
import UIKit
// MARK: - 弹框
extension NSObject {
/// 只有是控制器和继承UIView的控件才会弹框
/**
* - 弹框提示
* - @param info 要提醒的内容
*/
func showInfo(info: String) {
if self.isKind(of: UIViewController.self) || self.isKind(of: UIView.self) {
let alertVc = UIAlertController(title: info, message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "好的", style: .cancel, handler: nil)
alertVc.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertVc, animated: true, completion: nil)
}
}
static func showInfo(info: String) {
if self.isKind(of: UIViewController.self) || self.isKind(of: UIView.self) {
let alertVc = UIAlertController(title: info, message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "好的", style: .cancel, handler: nil)
alertVc.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertVc, animated: true, completion: nil)
}
}
}
// MARK: - RunTime
extension NSObject {
/**
获取所有的方法和属性
- parameter cls: 当前类
*/
func mg_GetMethodAndPropertiesFromClass(cls: AnyClass) {
debugPrint("方法========================================================")
var methodNum: UInt32 = 0
let methods = class_copyMethodList(cls, &methodNum)
for index in 0..<numericCast(methodNum) {
let met: Method = methods![index]
debugPrint("m_name: \(method_getName(met))")
// debugPrint("m_returnType: \(String(utf8String: method_copyReturnType(met))!)")
// debugPrint("m_type: \(String(utf8String: method_getTypeEncoding(met))!)")
}
debugPrint("属性=========================================================")
var propNum: UInt32 = 0
let properties = class_copyPropertyList(cls, &propNum)
for index in 0..<Int(propNum) {
let prop: objc_property_t = properties![index]
debugPrint("p_name: \(String(utf8String: property_getName(prop))!)")
// debugPrint("p_Attr: \(String(utf8String: property_getAttributes(prop))!)")
}
debugPrint("成员变量======================================================")
var ivarNum: UInt32 = 0
let ivars = class_copyIvarList(cls, &ivarNum)
for index in 0..<numericCast(ivarNum) {
let ivar: objc_property_t = ivars![index]
let name = ivar_getName(ivar)
debugPrint("ivar_name: \(String(cString: name!))")
}
}
/**
- parameter cls: : 当前类
- parameter originalSelector: : 原方法
- parameter swizzledSelector: : 要交换的方法
*/
/// RunTime交换方法
class func mg_SwitchMethod(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
guard let originalMethod = class_getInstanceMethod(cls, originalSelector) else {
return;
}
guard let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) else {
return;
}
let didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
//
public func ClassIvarsNames(c: AnyClass) -> [Any]? {
var array: [AnyHashable] = []
var ivarNum: UInt32 = 0
let ivars = class_copyIvarList(c, &ivarNum)
for index in 0..<numericCast(ivarNum) {
let ivar: objc_property_t = ivars![index]
if let name:UnsafePointer<Int8> = ivar_getName(ivar) {
debugPrint("ivar_name: \(String(cString: name))")
if let key = String(utf8String:name) {
array.append(key)
array.append("\n")
}
}
}
free(ivars)
return array
}
public func ClassMethodNames(c: AnyClass) -> [Any]? {
var array: [AnyHashable] = []
var methodCount: UInt32 = 0
let methodList = class_copyMethodList(c, &methodCount)
guard let methodArray = methodList else {
return array;
}
for i in 0..<methodCount {
array.append(NSStringFromSelector(method_getName(methodArray[Int(i)])))
}
free(methodArray)
return array
}
}
protocol SelfAware: class {
static func awake()
static func swizzlingForClass(_ forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector)
}
extension SelfAware {
static func swizzlingForClass(_ forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
let originalMethod = class_getInstanceMethod(forClass, originalSelector)
let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
guard (originalMethod != nil && swizzledMethod != nil) else {
return
}
if class_addMethod(forClass, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) {
class_replaceMethod(forClass, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
}
class NothingToSeeHere {
static func harmlessFunction() {
let typeCount = Int(objc_getClassList(nil, 0))
let types = UnsafeMutablePointer.allocate(capacity: typeCount)
let autoreleasingTypes = AutoreleasingUnsafeMutablePointer(types)
objc_getClassList(autoreleasingTypes, Int32(typeCount))
for index in 0 ..< typeCount {
(types[index] as? SelfAware.Type)?.awake()
}
types.deallocate()
}
}
extension UIApplication {
private static let runOnce: Void = {
NothingToSeeHere.harmlessFunction()
}()
override open var next: UIResponder? {
UIApplication.runOnce
return super.next
}
}
extension UIButton: SelfAware {
static func awake() {
UIButton.takeOnceTime
}
private static let takeOnceTime: Void = {
let originalSelector = #selector(sendAction)
let swizzledSelector = #selector(xxx_sendAction(action:to:forEvent:))
swizzlingForClass(UIButton.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
}()
@objc public func xxx_sendAction(action: Selector, to: AnyObject!, forEvent: UIEvent!) {
struct xxx_buttonTapCounter {
static var count: Int = 0
}
xxx_buttonTapCounter.count += 1
print(xxx_buttonTapCounter.count)
xxx_sendAction(action: action, to: to, forEvent: forEvent)
}
}
| mit |
airbnb/lottie-ios | Tests/SnapshotTests.swift | 2 | 10745 | // Created by Cal Stephens on 12/8/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import SnapshotTesting
import XCTest
#if canImport(UIKit)
import UIKit
#endif
@testable import Lottie
// MARK: - SnapshotTests
@MainActor
class SnapshotTests: XCTestCase {
// MARK: Internal
/// Snapshots all of the sample animation JSON files visible to this test target
func testMainThreadRenderingEngine() async throws {
try await compareSampleSnapshots(configuration: LottieConfiguration(renderingEngine: .mainThread))
}
/// Snapshots sample animation files using the Core Animation rendering engine
func testCoreAnimationRenderingEngine() async throws {
try await compareSampleSnapshots(configuration: LottieConfiguration(renderingEngine: .coreAnimation))
}
/// Snapshots sample animation files using the automatic rendering engine option
func testAutomaticRenderingEngine() async throws {
try await compareSampleSnapshots(configuration: LottieConfiguration(renderingEngine: .automatic))
}
/// Validates that all of the snapshots in __Snapshots__ correspond to
/// a sample JSON file that is visible to this test target.
func testAllSnapshotsHaveCorrespondingSampleFile() {
for snapshotURL in Samples.snapshotURLs {
// Exclude snapshots of private samples, since those aren't checked in to the repo
if snapshotURL.lastPathComponent.contains("Private") {
continue
}
// The snapshot files follow the format `testCaseName.animationName-percentage.png`
// - We remove the known prefix and known suffixes to recover the input file name
// - `animationName` can contain dashes, so we can't just split the string at each dash
var animationName = snapshotURL.lastPathComponent
.replacingOccurrences(of: "testMainThreadRenderingEngine.", with: "")
.replacingOccurrences(of: "testCoreAnimationRenderingEngine.", with: "")
.replacingOccurrences(of: "testAutomaticRenderingEngine.", with: "")
for percentage in progressPercentagesToSnapshot {
animationName = animationName.replacingOccurrences(
of: "-\(Int(percentage * 100)).png",
with: "")
}
animationName = animationName.replacingOccurrences(of: "-", with: "/")
XCTAssert(
Samples.sampleAnimationURLs.contains(where: { $0.absoluteString.hasSuffix("\(animationName).json") })
|| Samples.sampleAnimationURLs.contains(where: { $0.absoluteString.hasSuffix("\(animationName).lottie") }),
"Snapshot \"\(snapshotURL.lastPathComponent)\" has no corresponding sample animation")
}
}
/// Validates that all of the custom snapshot configurations in `SnapshotConfiguration.customMapping`
/// reference a sample json file that actually exists
func testCustomSnapshotConfigurationsHaveCorrespondingSampleFile() {
for (animationName, _) in SnapshotConfiguration.customMapping {
let expectedSampleFile = Bundle.module.bundleURL.appendingPathComponent("Samples/\(animationName).json")
XCTAssert(
Samples.sampleAnimationURLs.contains(expectedSampleFile),
"Custom configuration for \"\(animationName)\" has no corresponding sample animation")
}
}
/// Validates that this test target can access sample json files from `Tests/Samples`
/// and snapshot images from `Tests/__Snapshots__`.
func testCanAccessSamplesAndSnapshots() {
XCTAssert(Samples.sampleAnimationURLs.count > 50)
XCTAssert(Samples.snapshotURLs.count > 300)
}
override func setUp() {
LottieLogger.shared = .printToConsole
TestHelpers.snapshotTestsAreRunning = true
}
override func tearDown() {
LottieLogger.shared = LottieLogger()
TestHelpers.snapshotTestsAreRunning = false
}
// MARK: Private
/// `currentProgress` percentages that should be snapshot in `compareSampleSnapshots`
private let progressPercentagesToSnapshot = [0, 0.25, 0.5, 0.75, 1.0]
/// Captures snapshots of `sampleAnimationURLs` and compares them to the snapshot images stored on disk
private func compareSampleSnapshots(
configuration: LottieConfiguration,
testName: String = #function)
async throws
{
#if os(iOS)
guard UIScreen.main.scale == 2 else {
/// Snapshots are captured at a 2x scale, so we can only support
/// running tests on a device that has a 2x scale.
/// - In CI we run tests on an iPhone 8 simulator,
/// but any device with a 2x scale works.
throw SnapshotError.unsupportedDevice
}
for sampleAnimationName in Samples.sampleAnimationNames {
for percent in progressPercentagesToSnapshot {
guard
let animationView = await SnapshotConfiguration.makeAnimationView(
for: sampleAnimationName,
configuration: configuration)
else { continue }
animationView.currentProgress = CGFloat(percent)
assertSnapshot(
matching: animationView,
as: .imageOfPresentationLayer(
precision: SnapshotConfiguration.forSample(named: sampleAnimationName).precision),
named: "\(sampleAnimationName) (\(Int(percent * 100))%)",
testName: testName)
}
}
#else
// We only run snapshot tests on iOS, since running snapshot tests
// for macOS and tvOS would triple the number of snapshot images
// we have to check in to the repo.
throw SnapshotError.unsupportedPlatform
#endif
}
}
// MARK: Animation + snapshotSize
extension LottieAnimation {
/// The size that this animation should be snapshot at
fileprivate var snapshotSize: CGSize {
let maxDimension: CGFloat = 500
// If this is a landscape aspect ratio, we clamp the width
if width > height {
let newWidth = min(CGFloat(width), maxDimension)
let newHeight = newWidth * (CGFloat(height) / CGFloat(width))
return CGSize(width: newWidth, height: newHeight)
}
// otherwise, this is either a square or portrait aspect ratio,
// in which case we clamp the height
else {
let newHeight = min(CGFloat(height), maxDimension)
let newWidth = newHeight * (CGFloat(width) / CGFloat(height))
return CGSize(width: newWidth, height: newHeight)
}
}
}
// MARK: - SnapshotError
enum SnapshotError: Error {
/// We only run snapshot tests on iOS, since running snapshot tests
/// for macOS and tvOS would triple the number of snapshot images
/// we have to check in to the repo.
case unsupportedPlatform
/// Snapshots are captured at a 2x scale, so we can only support
/// running tests on a device that has a 2x scale.
case unsupportedDevice
}
// MARK: - Samples
/// MARK: - Samples
enum Samples {
/// The name of the directory that contains the sample json files
static let directoryName = "Samples"
/// The list of snapshot image files in `Tests/__Snapshots__`
static let snapshotURLs = Bundle.module.fileURLs(
in: "__Snapshots__",
withSuffix: "png")
/// The list of sample animation files in `Tests/Samples`
static let sampleAnimationURLs = Bundle.module.fileURLs(in: Samples.directoryName, withSuffix: "json")
+ Bundle.module.fileURLs(in: Samples.directoryName, withSuffix: "lottie")
/// The list of sample animation names in `Tests/Samples`
static let sampleAnimationNames = sampleAnimationURLs.lazy
.map { sampleAnimationURL -> String in
// Each of the sample animation URLs has the format
// `.../*.bundle/Samples/{subfolder}/{animationName}.json`.
// The sample animation name should include the subfolders
// (since that helps uniquely identity the animation JSON file).
let pathComponents = sampleAnimationURL.pathComponents
let samplesIndex = pathComponents.lastIndex(of: Samples.directoryName)!
let subpath = pathComponents[(samplesIndex + 1)...]
return subpath
.joined(separator: "/")
.replacingOccurrences(of: ".json", with: "")
.replacingOccurrences(of: ".lottie", with: "")
}
static func animation(named sampleAnimationName: String) -> LottieAnimation? {
guard
let animation = LottieAnimation.named(
sampleAnimationName,
bundle: .module,
subdirectory: Samples.directoryName)
else { return nil }
return animation
}
static func dotLottie(named sampleDotLottieName: String) async -> DotLottieFile? {
guard
let dotLottieFile = try? await DotLottieFile.named(
sampleDotLottieName,
bundle: .module,
subdirectory: Samples.directoryName)
else {
XCTFail("Could not parse Samples/\(sampleDotLottieName).lottie")
return nil
}
return dotLottieFile
}
}
extension SnapshotConfiguration {
/// Creates a `LottieAnimationView` for the sample snapshot with the given name
@MainActor
static func makeAnimationView(
for sampleAnimationName: String,
configuration: LottieConfiguration,
logger: LottieLogger = LottieLogger.shared)
async -> LottieAnimationView?
{
let snapshotConfiguration = SnapshotConfiguration.forSample(named: sampleAnimationName)
guard snapshotConfiguration.shouldSnapshot(using: configuration) else {
return nil
}
let animationView: LottieAnimationView
if let animation = Samples.animation(named: sampleAnimationName) {
animationView = LottieAnimationView(
animation: animation,
configuration: configuration,
logger: logger)
} else if let dotLottieFile = await Samples.dotLottie(named: sampleAnimationName) {
animationView = LottieAnimationView(
dotLottie: dotLottieFile,
configuration: configuration,
logger: logger)
} else {
XCTFail("Couldn't create Animation View for \(sampleAnimationName)")
return nil
}
guard let animation = animationView.animation else {
XCTFail("Couldn't create Animation View for \(sampleAnimationName)")
return nil
}
// Set up the animation view with a valid frame
// so the geometry is correct when setting up the `CAAnimation`s
animationView.frame.size = animation.snapshotSize
for (keypath, customValueProvider) in snapshotConfiguration.customValueProviders {
animationView.setValueProvider(customValueProvider, keypath: keypath)
}
if let customImageProvider = snapshotConfiguration.customImageProvider {
animationView.imageProvider = customImageProvider
}
if let customTextProvider = snapshotConfiguration.customTextProvider {
animationView.textProvider = customTextProvider
}
if let customFontProvider = snapshotConfiguration.customFontProvider {
animationView.fontProvider = customFontProvider
}
return animationView
}
}
| apache-2.0 |
ziligy/SnapLocation | SnapLocation/BlurredBackgroundView.swift | 1 | 1339 | //
// BlurredBackgroundView.swift
//
// Created by Jeff on 12/4/15.
// Copyright © 2015 Jeff Greenberg. All rights reserved.
//
import UIKit
/// UIView that's a blurred image for background display
public class BlurredBackgroundView: UIView {
private var imageView: UIImageView!
private var effectView: UIVisualEffectView!
public func getBlurEffect() -> UIBlurEffect {
return (self.effectView.effect as! UIBlurEffect)
}
convenience init(frame: CGRect, img: UIImage) {
self.init(frame: frame)
self.setImageWithBlurEffect(img)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
public convenience required init?(coder aDecoder: NSCoder) {
self.init(frame: CGRectZero)
}
/// create blurred background based on image
/// adds image & effect as subviews
private func setImageWithBlurEffect(img: UIImage) {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
effectView = UIVisualEffectView(effect: blurEffect)
imageView = UIImageView(image: img)
addSubview(imageView)
addSubview(effectView)
}
public override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
effectView.frame = bounds
}
}
| mit |
jiecao-fm/SwiftTheme | PlistDemo/SwitchNightCell.swift | 1 | 950 | //
// SwitchNightCell.swift
// PlistDemo
//
// Created by Gesen on 16/3/2.
// Copyright © 2016年 Gesen. All rights reserved.
//
import UIKit
import SwiftTheme
class SwitchNightCell: BaseCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var nightIcon: UIImageView!
@IBOutlet weak var nightSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
title.theme_textColor = "Global.textColor"
nightIcon.theme_image = "SwitchNightCell.iconImage"
updateNightSwitch()
NotificationCenter.default.addObserver(self, selector: #selector(updateNightSwitch), name: NSNotification.Name(rawValue: ThemeUpdateNotification), object: nil)
}
@IBAction func changeNight(_ sender: UISwitch) {
MyThemes.switchNight(sender.isOn)
}
@objc fileprivate func updateNightSwitch() {
nightSwitch.isOn = MyThemes.isNight()
}
}
| mit |
techmehra/AJCountryPicker | AJCountryPicker/Source/NibOwnerLoadable.swift | 1 | 1592 |
import UIKit
// MARK: Protocol Definition
/// Make your UIView subclasses conform to this protocol when:
/// * they *are* NIB-based, and
/// * this class is used as the XIB's File's Owner
///
/// to be able to instantiate them from the NIB in a type-safe manner
public protocol NibOwnerLoadable: class {
/// The nib file to use to load a new instance of the View designed in a XIB
static var nib: UINib { get }
}
// MARK: Default implementation
public extension NibOwnerLoadable {
/// By default, use the nib which have the same name as the name of the class,
/// and located in the bundle of that class
static var nib: UINib {
return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
}
}
// MARK: Support for instantiation from NIB
public extension NibOwnerLoadable where Self: UIView {
/**
Adds content loaded from the nib to the end of the receiver's list of subviews and adds constraints automatically.
*/
func loadNibContent() {
let layoutAttributes: [NSLayoutAttribute] = [.top, .leading, .bottom, .trailing]
for view in Self.nib.instantiate(withOwner: self, options: nil) {
if let view = view as? UIView {
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
layoutAttributes.forEach { attribute in
self.addConstraint(NSLayoutConstraint(item: view,
attribute: attribute,
relatedBy: .equal,
toItem: self,
attribute: attribute,
multiplier: 1,
constant: 0.0))
}
}
}
}
}
| mit |
overtake/TelegramSwift | packages/TGUIKit/Sources/GridNode.swift | 1 | 61950 | import Cocoa
import AVFoundation
public struct GridNodeInsertItem {
public let index: Int
public let item: GridItem
public let previousIndex: Int?
public init(index: Int, item: GridItem, previousIndex: Int?) {
self.index = index
self.item = item
self.previousIndex = previousIndex
}
}
public struct GridNodeUpdateItem {
public let index: Int
public let previousIndex: Int
public let item: GridItem
public init(index: Int, previousIndex: Int, item: GridItem) {
self.index = index
self.previousIndex = previousIndex
self.item = item
}
}
public enum GridNodeScrollToItemPosition {
case top
case bottom
case center
}
public struct GridNodeScrollToItem {
public let index: Int
public let position: GridNodeScrollToItemPosition
public let transition: ContainedViewLayoutTransition
public let directionHint: GridNodePreviousItemsTransitionDirectionHint
public let adjustForSection: Bool
public let adjustForTopInset: Bool
public init(index: Int, position: GridNodeScrollToItemPosition, transition: ContainedViewLayoutTransition, directionHint: GridNodePreviousItemsTransitionDirectionHint, adjustForSection: Bool, adjustForTopInset: Bool = false) {
self.index = index
self.position = position
self.transition = transition
self.directionHint = directionHint
self.adjustForSection = adjustForSection
self.adjustForTopInset = adjustForTopInset
}
}
public enum GridNodeLayoutType: Equatable {
case fixed(itemSize: CGSize, lineSpacing: CGFloat)
case balanced(idealHeight: CGFloat)
public static func ==(lhs: GridNodeLayoutType, rhs: GridNodeLayoutType) -> Bool {
switch lhs {
case let .fixed(itemSize, lineSpacing):
if case .fixed(itemSize, lineSpacing) = rhs {
return true
} else {
return false
}
case let .balanced(idealHeight):
if case .balanced(idealHeight) = rhs {
return true
} else {
return false
}
}
}
}
public struct GridNodeLayout: Equatable {
public let size: CGSize
public let insets: NSEdgeInsets
public let scrollIndicatorInsets: NSEdgeInsets?
public let preloadSize: CGFloat
public let type: GridNodeLayoutType
public init(size: CGSize, insets: NSEdgeInsets, scrollIndicatorInsets: NSEdgeInsets? = nil, preloadSize: CGFloat, type: GridNodeLayoutType) {
self.size = size
self.insets = insets
self.scrollIndicatorInsets = scrollIndicatorInsets
self.preloadSize = preloadSize
self.type = type
}
public static func ==(lhs: GridNodeLayout, rhs: GridNodeLayout) -> Bool {
return lhs.size.equalTo(rhs.size) && NSEdgeInsetsEqual(lhs.insets, rhs.insets) && lhs.preloadSize.isEqual(to: rhs.preloadSize) && lhs.type == rhs.type
}
}
public struct GridNodeUpdateLayout {
public let layout: GridNodeLayout
public let transition: ContainedViewLayoutTransition
public init(layout: GridNodeLayout, transition: ContainedViewLayoutTransition) {
self.layout = layout
self.transition = transition
}
}
/*private func binarySearch(_ inputArr: [GridNodePresentationItem], searchItem: CGFloat) -> Int? {
if inputArr.isEmpty {
return nil
}
var lowerPosition = inputArr[0].frame.origin.y + inputArr[0].frame.size.height
var upperPosition = inputArr[inputArr.count - 1].frame.origin.y
if lowerPosition > upperPosition {
return nil
}
while (true) {
let currentPosition = (lowerIndex + upperIndex) / 2
if (inputArr[currentIndex] == searchItem) {
return currentIndex
} else if (lowerIndex > upperIndex) {
return nil
} else {
if (inputArr[currentIndex] > searchItem) {
upperIndex = currentIndex - 1
} else {
lowerIndex = currentIndex + 1
}
}
}
}*/
public enum GridNodeStationaryItems {
case none
case all
case indices(Set<Int>)
}
public struct GridNodeTransaction {
public let deleteItems: [Int]
public let insertItems: [GridNodeInsertItem]
public let updateItems: [GridNodeUpdateItem]
public let scrollToItem: GridNodeScrollToItem?
public let updateLayout: GridNodeUpdateLayout?
public let itemTransition: ContainedViewLayoutTransition
public let stationaryItems: GridNodeStationaryItems
public let updateFirstIndexInSectionOffset: Int?
public init(deleteItems: [Int], insertItems: [GridNodeInsertItem], updateItems: [GridNodeUpdateItem], scrollToItem: GridNodeScrollToItem?, updateLayout: GridNodeUpdateLayout?, itemTransition: ContainedViewLayoutTransition, stationaryItems: GridNodeStationaryItems, updateFirstIndexInSectionOffset: Int?) {
self.deleteItems = deleteItems
self.insertItems = insertItems
self.updateItems = updateItems
self.scrollToItem = scrollToItem
self.updateLayout = updateLayout
self.itemTransition = itemTransition
self.stationaryItems = stationaryItems
self.updateFirstIndexInSectionOffset = updateFirstIndexInSectionOffset
}
}
private struct GridNodePresentationItem {
let index: Int
let frame: CGRect
}
private struct GridNodePresentationSection {
let section: GridSection
let frame: CGRect
}
private struct GridNodePresentationLayout {
let layout: GridNodeLayout
let contentOffset: CGPoint
let contentSize: CGSize
let items: [GridNodePresentationItem]
let sections: [GridNodePresentationSection]
}
public enum GridNodePreviousItemsTransitionDirectionHint {
case up
case down
}
private struct GridNodePresentationLayoutTransition {
let layout: GridNodePresentationLayout
let directionHint: GridNodePreviousItemsTransitionDirectionHint
let transition: ContainedViewLayoutTransition
}
public struct GridNodeCurrentPresentationLayout {
public let layout: GridNodeLayout
public let contentOffset: CGPoint
public let contentSize: CGSize
}
private final class GridNodeItemLayout {
let contentSize: CGSize
let items: [GridNodePresentationItem]
let sections: [GridNodePresentationSection]
init(contentSize: CGSize, items: [GridNodePresentationItem], sections: [GridNodePresentationSection]) {
self.contentSize = contentSize
self.items = items
self.sections = sections
}
}
public struct GridNodeDisplayedItemRange: Equatable {
public let loadedRange: Range<Int>?
public let visibleRange: Range<Int>?
public static func ==(lhs: GridNodeDisplayedItemRange, rhs: GridNodeDisplayedItemRange) -> Bool {
return lhs.loadedRange == rhs.loadedRange && lhs.visibleRange == rhs.visibleRange
}
}
private struct WrappedGridSection: Hashable {
let section: GridSection
init(_ section: GridSection) {
self.section = section
}
var hashValue: Int {
return self.section.hashValue
}
static func ==(lhs: WrappedGridSection, rhs: WrappedGridSection) -> Bool {
return lhs.section.isEqual(to: rhs.section)
}
}
public struct GridNodeVisibleItems {
public let top: (Int, GridItem)?
public let bottom: (Int, GridItem)?
public let topVisible: (Int, GridItem)?
public let bottomVisible: (Int, GridItem)?
public let topSectionVisible: GridSection?
public let count: Int
}
private struct WrappedGridItemNode: Hashable {
let node: View
var hashValue: Int {
return node.hashValue
}
static func ==(lhs: WrappedGridItemNode, rhs: WrappedGridItemNode) -> Bool {
return lhs.node === rhs.node
}
}
open class GridNode: ScrollView, InteractionContentViewProtocol, AppearanceViewProtocol {
private var gridLayout = GridNodeLayout(size: CGSize(), insets: NSEdgeInsets(), preloadSize: 0.0, type: .fixed(itemSize: CGSize(), lineSpacing: 0.0))
private var firstIndexInSectionOffset: Int = 0
private var items: [GridItem] = []
private var itemNodes: [Int: GridItemNode] = [:]
private var sectionNodes: [WrappedGridSection: View] = [:]
private var itemLayout = GridNodeItemLayout(contentSize: CGSize(), items: [], sections: [])
private var cachedNodes:[GridItemNode] = []
private var applyingContentOffset = false
public var visibleItemsUpdated: ((GridNodeVisibleItems) -> Void)?
public var presentationLayoutUpdated: ((GridNodeCurrentPresentationLayout, ContainedViewLayoutTransition) -> Void)?
public final var floatingSections = false
private let document: View
public override init(frame frameRect: NSRect) {
document = View(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height))
super.init(frame: frameRect)
document.backgroundColor = .clear
deltaCorner = 45
self.autoresizesSubviews = true;
// self.autoresizingMask = [NSAutoresizingMaskOptions.width, NSAutoresizingMaskOptions.height]
self.hasVerticalScroller = true
self.documentView = document
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func updateLocalizationAndTheme(theme: PresentationTheme) {
guard let documentView = documentView else {return}
layer?.backgroundColor = presentation.colors.background.cgColor
for view in documentView.subviews {
if let view = view as? AppearanceViewProtocol {
view.updateLocalizationAndTheme(theme: theme)
}
}
}
public func transaction(_ transaction: GridNodeTransaction, completion: (GridNodeDisplayedItemRange) -> Void) {
if transaction.deleteItems.isEmpty && transaction.insertItems.isEmpty && transaction.scrollToItem == nil && transaction.updateItems.isEmpty && (transaction.updateLayout == nil || transaction.updateLayout!.layout == self.gridLayout && (transaction.updateFirstIndexInSectionOffset == nil || transaction.updateFirstIndexInSectionOffset == self.firstIndexInSectionOffset)) {
if let presentationLayoutUpdated = self.presentationLayoutUpdated {
presentationLayoutUpdated(GridNodeCurrentPresentationLayout(layout: self.gridLayout, contentOffset: documentOffset, contentSize: self.itemLayout.contentSize), .immediate)
}
completion(self.displayedItemRange())
return
}
if let updateFirstIndexInSectionOffset = transaction.updateFirstIndexInSectionOffset {
self.firstIndexInSectionOffset = updateFirstIndexInSectionOffset
}
var layoutTransactionOffset: CGFloat = 0.0
if let updateLayout = transaction.updateLayout {
layoutTransactionOffset += updateLayout.layout.insets.top - self.gridLayout.insets.top
self.gridLayout = updateLayout.layout
}
for updatedItem in transaction.updateItems {
self.items[updatedItem.previousIndex] = updatedItem.item
if let itemNode = self.itemNodes[updatedItem.previousIndex] {
updatedItem.item.update(node: itemNode)
}
}
var removedNodes: [GridItemNode] = []
if !transaction.deleteItems.isEmpty || !transaction.insertItems.isEmpty {
let deleteItems = transaction.deleteItems.sorted()
for deleteItemIndex in deleteItems.reversed() {
self.items.remove(at: deleteItemIndex)
if let itemNode = self.itemNodes[deleteItemIndex] {
removedNodes.append(itemNode)
self.removeItemNodeWithIndex(deleteItemIndex, removeNode: false)
} else {
self.removeItemNodeWithIndex(deleteItemIndex, removeNode: true)
}
}
var remappedDeletionItemNodes: [Int: GridItemNode] = [:]
for (index, itemNode) in self.itemNodes {
var indexOffset = 0
for deleteIndex in deleteItems {
if deleteIndex < index {
indexOffset += 1
} else {
break
}
}
remappedDeletionItemNodes[index - indexOffset] = itemNode
}
let insertItems = transaction.insertItems.sorted(by: { $0.index < $1.index })
if self.items.count == 0 && !insertItems.isEmpty {
if insertItems[0].index != 0 {
fatalError("transaction: invalid insert into empty list")
}
}
for insertedItem in insertItems {
self.items.insert(insertedItem.item, at: insertedItem.index)
}
let sortedInsertItems = transaction.insertItems.sorted(by: { $0.index < $1.index })
var remappedInsertionItemNodes: [Int: GridItemNode] = [:]
for (index, itemNode) in remappedDeletionItemNodes {
var indexOffset = 0
for insertedItem in sortedInsertItems {
if insertedItem.index <= index + indexOffset {
indexOffset += 1
}
}
remappedInsertionItemNodes[index + indexOffset] = itemNode
}
self.itemNodes = remappedInsertionItemNodes
}
let previousLayoutWasEmpty = self.itemLayout.items.isEmpty
self.itemLayout = self.generateItemLayout()
let generatedScrollToItem: GridNodeScrollToItem?
if let scrollToItem = transaction.scrollToItem {
generatedScrollToItem = scrollToItem
} else if previousLayoutWasEmpty {
generatedScrollToItem = GridNodeScrollToItem(index: 0, position: .top, transition: .immediate, directionHint: .up, adjustForSection: true, adjustForTopInset: true)
} else {
generatedScrollToItem = nil
}
self.applyPresentaionLayoutTransition(self.generatePresentationLayoutTransition(stationaryItems: transaction.stationaryItems, layoutTransactionOffset: layoutTransactionOffset, scrollToItem: generatedScrollToItem), removedNodes: removedNodes, updateLayoutTransition: transaction.updateLayout?.transition, itemTransition: transaction.itemTransition, completion: completion)
}
var rows: Int {
return items.count / inRowCount
}
var inRowCount: Int {
var count: Int = 0
if let range = displayedItemRange().visibleRange {
let y: CGFloat? = itemNodes[range.lowerBound]?.frame.minY
for item in itemNodes {
if item.value.frame.minY == y {
count += 1
}
}
} else {
return 1
}
return count
}
private var previousScroll:ScrollPosition?
public var scrollHandler:(_ scrollPosition:ScrollPosition) ->Void = {_ in} {
didSet {
previousScroll = nil
}
}
open override func viewDidMoveToSuperview() {
if superview != nil {
NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: self.contentView, queue: nil, using: { [weak self] notification in
if let strongSelf = self {
if !strongSelf.applyingContentOffset {
strongSelf.applyPresentaionLayoutTransition(strongSelf.generatePresentationLayoutTransition(layoutTransactionOffset: 0.0), removedNodes: [], updateLayoutTransition: nil, itemTransition: .immediate, completion: { _ in })
}
let reqCount = 1
if let range = strongSelf.displayedItemRange().visibleRange {
let range = NSMakeRange(range.lowerBound / strongSelf.inRowCount, range.upperBound / strongSelf.inRowCount - range.lowerBound / strongSelf.inRowCount)
let scroll = strongSelf.scrollPosition()
if (!strongSelf.clipView.isAnimateScrolling) {
if(scroll.current.rect != strongSelf.previousScroll?.rect) {
switch(scroll.current.direction) {
case .top:
if(range.location <= reqCount) {
strongSelf.scrollHandler(scroll.current)
strongSelf.previousScroll = scroll.current
}
case .bottom:
if(strongSelf.rows - (range.location + range.length) <= reqCount) {
strongSelf.scrollHandler(scroll.current)
strongSelf.previousScroll = scroll.current
}
case .none:
strongSelf.scrollHandler(scroll.current)
strongSelf.previousScroll = scroll.current
}
}
}
}
strongSelf.reflectScrolledClipView(strongSelf.contentView)
}
})
} else {
NotificationCenter.default.removeObserver(self)
}
}
open override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
}
private func displayedItemRange() -> GridNodeDisplayedItemRange {
var minIndex: Int?
var maxIndex: Int?
for index in self.itemNodes.keys {
if minIndex == nil || minIndex! > index {
minIndex = index
}
if maxIndex == nil || maxIndex! < index {
maxIndex = index
}
}
if let minIndex = minIndex, let maxIndex = maxIndex {
return GridNodeDisplayedItemRange(loadedRange: minIndex ..< maxIndex, visibleRange: minIndex ..< maxIndex)
} else {
return GridNodeDisplayedItemRange(loadedRange: nil, visibleRange: nil)
}
}
private func generateItemLayout() -> GridNodeItemLayout {
if CGFloat(0.0).isLess(than: gridLayout.size.width) && CGFloat(0.0).isLess(than: gridLayout.size.height) && !self.items.isEmpty {
var contentSize = CGSize(width: gridLayout.size.width, height: 0.0)
var items: [GridNodePresentationItem] = []
var sections: [GridNodePresentationSection] = []
switch gridLayout.type {
case let .fixed(itemSize, lineSpacing):
// let s = floorToScreenPixels(backingScaleFactor, gridLayout.size.width/floor(gridLayout.size.width/itemSize.width))
// let itemSize = NSMakeSize(s, s)
let itemsInRow = Int(gridLayout.size.width / itemSize.width)
let itemsInRowWidth = CGFloat(itemsInRow) * itemSize.width
let remainingWidth = max(0.0, gridLayout.size.width - itemsInRowWidth)
let itemSpacing = floorToScreenPixels(backingScaleFactor, remainingWidth / CGFloat(itemsInRow + 1))
var incrementedCurrentRow = false
var nextItemOrigin = CGPoint(x: itemSpacing, y: 0.0)
var index = 0
var previousSection: GridSection?
for item in self.items {
let section = item.section
var keepSection = true
if let previousSection = previousSection, let section = section {
keepSection = previousSection.isEqual(to: section)
} else if (previousSection != nil) != (section != nil) {
keepSection = false
}
if !keepSection {
if incrementedCurrentRow {
nextItemOrigin.x = itemSpacing
nextItemOrigin.y += itemSize.height + lineSpacing
incrementedCurrentRow = false
}
if let section = section {
sections.append(GridNodePresentationSection(section: section, frame: CGRect(origin: CGPoint(x: 0.0, y: nextItemOrigin.y), size: CGSize(width: gridLayout.size.width, height: section.height))))
nextItemOrigin.y += section.height
contentSize.height += section.height
}
}
previousSection = section
if !incrementedCurrentRow {
incrementedCurrentRow = true
contentSize.height += itemSize.height + lineSpacing
}
if index == 0 {
let itemsInRow = Int(gridLayout.size.width) / Int(itemSize.width)
let normalizedIndexOffset = self.firstIndexInSectionOffset % itemsInRow
nextItemOrigin.x += (itemSize.width + itemSpacing) * CGFloat(normalizedIndexOffset)
}
items.append(GridNodePresentationItem(index: index, frame: CGRect(origin: nextItemOrigin, size: itemSize)))
index += 1
nextItemOrigin.x += itemSize.width + itemSpacing
if nextItemOrigin.x + itemSize.width > gridLayout.size.width {
nextItemOrigin.x = itemSpacing
nextItemOrigin.y += itemSize.height + lineSpacing
incrementedCurrentRow = false
}
}
case let .balanced(idealHeight):
var weights: [Int] = []
for item in self.items {
weights.append(Int(item.aspectRatio * 100))
}
var totalItemSize: CGFloat = 0.0
for i in 0 ..< self.items.count {
totalItemSize += self.items[i].aspectRatio * idealHeight
}
let numberOfRows = max(Int(round(totalItemSize / gridLayout.size.width)), 1)
let partition = linearPartitionForWeights(weights, numberOfPartitions:numberOfRows)
var i = 0
var offset = CGPoint(x: 0.0, y: 0.0)
var previousItemSize: CGFloat = 0.0
var contentMaxValueInScrollDirection: CGFloat = 0.0
let maxWidth = gridLayout.size.width
let minimumInteritemSpacing: CGFloat = 1.0
let minimumLineSpacing: CGFloat = 1.0
let viewportWidth: CGFloat = gridLayout.size.width
let preferredRowSize = idealHeight
var rowIndex = -1
for row in partition {
rowIndex += 1
var summedRatios: CGFloat = 0.0
var j = i
var n = i + row.count
while j < n {
summedRatios += self.items[j].aspectRatio
j += 1
}
var rowSize = gridLayout.size.width - (CGFloat(row.count - 1) * minimumInteritemSpacing)
if rowIndex == partition.count - 1 {
if row.count < 2 {
rowSize = floor(viewportWidth / 3.0) - (CGFloat(row.count - 1) * minimumInteritemSpacing)
} else if row.count < 3 {
rowSize = floor(viewportWidth * 2.0 / 3.0) - (CGFloat(row.count - 1) * minimumInteritemSpacing)
}
}
j = i
n = i + row.count
while j < n {
let preferredAspectRatio = self.items[j].aspectRatio
let actualSize = CGSize(width: round(rowSize / summedRatios * (preferredAspectRatio)), height: preferredRowSize)
var frame = CGRect(x: offset.x, y: offset.y, width: actualSize.width, height: actualSize.height)
if frame.origin.x + frame.size.width >= maxWidth - 2.0 {
frame.size.width = max(1.0, maxWidth - frame.origin.x)
}
items.append(GridNodePresentationItem(index: j, frame: frame))
offset.x += actualSize.width + minimumInteritemSpacing
previousItemSize = actualSize.height
contentMaxValueInScrollDirection = frame.maxY
j += 1
}
if row.count > 0 {
offset = CGPoint(x: 0.0, y: offset.y + previousItemSize + minimumLineSpacing)
}
i += row.count
}
contentSize = CGSize(width: gridLayout.size.width, height: contentMaxValueInScrollDirection)
}
return GridNodeItemLayout(contentSize: contentSize, items: items, sections: sections)
} else {
return GridNodeItemLayout(contentSize: CGSize(), items: [], sections: [])
}
}
private func generatePresentationLayoutTransition(stationaryItems: GridNodeStationaryItems = .none, layoutTransactionOffset: CGFloat, scrollToItem: GridNodeScrollToItem? = nil) -> GridNodePresentationLayoutTransition {
if CGFloat(0.0).isLess(than: gridLayout.size.width) && CGFloat(0.0).isLess(than: gridLayout.size.height) && !self.itemLayout.items.isEmpty {
var transitionDirectionHint: GridNodePreviousItemsTransitionDirectionHint = .up
var transition: ContainedViewLayoutTransition = .immediate
let contentOffset: CGPoint
var updatedStationaryItems = stationaryItems
if scrollToItem != nil {
updatedStationaryItems = .none
}
switch updatedStationaryItems {
case .none:
if let scrollToItem = scrollToItem {
let itemFrame = self.itemLayout.items[scrollToItem.index]
var additionalOffset: CGFloat = 0.0
if scrollToItem.adjustForSection {
var adjustForSection: GridSection?
if scrollToItem.index == 0 {
if let itemSection = self.items[scrollToItem.index].section {
adjustForSection = itemSection
}
} else {
let itemSection = self.items[scrollToItem.index].section
let previousSection = self.items[scrollToItem.index - 1].section
if let itemSection = itemSection, let previousSection = previousSection {
if !itemSection.isEqual(to: previousSection) {
adjustForSection = itemSection
}
} else if let itemSection = itemSection {
adjustForSection = itemSection
}
}
if let adjustForSection = adjustForSection {
additionalOffset = -adjustForSection.height
}
if scrollToItem.adjustForTopInset {
additionalOffset += -gridLayout.insets.top
}
} else if scrollToItem.adjustForTopInset {
additionalOffset = -gridLayout.insets.top
}
let displayHeight = max(0.0, self.gridLayout.size.height - self.gridLayout.insets.top - self.gridLayout.insets.bottom)
var verticalOffset: CGFloat
switch scrollToItem.position {
case .top:
verticalOffset = itemFrame.frame.minY + additionalOffset
case .center:
verticalOffset = floor(itemFrame.frame.minY + itemFrame.frame.size.height / 2.0 - displayHeight / 2.0 - self.gridLayout.insets.top) + additionalOffset
case .bottom:
verticalOffset = itemFrame.frame.maxY - displayHeight + additionalOffset
}
if verticalOffset > self.itemLayout.contentSize.height + self.gridLayout.insets.bottom - self.gridLayout.size.height {
verticalOffset = self.itemLayout.contentSize.height + self.gridLayout.insets.bottom - self.gridLayout.size.height
}
if verticalOffset < -self.gridLayout.insets.top {
verticalOffset = -self.gridLayout.insets.top
}
transitionDirectionHint = scrollToItem.directionHint
transition = scrollToItem.transition
contentOffset = CGPoint(x: 0.0, y: verticalOffset)
} else {
if !layoutTransactionOffset.isZero {
var verticalOffset = self.contentOffset.y - layoutTransactionOffset
if verticalOffset > self.itemLayout.contentSize.height + self.gridLayout.insets.bottom - self.gridLayout.size.height {
verticalOffset = self.itemLayout.contentSize.height + self.gridLayout.insets.bottom - self.gridLayout.size.height
}
if verticalOffset < -self.gridLayout.insets.top {
verticalOffset = -self.gridLayout.insets.top
}
contentOffset = CGPoint(x: 0.0, y: verticalOffset)
} else {
contentOffset = self.contentOffset
}
}
case let .indices(stationaryItemIndices):
var selectedContentOffset: CGPoint?
for (index, itemNode) in self.itemNodes {
if stationaryItemIndices.contains(index) {
//let currentScreenOffset = itemNode.frame.origin.y - self.scrollView.contentOffset.y
selectedContentOffset = CGPoint(x: 0.0, y: self.itemLayout.items[index].frame.origin.y - itemNode.frame.origin.y + self.contentOffset.y)
break
}
}
if let selectedContentOffset = selectedContentOffset {
contentOffset = selectedContentOffset
} else {
contentOffset = documentOffset
}
case .all:
var selectedContentOffset: CGPoint?
for (index, itemNode) in self.itemNodes {
//let currentScreenOffset = itemNode.frame.origin.y - self.scrollView.contentOffset.y
selectedContentOffset = CGPoint(x: 0.0, y: self.itemLayout.items[index].frame.origin.y - itemNode.frame.origin.y + self.contentOffset.y)
break
}
if let selectedContentOffset = selectedContentOffset {
contentOffset = selectedContentOffset
} else {
contentOffset = documentOffset
}
}
let lowerDisplayBound = contentOffset.y - self.gridLayout.preloadSize
let upperDisplayBound = contentOffset.y + self.gridLayout.size.height + self.gridLayout.preloadSize
var presentationItems: [GridNodePresentationItem] = []
var validSections = Set<WrappedGridSection>()
for item in self.itemLayout.items {
if item.frame.origin.y < lowerDisplayBound {
continue
}
if item.frame.origin.y + item.frame.size.height > upperDisplayBound {
break
}
presentationItems.append(item)
if self.floatingSections {
if let section = self.items[item.index].section {
validSections.insert(WrappedGridSection(section))
}
}
}
var presentationSections: [GridNodePresentationSection] = []
for section in self.itemLayout.sections {
if section.frame.origin.y < lowerDisplayBound {
if !validSections.contains(WrappedGridSection(section.section)) {
continue
}
}
if section.frame.origin.y + section.frame.size.height > upperDisplayBound {
break
}
presentationSections.append(section)
}
return GridNodePresentationLayoutTransition(layout: GridNodePresentationLayout(layout: self.gridLayout, contentOffset: contentOffset, contentSize: self.itemLayout.contentSize, items: presentationItems, sections: presentationSections), directionHint: transitionDirectionHint, transition: transition)
} else {
return GridNodePresentationLayoutTransition(layout: GridNodePresentationLayout(layout: self.gridLayout, contentOffset: CGPoint(), contentSize: self.itemLayout.contentSize, items: [], sections: []), directionHint: .up, transition: .immediate)
}
}
private func lowestSectionNode() -> View? {
var lowestHeaderNode: View?
var lowestHeaderNodeIndex: Int?
for (_, headerNode) in self.sectionNodes {
if let index = self.subviews.index(of: headerNode) {
if lowestHeaderNodeIndex == nil || index < lowestHeaderNodeIndex! {
lowestHeaderNodeIndex = index
lowestHeaderNode = headerNode
}
}
}
return lowestHeaderNode
}
private func applyPresentaionLayoutTransition(_ presentationLayoutTransition: GridNodePresentationLayoutTransition, removedNodes: [GridItemNode], updateLayoutTransition: ContainedViewLayoutTransition?, itemTransition: ContainedViewLayoutTransition, completion: (GridNodeDisplayedItemRange) -> Void) {
var previousItemFrames: [WrappedGridItemNode: CGRect]?
var saveItemFrames = false
switch presentationLayoutTransition.transition {
case .animated:
saveItemFrames = true
case .immediate:
break
}
if case .animated = itemTransition {
saveItemFrames = true
}
if saveItemFrames {
var itemFrames: [WrappedGridItemNode: CGRect] = [:]
let contentOffset = self.contentOffset
for (_, itemNode) in self.itemNodes {
itemFrames[WrappedGridItemNode(node: itemNode)] = itemNode.frame.offsetBy(dx: 0.0, dy: -contentOffset.y)
}
for (_, sectionNode) in self.sectionNodes {
itemFrames[WrappedGridItemNode(node: sectionNode)] = sectionNode.frame.offsetBy(dx: 0.0, dy: -contentOffset.y)
}
for itemNode in removedNodes {
itemFrames[WrappedGridItemNode(node: itemNode)] = itemNode.frame.offsetBy(dx: 0.0, dy: -contentOffset.y)
}
previousItemFrames = itemFrames
}
applyingContentOffset = true
self.documentView?.setFrameSize(presentationLayoutTransition.layout.contentSize)
self.contentView.contentInsets = presentationLayoutTransition.layout.layout.insets
if !documentOffset.equalTo(presentationLayoutTransition.layout.contentOffset) || self.bounds.size != presentationLayoutTransition.layout.layout.size {
//self.scrollView.contentOffset = presentationLayoutTransition.layout.contentOffset
self.contentView.bounds = CGRect(origin: presentationLayoutTransition.layout.contentOffset, size: self.contentView.bounds.size)
}
reflectScrolledClipView(contentView)
applyingContentOffset = false
let lowestSectionNode: View? = self.lowestSectionNode()
var existingItemIndices = Set<Int>()
for item in presentationLayoutTransition.layout.items {
existingItemIndices.insert(item.index)
if let itemNode = self.itemNodes[item.index] {
if itemNode.frame != item.frame {
itemNode.frame = item.frame
}
} else {
let cachedNode = !cachedNodes.isEmpty ? cachedNodes.removeFirst() : nil
let itemNode = self.items[item.index].node(layout: presentationLayoutTransition.layout.layout, gridNode: self, cachedNode: cachedNode)
itemNode.frame = item.frame
self.addItemNode(index: item.index, itemNode: itemNode, lowestSectionNode: lowestSectionNode)
}
}
var existingSections = Set<WrappedGridSection>()
for i in 0 ..< presentationLayoutTransition.layout.sections.count {
let section = presentationLayoutTransition.layout.sections[i]
let wrappedSection = WrappedGridSection(section.section)
existingSections.insert(wrappedSection)
var sectionFrame = section.frame
if self.floatingSections {
var maxY = CGFloat.greatestFiniteMagnitude
if i != presentationLayoutTransition.layout.sections.count - 1 {
maxY = presentationLayoutTransition.layout.sections[i + 1].frame.minY - sectionFrame.height
}
sectionFrame.origin.y = max(sectionFrame.minY, min(maxY, presentationLayoutTransition.layout.contentOffset.y + presentationLayoutTransition.layout.layout.insets.top))
}
if let sectionNode = self.sectionNodes[wrappedSection] {
sectionNode.frame = sectionFrame
document.addSubview(sectionNode)
} else {
let sectionNode = section.section.node()
sectionNode.frame = sectionFrame
self.addSectionNode(section: wrappedSection, sectionNode: sectionNode)
}
}
if let previousItemFrames = previousItemFrames, case let .animated(duration, curve) = presentationLayoutTransition.transition {
let contentOffset = presentationLayoutTransition.layout.contentOffset
var offset: CGFloat?
for (index, itemNode) in self.itemNodes {
if let previousFrame = previousItemFrames[WrappedGridItemNode(node: itemNode)], existingItemIndices.contains(index) {
let currentFrame = itemNode.frame.offsetBy(dx: 0.0, dy: -presentationLayoutTransition.layout.contentOffset.y)
offset = previousFrame.origin.y - currentFrame.origin.y
break
}
}
if offset == nil {
var previousUpperBound: CGFloat?
var previousLowerBound: CGFloat?
for (_, frame) in previousItemFrames {
if previousUpperBound == nil || previousUpperBound! > frame.minY {
previousUpperBound = frame.minY
}
if previousLowerBound == nil || previousLowerBound! < frame.maxY {
previousLowerBound = frame.maxY
}
}
var updatedUpperBound: CGFloat?
var updatedLowerBound: CGFloat?
for item in presentationLayoutTransition.layout.items {
let frame = item.frame.offsetBy(dx: 0.0, dy: -contentOffset.y)
if updatedUpperBound == nil || updatedUpperBound! > frame.minY {
updatedUpperBound = frame.minY
}
if updatedLowerBound == nil || updatedLowerBound! < frame.maxY {
updatedLowerBound = frame.maxY
}
}
for section in presentationLayoutTransition.layout.sections {
let frame = section.frame.offsetBy(dx: 0.0, dy: -contentOffset.y)
if updatedUpperBound == nil || updatedUpperBound! > frame.minY {
updatedUpperBound = frame.minY
}
if updatedLowerBound == nil || updatedLowerBound! < frame.maxY {
updatedLowerBound = frame.maxY
}
}
if let updatedUpperBound = updatedUpperBound, let updatedLowerBound = updatedLowerBound {
switch presentationLayoutTransition.directionHint {
case .up:
offset = -(updatedLowerBound - (previousUpperBound ?? 0.0))
case .down:
offset = -(updatedUpperBound - (previousLowerBound ?? presentationLayoutTransition.layout.layout.size.height))
}
}
}
if let offset = offset {
let timingFunction: CAMediaTimingFunctionName = curve.timingFunction
for (index, itemNode) in self.itemNodes where existingItemIndices.contains(index) {
itemNode.layer!.animatePosition(from: CGPoint(x: 0.0, y: offset), to: CGPoint(), duration: duration, timingFunction: timingFunction, additive: true)
}
for (wrappedSection, sectionNode) in self.sectionNodes where existingSections.contains(wrappedSection) {
sectionNode.layer!.animatePosition(from: CGPoint(x: 0.0, y: offset), to: CGPoint(), duration: duration, timingFunction: timingFunction, additive: true)
}
for index in self.itemNodes.keys {
if !existingItemIndices.contains(index) {
let itemNode = self.itemNodes[index]!
if let previousFrame = previousItemFrames[WrappedGridItemNode(node: itemNode)] {
self.removeItemNodeWithIndex(index, removeNode: false)
let position = CGPoint(x: previousFrame.midX, y: previousFrame.midY)
itemNode.layer!.animatePosition(from: CGPoint(x: position.x, y: position.y + contentOffset.y), to: CGPoint(x: position.x, y: position.y + contentOffset.y - offset), duration: duration, timingFunction: timingFunction, removeOnCompletion: false, completion: { [weak itemNode] _ in
itemNode?.removeFromSuperview()
})
} else {
self.removeItemNodeWithIndex(index, removeNode: true)
}
}
}
for itemNode in removedNodes {
if let previousFrame = previousItemFrames[WrappedGridItemNode(node: itemNode)] {
let position = CGPoint(x: previousFrame.midX, y: previousFrame.midY)
itemNode.layer!.animatePosition(from: CGPoint(x: position.x, y: position.y + contentOffset.y), to: CGPoint(x: position.x, y: position.y + contentOffset.y - offset), duration: duration, timingFunction: timingFunction, removeOnCompletion: false, completion: { [weak itemNode] _ in
itemNode?.removeFromSuperview()
})
} else {
itemNode.removeFromSuperview()
}
}
for wrappedSection in self.sectionNodes.keys {
if !existingSections.contains(wrappedSection) {
let sectionNode = self.sectionNodes[wrappedSection]!
if let previousFrame = previousItemFrames[WrappedGridItemNode(node: sectionNode)] {
self.removeSectionNodeWithSection(wrappedSection, removeNode: false)
let position = CGPoint(x: previousFrame.midX, y: previousFrame.midY)
sectionNode.layer!.animatePosition(from: CGPoint(x: position.x, y: position.y + contentOffset.y), to: CGPoint(x: position.x, y: position.y + contentOffset.y - offset), duration: duration, timingFunction: timingFunction, removeOnCompletion: false, completion: { [weak sectionNode] _ in
sectionNode?.removeFromSuperview()
})
} else {
self.removeSectionNodeWithSection(wrappedSection, removeNode: true)
}
}
}
} else {
for index in self.itemNodes.keys {
if !existingItemIndices.contains(index) {
self.removeItemNodeWithIndex(index)
}
}
for wrappedSection in self.sectionNodes.keys {
if !existingSections.contains(wrappedSection) {
self.removeSectionNodeWithSection(wrappedSection)
}
}
for itemNode in removedNodes {
itemNode.removeFromSuperview()
}
}
} else if let previousItemFrames = previousItemFrames, case let .animated(duration, curve) = itemTransition {
let timingFunction: CAMediaTimingFunctionName = curve.timingFunction
for index in self.itemNodes.keys {
let itemNode = self.itemNodes[index]!
if !existingItemIndices.contains(index) {
if let _ = previousItemFrames[WrappedGridItemNode(node: itemNode)] {
self.removeItemNodeWithIndex(index, removeNode: false)
itemNode.layer!.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, timingFunction: CAMediaTimingFunctionName.easeIn, removeOnCompletion: false)
itemNode.layer!.animateScale(from: 1.0, to: 0.1, duration: 0.2, timingFunction: CAMediaTimingFunctionName.easeIn, removeOnCompletion: false, completion: { [weak itemNode] _ in
itemNode?.removeFromSuperview()
})
} else {
self.removeItemNodeWithIndex(index, removeNode: true)
}
} else if let previousFrame = previousItemFrames[WrappedGridItemNode(node: itemNode)] {
itemNode.layer!.animatePosition(from: CGPoint(x: previousFrame.midX, y: previousFrame.midY), to: itemNode.layer!.position, duration: duration, timingFunction: timingFunction)
} else {
itemNode.layer!.animateAlpha(from: 0.0, to: 1.0, duration: 0.12, timingFunction: CAMediaTimingFunctionName.easeIn)
itemNode.layer!.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.5)
}
}
for itemNode in removedNodes {
if let _ = previousItemFrames[WrappedGridItemNode(node: itemNode)] {
itemNode.layer!.animateAlpha(from: 1.0, to: 0.0, duration: 0.18, timingFunction: CAMediaTimingFunctionName.easeIn, removeOnCompletion: false)
itemNode.layer!.animateScale(from: 1.0, to: 0.1, duration: 0.18, timingFunction: CAMediaTimingFunctionName.easeIn, removeOnCompletion: false, completion: { [weak itemNode] _ in
itemNode?.removeFromSuperview()
})
} else {
itemNode.removeFromSuperview()
cachedNodes.append(itemNode)
}
}
for wrappedSection in self.sectionNodes.keys {
let sectionNode = self.sectionNodes[wrappedSection]!
if !existingSections.contains(wrappedSection) {
if let _ = previousItemFrames[WrappedGridItemNode(node: sectionNode)] {
self.removeSectionNodeWithSection(wrappedSection, removeNode: false)
sectionNode.layer!.animateAlpha(from: 1.0, to: 0.0, duration: duration, timingFunction: timingFunction, removeOnCompletion: false, completion: { [weak sectionNode] _ in
sectionNode?.removeFromSuperview()
})
} else {
self.removeSectionNodeWithSection(wrappedSection, removeNode: true)
}
} else if let previousFrame = previousItemFrames[WrappedGridItemNode(node: sectionNode)] {
sectionNode.layer!.animatePosition(from: CGPoint(x: previousFrame.midX, y: previousFrame.midY), to: sectionNode.layer!.position, duration: duration, timingFunction: timingFunction)
} else {
sectionNode.layer!.animateAlpha(from: 0.0, to: 1.0, duration: 0.2, timingFunction: CAMediaTimingFunctionName.easeIn)
}
}
} else {
for index in self.itemNodes.keys {
if !existingItemIndices.contains(index) {
self.removeItemNodeWithIndex(index)
}
}
for wrappedSection in self.sectionNodes.keys {
if !existingSections.contains(wrappedSection) {
self.removeSectionNodeWithSection(wrappedSection)
}
}
for itemNode in removedNodes {
itemNode.removeFromSuperview()
cachedNodes.append(itemNode)
}
}
completion(self.displayedItemRange())
self.updateItemNodeVisibilititesAndScrolling()
if let visibleItemsUpdated = self.visibleItemsUpdated {
if presentationLayoutTransition.layout.items.count != 0 {
let topIndex = presentationLayoutTransition.layout.items.first!.index
let bottomIndex = presentationLayoutTransition.layout.items.last!.index
var topVisible: (Int, GridItem) = (topIndex, self.items[topIndex])
let bottomVisible: (Int, GridItem) = (bottomIndex, self.items[bottomIndex])
let lowerDisplayBound = presentationLayoutTransition.layout.contentOffset.y
//let upperDisplayBound = presentationLayoutTransition.layout.contentOffset.y + self.gridLayout.size.height
for item in presentationLayoutTransition.layout.items {
if lowerDisplayBound.isLess(than: item.frame.maxY) {
topVisible = (item.index, self.items[item.index])
break
}
}
var topSectionVisible: GridSection?
for section in presentationLayoutTransition.layout.sections {
if lowerDisplayBound.isLess(than: section.frame.maxY) {
if self.itemLayout.items[topVisible.0].frame.minY > section.frame.minY {
topSectionVisible = section.section
}
break
}
}
visibleItemsUpdated(GridNodeVisibleItems(top: (topIndex, self.items[topIndex]), bottom: (bottomIndex, self.items[bottomIndex]), topVisible: topVisible, bottomVisible: bottomVisible, topSectionVisible: topSectionVisible, count: self.items.count))
} else {
visibleItemsUpdated(GridNodeVisibleItems(top: nil, bottom: nil, topVisible: nil, bottomVisible: nil, topSectionVisible: nil, count: self.items.count))
}
}
if let presentationLayoutUpdated = self.presentationLayoutUpdated {
presentationLayoutUpdated(GridNodeCurrentPresentationLayout(layout: presentationLayoutTransition.layout.layout, contentOffset: presentationLayoutTransition.layout.contentOffset, contentSize: presentationLayoutTransition.layout.contentSize), updateLayoutTransition ?? presentationLayoutTransition.transition)
}
}
private func addItemNode(index: Int, itemNode: GridItemNode, lowestSectionNode: View?) {
assert(self.itemNodes[index] == nil)
self.itemNodes[index] = itemNode
if itemNode.superview == nil {
if let lowestSectionNode = lowestSectionNode {
document.addSubview(itemNode, positioned: .below, relativeTo: lowestSectionNode)
} else {
document.addSubview(itemNode)
}
}
}
private func addSectionNode(section: WrappedGridSection, sectionNode: View) {
assert(self.sectionNodes[section] == nil)
self.sectionNodes[section] = sectionNode
if sectionNode.superview == nil {
document.addSubview(sectionNode)
}
}
private func removeItemNodeWithIndex(_ index: Int, removeNode: Bool = true) {
if let itemNode = self.itemNodes.removeValue(forKey: index) {
if removeNode {
itemNode.removeFromSuperview()
cachedNodes.append(itemNode)
}
}
}
private func removeSectionNodeWithSection(_ section: WrappedGridSection, removeNode: Bool = true) {
if let sectionNode = self.sectionNodes.removeValue(forKey: section) {
if removeNode {
sectionNode.removeFromSuperview()
}
}
}
public var itemsCount: Int {
return self.items.count
}
public var isEmpty: Bool {
return self.items.isEmpty
}
private func updateItemNodeVisibilititesAndScrolling() {
let visibleRect = self.contentView.bounds
let isScrolling = self.clipView.isScrolling
for (_, itemNode) in self.itemNodes {
let visible = itemNode.frame.intersects(visibleRect)
if itemNode.isVisibleInGrid != visible {
itemNode.isVisibleInGrid = visible
}
if itemNode.isGridScrolling != isScrolling {
itemNode.isGridScrolling = isScrolling
}
}
}
public func forEachItemNode(_ f: (View) -> Void) {
for (_, node) in self.itemNodes {
f(node)
}
}
public func contentInteractionView(for stableId: AnyHashable, animateIn: Bool) -> NSView? {
for (_, node) in itemNodes {
if node.stableId == stableId {
return node
}
}
return nil;
}
public func interactionControllerDidFinishAnimation(interactive: Bool, for stableId: AnyHashable) {
}
public func addAccesoryOnCopiedView(for stableId: AnyHashable, view: NSView) {
}
public func videoTimebase(for stableId: AnyHashable) -> CMTimebase? {
return nil
}
public func applyTimebase(for stableId: AnyHashable, timebase: CMTimebase?) {
}
public func forEachRow(_ f: ([View]) -> Void) {
var row: [View] = []
var previousMinY: CGFloat?
for index in self.itemNodes.keys.sorted() {
let itemNode = self.itemNodes[index]!
if let previousMinY = previousMinY, !previousMinY.isEqual(to: itemNode.frame.minY) {
if !row.isEmpty {
f(row)
row.removeAll()
}
}
previousMinY = itemNode.frame.minY
row.append(itemNode)
}
if !row.isEmpty {
f(row)
}
}
public func itemNodeAtPoint(_ point: CGPoint) -> View? {
for (_, node) in self.itemNodes {
if node.frame.contains(point) {
return node
}
}
return nil
}
open override func layout() {
super.layout()
gridLayout = GridNodeLayout(size: frame.size, insets: gridLayout.insets, scrollIndicatorInsets:gridLayout.scrollIndicatorInsets, preloadSize: gridLayout.preloadSize, type: gridLayout.type)
self.itemLayout = generateItemLayout()
applyPresentaionLayoutTransition(generatePresentationLayoutTransition(layoutTransactionOffset: 0), removedNodes: [], updateLayoutTransition: nil, itemTransition: .immediate, completion: {_ in})
}
public func removeAllItems() ->Void {
self.items.removeAll()
self.itemLayout = generateItemLayout()
applyPresentaionLayoutTransition(generatePresentationLayoutTransition(layoutTransactionOffset: 0.0), removedNodes: [], updateLayoutTransition: nil, itemTransition: .immediate, completion: { _ in })
}
}
private func NH_LP_TABLE_LOOKUP(_ table: inout [Int], _ i: Int, _ j: Int, _ rowsize: Int) -> Int {
return table[i * rowsize + j]
}
private func NH_LP_TABLE_LOOKUP_SET(_ table: inout [Int], _ i: Int, _ j: Int, _ rowsize: Int, _ value: Int) {
table[i * rowsize + j] = value
}
private func linearPartitionTable(_ weights: [Int], numberOfPartitions: Int) -> [Int] {
let n = weights.count
let k = numberOfPartitions
let tableSize = n * k;
var tmpTable = Array<Int>(repeatElement(0, count: tableSize))
let solutionSize = (n - 1) * (k - 1)
var solution = Array<Int>(repeatElement(0, count: solutionSize))
for i in 0 ..< n {
let offset = i != 0 ? NH_LP_TABLE_LOOKUP(&tmpTable, i - 1, 0, k) : 0
NH_LP_TABLE_LOOKUP_SET(&tmpTable, i, 0, k, Int(weights[i]) + offset)
}
for j in 0 ..< k {
NH_LP_TABLE_LOOKUP_SET(&tmpTable, 0, j, k, Int(weights[0]))
}
for i in 1 ..< n {
for j in 1 ..< k {
var currentMin = 0
var minX = Int.max
for x in 0 ..< i {
let c1 = NH_LP_TABLE_LOOKUP(&tmpTable, x, j - 1, k)
let c2 = NH_LP_TABLE_LOOKUP(&tmpTable, i, 0, k) - NH_LP_TABLE_LOOKUP(&tmpTable, x, 0, k)
let cost = max(c1, c2)
if x == 0 || cost < currentMin {
currentMin = cost;
minX = x
}
}
NH_LP_TABLE_LOOKUP_SET(&tmpTable, i, j, k, currentMin)
NH_LP_TABLE_LOOKUP_SET(&solution, i - 1, j - 1, k - 1, minX)
}
}
return solution
}
private func linearPartitionForWeights(_ weights: [Int], numberOfPartitions: Int) -> [[Int]] {
var n = weights.count
var k = numberOfPartitions
if k <= 0 {
return []
}
if k >= n {
var partition: [[Int]] = []
for weight in weights {
partition.append([weight])
}
return partition
}
if n == 1 {
return [weights]
}
var solution = linearPartitionTable(weights, numberOfPartitions: numberOfPartitions)
let solutionRowSize = numberOfPartitions - 1
k = k - 2;
n = n - 1;
var answer: [[Int]] = []
while k >= 0 {
if n < 1 {
answer.insert([], at: 0)
} else {
var currentAnswer: [Int] = []
var i = NH_LP_TABLE_LOOKUP(&solution, n - 1, k, solutionRowSize) + 1
let range = n + 1
while i < range {
currentAnswer.append(weights[i])
i += 1
}
answer.insert(currentAnswer, at: 0)
n = NH_LP_TABLE_LOOKUP(&solution, n - 1, k, solutionRowSize)
}
k = k - 1
}
var currentAnswer: [Int] = []
var i = 0
let range = n + 1
while i < range {
currentAnswer.append(weights[i])
i += 1
}
answer.insert(currentAnswer, at: 0)
return answer
}
| gpl-2.0 |
ton252/EasyDAO | Example/EasyDAO/AppDelegate.swift | 1 | 2178 | //
// AppDelegate.swift
// EasyDAO
//
// Created by ton252 on 02/14/2017.
// Copyright (c) 2017 ton252. All rights reserved.
//
import UIKit
import EasyDAO
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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 |
practicalswift/swift | validation-test/compiler_crashers_fixed/27923-swift-modulefile-gettype.swift | 65 | 447 | // 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
extension String{enum a{{}}class B{class B<f:f.c
| apache-2.0 |
debugsquad/metalic | metalic/Metal/Basic/MetalFilterBasicTest.swift | 1 | 306 | import MetalPerformanceShaders
class MetalFilterBasicTest:MetalFilter
{
required init(device:MTLDevice)
{
super.init(device:device, functionName:nil)
}
override func encode(commandBuffer:MTLCommandBuffer, sourceTexture:MTLTexture, destinationTexture:MTLTexture)
{
}
}
| mit |
huangboju/Moots | 算法学习/LeetCode/LeetCode/Rotate.swift | 1 | 334 | //
// Rotate.swift
// LeetCode
//
// Created by 黄伯驹 on 2019/4/27.
// Copyright © 2019 伯驹 黄. All rights reserved.
//
import Foundation
func rotate(_ nums: inout [Int], _ k: Int) {
for _ in 0 ..< k {
guard let n = nums.popLast() else {
continue
}
nums.insert(n, at: 0)
}
}
| mit |
jxxcarlson/exploring_swift | IOSGraphicsApp/IOSGraphicsApp/ViewController.swift | 1 | 1560 | //
// ViewController.swift
// IOSGraphicsApp
//
// Created by James Carlson on 6/21/15.
// Copyright © 2015 James Carlson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let graphicsView = GraphicsView()
let backgroundLabel = UILabel()
let statusLabel = UILabel()
func setupLabels() {
// Background label
let backgroundFrame = CGRect(x:0, y:0, width: 380, height: 640)
backgroundLabel.frame = backgroundFrame
let g: CGFloat = 0.2
backgroundLabel.backgroundColor = UIColor(red: g, green: g, blue: g, alpha: 1.0)
self.view.addSubview(backgroundLabel)
// Status label
let labelFrame = CGRect(x: 20, y: 395, width: 335, height: 50)
statusLabel.frame = labelFrame
statusLabel.font = UIFont(name: "Courier", size: 18)
statusLabel.textColor = UIColor.whiteColor()
statusLabel.backgroundColor = UIColor.blackColor()
self.view.addSubview(statusLabel)
statusLabel.text = " Welcome!"
}
func setupGraphicsView() {
self.view.addSubview(graphicsView)
let graphicsFrame = CGRect(x: 20, y: 40, width: 330, height: 330)
graphicsView.frame = graphicsFrame
}
override func viewDidLoad() {
super.viewDidLoad()
setupLabels()
setupGraphicsView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
PrateekVarshney/AppTour | AppTourDemo/ViewController.swift | 1 | 2208 | //
// ViewController.swift
// AppTourDemo
//
// Created by Prateek Varshney on 20/04/17.
// Copyright © 2017 PrateekVarshney. All rights reserved.
//
import UIKit
import AppTour
class ViewController: UIViewController, AppTourDelegate {
@IBOutlet var titleLabel : UILabel!
@IBOutlet var nextButton : UIButton!
let appTour : AppTour = AppTour()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
appTour.delegate = self
appTour.tintAlpha = 0.65
appTour.actionButton.displaysActionButton = true
appTour.textLabel.displaysTextLabel = true
appTour.shouldBlurBackground = false
appTour.textLabel.font = UIFont.boldSystemFont(ofSize: 22.0)
appTour.actionButton.layer.cornerRadius = 5.0
appTour.actionButton.clipsToBounds = true
appTour.actionButton.font = UIFont.boldSystemFont(ofSize: 22.0)
}
override func viewDidAppear(_ animated: Bool) {
appTour.textLabel.textForLabel = "This text is to make a user aware that this is a label which shows some information about the image."
appTour.actionButton.actionButtonTitle = "GOT IT"
let firstAppTourView = appTour.showOnBoardingView(viewController: self, view: self.titleLabel, isViewInTable: false, tableObj: nil, indexPath: nil)
firstAppTourView.tag = 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func onBoardingCleared(view: UIView?) {
print("Onboarding removed : \(String(describing: view?.tag))")
if view?.tag == 1
{
appTour.textLabel.textForLabel = "This text is to make a user aware that this is a button which performs some action."
appTour.actionButton.actionButtonTitle = "GOT IT"
let secondAppTourView = appTour.showOnBoardingView(viewController: self, view: self.nextButton, isViewInTable: false, tableObj: nil, indexPath: nil)
secondAppTourView.tag = 2
}
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1917-getselftypeforcontainer.swift | 13 | 320 | // 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
var b: a {
struct D : P> String {
}
class A = e? {
}
protocol P {
return {
}
protocol B : a {
func a"[T:
| apache-2.0 |
karstengresch/rw_studies | PaintCode/PaintCode/PaintCode/Stopwatch.swift | 1 | 226 | //
// Stopwatch.swift
// PaintCode
//
// Created by Karsten Gresch on 02.10.15.
//
import UIKit
@IBDesignable
class Stopwatch: UIView {
override func drawRect(rect: CGRect) {
PaintCodeTutorial.drawStopwatch()
}
}
| unlicense |
optimizely/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/WebSocket.swift | 2 | 34263 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2015 Dalton Cherry.
//
// 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 CoreFoundation
import Security
let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
protocol WebSocketDelegate: class {
func websocketDidConnect(_ socket: WebSocket)
func websocketDidDisconnect(_ socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(_ socket: WebSocket, text: String)
func websocketDidReceiveData(_ socket: WebSocket, data: Data)
}
protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(_ socket: WebSocket)
}
class WebSocket: NSObject, StreamDelegate {
enum OpCode: UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
enum CloseCode: UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
static let ErrorDomain = "WebSocket"
enum InternalErrorCode: UInt16 {
// 0-999 WebSocket status codes not used
case outputStreamWriteError = 1
}
// Where the callback is executed. It defaults to the main UI thread queue.
var callbackQueue = DispatchQueue.main
var optionalProtocols: [String]?
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
class WSResponse {
var isFin = false
var code: OpCode = .continueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
weak var delegate: WebSocketDelegate?
/// Recives a callback for each pong message recived.
weak var pongDelegate: WebSocketPongDelegate?
// MARK: - Block based API.
var onConnect: (() -> Void)?
var onDisconnect: ((NSError?) -> Void)?
var onText: ((String) -> Void)?
var onData: ((Data) -> Void)?
var onPong: (() -> Void)?
var headers = [String: String]()
var voipEnabled = false
var selfSignedSSL = false
var security: SSLSecurity?
var enabledSSLCipherSuites: [SSLCipherSuite]?
var origin: String?
var timeout = 5
var isConnected: Bool {
return connected
}
var currentURL: URL { return url }
// MARK: - Private
private var url: URL
private var inputStream: InputStream?
private var outputStream: OutputStream?
private var connected = false
private var isConnecting = false
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private let mutex = NSLock()
private let notificationCenter = NotificationCenter.default
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// The shared processing queue used for all WebSocket.
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
init(url: URL, protocols: [String]? = nil) {
self.url = url
self.origin = url.absoluteString
writeQueue.maxConcurrentOperationCount = 1
optionalProtocols = protocols
}
/// Connect to the WebSocket server on a background thread.
func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
isConnecting = false
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame
and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket.
After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`,
I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
*/
func disconnect(forceTimeout: TimeInterval? = nil) {
switch forceTimeout {
case .some(let seconds) where seconds > 0:
callbackQueue.asyncAfter(deadline: .now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
[weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(CloseCode.normal.rawValue)
default:
disconnectStream(nil)
break
}
}
func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
func write(_ ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString,
url as CFURL, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ","))
}
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
if let origin = origin {
addHeader(urlRequest, key: headerOriginName, val: origin)
}
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key, value) in headers {
addHeader(urlRequest, key: key, val: value)
}
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest as Data, Int(port!))
}
}
private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) {
CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString)
}
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
private func initStreamsWithData(_ data: Data, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if supportedSSLSchemes.contains(url.scheme!) {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
}
if selfSignedSSL {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false),
kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream,
CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream,
CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
var out = timeout * 1000000 // wait 5 seconds before giving up
writeQueue.addOperation { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return // disconnectStream will be called.
}
}
outStream.write(bytes, maxLength: data.count)
}
}
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) {
let trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as AnyObject
let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
if sec.isValid(trust as! SecTrust, domain: domain) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
disconnectStream(error)
return
}
}
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
processInputStream()
}
} else if eventCode == .errorOccurred {
disconnectStream(aStream.streamError as NSError?)
} else if eventCode == .endEncountered {
disconnectStream(nil)
}
}
private func disconnectStream(_ error: NSError?) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
}
private func cleanupStream() {
outputStream?.delegate = nil
inputStream?.delegate = nil
if let stream = inputStream {
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
guard length > 0 else { return }
var process = false
if inputQueue.isEmpty {
process = true
}
inputQueue.append(Data(bytes: buffer, count: length))
if process {
dequeueInput()
}
}
private func dequeueInput() {
while !inputQueue.isEmpty {
let data = inputQueue[0]
var work = data
if let fragBuffer = fragBuffer {
var combine = NSData(data: fragBuffer) as Data
combine.append(data)
work = combine
self.fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter { $0 != data }
}
}
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
connected = true
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(s)
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
let code = CFHTTPMessageGetResponseStatusCode(response)
if code != httpSwitchProtocolCode {
return code
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString {
if acceptKey.length > 0 {
return 0
}
}
}
return -1
}
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
let detail = (receivedOpcode != nil) ? "unknown opcode: \(receivedOpcode!)" : "unknown opcode"
doDisconnect(errorWithDetail(detail, code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return emptyBuffer
}
if receivedOpcode == .connectionClose {
var code = CloseCode.normal.rawValue
if payloadLen == 1 {
code = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
code = WebSocket.readUint16(baseAddress, offset: offset)
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.protocolError.rawValue
}
offset += 2
}
var closeReason = "connection closed by server"
if payloadLen > 2 {
let len = Int(payloadLen - 2)
if len > 0 {
let bytes = baseAddress + offset
if let customCloseReason = String(data: Data(bytes: bytes, count: len), encoding: .utf8) {
closeReason = customCloseReason
} else {
code = CloseCode.protocolError.rawValue
}
}
}
doDisconnect(errorWithDetail(closeReason, code: code))
writeError(code)
return emptyBuffer
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
let data = Data(bytes: baseAddress+offset, count: Int(len))
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onPong?()
s.pongDelegate?.websocketDidReceivePong(s)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if !buffer.isEmpty {
fragBuffer = Data(buffer: buffer)
}
}
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
} else if response.code == .textFrame {
let str: NSString? = NSString(data: response.buffer! as Data, encoding: String.Encoding.utf8.rawValue)
if str == nil {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(s, data: data as Data)
}
}
}
readStack.removeLast()
return true
}
return false
}
private func errorWithDetail(_ detail: String, code: UInt16) -> NSError {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
}
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperation { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
var offset = 2
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = s.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while true {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = outStream.write(writeBuffer, maxLength: offset-total)
if len < 0 {
var error: Error?
if let streamError = outStream.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.outputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
}
s.doDisconnect(error as NSError?)
break
} else {
total += len
}
if total >= offset {
if let queue = self?.callbackQueue, let callback = writeCompletion {
queue.async {
callback()
}
}
break
}
}
}
}
private func doDisconnect(_ error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
connected = false
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(s, error: error)
let userInfo = error.map { [WebsocketDisconnectionErrorKeyName: $0] }
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
| apache-2.0 |
linhaosunny/yeehaiyake | 椰海雅客微博/椰海雅客微博/Classes/Tools/UIButton+Extension.swift | 1 | 618 | //
// UIButton+Extension.swift
// 椰海雅客微博
//
// Created by 李莎鑫 on 2017/4/2.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(imageName:String,backgroundName:String) {
self.init()
setImage(UIImage(named: imageName), for: .normal)
setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted)
setBackgroundImage(UIImage(named: backgroundName), for: .normal)
setBackgroundImage(UIImage(named: backgroundName + "_highlighted"), for: .highlighted)
sizeToFit()
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/00453-resolvetypedecl.swift | 65 | 504 | // 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
struct d<T where g: A? = [T
protocol d = c, U)"
struct Q<U -> {
enum A : d = b
func g: A> {
}
var e: A> {
| apache-2.0 |
sharath-cliqz/browser-ios | AccountTests/TokenServerClientTests.swift | 2 | 4982 | /* 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/. */
@testable import Account
import Foundation
import FxA
import UIKit
import XCTest
// Testing client state is so delicate that I'm not going to test this. The test below does two
// requests; we would need a third, and a guarantee of the server state, to test this completely.
// The rule is: if you turn up with a never-before-seen client state; you win. If you turn up with
// a seen-before client state, you lose.
class TokenServerClientTests: LiveAccountTest {
func testErrorOutput() {
// Make sure we don't hide error details.
let error = NSError(domain: "test", code: 123, userInfo: nil)
XCTAssertEqual(
"<TokenServerError.Local Error Domain=test Code=123 \"The operation couldn’t be completed. (test error 123.)\">",
TokenServerError.Local(error).description)
}
func testAudienceForEndpoint() {
func audienceFor(endpoint: String) -> String {
return TokenServerClient.getAudienceForURL(URL(string: endpoint)!)
}
// Sub-domains and path components.
XCTAssertEqual("http://sub.test.com", audienceFor("http://sub.test.com"));
XCTAssertEqual("http://test.com", audienceFor("http://test.com/"));
XCTAssertEqual("http://test.com", audienceFor("http://test.com/path/component"));
XCTAssertEqual("http://test.com", audienceFor("http://test.com/path/component/"));
// No port and default port.
XCTAssertEqual("http://test.com", audienceFor("http://test.com"));
XCTAssertEqual("http://test.com:80", audienceFor("http://test.com:80"));
XCTAssertEqual("https://test.com", audienceFor("https://test.com"));
XCTAssertEqual("https://test.com:443", audienceFor("https://test.com:443"));
// Ports that are the default ports for a different scheme.
XCTAssertEqual("https://test.com:80", audienceFor("https://test.com:80"));
XCTAssertEqual("http://test.com:443", audienceFor("http://test.com:443"));
// Arbitrary ports.
XCTAssertEqual("http://test.com:8080", audienceFor("http://test.com:8080"));
XCTAssertEqual("https://test.com:4430", audienceFor("https://test.com:4430"));
}
func testTokenSuccess() {
let audience = TokenServerClient.getAudienceForURL(ProductionSync15Configuration().tokenServerEndpointURL)
withCertificate { expectation, emailUTF8, keyPair, certificate in
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSignWith(keyPair.privateKey,
certificate: certificate, audience: audience)
let client = TokenServerClient()
client.token(assertion).upon { result in
if let token = result.successValue {
XCTAssertNotNil(token.id)
XCTAssertNotNil(token.key)
XCTAssertNotNil(token.api_endpoint)
XCTAssertTrue(token.uid >= 0)
XCTAssertTrue(token.api_endpoint.hasSuffix(String(token.uid)))
XCTAssertTrue(token.remoteTimestamp >= 1429121686000) // Not a special timestamp; just a sanity check.
} else {
XCTAssertEqual(result.failureValue!.description, "")
}
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
func testTokenFailure() {
withVerifiedAccount { _, _ in
// Account details aren't used, but we want to skip when we're not running live tests.
let e = self.expectationWithDescription("")
let assertion = "BAD ASSERTION"
let client = TokenServerClient()
client.token(assertion).upon { result in
if let token = result.successValue {
XCTFail("Got token: \(token)")
} else {
if let error = result.failureValue as? TokenServerError {
switch error {
case let .Remote(code, status, remoteTimestamp):
XCTAssertEqual(code, Int32(401)) // Bad auth.
XCTAssertEqual(status!, "error")
XCTAssertFalse(remoteTimestamp == nil)
XCTAssertTrue(remoteTimestamp >= 1429121686000) // Not a special timestamp; just a sanity check.
case let .Local(error):
XCTAssertNil(error)
}
} else {
XCTFail("Expected TokenServerError")
}
}
e.fulfill()
}
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
| mpl-2.0 |
avito-tech/Marshroute | Example/NavigationDemo/VIPER/SearchResults/Assembly/SearchResultsAssemblyImpl.swift | 1 | 1697 | import UIKit
import Marshroute
final class SearchResultsAssemblyImpl: BaseAssembly, SearchResultsAssembly {
// MARK: - SearchResultsAssembly
func module(categoryId: CategoryId, routerSeed: RouterSeed)
-> UIViewController
{
let router = SearchResultsRouterIphone(
assemblyFactory: assemblyFactory,
routerSeed: routerSeed
)
return module(categoryId: categoryId, router: router)
}
func ipadModule(categoryId: CategoryId, routerSeed: RouterSeed)
-> UIViewController
{
let router = SearchResultsRouterIpad(
assemblyFactory: assemblyFactory,
routerSeed: routerSeed
)
return module(categoryId: categoryId, router: router)
}
// MARK - Private
private func module(categoryId: CategoryId, router: SearchResultsRouter)
-> UIViewController
{
let interactor = SearchResultsInteractorImpl(
categoryId: categoryId,
categoriesProvider: serviceFactory.categoriesProvider(),
searchResultsProvider: serviceFactory.searchResultsProvider()
)
let presenter = SearchResultsPresenter(
interactor: interactor,
router: router
)
presenter.applicationModuleInput = assemblyFactory.applicationAssembly().sharedModuleInput()
let viewController = SearchResultsViewController(
peekAndPopUtility: marshrouteStack.peekAndPopUtility
)
viewController.addDisposable(presenter)
presenter.view = viewController
return viewController
}
}
| mit |
NikKovIos/NKVPhonePicker | Sources/Models/Country.swift | 1 | 7459 | //
// Be happy and free :)
//
// Nik Kov
// nik-kov.com
//
#if os(iOS)
import Foundation
import UIKit
open class Country: NSObject {
// MARK: - Properties
/// Ex: "RU"
@objc public var countryCode: String
/// Ex: "7"
@objc public var phoneExtension: String
/// Ex: "Russia"
@objc public var name: String {
return NKVLocalizationHelper.countryName(by: countryCode) ?? ""
}
/// Ex: "### ## ######"
@objc public var formatPattern: String
/// A flag image for this country. May be nil.
public var flag: UIImage? {
return NKVSourcesHelper.flag(for: NKVSource(country: self))
}
// MARK: - Initialization
public init(countryCode: String,
phoneExtension: String,
formatPattern: String = "###################") {
self.countryCode = countryCode
self.phoneExtension = phoneExtension
self.formatPattern = formatPattern
}
// MARK: - Country entities
/// A Country entity of the current iphone's localization region code
/// or nil if it not exist.
public static var currentCountry: Country? {
guard let currentCountryCode = NKVLocalizationHelper.currentCode else {
return nil
}
return Country.country(for: NKVSource(countryCode: currentCountryCode))
}
/// An empty country entity for test or other purposes.
/// "_unknown" country code returns a "question" flag.
public static var empty: Country {
return Country(countryCode: "_unknown", phoneExtension: "")
}
// MARK: - Methods
/// A main method for fetching a country
///
/// - Parameter source: Any of the source, look **NKVSourceType**
/// - Returns: A Country entity or nil if there is no exist for the source
public class func country(`for` source: NKVSource) -> Country? {
switch source {
case .country(let country):
return country
case .code(let code):
for country in NKVSourcesHelper.countries {
if code.code.lowercased() == country.countryCode.lowercased() {
return country
}
}
case .phoneExtension(let phoneExtension):
var matchingCountries = [Country]()
let phoneExtension = phoneExtension.phoneExtension.cutPluses
for country in NKVSourcesHelper.countries {
if phoneExtension == country.phoneExtension {
matchingCountries.append(country)
}
}
// If phone extension does not match any specific country, see if prefix of the extension is a match so we can pinpoint the country by local area code
if matchingCountries.count == 0 {
for country in NKVSourcesHelper.countries {
var tempPhoneExtension = phoneExtension
while tempPhoneExtension.count > 0 {
if tempPhoneExtension == country.phoneExtension {
matchingCountries.append(country)
break
} else {
tempPhoneExtension.remove(at: tempPhoneExtension.index(before: tempPhoneExtension.endIndex))
}
}
}
}
// We have multiple countries for same phone extension. We decide which one to pick here.
if matchingCountries.count > 0 {
let matchingPhoneExtension = matchingCountries.first!.phoneExtension
if phoneExtension.count > 1 {
// Deciding which country to pick based on local area code.
do {
if let file = Bundle(for: NKVPhonePickerTextField.self).url(forResource: "Countries.bundle/Data/localAreaCodes", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let array = json as? [String : [AnyObject]] {
if array.index(forKey: matchingPhoneExtension) != nil {
// Found countries with given phone extension.
for country in array[array.index(forKey: matchingPhoneExtension)!].value {
if let areaCodes = country["localAreaCodes"] as? [String] {
if phoneExtension.hasPrefix(matchingPhoneExtension) {
var localAreaCode = String(phoneExtension.dropFirst(matchingPhoneExtension.count))
localAreaCode = String(localAreaCode.prefix(areaCodes.first!.count))
if areaCodes.contains(localAreaCode) {
// Found a specific country with given phone extension and local area code.
if let currentCountry = country["countryCode"] as? String {
return Country.country(for: NKVSource(countryCode: currentCountry))
}
}
}
}
}
}
}
} else {
print("NKVPhonePickerTextField >>> Can't find a bundle for the local area codes")
}
} catch {
print("NKVPhonePickerTextField >>> \(error.localizedDescription)")
}
}
// Deciding which country to pick based on country priority.
if let countryPriorities = NKVPhonePickerTextField.samePhoneExtensionCountryPriorities {
if let prioritizedCountry = countryPriorities[matchingPhoneExtension] {
return Country.country(for: NKVSource(countryCode: prioritizedCountry))
}
}
return matchingCountries.first
}
}
return nil
}
/// Returns a countries array from the country codes.
///
/// - Parameter countryCodes: For example: ["FR", "EN"]
public class func countriesBy(countryCodes: [String]) -> [Country] {
return countryCodes.map { code in
if let country = Country.country(for: NKVSource(countryCode: code)) {
return country
} else {
print("⚠️ Country >>> Can't find a country for country code: \(code).\r Replacing it with dummy country. Please check your country ID or update a country database.")
return Country.empty
}
}
}
}
// MARK: - Equitable
extension Country {
/// Making entities comparable
static public func ==(lhs: Country, rhs: Country) -> Bool {
return lhs.countryCode == rhs.countryCode
}
}
#endif
| mit |
svanimpe/around-the-table | Tests/AroundTheTableTests/Models/GameTests.swift | 1 | 15108 | import BSON
import Foundation
import XCTest
@testable import AroundTheTable
class GameTests: XCTestCase {
static var allTests: [(String, (GameTests) -> () throws -> Void)] {
return [
("testParseXML", testParseXML),
("testParseXMLNoID", testParseXMLNoID),
("testParseXMLNoName", testParseXMLNoName),
("testParseXMLZeroYear", testParseXMLZeroYear),
("testParseXMLNoMinPlayers", testParseXMLNoMinPlayers),
("testParseXMLNoMaxPlayers", testParseXMLNoMaxPlayers),
("testParseXMLZeroPlayerCount", testParseXMLZeroPlayerCount),
("testParseXMLZeroMinPlayers", testParseXMLZeroMinPlayers),
("testParseXMLZeroMaxPlayers", testParseXMLZeroMaxPlayers),
("testParseXMLInvertedPlayerCount", testParseXMLInvertedPlayerCount),
("testParseXMLNoMinPlaytime", testParseXMLNoMinPlaytime),
("testParseXMLNoMaxPlaytime", testParseXMLNoMaxPlaytime),
("testParseXMLZeroPlaytime", testParseXMLZeroPlaytime),
("testParseXMLZeroMinPlaytime", testParseXMLZeroMinPlaytime),
("testParseXMLZeroMaxPlaytime", testParseXMLZeroMaxPlaytime),
("testParseXMLInvertedPlaytime", testParseXMLInvertedPlaytime),
("testParseXMLNoImage", testParseXMLNoImage),
("testParseXMLNoThumbnail", testParseXMLNoThumbnail),
("testEncode", testEncode),
("testEncodeSkipsNilValues", testEncodeSkipsNilValues),
("testDecode", testDecode),
("testDecodeNotADocument", testDecodeNotADocument),
("testDecodeMissingID", testDecodeMissingID),
("testDecodeMissingCreationDate", testDecodeMissingCreationDate),
("testDecodeMissingName", testDecodeMissingName),
("testDecodeMissingNames", testDecodeMissingNames),
("testDecodeMissingYear", testDecodeMissingID),
("testDecodeMissingPlayerCount", testDecodeMissingPlayerCount),
("testDecodeMissingPlayingTime", testDecodeMissingPlayingTime)
]
}
private let now = Date()
private let picture = URL(string: "https://cf.geekdo-images.com/original/img/ME73s_0dstlA4qLpLEBvPyvq8gE=/0x0/pic3090929.jpg")!
private let thumbnail = URL(string: "https://cf.geekdo-images.com/thumb/img/7X5vG9KruQ9CmSMVZ3rmiSSqTCM=/fit-in/200x150/pic3090929.jpg")!
/* XML */
func testParseXML() throws {
guard let data = loadFixture(file: "xml/valid.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.id == 192457)
XCTAssert(result.name == "Cry Havoc")
XCTAssert(result.names == ["Cry Havoc"])
XCTAssert(result.yearPublished == 2016)
XCTAssert(result.playerCount == 2...4)
XCTAssert(result.playingTime == 60...120)
XCTAssert(result.picture == picture)
XCTAssert(result.thumbnail == thumbnail)
}
func testParseXMLNoID() throws {
guard let data = loadFixture(file: "xml/no-id.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLNoName() throws {
guard let data = loadFixture(file: "xml/no-name.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLZeroYear() throws {
guard let data = loadFixture(file: "xml/zero-year.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLNoMinPlayers() throws {
guard let data = loadFixture(file: "xml/no-minplayers.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLNoMaxPlayers() throws {
guard let data = loadFixture(file: "xml/no-maxplayers.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLZeroPlayerCount() throws {
guard let data = loadFixture(file: "xml/zero-playercount.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLZeroMinPlayers() throws {
guard let data = loadFixture(file: "xml/zero-minplayers.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.playerCount == 4...4)
}
func testParseXMLZeroMaxPlayers() throws {
guard let data = loadFixture(file: "xml/zero-maxplayers.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.playerCount == 2...2)
}
func testParseXMLInvertedPlayerCount() throws {
guard let data = loadFixture(file: "xml/inverted-playercount.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.playerCount == 2...4)
}
func testParseXMLNoMinPlaytime() throws {
guard let data = loadFixture(file: "xml/no-minplaytime.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLNoMaxPlaytime() throws {
guard let data = loadFixture(file: "xml/no-maxplaytime.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLZeroPlaytime() throws {
guard let data = loadFixture(file: "xml/zero-playtime.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
XCTAssertThrowsError(try Game(xml: node))
}
func testParseXMLZeroMinPlaytime() throws {
guard let data = loadFixture(file: "xml/zero-minplaytime.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.playingTime == 120...120)
}
func testParseXMLZeroMaxPlaytime() throws {
guard let data = loadFixture(file: "xml/zero-maxplaytime.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.playingTime == 60...60)
}
func testParseXMLInvertedPlaytime() throws {
guard let data = loadFixture(file: "xml/inverted-playtime.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssert(result.playingTime == 60...120)
}
func testParseXMLNoImage() throws {
guard let data = loadFixture(file: "xml/no-image.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssertNil(result.picture)
}
func testParseXMLNoThumbnail() throws {
guard let data = loadFixture(file: "xml/no-thumbnail.xml") else {
return XCTFail()
}
let xml = try XMLDocument(data: data, options: [])
guard let node = try xml.nodes(forXPath: "/items/item").first else {
return XCTFail()
}
let result = try Game(xml: node)
XCTAssertNil(result.thumbnail)
}
/* BSON */
func testEncode() {
let input = Game(id: 1,
name: "game", names: ["game", "spiel"],
yearPublished: 2000,
playerCount: 2...4,
playingTime: 45...60,
picture: picture, thumbnail: thumbnail)
let expected: Document = [
"_id": 1,
"creationDate": input.creationDate,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60,
"picture": picture,
"thumbnail": thumbnail
]
XCTAssert(input.typeIdentifier == expected.typeIdentifier)
XCTAssert(input.document == expected)
}
func testEncodeSkipsNilValues() {
let input = Game(id: 1,
name: "game", names: ["game", "spiel"],
yearPublished: 2000,
playerCount: 2...4,
playingTime: 45...60,
picture: nil, thumbnail: nil)
let expected: Document = [
"_id": 1,
"creationDate": input.creationDate,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60
]
XCTAssert(input.typeIdentifier == expected.typeIdentifier)
XCTAssert(input.document == expected)
}
func testDecode() throws {
let input: Document = [
"_id": 1,
"creationDate": now,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60,
"picture": picture,
"thumbnail": thumbnail
]
guard let result = try Game(input) else {
return XCTFail()
}
XCTAssert(result.id == 1)
assertDatesEqual(result.creationDate, now)
XCTAssert(result.name == "game")
XCTAssert(result.names == ["game", "spiel"])
XCTAssert(result.yearPublished == 2000)
XCTAssert(result.playerCount == 2...4)
XCTAssert(result.playingTime == 45...60)
XCTAssert(result.picture == picture)
XCTAssert(result.thumbnail == thumbnail)
}
func testDecodeNotADocument() throws {
let input: Primitive = 1
let result = try Game(input)
XCTAssertNil(result)
}
func testDecodeMissingID() {
let input: Document = [
"creationDate": now,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60
]
XCTAssertThrowsError(try Game(input))
}
func testDecodeMissingCreationDate() {
let input: Document = [
"_id": 1,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60
]
XCTAssertThrowsError(try Game(input))
}
func testDecodeMissingName() {
let input: Document = [
"_id": 1,
"creationDate": now,
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60
]
XCTAssertThrowsError(try Game(input))
}
func testDecodeMissingNames() {
let input: Document = [
"_id": 1,
"creationDate": now,
"name": "game",
"yearPublished": 2000,
"playerCount": 2...4,
"playingTime": 45...60
]
XCTAssertThrowsError(try Game(input))
}
func testDecodeMissingYear() {
let input: Document = [
"_id": 1,
"creationDate": now,
"name": "game",
"names": ["game", "spiel"],
"playerCount": 2...4,
"playingTime": 45...60
]
XCTAssertThrowsError(try Game(input))
}
func testDecodeMissingPlayerCount() {
let input: Document = [
"_id": 1,
"creationDate": now,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playingTime": 45...60
]
XCTAssertThrowsError(try Game(input))
}
func testDecodeMissingPlayingTime() {
let input: Document = [
"_id": 1,
"creationDate": now,
"name": "game",
"names": ["game", "spiel"],
"yearPublished": 2000,
"playerCount": 2...4
]
XCTAssertThrowsError(try Game(input))
}
}
| bsd-2-clause |
amarcu5/PiPer | src/safari/App/LocalizedTextField.swift | 1 | 661 | //
// LocalizedTextField.swift
// PiPer
//
// Created by Adam Marcus on 13/10/2018.
// Copyright © 2018 Adam Marcus. All rights reserved.
//
import Cocoa
@IBDesignable
class LocalizedTextField: NSTextField {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
localizeValue()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
localizeValue()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
localizeValue()
}
func localizeValue() {
self.stringValue = LocalizationManager.default.localizedString(forKey:self.stringValue)
}
}
| gpl-3.0 |
adamnemecek/AudioKit | Playgrounds/Hello World.playground/Contents.swift | 1 | 391 | //: Run this playground to test that AudioKit is working
import AudioKit
import AudioKitEX
import Foundation
var greeting = "Hello, playground"
let osc = PlaygroundOscillator()
let engine = AudioEngine()
engine.output = osc
try! engine.start()
osc.play()
while true {
osc.frequency = Float.random(in: 200...800)
osc.amplitude = Float.random(in: 0.0...0.3)
usleep(100000)
}
| mit |
doushiDev/ds_ios | TouTiao/Video.swift | 1 | 349 | //
// Video.swift
// TouTiao
//
// Created by Songlijun on 2017/2/25.
// Copyright © 2017年 Songlijun. All rights reserved.
//
import Foundation
import HandyJSON
struct Video: HandyJSON {
var vid:String?
var title:String?
var pic:String?
var shareUrl:String = ""
var videoUrl:String = ""
var at:Int = 0
}
| mit |
yarshure/Surf | Surf/RuleResultsViewController.swift | 1 | 10821 | //
// RuleResultsViewController.swift
// Surf
//
// Created by yarshure on 16/2/14.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
import NetworkExtension
import SwiftyJSON
import SFSocket
class RuleResultsViewController: SFTableViewController {
var results:[SFRuleResult] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Rule Test Results"
recent()
//test()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
let item = UIBarButtonItem.init(image: UIImage.init(named: "760-refresh-3-toolbar"), style: .plain, target: self, action: #selector(RuleResultsViewController.refreshAction(_:)))
self.navigationItem.rightBarButtonItem = item
}
func refreshAction(_ sender:AnyObject){
recent()
}
// func test() {
// let path = Bundle.main.path(forResource: "1.txt", ofType: nil)
// if let data = try! Data.init(contentsOf: path) {
// processData(data: data)
// }
// }
func recent(){
// Send a simple IPC message to the provider, handle the response.
//AxLogger.log("send Hello Provider")
if let m = SFVPNManager.shared.manager, m.isEnabled{
let date = NSDate()
let me = SFVPNXPSCommand.RULERESULT.rawValue + "|\(date)"
if let session = m.connection as? NETunnelProviderSession,
let message = me.data(using: .utf8), m.connection.status == .connected
{
do {
try session.sendProviderMessage(message) { [weak self] response in
if response != nil {
self!.processData(data: response!)
} else {
self!.alertMessageAction("Got a nil response from the provider",complete: nil)
}
}
} catch {
alertMessageAction("Failed to Get result ",complete: nil)
}
}else {
alertMessageAction("Connection not Started",complete: nil)
}
}else {
alertMessageAction("VPN not running",complete: nil)
}
}
func processData(data:Data) {
results.removeAll()
//let responseString = NSString(data: response!, encoding: NSUTF8StringEncoding)
let obj = JSON.init(data: data)
if obj.error == nil {
if obj.type == .array {
for item in obj {
//{"api.smoot.apple.com":{"Name":"apple.com","Type":"DOMAIN-SUFFIX","Proxy":"jp","Policy":"Proxy"}}
let json = item.1
for (k,v) in json {
let rule = SFRuler()
rule.mapObject(v)
//let policy = v["Policy"].stringValue
let result = SFRuleResult.init(request: k, r: rule)
results.append(result)
}
}
}
if results.count > 0 {
tableView.reloadData()
}else {
alertMessageAction("Don't have Record yet!",complete: nil)
}
}
//mylog("Received response from the provider: \(responseString)")
//self.registerStatus()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return results.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "rule", for: indexPath as IndexPath)
// Configure the cell...
let x = results[indexPath.row]
cell.textLabel?.text = x.req
var proxyName = ""
if x.result.proxyName == "" {
proxyName = x.result.name
}else {
proxyName = x.result.proxyName
}
let timing = String.init(format: " timing: %.04f sec", x.result.timming)
if x.result.type == .final {
cell.detailTextLabel?.text = x.result.type.description + " " + x.result.policy.description + "->" + proxyName + timing
}else {
cell.detailTextLabel?.text = x.result.type.description + " " + x.result.name + "->" + proxyName + timing
}
cell.updateUI()
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
changeRule()
}
func changeRule() {
var style:UIAlertControllerStyle = .alert
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
switch deviceIdiom {
case .pad:
style = .alert
default:
style = .actionSheet
break
}
guard let indexPath = tableView.indexPathForSelectedRow else {return}
let result = results[indexPath.row]
let alert = UIAlertController.init(title: "Alert", message: "Please Select Policy", preferredStyle: style)
let action = UIAlertAction.init(title: "PROXY", style: .default) {[unowned self ] (action:UIAlertAction) -> Void in
result.result.proxyName = "Proxy"
self.updateResult(rr: result)
self.tableView.deselectRow(at: indexPath, animated: true)
}
let action1 = UIAlertAction.init(title: "REJECT", style: .default) { [unowned self ] (action:UIAlertAction) -> Void in
result.result.proxyName = "REJECT"
self.updateResult(rr: result)
self.tableView.deselectRow(at: indexPath, animated: true)
}
let action2 = UIAlertAction.init(title: "DIRECT", style: .default) { [unowned self ] (action:UIAlertAction) -> Void in
result.result.proxyName = "DIRECT"
self.updateResult(rr: result)
self.tableView.deselectRow(at: indexPath, animated: true)
}
let cancle = UIAlertAction.init(title: "Cancel", style: .cancel) { [unowned self ] (action:UIAlertAction) -> Void in
self.tableView.deselectRow(at: indexPath, animated: true)
}
alert.addAction(action)
alert.addAction(action1)
alert.addAction(action2)
alert.addAction(cancle)
self.present(alert, animated: true) { () -> Void in
}
}
func updateResult(rr:SFRuleResult){
var r:[String:AnyObject] = [:]
r["request"] = rr.req as AnyObject?
r["ruler"] = rr.result.resp() as AnyObject?
let j = JSON(r)
var data:Data
do {
try data = j.rawData()
}catch let error as NSError {
//AxLogger.log("ruleResultData error \(error.localizedDescription)")
//let x = error.localizedDescription
//data = error.localizedDescription.dataUsingEncoding(NSUTF8StringEncoding)!// NSData()
alertMessageAction("error :\(error.localizedDescription)", complete: {
})
return
}
let me = SFVPNXPSCommand.UPDATERULE.rawValue + "|"
var message = Data.init()
message.append(me.data(using: .utf8)!)
if let m = SFVPNManager.shared.manager, m.connection.status == .connected {
if let session = m.connection as? NETunnelProviderSession
{
do {
try session.sendProviderMessage(message) { [weak self] response in
if let r = String.init(data: response!, encoding: String.Encoding.utf8) {
print("change policy : \(r)")
//self!.alertMessageAction(r,complete: nil)
} else {
self!.alertMessageAction("Failed to Change Policy",complete: nil)
}
}
} catch let e as NSError{
alertMessageAction("Failed to Change Proxy,reason \(e.description)",complete: nil)
}
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause |
XiongJoJo/OFO | App/OFO/OFO/MyPinAnnotation.swift | 1 | 197 | //
// MyPintAnnotion.swift
// OFO
//
// Created by iMac on 2017/6/5.
// Copyright © 2017年 JoJo. All rights reserved.
//
import Foundation
class MyPinAnnotation: MAPointAnnotation {
}
| apache-2.0 |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/I18n.swift | 1 | 165 | import Foundation
// Helper function that returns a localized string
func i18n(_ content: String) -> String {
return NSLocalizedString(content, comment: "_")
}
| gpl-2.0 |
palle-k/SocketKit | Sources/Socket.swift | 2 | 11913 | //
// Socket.swift
// SocketKit
//
// Created by Palle Klewitz on 10.04.16.
// Copyright © 2016 Palle Klewitz.
//
// 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 CoreFoundation
import Darwin
import Foundation
/**
The Socket protocol provides an interface for a network socket,
which is an endpoint in network communication.
The user can communicate through the streams provided by the socket.
Incoming data can be retrieved through the input stream and data can be written
to the network with the output stream.
*/
public protocol Socket : class
{
/**
Host address of the peer.
Only used for outgoing connections.
*/
var hostAddress: String? { get }
/**
The input stream of the socket.
Incoming data can be read from it.
If the socket uses non-blocking I/O,
a delegate should be used to receive notifications about
incoming data.
*/
var inputStream: InputStream! { get }
/**
The output stream of the socket.
Can write data to the socket.
If the socket uses non-blocking I/O,
the operation may fail and a
.WouldBlock or .Again IOError may be thrown.
The operation must then be tried again.
*/
var outputStream: OutputStream! { get }
/**
Indicates, if non-blocking I/O is used
or en-/disables non-blocking I/O.
If non-blocking I/O is used, reading
from the socket may not return any data
and writing may fail because it would otherwise
block the current thread.
In this case, a .WouldBlock or .Again
IOError will be thrown.
The operation must be repeated until it was successful.
For read operations, the delegate of the stream should be used
for efficient reading.
- parameter new: Specifies, if the socket should be non-blocking or not.
A value of true sets the socket to nonblocking mode, false to blocking mode.
- returns: true, if the socket is nonblocking, false if it is blocking.
*/
var nonblocking: Bool { get set }
/**
Checks if the socket is open.
The socket is open if at least one of the streams associated with this socket is open.
*/
var open:Bool { get }
/**
Manually closes the socket
and releases any ressources related to it.
Subsequent calls of the streams' read and write
functions will fail.
*/
func close()
/**
Checks the status of the streams which read and write from and to this socket.
If both streams are closed, the socket will be closed.
*/
func checkStreams()
}
/**
Extension for stream checking.
*/
public extension Socket
{
/**
Checks the status of the streams which read and write from and to this socket.
If both streams are closed, the socket will be closed.
*/
func checkStreams()
{
if !inputStream.open && !outputStream.open
{
close()
}
}
}
/**
A socket which internally uses POSIX APIs
This may include UDP, TCP or RAW sockets.
*/
internal protocol POSIXSocket : Socket
{
/**
The POSIX-socket handle of this socket.
Input and output streams use this for read
and write operations.
*/
var handle: Int32 { get }
/**
The address of the socket.
Contains port and ip information
*/
var address: sockaddr { get }
}
/**
Socket: Endpoint of a TCP/IP connection.
Data can be read from the socket with the input stream
provided as a property of a socket instance.
Data can be written to the socket with the output stream
provided as a property of a socket instance.
*/
open class TCPSocket : POSIXSocket, CustomStringConvertible
{
/**
The POSIX-socket handle of this socket.
Input and output streams use this for read
and write operations.
*/
internal let handle: Int32
/**
The address of the socket.
Contains port and ip information
*/
internal var address: sockaddr
/**
Host address of the peer.
Only used for outgoing connections.
*/
open fileprivate(set) var hostAddress: String?
/**
Indicates, if non-blocking I/O is used
or en-/disables non-blocking I/O.
If non-blocking I/O is used, reading
from the socket may not return any data
and writing may fail because it would otherwise
block the current thread.
In this case, a .WouldBlock or .Again IOError will be thrown.
The operation must be repeated until it was successful.
For read operations, the delegate of the stream should be used
for efficient reading.
- parameter new: Specifies, if the socket should be non-blocking or not.
A value of true sets the socket to nonblocking mode, false to blocking mode.
- returns: true, if the socket is nonblocking, false if it is blocking.
*/
open var nonblocking: Bool
{
get
{
let flags = fcntl(handle, F_GETFL, 0)
return (flags & O_NONBLOCK) != 0
}
set (new)
{
let flags = fcntl(handle, F_GETFL, 0)
_ = fcntl(handle, F_SETFL, new ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK))
}
}
/**
The input stream of the socket.
Incoming data can be read from it.
If the socket uses non-blocking I/O,
a delegate should be used to receive notifications about
incoming data.
*/
open fileprivate(set) var inputStream: InputStream!
/**
The output stream of the socket.
Can write data to the socket.
If the socket uses non-blocking I/O,
the operation may fail and a
.WouldBlock or .Again IOError may be thrown.
The operation must then be tried again.
*/
open fileprivate(set) var outputStream: OutputStream!
/**
Returns the IP address of the peer
to which this socket is connected to.
The result is a IPv4 or IPv6 address
depending on the IP protocol version used.
*/
open var peerIP:String?
{
if address.sa_family == sa_family_t(AF_INET)
{
let ptr = UnsafeMutablePointer<CChar>.allocate(capacity: Int(INET_ADDRSTRLEN))
var address_in = sockaddr_cast(&address)
inet_ntop(AF_INET, &address_in.sin_addr, ptr, socklen_t(INET_ADDRSTRLEN))
return String(cString: ptr)
}
else if address.sa_family == sa_family_t(AF_INET6)
{
let ptr = UnsafeMutablePointer<CChar>.allocate(capacity: Int(INET6_ADDRSTRLEN))
var address_in = sockaddr_cast(&address)
inet_ntop(AF_INET, &address_in.sin_addr, ptr, socklen_t(INET6_ADDRSTRLEN))
return String(cString: ptr)
}
return nil
}
/**
Checks if the socket is open.
The socket is open if at least one of the streams associated with this socket is open.
*/
open var open:Bool
{
return inputStream.open || outputStream.open
}
/**
A textual representation of self.
*/
open var description: String
{
return "Socket (host: \(self.hostAddress ?? "unknown"), ip: \(self.peerIP ?? "unknown"), \(self.open ? "open" : "closed"))\n\t-> \(self.inputStream)\n\t<- \(self.outputStream)"
}
/**
Initializes the socket and connects to the address specified in `host`.
The `host` address must be an IPv4 address.
- parameter host: IPv4 peer address string
- parameter port: Port to which the socket should connect.
- throws: A SocketError if the socket could not be connected.
*/
public convenience init(ipv4host host: String, port: UInt16) throws
{
let handle = Darwin.socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)
guard handle >= 0
else
{
_ = Darwin.close(handle)
throw SocketError.open
}
var address = sockaddr_in()
address.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
address.sin_port = htons(port)
address.sin_addr = in_addr(s_addr: inet_addr(host))
let success = connect(handle, [sockaddr_in_cast(&address)], socklen_t(MemoryLayout<sockaddr_in>.size))
guard success >= 0
else
{
_ = Darwin.close(handle)
throw SocketError.open
}
self.init(handle: handle, address: sockaddr())
hostAddress = host
}
/**
Initializes a socket with a given host address and TCP port
The socket will automatically connect to the given host.
- parameter address: The host address of the server to connect to.
- parameter port: The TCP port on which the server should be connected.
*/
public init?(address: String, port: UInt16) throws
{
var readStreamRef:Unmanaged<CFReadStream>?
var writeStreamRef:Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, address as CFString!, UInt32(port), &readStreamRef, &writeStreamRef)
guard
let readStream = readStreamRef?.takeRetainedValue(),
let writeStream = writeStreamRef?.takeRetainedValue()
else { return nil }
CFReadStreamOpen(readStream)
CFWriteStreamOpen(writeStream)
guard let handle = CFReadStreamCopyProperty(readStream, CFStreamPropertyKey.socketNativeHandle) as? Int32 else { return nil }
self.handle = handle
var sockaddress = sockaddr()
var sockaddrlen = socklen_t(MemoryLayout<sockaddr>.size)
getpeername(handle, &sockaddress, &sockaddrlen)
self.address = sockaddress
}
/**
Initializes a socket with the given handle and address.
The handle must be the value of a POSIX-socket.
The socket address should contain information about the
peer to which this socket is connected.
- parameter handle: The POSIX-socket handle.
- parameter address: The peer address.
*/
internal init(handle: Int32, address: sockaddr)
{
self.handle = handle
self.address = address
var one:Int32 = 1
setsockopt(self.handle, SOL_SOCKET, SO_NOSIGPIPE, &one, UInt32(MemoryLayout<Int32>.size))
nonblocking = false
// let success_nodelay = setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, &one, socklen_t(sizeof(Int32)))
// DEBUG && success_nodelay < 0 ?-> print("Failed to set TCP_NODELAY.")
inputStream = SocketInputStreamImpl(socket: self, handle: handle)
outputStream = SocketOutputStreamImpl(socket: self, handle: handle)
}
/**
The socket is closed when deallocated.
*/
deinit
{
close()
}
/**
Manually closes the socket
and releases any ressources related to it.
Subsequent calls of the streams' read and write
functions will fail.
*/
open func close()
{
DEBUG ?-> print("Closing socket...")
inputStream.close()
outputStream.close()
_ = Darwin.close(handle)
}
/**
Checks the status of the streams which read and write from and to this socket.
If both streams are closed, the socket will be closed.
*/
open func checkStreams()
{
DEBUG ?-> print("Checking streams. input stream: \(inputStream.open ? "open" : "closed"), output stream: \(outputStream.open ? "open" : "closed")")
if !inputStream.open && !outputStream.open
{
close()
}
}
}
/**
Compares two sockets.
If the handles of the left and right socket are
equal, true is returned, otherwise falls will be returned.
- parameter left: First socket to compare
- parameter right: Second socket to compare
- returns: The comparison result from the comparison of the two sockets.
*/
internal func == (left: POSIXSocket, right: POSIXSocket) -> Bool
{
return left.handle == right.handle
}
| mit |
qiuncheng/study-for-swift | learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/Debunce.swift | 5 | 2629 | //
// Debunce.swift
// Rx
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = NSRecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element? = nil
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
self.cancellable.disposable = d
d.disposable = scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
class Debounce<Element> : Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
| mit |
mlibai/XZKit | Projects/XZKit/XZKitTests/XZURLTests.swift | 1 | 6150 | //
// XZURLTests.swift
// XZKitTests
//
// Created by 徐臻 on 2020/5/16.
// Copyright © 2020 Xezun Inc. All rights reserved.
//
import XCTest
import XZKit
class XZURLTests: XCTestCase {
override func setUpWithError() throws {
print("XZKit Debug Mode: \(XZKit.isDebugMode)")
}
override func tearDownWithError() throws {
}
func testExample() throws {
guard var url = URL(string: "https://www.xezun.com/s?a=1&b=2&c=3&e=&f&=g&a=11") else { return }
XZLog("queryComponent: %@", url.queryComponent)
XZLog("验证 keyedValues 属性:\n%@", String(json: url.queryComponent?.keyedValues, options: .prettyPrinted))
url.queryComponent?.addValue("addValue", forKey: "d")
XZLog("%@", url)
}
func testSetValueForKey() throws {
XZLog("测试 setValue(_:forKey:) 方法开始!")
guard var url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
url.queryComponent?.setValue("a1", forKey: "a")
XZLog("设置字段a=a1:%@", url)
url.queryComponent?.setValue(NSNull.init(), forKey: "a")
XZLog("设置字段a=NSNull:%@", url)
url.queryComponent?.setValue(2, forKey: "a")
XZLog("设置字段a=2:%@", url)
url.queryComponent?.setValue(nil, forKey: "a")
XZLog("设置字段a=nil:%@", url)
url.queryComponent?.setValue(["a1"], forKey: "a")
XZLog("设置字段a=[a1]:%@", url)
url.queryComponent?.setValue(["a2", "a3"], forKey: "a")
XZLog("设置字段a=[a2, a3]:%@", url)
url.queryComponent?.setValue(["a4", "a5", "a6"], forKey: "a")
XZLog("设置字段a=[a4, a5, a6]:%@", url)
url.queryComponent?.setValue(["a7", "a8"], forKey: "a")
XZLog("设置字段a=[a7, a8]:%@", url)
url.queryComponent?.setValue(["a9"], forKey: "a")
XZLog("设置字段a=[a9]:%@", url)
url.queryComponent?.setValue(["a4", "a5", "a6"], forKey: "a")
XZLog("设置字段a=[a4, a5, a6]:%@", url)
url.queryComponent?.setValue("a7", forKey: "a")
XZLog("设置字段a=[a7]:%@", url)
url.queryComponent?.setValue(["a4", "a5", "a6"], forKey: "a")
XZLog("设置字段a=[a4, a5, a6]:%@", url)
url.queryComponent?.setValue(nil, forKey: "a")
XZLog("设置字段a=nil:%@", url)
XZLog("测试 setValue(_:forKey:) 方法结束!")
}
func testAddValueForKey() throws {
guard var url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
url.queryComponent?.addValue("a1", forKey: "a")
XZLog("%@", url)
url.queryComponent?.addValue("b1", forKey: "b")
XZLog("%@", url)
url.queryComponent?.addValue(["b4", "b2"], forKey: "b")
XZLog("%@", url)
url.queryComponent?.addValue(nil, forKey: "b")
XZLog("%@", url)
}
func testValueForKey() throws {
guard let url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
XZLog("%@", url.queryComponent?.value(forKey: "a"))
XZLog("%@", url.queryComponent?.value(forKey: "b"))
XZLog("%@", url.queryComponent?.value(forKey: "c"))
XZLog("%@", url.queryComponent?.value(forKey: "d"))
}
func testRemoveValueForKey() {
guard var url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
url.queryComponent?.removeValue(nil, forKey: "a")
XZLog("%@", url)
url.queryComponent?.removeValue("3", forKey: "b")
XZLog("%@", url)
url.queryComponent?.removeValue(["1", "2"], forKey: "d")
XZLog("%@", url)
}
func testRemoveValueForKey2() {
guard var url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
url.queryComponent?.removeValue(forKey: "b")
XZLog("%@", url)
url.queryComponent?.removeValue(forKey: "d")
XZLog("%@", url)
}
func testContainsKey() {
guard let url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
XZLog("%@", url.queryComponent?.contains(key: "a"))
XZLog("%@", url.queryComponent?.contains(key: "b"))
XZLog("%@", url.queryComponent?.contains(key: "d"))
}
func testAddValuesForKeysFrom() {
guard var url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
url.queryComponent?.addValuesForKeys(from: "a")
XZLog("%@", url)
url.queryComponent?.addValuesForKeys(from: "b")
XZLog("%@", url)
url.queryComponent?.addValuesForKeys(from: ["a": 1, "b": "2"])
XZLog("%@", url)
url.queryComponent?.addValuesForKeys(from: ["c", "d"])
XZLog("%@", url)
}
func testSetValuesForKeysFrom() {
guard var url = URL(string: "https://www.xezun.com/?b=3&c=7&d=1&d=2") else { return }
XZLog("原始URL:%@", url)
url.queryComponent?.setValuesForKeys(from: "a")
XZLog("%@", url)
url.queryComponent?.setValuesForKeys(from: "b")
XZLog("%@", url)
url.queryComponent?.setValuesForKeys(from: ["a": 1, "b": "2"])
XZLog("%@", url)
url.queryComponent?.setValuesForKeys(from: ["c", "d"])
XZLog("%@", url)
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
cocoascientist/Jetstream | JetstreamCore/Model/Conditions.swift | 1 | 3509 | //
// Conditions+JSON.swift
// Jetstream
//
// Created by Andrew Shepard on 11/20/16.
// Copyright © 2016 Andrew Shepard. All rights reserved.
//
import Foundation
import CoreData
public class Conditions: NSManagedObject, Decodable {
@NSManaged public var icon: String
@NSManaged public var details: String
@NSManaged public var summary: String
@NSManaged public var time: Date
@NSManaged public var sunrise: Date?
@NSManaged public var sunset: Date?
@NSManaged public var apparentTemperature: Double
@NSManaged public var temperature: Double
@NSManaged public var humidity: Double
@NSManaged public var dewPoint: Double
@NSManaged public var cloudCover: Double
@NSManaged public var visibility: Double
@NSManaged public var windSpeed: Double
@NSManaged public var windBearing: UInt16
@NSManaged public var lastUpdated: Date
enum WrapperKeys: String, CodingKey {
case currently
case daily
}
enum CurrentlyKeys: String, CodingKey {
case icon
case temperature
case dewPoint
case humidity
case windSpeed
case windBearing
case summary
case cloudCover
case visibility
case apparentTemperature
}
enum DailyKeys: String, CodingKey {
case data
case details = "summary"
}
private struct SunTime: Codable {
enum CodingKeys: String, CodingKey {
case sunset = "sunsetTime"
case sunrise = "sunriseTime"
}
let sunset: Double
let sunrise: Double
}
public required convenience init(from decoder: Decoder) throws {
guard let context = decoder.userInfo[.context] as? NSManagedObjectContext else { fatalError() }
guard let entity = NSEntityDescription.entity(forEntityName: "Conditions", in: context) else { fatalError() }
self.init(entity: entity, insertInto: context)
let wrapper = try decoder.container(keyedBy: WrapperKeys.self)
let currently = try wrapper.nestedContainer(keyedBy: CurrentlyKeys.self, forKey: .currently)
self.icon = try currently.decode(String.self, forKey: .icon)
self.summary = try currently.decode(String.self, forKey: .summary)
self.temperature = try currently.decode(Double.self, forKey: .temperature)
self.apparentTemperature = try currently.decode(Double.self, forKey: .apparentTemperature)
self.dewPoint = try currently.decode(Double.self, forKey: .dewPoint)
self.humidity = try currently.decode(Double.self, forKey: .humidity)
self.visibility = try currently.decode(Double.self, forKey: .cloudCover)
self.cloudCover = try currently.decode(Double.self, forKey: .visibility)
self.windSpeed = try currently.decode(Double.self, forKey: .windSpeed)
self.windBearing = try currently.decode(UInt16.self, forKey: .windBearing)
let daily = try wrapper.nestedContainer(keyedBy: DailyKeys.self, forKey: .daily)
self.details = try daily.decode(String.self, forKey: .details)
let suntimes = try daily.decode([SunTime].self, forKey: .data)
self.sunset = Date(timeIntervalSince1970: suntimes.first?.sunset ?? 0)
self.sunrise = Date(timeIntervalSince1970: suntimes.first?.sunrise ?? 0)
self.lastUpdated = Date()
}
}
| mit |
nitrado/NitrAPI-Swift | Pod/Classes/services/gameservers/minecraft/McMyAdmin.swift | 1 | 651 | import ObjectMapper
open class McMyAdmin: Mappable {
// MARK: - Attributes
open fileprivate(set) var enabled: Bool?
open fileprivate(set) var url: String?
open fileprivate(set) var username: String?
open fileprivate(set) var password: String?
open fileprivate(set) var language: String?
// MARK: - Initialization
public required init?(map: Map) {
}
open func mapping(map: Map) {
enabled <- map["enabled"]
url <- map["url"]
username <- map["username"]
password <- map["password"]
language <- map["language"]
}
}
| mit |
bogosmer/UnitKit | UnitKit/Source/Units/VolumeUnit.swift | 1 | 10074 | //
// VolumeType.swift
// UnitKit
//
// Created by Bo Gosmer on 09/02/2016.
// Copyright © 2016 Deadlock Baby. All rights reserved.
//
import Foundation
public struct VolumeUnit: _Unit {
// MARK: - Public properties
public static var sharedDecimalNumberHandler: NSDecimalNumberHandler?
public var decimalNumberHandler: NSDecimalNumberHandler?
public let unitType: VolumeUnitType
public private(set) var baseUnitTypeValue: NSDecimal = NSDecimalNumber.double(0).decimalValue
public var millilitreValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Millilitre)
}
public var litreValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Litre)
}
public var cubicMetreValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.CubicMetre)
}
public var cubicInchValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.CubicInch)
}
public var cubicFootValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.CubicFoot)
}
public var fluidOunceValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.FluidOunce)
}
public var gillValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Gill)
}
public var pintValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Pint)
}
public var quartValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Quart)
}
public var gallonValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Gallon)
}
public var bushelValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.Bushel)
}
public var usFluidOunceValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USFluidOunce)
}
public var usLiquidGillValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USLiquidGill)
}
public var usLiquidPintValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USLiquidPint)
}
public var usDryPintValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USDryPint)
}
public var usLiquidQuartValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USLiquidQuart)
}
public var usDryQuartValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USDryQuart)
}
public var usLiquidGallonValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USLiquidGallon)
}
public var usDryGallonValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USDryGallon)
}
public var usBushelValue: NSDecimalNumber {
return convertFromBaseUnitTypeTo(VolumeUnitType.USBushel)
}
// MARK: - Lifecycle
public init(value: NSDecimalNumber, type: VolumeUnitType) {
self.unitType = type
self.baseUnitTypeValue = convertToBaseUnitType(value, fromType: type).decimalValue
}
public init(value: Double, type: VolumeUnitType) {
self.init(value: NSDecimalNumber.double(value), type: type)
}
public init(value: Int, type: VolumeUnitType) {
self.init(value: NSDecimalNumber.integer(value), type: type)
}
// MARK: - Public functions
public func valueForUnitType(type: VolumeUnitType) -> NSDecimalNumber {
switch type {
case .Millilitre:
return millilitreValue
case .Litre:
return litreValue
case .CubicMetre:
return cubicMetreValue
case .CubicInch:
return cubicInchValue
case .CubicFoot:
return cubicFootValue
case .FluidOunce:
return fluidOunceValue
case .Gill:
return gillValue
case .Pint:
return pintValue
case .Quart:
return quartValue
case .Gallon:
return gallonValue
case .Bushel:
return bushelValue
case .USFluidOunce:
return usFluidOunceValue
case .USLiquidGill:
return usLiquidGillValue
case .USLiquidPint:
return usLiquidPintValue
case .USDryPint:
return usDryPintValue
case .USLiquidQuart:
return usLiquidQuartValue
case .USDryQuart:
return usDryQuartValue
case .USLiquidGallon:
return usLiquidGallonValue
case .USDryGallon:
return usDryGallonValue
case .USBushel:
return usBushelValue
}
}
}
// MARK: - Double extenstion
public extension Double {
public func millilitres() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Millilitre)
}
public func litres() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Litre)
}
public func cubicMetres() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.CubicMetre)
}
public func cubicInches() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.CubicInch)
}
public func cubicFeet() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.CubicFoot)
}
public func fluidOunces() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.FluidOunce)
}
public func gills() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Gill)
}
public func pints() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Pint)
}
public func quarts() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Quart)
}
public func gallons() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Gallon)
}
public func bushels() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Bushel)
}
public func usFluidOunces() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USFluidOunce)
}
public func usLiquidGills() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidGill)
}
public func usLiquidPints() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidPint)
}
public func usDryPints() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USDryPint)
}
public func usLiquidQuarts() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidQuart)
}
public func usDryQuarts() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USDryQuart)
}
public func usLiquidGallons() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidGallon)
}
public func usDryGallons() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USDryGallon)
}
public func usBushels() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USBushel)
}
}
// MARK: - Int extenstion
public extension Int {
public func millilitres() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Millilitre)
}
public func litres() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Litre)
}
public func cubicMetres() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.CubicMetre)
}
public func cubicInches() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.CubicInch)
}
public func cubicFeet() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.CubicFoot)
}
public func fluidOunces() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.FluidOunce)
}
public func gills() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Gill)
}
public func pints() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Pint)
}
public func quarts() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Quart)
}
public func gallons() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Gallon)
}
public func bushels() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.Bushel)
}
public func usFluidOunces() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USFluidOunce)
}
public func usLiquidGills() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidGill)
}
public func usLiquidPints() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidPint)
}
public func usDryPints() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USDryPint)
}
public func usLiquidQuarts() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidQuart)
}
public func usDryQuarts() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USDryQuart)
}
public func usLiquidGallons() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USLiquidGallon)
}
public func usDryGallons() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USDryGallon)
}
public func usBushels() -> VolumeUnit {
return VolumeUnit(value: self, type: VolumeUnitType.USBushel)
}
} | mit |
jgrantr/GRNetworkKit | Example/Pods/PromiseKit/Sources/Catchable.swift | 1 | 7986 | import Dispatch
/// Provides `catch` and `recover` to your object that conforms to `Thenable`
public protocol CatchMixin: Thenable
{}
public extension CatchMixin {
/**
The provided closure executes when this promise rejects.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- Returns: A promise finalizer.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@discardableResult
func `catch`(on: DispatchQueue? = conf.Q.return, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) -> Void) -> PMKFinalizer {
let finalizer = PMKFinalizer()
pipe {
switch $0 {
case .rejected(let error):
guard policy == .allErrors || !error.isCancelled else {
fallthrough
}
on.async {
body(error)
finalizer.pending.resolve(())
}
case .fulfilled:
finalizer.pending.resolve(())
}
}
return finalizer
}
}
public class PMKFinalizer {
let pending = Guarantee<Void>.pending()
/// `finally` is the same as `ensure`, but it is not chainable
public func finally(_ body: @escaping () -> Void) {
pending.guarantee.done(body)
}
}
public extension CatchMixin {
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain.
Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
firstly {
CLLocationManager.requestLocation()
}.recover { error in
guard error == CLError.unknownLocation else { throw error }
return .value(CLLocation.chicago)
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
func recover<U: Thenable>(on: DispatchQueue? = conf.Q.map, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> U) -> Promise<T> where U.T == T {
let rp = Promise<U.T>(.pending)
pipe {
switch $0 {
case .fulfilled(let value):
rp.box.seal(.fulfilled(value))
case .rejected(let error):
if policy == .allErrors || !error.isCancelled {
on.async {
do {
let rv = try body(error)
guard rv !== rp else { throw PMKError.returnedSelf }
rv.pipe(to: rp.box.seal)
} catch {
rp.box.seal(.rejected(error))
}
}
} else {
rp.box.seal(.rejected(error))
}
}
}
return rp
}
/**
The provided closure executes when this promise rejects.
This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`.
Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@discardableResult
func recover(on: DispatchQueue? = conf.Q.map, _ body: @escaping(Error) -> Guarantee<T>) -> Guarantee<T> {
let rg = Guarantee<T>(.pending)
pipe {
switch $0 {
case .fulfilled(let value):
rg.box.seal(value)
case .rejected(let error):
on.async {
body(error).pipe(to: rg.box.seal)
}
}
}
return rg
}
/**
The provided closure executes when this promise resolves, whether it rejects or not.
firstly {
UIApplication.shared.networkActivityIndicatorVisible = true
}.done {
//…
}.ensure {
UIApplication.shared.networkActivityIndicatorVisible = false
}.catch {
//…
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
func ensure(on: DispatchQueue? = conf.Q.return, _ body: @escaping () -> Void) -> Promise<T> {
let rp = Promise<T>(.pending)
pipe { result in
on.async {
body()
rp.box.seal(result)
}
}
return rp
}
/**
Consumes the Swift unused-result warning.
- Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear.
*/
func cauterize() {
self.catch {
Swift.print("PromiseKit:cauterized-error:", $0)
}
}
}
public extension CatchMixin where T == Void {
/**
The provided closure executes when this promise rejects.
This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@discardableResult
func recover(on: DispatchQueue? = conf.Q.map, _ body: @escaping(Error) -> Void) -> Guarantee<Void> {
let rg = Guarantee<Void>(.pending)
pipe {
switch $0 {
case .fulfilled:
rg.box.seal(())
case .rejected(let error):
on.async {
body(error)
rg.box.seal(())
}
}
}
return rg
}
/**
The provided closure executes when this promise rejects.
This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
func recover(on: DispatchQueue? = conf.Q.map, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> Void) -> Promise<Void> {
let rg = Promise<Void>(.pending)
pipe {
switch $0 {
case .fulfilled:
rg.box.seal(.fulfilled(()))
case .rejected(let error):
if policy == .allErrors || !error.isCancelled {
on.async {
do {
rg.box.seal(.fulfilled(try body(error)))
} catch {
rg.box.seal(.rejected(error))
}
}
} else {
rg.box.seal(.rejected(error))
}
}
}
return rg
}
}
| mit |
byu-oit/ios-byuSuite | byuSuite/Apps/YTime/controller/YTimeRootViewController.swift | 1 | 8754 | //
// YTimeRootViewController.swift
// byuSuite
//
// Created by Eric Romrell on 5/18/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import CoreLocation
private let TIMESHEETS_SEGUE_ID = "showTimesheets"
private let CALENDAR_SEGUE_ID = "showCalendar"
class YTimeRootViewController: ByuViewController2, UITableViewDataSource, CLLocationManagerDelegate, YTimePunchDelegate {
private struct UI {
static var fadeDuration = 0.25
}
//MARK: Outlets
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var viewTimesheetButton: UIBarButtonItem!
//MARK: Properties
private var refreshControl = UIRefreshControl()
private var timesheet: YTimeTimesheet?
private var punch: YTimePunch? //This object will hold a punch from the time that the button is tapped, through when the location is discovered, and finally until it is sent off to the web service.
private var punchLocation: CLLocation? //This will contain the last valid known location of the user. If location services aren't enabled, this should be nil.
private var locationManager: CLLocationManager!
private var loadingView: LoadingView?
override func viewDidLoad() {
super.viewDidLoad()
//Set up the location manager and start receiving updates
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
tableView.hideEmptyCells()
refreshControl = tableView.addDefaultRefreshControl(target: self, action: #selector(loadData))
loadData()
}
override func viewWillAppear(_ animated: Bool) {
locationManager.startUpdatingLocation()
NotificationCenter.default.addObserver(self, selector: #selector(viewWillEnterForeground), name: .UIApplicationWillEnterForeground, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
//Query status of Location Services to display error if disabled when returning to view from PunchView.
if CLLocationManager.locationServicesEnabled() == false {
showLocationError()
}
}
override func viewWillDisappear(_ animated: Bool) {
locationManager.stopUpdatingLocation()
NotificationCenter.default.removeObserver(self)
}
@objc func viewWillEnterForeground() {
//Reload the data on the screen
spinner?.startAnimating()
tableView.isUserInteractionEnabled = false
tableView.alpha = 0
loadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == TIMESHEETS_SEGUE_ID, let vc = segue.destination.childViewControllers.first as? YTimeJobsViewController, let jobs = timesheet?.jobs {
vc.jobs = jobs
} else if segue.identifier == CALENDAR_SEGUE_ID, let vc = segue.destination.childViewControllers.first as? YTimeCalendarViewController, let job = timesheet?.jobs.first {
//Use the first job, as this segue will only ever happen when the user only has one job
vc.job = job
}
}
deinit {
locationManager?.delegate = nil
}
//MARK: UITableViewDataSource/Delegate callbacks
func numberOfSections(in tableView: UITableView) -> Int {
//The first section contains all of the jobs, the second contains the hour summaries
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Return 2 for the weekly and period summaries
return section == 0 ? timesheet?.jobs.count ?? 0 : 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
tableView.estimatedRowHeight = 100
return UITableViewAutomaticDimension
} else {
return 45
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0, let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "jobCell") as? YTimeJobTableViewCell {
cell.delegate = self
cell.job = timesheet?.jobs[indexPath.row]
return cell
} else {
let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "paySummary")
if indexPath.row == 0 {
cell.textLabel?.text = "Week Total:"
cell.detailTextLabel?.text = timesheet?.weeklyTotal
} else {
cell.textLabel?.text = "Pay Period Total:"
cell.detailTextLabel?.text = timesheet?.periodTotal
}
return cell
}
}
//MARK: CLLocationMangerDelegate callbacks
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .denied || status == .restricted {
//Disable the table view so that nobody can quickly create a punch while we're segueing
self.tableView.isUserInteractionEnabled = false
//Remove queued punch and location
self.punchLocation = nil
self.punch = nil
showLocationError()
} else {
manager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
punchLocation = locations.last
punchIfReady()
}
//MARK: YTimePunchDelegate callback
func createPunch(punchIn: Bool, job: YTimeJob, sender: Any) {
if let employeeRecord = job.employeeRecord {
let startRequest: (() -> Void) = {
self.loadingView = self.displayLoadingView(message: "Submitting Punch...")
//Disable the table to prevent inadvertent multiple taps
self.tableView.isUserInteractionEnabled = false
//Set value of punch only after confirmation has been given in case of duplicate punch.
self.punch = YTimePunch(employeeRecord: employeeRecord, clockingIn: punchIn)
//We are now ready to punch whenever a location has been found
self.punchIfReady()
}
if punchIn == job.clockedIn {
//Verify that they want to double punch
let status = punchIn ? "in" : "out"
displayActionSheet(from: sender, title: "You are already clocked \(status). Please confirm that you would like to clock \(status) again.", actions: [
UIAlertAction(title: "Confirm", style: .default, handler: { (_) in
startRequest()
})
])
} else {
startRequest()
}
}
}
//MARK: Listeners
@objc func loadData() {
YTimeClient.getTimesheet { (sheet, error) in
//If refreshing the table, end the refresh control. If loading view for first time, stop the spinner and make the table visible.
self.refreshControl.endRefreshing()
self.spinner?.stopAnimating()
UIView.animate(withDuration: UI.fadeDuration) {
self.tableView.isUserInteractionEnabled = true
self.tableView.alpha = 1
}
if let sheet = sheet {
self.timesheet = sheet
self.viewTimesheetButton.isEnabled = true
} else {
//If the timesheet has previously been loaded let the user stay on this screen.
if self.timesheet == nil {
super.displayAlert(error: error)
} else {
super.displayAlert(error: error, alertHandler: nil)
}
}
self.tableView.reloadData()
}
}
@IBAction func didTapTimesheetButton(_ sender: Any) {
if timesheet?.jobs.count ?? 0 > 1 {
performSegue(withIdentifier: TIMESHEETS_SEGUE_ID, sender: sender)
} else {
performSegue(withIdentifier: CALENDAR_SEGUE_ID, sender: sender)
}
}
//MARK: Private functions
private func punchIfReady() {
if let location = punchLocation, let punch = punch {
punch.location = location
//Reset the punch location so that it will not be cached and sent again for a future punch.
self.punch = nil
self.punchLocation = nil
YTimeClient.createPunch(punch) { (sheet, error) in
self.loadingView?.removeFromSuperview()
self.tableView.isUserInteractionEnabled = true
if let sheet = sheet {
self.timesheet = sheet
self.showToast(message: "Your punch was submitted successfully.", dismissDelay: 5)
self.viewTimesheetButton.isEnabled = true
} else {
super.displayAlert(error: error, alertHandler: nil)
}
self.tableView.reloadData()
}
}
}
private func showLocationError() {
let alert = UIAlertController(title: "Location Services Required", message: "In order to use the Y-Time feature, location services must be enabled. Please change your settings to allow for this.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (_) in
self.popBack()
}))
alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (_) in
//Pop back so that they have to reenter the feature (and go through the same location permission requirements)
self.popBack()
if let url = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.open(url: url)
}
}))
//Only display the alert if the root View Controller is currently displayed
if self.view.window != nil {
present(alert, animated: true)
}
}
}
| apache-2.0 |
indragiek/MarkdownTextView | MarkdownTextView/MarkdownLinkHighlighter.swift | 2 | 1027 | //
// MarkdownLinkHighlighter.swift
// MarkdownTextView
//
// Created by Indragie on 4/29/15.
// Copyright (c) 2015 Indragie Karunaratne. All rights reserved.
//
import UIKit
/**
* Highlights Markdown links (not including link references)
*/
public final class MarkdownLinkHighlighter: HighlighterType {
// From markdown.pl v1.0.1 <http://daringfireball.net/projects/markdown/>
private static let LinkRegex = regexFromPattern("\\[([^\\[]+)\\]\\([ \t]*<?(.*?)>?[ \t]*((['\"])(.*?)\\4)?\\)")
// MARK: HighlighterType
public func highlightAttributedString(attributedString: NSMutableAttributedString) {
let string = attributedString.string
enumerateMatches(self.dynamicType.LinkRegex, string: string) {
let URLString = (string as NSString).substringWithRange($0.rangeAtIndex(2))
let linkAttributes = [
NSLinkAttributeName: URLString
]
attributedString.addAttributes(linkAttributes, range: $0.range)
}
}
}
| mit |
Hout/Period | Pod/Classes/PeriodOperators.swift | 1 | 2350 | //
// PeriodOperators.swift
// Pods
//
// Created by Jeroen Houtzager on 09/11/15.
//
//
extension NSDate {
/// Returns `true` when the receiver date is within the period.
///
/// - Parameters:
/// - period: the period to evaluate the date against
///
/// - Returns: `true` if the date is within the period, `false` if it is before the start date or after the end date.
///
/// - Note: start- and end dates are part of the period!
public func inPeriod(period: Period) -> Bool {
if self.compare(period.startDate) == NSComparisonResult.OrderedAscending {
return false
}
if self.compare(period.endDate) == NSComparisonResult.OrderedDescending {
return false
}
return true
}
}
extension Period {
/// Returns `true` when the receiver period is within the given period.
///
/// - Parameters:
/// - period: the period to evaluate the receiver against
///
/// - Returns: `true` if the receiver period is completely within the given period,
/// `false` if the receiver start date is before `period` start date or the receiver end date is after `period` end date.
///
/// - Note: start- and end dates are part of the period!
public func inPeriod(period: Period) -> Bool {
if startDate.compare(period.startDate) == NSComparisonResult.OrderedAscending {
return false
}
if endDate.compare(period.endDate) == NSComparisonResult.OrderedDescending {
return false
}
return true
}
/// Returns `true` when the receiver period overlaps the given period.
///
/// - Parameters:
/// - period: the period to evaluate the receiver against
///
/// - Returns: `true` if the receiver period overlaps within the given period,
/// `false` if the receiver ends before `period` or the receiver starts after `period`.
///
/// - Note: start- and end dates are part of the period!
public func overlapsPeriod(period: Period) -> Bool {
if startDate.compare(period.endDate) == NSComparisonResult.OrderedDescending {
return false
}
if endDate.compare(period.startDate) == NSComparisonResult.OrderedAscending {
return false
}
return true
}
}
| mit |
TheAppCookbook/templates | templates/ACBInfoPanel/NSURL+ACBUrls.swift | 1 | 658 | //
// NSURL+ACBUrls.swift
// ACBInfoPanel
//
// Created by PATRICK PERINI on 8/9/15.
// Copyright (c) 2015 AppCookbook. All rights reserved.
//
import Foundation
public extension NSURL {
// MARK: Constants
public static var cookbookInfoURL: NSURL! { return NSURL(string: "http://the.appcookbook.in") }
// Twitter
public static var cookbookTwitterURL: NSURL! { return NSURL(string: "http://twitter.com/@TheAppCookbook") }
public static var alecTwitterURL: NSURL! { return NSURL(string: "http://twitter.com/@alecat1008") }
public static var patrickTwitterURL: NSURL! { return NSURL(string: "http://twitter.com/@pcperini") }
} | mit |
dhardiman/Fetch | Tests/FetchTests/FetchTests.swift | 1 | 13635 | //
// FetchTests.swift
// FetchTests
//
// Created by David Hardiman on 13/02/2016.
// Copyright © 2016 David Hardiman. All rights reserved.
//
@testable import Fetch
import Nimble
import OHHTTPStubs
import XCTest
let testString = "{ \"name\": \"test name\", \"desc\": \"test desc\" }"
let testURL = URL(string: "https://fetch.davidhardiman.me")!
let basicRequest = BasicURLRequest(url: testURL)
struct TestResponse: Parsable {
enum Fail: Error {
case statusFail
case parseFail
}
let name: String
let desc: String
let response: Response
static func parse(response: Response, errorParser: ErrorParsing.Type?) -> FetchResult<TestResponse> {
if response.status != 200 {
return .failure(Fail.statusFail)
}
do {
if let data = response.data, let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String] {
return .success(TestResponse(name: dict["name"]!, desc: dict["desc"]!, response: response))
}
} catch {}
return .failure(Fail.parseFail)
}
}
enum CustomError: ErrorParsing, Error {
static func parseError(from data: Data?, statusCode: Int) -> Error? {
return CustomError.error
}
case error
}
class FetchTests: XCTestCase {
var session: Session!
override func setUp() {
super.setUp()
session = Session()
}
override func tearDown() {
session = nil
HTTPStubs.removeAllStubs()
super.tearDown()
}
func stubRequest(statusCode: Int32 = 200, passingTest test: @escaping HTTPStubsTestBlock) {
HTTPStubs.stubRequests(passingTest: test) { (_) -> HTTPStubsResponse in
return HTTPStubsResponse(data: testString.data(using: String.Encoding.utf8)!, statusCode: statusCode, headers: ["header": "test header"])
}
}
typealias TestBlock = (FetchResult<TestResponse>?) -> Void
func performGetRequestTest(request: Request = basicRequest, statusCode: Int32 = 200, passingTest requestTest: HTTPStubsTestBlock?, testBlock testToPerform: TestBlock) {
if let requestTest = requestTest {
stubRequest(statusCode: statusCode, passingTest: requestTest)
}
let exp = expectation(description: "get request")
var receivedResult: FetchResult<TestResponse>?
session.perform(request) { (result: FetchResult<TestResponse>) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
testToPerform(receivedResult)
}
func testItIsPossibleToMakeAGetRequest() {
performGetRequestTest(passingTest: { (request) -> Bool in
request.url! == testURL && request.httpMethod == "GET"
}, testBlock: { receivedResult in
guard let testResult = receivedResult else {
fail("Should have received a result")
return
}
switch testResult {
case .success(let response):
expect(response.name).to(equal("test name"))
expect(response.desc).to(equal("test desc"))
expect(response.response.headers).to(equal(["header": "test header", "Content-Length": "44"]))
default:
fail("Should be a successful response")
}
})
}
func testItIsPossibleToMakeAPostRequest() {
stubRequest { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "POST"
}
let exp = expectation(description: "post request")
var receivedResult: FetchResult<TestResponse>?
session.perform(BasicURLRequest(url: testURL, method: .post)) { (result: FetchResult<TestResponse>) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
switch receivedResult! {
case .success:
break
default:
fail("Should be a successful response")
}
}
func testSessionErrorsAreReturned() {
let testError = NSError(domain: "me.davidhardiman", code: 1234, userInfo: nil)
HTTPStubs.stubRequests(passingTest: { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "GET"
}, withStubResponse: { (_) -> HTTPStubsResponse in
return HTTPStubsResponse(error: testError)
})
performGetRequestTest(passingTest: nil) { receivedResult in
switch receivedResult! {
case .failure(let receivedError as NSError):
expect(receivedError.domain).to(equal(testError.domain))
expect(receivedError.code).to(equal(testError.code))
default:
fail("Should be an error response")
}
}
}
func testStatusCodesAreReportedToAllowParseFailures() {
performGetRequestTest(statusCode: 404, passingTest: { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "GET"
}, testBlock: { receivedResult in
switch receivedResult! {
case .failure(let receivedError as TestResponse.Fail):
expect(receivedError).to(equal(TestResponse.Fail.statusFail))
default:
fail("Should be an error response")
}
})
}
func testUserInfoIsPassedFromTheRequestToTheResponse() {
let request = BasicURLRequest(url: testURL, userInfo: ["Test": "Test Value!"])
let requestTestBlock = { (request: URLRequest) -> Bool in
let urlMatch = request.url == testURL
let methodMatch = request.httpMethod == "GET"
return urlMatch && methodMatch
}
performGetRequestTest(request: request, passingTest: requestTestBlock) { (receivedResult) -> Void in
switch receivedResult! {
case .success(let response):
expect(response.response.userInfo?["Test"] as? String).to(equal("Test Value!"))
default:
fail("Should be a successful response")
}
}
}
func testHeadersArePassedToTheRequest() {
let testRequest = BasicURLRequest(url: testURL, headers: ["Test Header": "Test Value"], body: nil)
let requestTestBlock = { (request: URLRequest) -> Bool in
let urlMatch = request.url == testURL
let methodMatch = request.httpMethod == "GET"
let headersMatch = request.allHTTPHeaderFields! == ["Test Header": "Test Value"]
return urlMatch && methodMatch && headersMatch
}
performGetRequestTest(request: testRequest, passingTest: requestTestBlock) { (receivedResult) -> Void in
switch receivedResult! {
case .success:
break
default:
fail("Should be a successful response")
}
}
}
func testBodyIsPassedToTheRequest() {
let testBody = "test body"
let testRequest = BasicURLRequest(url: testURL, method: .post, headers: nil, body: testBody.data(using: String.Encoding.utf8))
stubRequest { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "POST"
}
let mockSession = MockSession()
session = Session(session: mockSession)
session.perform(testRequest) { (_: FetchResult<TestResponse>) in
}
expect(mockSession.receivedBody).to(equal(testBody))
}
func testTheHTTPMethodIsPassedToTheResponse() {
stubRequest { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "TRACE"
}
let exp = expectation(description: "trace request")
var receivedResult: FetchResult<TestResponse>?
session.perform(BasicURLRequest(url: testURL, method: .trace)) { (result: FetchResult<TestResponse>) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
switch receivedResult! {
case .success(let response):
expect(response.response.originalRequest.method).to(equal(.trace))
default:
fail("Should be a successful response")
}
}
func testCallbackQueueCanBeSpecified() {
let callBackQueue = OperationQueue()
stubRequest { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "POST"
}
let exp = expectation(description: "post request")
var receivedQueue: OperationQueue?
session = Session(responseQueue: callBackQueue)
session.perform(BasicURLRequest(url: testURL, method: .post)) { (_: FetchResult<TestResponse>) in
receivedQueue = OperationQueue.current
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
expect(receivedQueue).to(equal(callBackQueue))
}
func testAnUnknownResponseTypeReturnsAnError() {
let mockSession = MockSession()
mockSession.mockResponse = URLResponse()
session = Session(session: mockSession)
var receivedResult: FetchResult<TestResponse>?
let exp = expectation(description: "test request")
session.perform(basicRequest) { (result: FetchResult<TestResponse>) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
guard let result = receivedResult, case .failure(let error) = result else {
return fail("Expected a failure")
}
guard let sessionError = error as? SessionError else {
return fail("Expected a session error")
}
expect(sessionError).to(equal(SessionError.unknownResponseType))
}
func testAllTasksCanBeCancelled() {
let mockSession = MockSession()
session = Session(session: mockSession)
let task1 = session.perform(BasicURLRequest(url: testURL), completion: { (_: FetchResult<TestResponse>) in }) as? MockTask
let task2 = session.perform(BasicURLRequest(url: testURL), completion: { (_: FetchResult<TestResponse>) in }) as? MockTask
session.cancelAllTasks()
expect(task1?.cancelCalled).to(beTrue())
expect(task2?.cancelCalled).to(beTrue())
}
func testNoDataResponseSuccess() {
stubRequest { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "GET"
}
let exp = expectation(description: "get request")
var receivedResult: VoidResult?
session.perform(BasicURLRequest(url: testURL)) { (result: VoidResult) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
switch receivedResult! {
case .success:
break
case .failure:
fail("Should be a successful response")
}
}
func testNoDataResponseFailure() {
stubRequest(statusCode: 400) { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "GET"
}
let exp = expectation(description: "get request")
var receivedResult: VoidResult?
session.perform(BasicURLRequest(url: testURL)) { (result: VoidResult) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
switch receivedResult! {
case .success:
fail("Should be a failing response")
case let .failure(NoDataResponseError.httpError(code)):
expect(code).to(equal(400))
default:
fail("Should be a 400 response")
}
}
func testNoDataResponseFailureWithCustomErrorHandler() {
stubRequest(statusCode: 400) { (request) -> Bool in
return request.url! == testURL && request.httpMethod == "GET"
}
let exp = expectation(description: "get request")
var receivedResult: VoidResult?
session.perform(BasicURLRequest(url: testURL), errorParser: CustomError.self) { (result: VoidResult) in
receivedResult = result
exp.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
switch receivedResult! {
case .success:
fail("Should be a failing response")
case .failure(let error as CustomError):
expect(error).to(equal(CustomError.error))
default:
fail("Expected a custom error")
}
}
}
public class MockSession: URLSession {
var receivedBody: String?
var mockResponse: URLResponse?
public override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
if let body = request.httpBody {
receivedBody = String(data: body, encoding: String.Encoding.utf8)
}
if let mockResponse = mockResponse {
completionHandler(nil, mockResponse, nil)
}
let task = MockTask()
mockedTasks.append(task)
return task
}
var mockedTasks = [URLSessionTask]()
public override func getAllTasks(completionHandler: @escaping ([URLSessionTask]) -> Void) {
completionHandler(mockedTasks)
}
}
public class MockTask: URLSessionDataTask {
var cancelCalled = false
public override func cancel() {
cancelCalled = true
}
override public func resume() {}
}
| mit |
MidnightPulse/Tabman | Sources/Tabman/TabmanBar/Utilities/ImageUtils.swift | 4 | 785 | //
// ImageUtils.swift
// Tabman
//
// Created by Merrick Sapsford on 14/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
extension UIImage {
func resize(toSize size: CGSize) -> UIImage {
let scale = size.width / self.size.width
let newHeight = self.size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: size.width, height: newHeight),
false,
UIScreen.main.scale)
self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? self
}
}
| mit |
coinbase/coinbase-ios-sdk | Tests/Integration/UserResourceSpec.swift | 1 | 2816 | //
// UserSpec.swift
// Coinbase
//
// Copyright © 2018 Coinbase, Inc. All rights reserved.
//
@testable import CoinbaseSDK
import Quick
import Nimble
import OHHTTPStubs
class UserResourceSpec: QuickSpec, IntegrationSpecProtocol {
override func spec() {
describe("UserResource") {
let userResource = specVar { Coinbase(accessToken: StubConstants.accessToken).userResource }
describe("current") {
itBehavesLikeResource(with: "auth_user.json",
requestedBy: { comp in userResource().current(completion: comp) },
expectationsForRequest: request(ofMethod: .get) && url(withPath: "/user") && hasAuthorization(),
expectationsForResult: successfulResult(ofType: User.self))
}
describe("get(by: ") {
let userID = "user_id"
itBehavesLikeResource(with: "user_by_id.json",
requestedBy: { comp in userResource().get(by: userID, completion: comp) },
expectationsForRequest: request(ofMethod: .get) && url(withPath: "/users/\(userID)") && hasAuthorization(),
expectationsForResult: successfulResult(ofType: User.self))
}
describe("authorizationInfo") {
itBehavesLikeResource(with: "auth_info.json",
requestedBy: { comp in userResource().authorizationInfo(completion: comp) },
expectationsForRequest: request(ofMethod: .get) && url(withPath: "/user/auth") && hasAuthorization(),
expectationsForResult: successfulResult(ofType: AuthorizationInfo.self))
}
describe("updateCurrent") {
let newName = "newName"
let timeZone = "newTimeZone"
let nativeCurrency = "newNativeCurrency"
let expectedBody = [
"name": newName,
"time_zone": timeZone,
"native_currency": nativeCurrency
]
itBehavesLikeResource(with: "auth_user.json",
requestedBy: { comp in userResource().updateCurrent(name: newName, timeZone: timeZone, nativeCurrency: nativeCurrency, completion: comp) },
expectationsForRequest: request(ofMethod: .put) && url(withPath: "/user") && hasAuthorization() && hasBody(parameters: expectedBody),
expectationsForResult: successfulResult(ofType: User.self))
}
}
}
}
| apache-2.0 |
emalyak/CMAltimeterDemo | CMAltimeterDemoTests/CMAltimeterDemoTests.swift | 1 | 919 | //
// CMAltimeterDemoTests.swift
// CMAltimeterDemoTests
//
// Created by Erik Malyak on 9/21/14.
// Copyright (c) 2014 Erik Malyak. All rights reserved.
//
import UIKit
import XCTest
class CMAltimeterDemoTests: 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 |
uasys/swift | test/IRGen/protocol_metadata.swift | 4 | 6760 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
@objc optional func opt()
@objc optional static func static_opt()
@objc optional var prop: O { get }
@objc optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// CHECK: @_T017protocol_metadata1AMp = hidden constant %swift.protocol {
// -- size 72
// -- flags: 1 = Swift | 2 = Not Class-Constrained | 4 = Needs Witness Table
// CHECK-SAME: i32 72, i32 7,
// CHECK-SAME: i16 1, i16 1,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[A_REQTS:@.*]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @_T017protocol_metadata1AMp, i32 0, i32 12) to i64)) to i32)
// CHECK-SAME: }
// CHECK: @_T017protocol_metadata1BMp = hidden constant %swift.protocol {
// CHECK-SAME: i32 72, i32 7,
// CHECK-SAME: i16 1, i16 1,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[B_REQTS:@.*]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @_T017protocol_metadata1BMp, i32 0, i32 12) to i64)) to i32)
// CHECK: }
// CHECK: @_T017protocol_metadata1CMp = hidden constant %swift.protocol {
// -- flags: 1 = Swift | 4 = Needs Witness Table
// CHECK-SAME: i32 72, i32 5,
// CHECK-SAME: i16 1, i16 1,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[C_REQTS:@.*]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @_T017protocol_metadata1CMp, i32 0, i32 12) to i64)) to i32)
// CHECK-SAME: }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant { {{.*}} i32, [1 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK-SAME: }
// CHECK: [[A_REQTS]] = internal unnamed_addr constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0 }]
// CHECK: [[B_REQTS]] = internal unnamed_addr constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0 }]
// CHECK: [[C_REQTS]] = internal unnamed_addr constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0 }]
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK-SAME: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 2,
// CHECK: %swift.protocol* @_T017protocol_metadata1AMp,
// CHECK: %swift.protocol* @_T017protocol_metadata1BMp
// CHECK: }
// CHECK: [[AB_REQTS:@.*]] = internal unnamed_addr constant [3 x %swift.protocol_requirement] [%swift.protocol_requirement zeroinitializer, %swift.protocol_requirement zeroinitializer, %swift.protocol_requirement { i32 17, i32 0 }]
// CHECK: @_T017protocol_metadata2ABMp = hidden constant %swift.protocol {
// CHECK-SAME: [[AB_INHERITED]]
// CHECK-SAME: i32 72, i32 7,
// CHECK-SAME: i16 3, i16 3,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([3 x %swift.protocol_requirement]* [[AB_REQTS]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @_T017protocol_metadata2ABMp, i32 0, i32 12) to i64)) to i32)
// CHECK-SAME: }
// CHECK: [[ABO_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 3,
// CHECK: %swift.protocol* @_T017protocol_metadata1AMp,
// CHECK: %swift.protocol* @_T017protocol_metadata1BMp,
// CHECK: {{.*}}* @_PROTOCOL__TtP17protocol_metadata1O_
// CHECK: }
protocol Comprehensive {
associatedtype Assoc : A
init()
func instanceMethod()
static func staticMethod()
var instance: Assoc { get set }
static var global: Assoc { get set }
}
// CHECK: [[COMPREHENSIVE_REQTS:@.*]] = internal unnamed_addr constant [11 x %swift.protocol_requirement]
// CHECK-SAME: [%swift.protocol_requirement { i32 6, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 7, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 2, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 17, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 1, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 19, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 20, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 21, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 3, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 4, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 5, i32 0 }]
func reify_metadata<T>(_ x: T) {}
// CHECK: define hidden swiftcc void @_T017protocol_metadata0A6_types{{[_0-9a-zA-Z]*}}F
func protocol_types(_ a: A,
abc: A & B & C,
abco: A & B & C & O) {
// CHECK: store %swift.protocol* @_T017protocol_metadata1AMp
// CHECK: call %swift.type* @swift_rt_swift_getExistentialTypeMetadata(i1 true, %swift.type* null, i64 1, %swift.protocol** {{%.*}})
reify_metadata(a)
// CHECK: store %swift.protocol* @_T017protocol_metadata1AMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1BMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1CMp
// CHECK: call %swift.type* @swift_rt_swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 3, %swift.protocol** {{%.*}})
reify_metadata(abc)
// CHECK: store %swift.protocol* @_T017protocol_metadata1AMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1BMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1CMp
// CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_"
// CHECK: [[O_REF_BITCAST:%.*]] = bitcast i8* [[O_REF]] to %swift.protocol*
// CHECK: store %swift.protocol* [[O_REF_BITCAST]]
// CHECK: call %swift.type* @swift_rt_swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 4, %swift.protocol** {{%.*}})
reify_metadata(abco)
}
| apache-2.0 |
mutualmobile/VIPER-SWIFT | VIPER-SWIFT/Classes/Modules/List/User Interface/Presenter/ListPresenter.swift | 1 | 1587 | //
// ListPresenter.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
import UIKit
class ListPresenter : NSObject, ListInteractorOutput, ListModuleInterface, AddModuleDelegate {
var listInteractor : ListInteractorInput?
var listWireframe : ListWireframe?
var userInterface : ListViewInterface?
// MARK: ListInteractorOutput
func foundUpcomingItems(_ upcomingItems: [UpcomingItem]) {
if upcomingItems.count == 0 {
userInterface?.showNoContentMessage()
} else {
updateUserInterfaceWithUpcomingItems(upcomingItems)
}
}
func updateUserInterfaceWithUpcomingItems(_ upcomingItems: [UpcomingItem]) {
let upcomingDisplayData = upcomingDisplayDataWithItems(upcomingItems)
userInterface?.showUpcomingDisplayData(upcomingDisplayData)
}
func upcomingDisplayDataWithItems(_ upcomingItems: [UpcomingItem]) -> UpcomingDisplayData {
let collection = UpcomingDisplayDataCollection()
collection.addUpcomingItems(upcomingItems)
return collection.collectedDisplayData()
}
// MARK: ListModuleInterface
func addNewEntry() {
listWireframe?.presentAddInterface()
}
func updateView() {
listInteractor?.findUpcomingItems()
}
// MARK: AddModuleDelegate
func addModuleDidCancelAddAction() {
// No action necessary
}
func addModuleDidSaveAddAction() {
updateView()
}
}
| mit |
nghiaphunguyen/NReact | NReact/Source/Protocols/NKActionable.swift | 1 | 251 | //
// NKActionable.swift
// NKit
//
// Created by Nghia Nguyen on 12/18/16.
// Copyright © 2016 Nghia Nguyen. All rights reserved.
//
import Foundation
public protocol NKActionable {
associatedtype NKAction
var action: NKAction {get}
}
| mit |
Aaron-zheng/SwiftTips | swifttips/swifttips/ControllerStatusBar.swift | 1 | 446 | //
// ControllerStatusBar.swift
// swifttips
//
// Created by Aaron on 5/8/2016.
// Copyright © 2016 sightcorner. All rights reserved.
//
import Foundation
import UIKit
/**
更改 status bar (运营商,时间,电池) 为白色
需要先修改 info.plist 里的 View controller-based status bar appearance 为 NO
*/
public func changeStatusBarToLight() {
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
| apache-2.0 |
swift-lang/swift-k | tests/functions/system_commandnotfound.swift | 1 | 128 | // THIS-SCRIPT-SHOULD-FAIL
type file;
string results[] = system("fdjskflsdk");
foreach r in results {
tracef("%s\n", r);
}
| apache-2.0 |
esttorhe/YOChartImageKit | Example/YOGraphImageKit Demo App (watchOS) Extension/BarChartInterfaceController.swift | 3 | 411 | import WatchKit
class BarChartInterfaceController: BaseInterfaceController {
override func willActivate() {
super.willActivate()
let chart = YOChart.BarChart
let frame = CGRectMake(0, 0, contentFrame.width, contentFrame.height / 1.5)
let image = chart.drawImage(frame, scale: WKInterfaceDevice.currentDevice().screenScale)
self.imageView.setImage(image)
}
}
| mit |
ibm-cloud-security/appid-clientsdk-swift | Source/IBMCloudAppID/internal/SecurityUtils.swift | 1 | 10424 | /* * Copyright 2016, 2017 IBM Corp.
* 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
internal class SecurityUtils {
private static func getKeyBitsFromKeyChain(_ tag:String) throws -> Data {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnData : true as AnyObject
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw AppIDError.generalError
}
return result as! Data
}
internal static func generateKeyPairAttrs(_ keySize:Int, publicTag:String, privateTag:String) -> [NSString:AnyObject] {
let privateKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : privateTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPrivate,
kSecAttrAccessible: AppID.secAttrAccess.rawValue
]
let publicKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : publicTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPublic,
kSecAttrAccessible: AppID.secAttrAccess.rawValue
]
let keyPairAttr : [NSString:AnyObject] = [
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrAccessible: AppID.secAttrAccess.rawValue,
kSecAttrKeySizeInBits : keySize as AnyObject,
kSecPublicKeyAttrs : publicKeyAttr as AnyObject,
kSecPrivateKeyAttrs : privateKeyAttr as AnyObject
]
return keyPairAttr
}
internal static func generateKeyPair(_ keySize:Int, publicTag:String, privateTag:String) throws {
//make sure keys are deleted
_ = SecurityUtils.deleteKeyFromKeyChain(publicTag)
_ = SecurityUtils.deleteKeyFromKeyChain(privateTag)
var status:OSStatus = noErr
var privateKey:SecKey?
var publicKey:SecKey?
let keyPairAttr = generateKeyPairAttrs(keySize, publicTag: publicTag, privateTag: privateTag)
status = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
if (status != errSecSuccess) {
throw AppIDError.generalError
}
}
static func getKeyRefFromKeyChain(_ tag:String) throws -> SecKey {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnRef : kCFBooleanTrue
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw AppIDError.generalError
}
return result as! SecKey
}
internal static func getItemFromKeyChain(_ label:String) -> String? {
let query: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecReturnData: kCFBooleanTrue
]
var results: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &results)
if status == errSecSuccess {
let data = results as! Data
let password = String(data: data, encoding: String.Encoding.utf8)!
return password
}
return nil
}
public static func getJWKSHeader() throws ->[String:Any] {
let publicKey = try? SecurityUtils.getKeyBitsFromKeyChain(AppIDConstants.publicKeyIdentifier)
guard let unWrappedPublicKey = publicKey, let pkModulus : Data = getPublicKeyMod(unWrappedPublicKey), let pkExponent : Data = getPublicKeyExp(unWrappedPublicKey) else {
throw AppIDError.generalError
}
let mod:String = Utils.base64StringFromData(pkModulus, isSafeUrl: true)
let exp:String = Utils.base64StringFromData(pkExponent, isSafeUrl: true)
let publicKeyJSON : [String:Any] = [
"e" : exp as AnyObject,
"n" : mod as AnyObject,
"kty" : AppIDConstants.JSON_RSA_VALUE
]
return publicKeyJSON
}
private static func getPublicKeyMod(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
_ = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1 // TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
// Ensure we got an exponent size
guard mod_size != -1, let range = Range(NSMakeRange(iterator, mod_size)) else {
return nil
}
return publicKeyBits.subdata(in: range)
}
//Return public key exponent
private static func getPublicKeyExp(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
_ = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1// TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
iterator += mod_size
iterator += 1 // TYPE - bit stream exp
let exp_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
//Ensure we got an exponent size
guard exp_size != -1, let range = Range(NSMakeRange(iterator, exp_size)) else {
return nil
}
return publicKeyBits.subdata(in: range)
}
private static func derEncodingGetSizeFrom(_ buf : Data, at iterator: inout Int) -> Int{
// Have to cast the pointer to the right size
//let pointer = UnsafePointer<UInt8>((buf as NSData).bytes)
//let count = buf.count
// Get our buffer pointer and make an array out of it
//let buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
let data = buf//[UInt8](buffer)
var itr : Int = iterator
var num_bytes :UInt8 = 1
var ret : Int = 0
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80
itr += 1
}
for i in 0 ..< Int(num_bytes) {
ret = (ret * 0x100) + Int(data[itr + i])
}
iterator = itr + Int(num_bytes)
return ret
}
internal static func signString(_ payloadString:String, keyIds ids:(publicKey: String, privateKey: String), keySize: Int) throws -> String {
do {
let privateKeySec = try getKeyRefFromKeyChain(ids.privateKey)
guard let payloadData : Data = payloadString.data(using: String.Encoding.utf8) else {
throw AppIDError.generalError
}
let signedData = try signData(payloadData, privateKey:privateKeySec)
//return signedData.base64EncodedString()
return Utils.base64StringFromData(signedData, isSafeUrl: true)
}
catch {
throw AppIDError.generalError
}
}
private static func signData(_ data:Data, privateKey:SecKey) throws -> Data {
func doSha256(_ dataIn:Data) throws -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
dataIn.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(dataIn.count), &hash)
}
return Data(bytes: hash)
}
guard let digest:Data = try? doSha256(data), let signedData: NSMutableData = NSMutableData(length: SecKeyGetBlockSize(privateKey)) else {
throw AppIDError.generalError
}
var signedDataLength: Int = signedData.length
let digestBytes: UnsafePointer<UInt8> = ((digest as NSData).bytes).bindMemory(to: UInt8.self, capacity: digest.count)
let digestlen = digest.count
let mutableBytes: UnsafeMutablePointer<UInt8> = signedData.mutableBytes.assumingMemoryBound(to: UInt8.self)
let signStatus:OSStatus = SecKeyRawSign(privateKey, SecPadding.PKCS1SHA256, digestBytes, digestlen,
mutableBytes, &signedDataLength)
guard signStatus == errSecSuccess else {
throw AppIDError.generalError
}
return signedData as Data
}
internal static func saveItemToKeyChain(_ data:String, label: String) -> Bool{
guard let stringData = data.data(using: String.Encoding.utf8) else {
return false
}
let key: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecValueData: stringData as AnyObject
]
var status = SecItemAdd(key as CFDictionary, nil)
if(status != errSecSuccess){
if(SecurityUtils.removeItemFromKeyChain(label) == true) {
status = SecItemAdd(key as CFDictionary, nil)
}
}
return status == errSecSuccess
}
internal static func removeItemFromKeyChain(_ label: String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
internal static func deleteKeyFromKeyChain(_ tag:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag : tag as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
}
| apache-2.0 |
midmirror/MetaBrowser | MetaBrowser/MetaBrowser/Class/View/BottomToolbar.swift | 1 | 3095 | //
// BottomBar.swift
// MetaBrowser
//
// Created by midmirror on 17/6/22.
// Copyright © 2017年 midmirror. All rights reserved.
//
import UIKit
class BottomToolbar: UIToolbar {
typealias BackClosure = () -> Void
typealias ForwardClosure = () -> Void
typealias FunctionClosure = () -> Void
typealias HomeClosure = () -> Void
typealias PageClosure = () -> Void
var backClosure: BackClosure?
var forwardClosure:ForwardClosure?
var functionClosure: FunctionClosure?
var homeClosure: HomeClosure?
var pageClosure: PageClosure?
override init(frame: CGRect) {
super.init(frame: frame)
let icon = MetaBrowserIcon.init(color: .black, size: 25)
let spaceItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
let backItem = UIBarButtonItem.init(image: icon.image(code: MetaBrowserIcon.back), style: UIBarButtonItemStyle.plain, target: self, action: #selector(goBack))
let forwardItem = UIBarButtonItem.init(image: icon.image(code: MetaBrowserIcon.forward), style: UIBarButtonItemStyle.plain, target: self, action: #selector(goForward))
let functionItem = UIBarButtonItem.init(image: icon.image(code: MetaBrowserIcon.function), style: UIBarButtonItemStyle.plain, target: self, action: #selector(touchFunction))
let homeItem = UIBarButtonItem.init(image: icon.image(code: MetaBrowserIcon.home), style: UIBarButtonItemStyle.plain, target: self, action: #selector(touchHome))
let pageItem = UIBarButtonItem.init(image: icon.image(code: MetaBrowserIcon.page), style: UIBarButtonItemStyle.plain, target: self, action: #selector(touchPage))
self.items = [backItem, spaceItem, forwardItem, spaceItem, functionItem, spaceItem, homeItem, spaceItem, pageItem]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func whenGoBack(closure: @escaping BackClosure) {
backClosure = closure
}
func whenGoForward(closure: @escaping ForwardClosure) {
forwardClosure = closure
}
func whenTouchFunction(closure: @escaping FunctionClosure) {
functionClosure = closure
}
func whenTouchHome(closure: @escaping HomeClosure) {
homeClosure = closure
}
func whenTouchPage(closure: @escaping PageClosure) {
pageClosure = closure
}
func goBack() {
if let backClosure = self.backClosure {
backClosure()
}
}
func goForward() {
if let forwardClosure = self.forwardClosure {
forwardClosure()
}
}
func touchFunction() {
if let functionClosure = self.functionClosure {
functionClosure()
}
}
func touchHome() {
if let homeClosure = self.homeClosure {
homeClosure()
}
}
func touchPage() {
if let pageClosure = self.pageClosure {
pageClosure()
}
}
}
| gpl-3.0 |
shvets/WebAPI | Sources/WebAPI/Files-extension.swift | 1 | 161 | import Foundation
import Files
extension File {
class func exists(atPath path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
} | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.