测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可 | Apache 2 |
发布最后发布 | 2017年3月 |
SwiftSwift版本 | 3.0 |
SPM支持SPM | ✓ |
由 Daniel Leping 维护。
模板库最初是为满足 Swift Express - Swift 的 Web 应用服务器端框架的需求而引入的。现在它是 Crossroad Labs 基础设施的一部分。
尽管如此,我们仍希望对其他人也有用。
将以下依赖项添加到您的 Package.swift
.Package(url: "https://github.com/crossroadlabs/Boilerplate.git", majorVersion: 0)
运行 swift build
构建您的应用。包管理器支持 OS X,但建议仅在 Linux 上使用。
Swift 3.0 的标准库 API 与 Swift 2.2 相比有很大变化。您可以将 Boilerplate 和以下代码(Swift 3.0 风格)导入,它将与您的 Swift 2.2 编译器一起运行
var array = ["a", "b", "c"]
array.append(contentsOf: ["e"]) //this is not correct in Swift 2.2 without Boilerplate
下面是一个快速示例,展示了如何轻松使用 Timeout 管理不同的时间 API
let to = Timeout.Infinity
XCTAssertEqual(to.timeSinceNow(), NSDate.distantFuture())
XCTAssertEqual(to.timeInterval, Double.infinity)
//convert to NSTimeInterval
to.timeInterval
//convert to NSDate
to.timeSinceNow()
//convert to dispatch_time_t
to.dispatchTime
其想法是将 (A, B, C...)->Z
转换为 (A)->(B)->(C)->...->Z
,分别称为 Curry 和 Uncurry。
func ftwo(b:Bool, i:Int) -> String {
return String(b) + "_" + String(i)
}
let ctwo = curry(ftwo)
print(ctwo(true)(1)) //call curried function
let utwo = uncurry(ctwo)
print(utwo(false, 0)) //uncurried back works as expected
允许以元组形式部分或完全应用函数
func fthree(b:Bool, i:Int, d:Double) -> String {
return String(b) + "_" + String(i) + "_" + String(d)
}
let fbi = (__, __, 1.0) |> fthree //operator way, __ stands for an argument
//you don't want to apply right now.
let fi = (true, __, 1.0) |> fthree //operator way
let fd = apply(args: (true, 1, _), to: fthree) //function way
print(fbi(false, 0)) //prints "false_0_1.0"
print(fi(0)) //prints "true_0_1.0"
print(fd(0.0)) //prints "true_1_0.0"
print((false, 0, 0.0) |> fthree) //full apply, prints "false_0_0.0"
行为与apply类似,但较弱。即传入的参数不会被保留。目前仅支持单个参数。在《UIViewController》中使用非常有用,可以避免保留self
//func inside UIViewController
//just imagine it does something very important
func mymagicfunc(s:String) {
print(self, s)
}
//your very advanced int formatting dependent on self
func myintformat(i:Int) -> String {
return self._formatWith(self._format, i)
}
//you can safely do that and self is not retained
//any calls to self._myprocstored will just do nothing if self isn't there anymore
self._myprocstored = self ~> ViewController.mymagicfunc
//format now has a signature of `(Int)->String?`; ? is not a mistake
let format = self ~> ViewController.myintformat
这里的格式是一个特殊函数。当self
存在时返回值,当不存在时返回nil
。返回值被转换为Optional
。
好了,你有一个像这样的元组 ((A, B), C)
,但你需要(A, B, C)吗?这就是所谓的元组展开,可以使用以下方法实现:
let t = ((true, 1), 1.0)
flatten(t) //here you get: (true, 1, 1.0)
不幸的是,在Swift中,现在不再可能将元组应用到具有多个参数的函数。您可以使用样板文件apply
(|>
运算符形式)来实现,或者将函数元组化。
func fthree(b:Bool, i:Int, d:Double) -> String {
return String(b) + "_" + String(i) + "_" + String(d)
}
let tuple = (false, 1, 0.0)
print(tuplify(fthree)(tuple)) //prints "false_1_0.0"
以上示例只是快速介绍一下Boilerplate可以为您提供什么。进去看看,亲自体验一下。它处理NS桥接和精确类型比较,以防您想避免自动桥接,一些功能扩展,CF桥接,错误处理包括底层的C API错误处理,集合例程,例如集合Zipping,跨平台线程等等。
欢迎做出贡献。我们一起摆脱Swift中的样板代码。
要开始,请签署贡献者许可协议。