我遇到了Swift编译器的奇怪问题。
此代码无法编译:
let str = "012345,abc,officer"
let components = split(str, { return $0 == "," })
// ^ error: 'NSString' is not a subtype of 'String'
虽然这个(没有return
)编译并按预期工作:
let components = split(str, { $0 == "," })
// -> ["012345", "abc", "officer"]
我不明白为什么第一个失败了。根据我对the doc的理解,{ expression }
只是{ return expression }
的语法糖。
这是一种错误,还是我错过了什么?
如果我像split
那样制作自己的功能,则无论return
如何都可以使用。
func mySplit(seq: String, isSeparator: ((Character) -> BooleanType)) -> [String]{
var ret:[String] = []
var startIdx = seq.startIndex;
for var idx = seq.startIndex; idx < seq.endIndex; idx = idx.successor() {
if isSeparator(seq[idx]) {
ret.append(seq[startIdx ..< idx])
startIdx = idx.successor()
}
}
if(startIdx <= seq.endIndex) {
ret.append(seq[startIdx ..< seq.endIndex])
}
return ret;
}
let result1 = mySplit(str, { $0 == "," })
let result2 = mySplit(str, { return $0 == "," })
编辑:我发现所有这些都有效。
split(str, { (chr:Character) -> Bool in return chr == "," })
split(str, { (chr:Character) -> Bool in chr == "," })
split(str, { chr -> Bool in return chr == "," })
split(str, { chr -> Bool in chr == "," })
split(str, { (chr:Character) in chr == "," })
split(str, { chr in chr == "," })
split(str, { $0 == "," })
但这些失败了:
split(str, { (chr:Character) in return chr == "," })
split(str, { chr in return chr == "," })
split(str, { return $0 == "," })
EDIT2:
像这样制作mySplit
可以重现问题。
func mySplit<R:BooleanType>(seq: String, isSeparator:(Character) -> R) -> [String] {