×

# Swift译:《Swift3中状态化循环和队列》

``````repeat {
let success = doSomething()
} while !success
``````

1.public func sequence<T>(first: T, next: (T) -> T?) -> UnfoldSequence<T, (T?, Bool)>

``````译者解读:

// 我们可以来走一遍树的元素,从一个节点到它的根元素
for node in sequence(first: leaf, next: { \$0.parent }) {
node是叶子节点, 然后是它的父节点, 再然后是它的父节点的父节点, etc.
}
public func sequence<T>(first: T, next: (T) -> T?) -> UnfoldFirstSequence<T> {
// 源码中其实调用了第二种函数,可以看出队列第一个first的元组是true,则直接输出第一个first元素,然后接下来队列中的元素都执行next后返回结果,直到最后结果为nil
return sequence(state: (first, true), next: { (state: inout (T?, Bool)) -> T? in
switch state {
case (let value, true):
state.1 = false
return value
case (let value?, _):
let nextValue = next(value)
state.0 = nextValue
return nextValue
case (nil, _):
return nil
}
})
}
``````

2.public func sequence<T, State>(state: State, next: (inout State) -> T?) -> UnfoldSequence<T, State>

``````译者解读:

public func sequence<T, State>(state: State, next: (inout State) -> T?)
-> UnfoldSequence<T, State> {
return UnfoldSequence(_state: state, _next: next)
//这里调用了另外一个结构体UnfoldSequence,名为展开队列
}
public struct UnfoldSequence<Element, State> : Sequence, IteratorProtocol {
public mutating func next() -> Element? {
guard !_done else { return nil }
if let elt = _next(&_state) {
//这句可以看出为什么sequence函数的next的返回类型都是可选类型,
//当执行next循环语句返回nil,队列剩余部分则不执行next函数,全部返回nil
return elt
} else {
_done = true
return nil
}
}
internal init(_state: State, _next: (inout State) -> Element?) {
self._state = _state
self._next = _next
}
internal var _state: State
internal let _next: (inout State) -> Element?
internal var _done = false
}
``````

``````var i = 0
repeat {
print(i) // some loop body
i = i + 5
} while i <= 100
``````

``````for i in sequence(first: 0, next: { \$0 + 5 }) {
print (i) // some loop body
if i >= 100 { break }
}
``````

``````for _ in sequence(first: 0, next: {
print(\$0) // some loop body
let value = \$0 + 5
return value <= 100 ? value : nil
}) {}
``````

1.这个for循环不需要变量。它只是被用于去执行这个序列。
2.这个循环体是空的,它仅仅被用于完成这个语法。当然你也可以去执行数组(也算一个序列),但那样将会需要申请内存,那个做法是十分浪费的。
3.这个序列当返回nil时会终止。这就意味着这个闭包的返回类型是T？,而T则是第一个参数的类型。在这个例子中return的值只可以返回数字类型,因为这个值并没有有意义的用途,它只是被用于检查false/nil。

``````extension Bool { var opt: Bool? { return self ? self : nil } }
``````

``````func perform<T>(
with state: T,
while test: (T) -> Bool,
repeat body: (inout T) -> Void) -> T {
var updatedState: T = state
let boolSequence = sequence(state: state, next: {
(state: inout T) -> Bool? in
body(&state)
updatedState = state
return test(updatedState) ? true : nil
})
for _ in boolSequence {}
return updatedState
}

// 下面的示例将这些单词连接到一个空格分隔的字符串中。
let joinedWords = perform(
with: ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit"],
while: { \$0.count > 1 })
{
(state: inout [String]) in
guard state.count >= 2 else { return }
let (last, butLast) = (state.removeLast(), state.removeLast())
let joinedLast = butLast + " " + last
state.append(joinedLast)
}.first!

debugPrint(joinedWords)

``````