为什么 Swift 的 enumerateSubstringsInRange 回调采用可选字符串?
Why does Swift's enumerateSubstringsInRange callback take an optional string?
我们可以像这样从 Swift 字符串中提取单词:
s.enumerateSubstringsInRange(s.characters.indices, options: .ByWords) {
(w,_,_,_) in print(w!)
}
但强制展开通常是一种代码味道。它在那里是因为回调的第一个参数是 String?
(可选)。我尝试了几种可能的字符串以强制函数将 nil
传递给回调(例如空字符串和没有单词字符的字符串)但没有运气!
所以我想知道为什么回调采用可选字符串。有什么我忽略的吗?是因为一个可变字符串可以同时传入和修改吗?如果是这样,那么如果我知道我的原始字符串是一个常量(用 let
定义),那么强制解包是否可以接受?
(以下信息来自对我问题的回复
https://forums.developer.apple.com/thread/28272 在
苹果开发者论坛。)
你可以将.SubstringNotRequired
选项传递给enumerateSubstringsInRange()
,然后闭包将被调用
substring == nil
。这个选项是documented as
NSStringEnumerationSubstringNotRequired
A way to indicate that the block does not need substring, in which
case nil will be passed. This is simply a performance shortcut.
示例:
let str = "Hello, playground"
str.enumerateSubstringsInRange(str.characters.indices,
options: [.ByWords, .SubstringNotRequired]) {
substring, substringRange, _, _ in
print(substring, substringRange)
}
输出:
nil 0..<5
nil 7..<17
我认为 substring != nil
如果
.SubstringNotRequired
未给出选项。
我们可以像这样从 Swift 字符串中提取单词:
s.enumerateSubstringsInRange(s.characters.indices, options: .ByWords) {
(w,_,_,_) in print(w!)
}
但强制展开通常是一种代码味道。它在那里是因为回调的第一个参数是 String?
(可选)。我尝试了几种可能的字符串以强制函数将 nil
传递给回调(例如空字符串和没有单词字符的字符串)但没有运气!
所以我想知道为什么回调采用可选字符串。有什么我忽略的吗?是因为一个可变字符串可以同时传入和修改吗?如果是这样,那么如果我知道我的原始字符串是一个常量(用 let
定义),那么强制解包是否可以接受?
(以下信息来自对我问题的回复 https://forums.developer.apple.com/thread/28272 在 苹果开发者论坛。)
你可以将.SubstringNotRequired
选项传递给enumerateSubstringsInRange()
,然后闭包将被调用
substring == nil
。这个选项是documented as
NSStringEnumerationSubstringNotRequired
A way to indicate that the block does not need substring, in which case nil will be passed. This is simply a performance shortcut.
示例:
let str = "Hello, playground"
str.enumerateSubstringsInRange(str.characters.indices,
options: [.ByWords, .SubstringNotRequired]) {
substring, substringRange, _, _ in
print(substring, substringRange)
}
输出:
nil 0..<5
nil 7..<17
我认为 substring != nil
如果
.SubstringNotRequired
未给出选项。