如何在Swift中使用字符串下标4
问题描述:
我想将swift3代码转换为swift4。但这个错误显示如何在Swift中使用字符串下标4
“子(来自:)”被弃用:请使用字符串的切片标 以‘从’操作部分范围。”
我的代码是:提前
extension String {
func substring(_ from: Int) -> String {
return self.substring(from: self.characters.index(self.startIndex, offsetBy: from))
}
的感谢!
答
你应该有:
extension String {
func substring(_ from: Int) -> String {
let start = index(startIndex, offsetBy: from)
return String(self[start ..< endIndex])
}
}
在迅速的,你可以得到一个使用字符串切片 - 一个建筑像这样:string[startIndex ..< endIndex]
。字符串索引是swift中的一种特殊类型,因此您不能使用简单的整数 - 您必须获得适当的索引,例如调用index(_,offsetBy:)
或使用预定义的startIndex
和endIndex
。
+0
thanksss !!!! @algrid .. –
查看https://stackoverflow.com/questions/45562662/how-to-use-string-slicing-subscript-in-swift-4 – algrid
我已经检查....但仍然不明白...你能解释一下吗... @algrid –
你能解释一下吗?@ MoeAbdul-Hameed –