问题描述
考虑以下扩展:
extension Array where Element == String {
func foo(){
}
}
并考虑我想拆分的以下字符串,以便我可以使用扩展名...
And consider the following string that I want to split so I can use the extension...
let string = "This|is|a|test"
let words = string.split(separator: "|")
问题是 words
是 [Substring]
而不是 [String]
所以我不能调用 foo()
就可以了.
The problem is words
is a [Substring]
and not [String]
so I can't call foo()
on it.
那么在 Swift 4 中,如何拆分字符串以返回 [String]
而不是 [Substring]
?
So in Swift 4, how do I split a string to return a [String]
and not a [Substring]
?
推荐答案
正如 Leo 上面所说,你可以使用 components(separatedBy:)
As Leo said above, you can use components(separatedBy:)
let string = "This|is|a|test"
let words = string.components(separatedBy: "|")
words.foo()
相反,它返回一个 [String]
.
如果你想坚持split()
(例如因为它有更多的选项,比如省略空子序列),那么您必须通过转换每个 Substring
来创建一个新数组到 String
:
If you want to stick withsplit()
(e.g. because it has more options, such as to omitempty subsequences), then you'll have to create a new array by converting each Substring
to a String
:
let string = "This|is|a|test"
let words = string.split(separator: "|").map(String.init)
words.foo()
或者——如果可能——使数组扩展方法更多一般采用符合 StringProtocol
协议的参数,涵盖 String
和 Substring
:
Alternatively – if possible – make the array extension method moregeneral to take arguments conforming to the StringProtocol
protocol,that covers both String
and Substring
:
extension Array where Element: StringProtocol {
func foo(){
}
}
这篇关于如何将字符串拆分为 [String] 而不是 [Substring]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!