如何将字符串拆分为 [String] 而不是 [Substring]? [英] How do you split a String into a [String] and not [Substring]?

查看:28
本文介绍了如何将字符串拆分为 [String] 而不是 [Substring]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下扩展:

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 with split() (e.g. because it has more options, such as to omit empty 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 协议的参数,涵盖 StringSubstring:

Alternatively – if possible – make the array extension method more general to take arguments conforming to the StringProtocol protocol, that covers both String and Substring:

extension Array where Element: StringProtocol {
    func foo(){
    }
}

这篇关于如何将字符串拆分为 [String] 而不是 [Substring]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆