脚本宝典收集整理的这篇文章主要介绍了Swift34/90Days - objc.io 的 Swift 片段 5,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Swift90Days - objc.io 的 Swift 片段 4
全排列
我们想通过 Swift 简单的实现全排列。
首先先写个例子,列出所有把元素插入到数组中的情况:
func between<T>(x: T, ys: [T]) -> [[T]] {
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x, tail).map { [head] + $0 }
} else {
return [[x]]
}
}
between(0, [1, 2, 3]) // [[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]]
接下来再通过 between
函数实现全排列:
func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(tail) >>= { permTail in
between(head, permTail)
}
} else {
return [[]]
}
}
其中 >>=
这个符号前面有提到过,返回所有的组合结果。完整的实现代码如下:
extension Array {
VAR decompose : (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
return xs.map(f).reduce([], combine: +)
}
func between<T>(x: T, ys: [T]) -> [[T]] {
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x, tail).map { [head] + $0 }
} else {
return [[x]]
}
}
func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(tail) >>= { permTail in
between(head, permTail)
}
} else {
return [[]]
}
}
轻量级解包
typealias JSONDictionary = [String:AnyObject]
func decodeJSON(data: NSData) -> JSONDictionary? {
return NSJSONSerialization.JSONObjectWithData(data,
options: .allZeros, error: nil) as? JSONDictionary
}
当然 encode
也一样:
func encodeJSON(input: JSONDictionary) -> NSData? {
return NSJSONSerialization.dataWithJSONObject(input,
options: .allZeros, error: nil)
}
References
以上是脚本宝典为你收集整理的Swift34/90Days - objc.io 的 Swift 片段 5全部内容,希望文章能够帮你解决Swift34/90Days - objc.io 的 Swift 片段 5所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。