如何在Swift 4中使用String切片下标?

我有以下用Swift 3编写的简单代码:


let str = "Hello, playground"

let index = str.index(of: ",")!

let newStr = str.substring(to: index)

从Xcode 9 beta 5,我收到以下警告:


substring(to:)不推荐使用“ ”:请String对带有“ partial range from”运算符的下标进行切片。


如何在Swift 4中使用部分范围的切片下标?


翻阅古今
浏览 810回答 3
3回答

慕神8447489

将子字符串(Swift 3)转换为字符串切片(Swift 4)Swift 3、4中的示例:let newStr = str.substring(to: index) // Swift 3let newStr = String(str[..<index]) // Swift 4let newStr = str.substring(from: index) // Swift 3let newStr = String(str[index...]) // Swift 4&nbsp;let range = firstIndex..<secondIndex // If you have a rangelet newStr = = str.substring(with: range) // Swift 3let newStr = String(str[range])&nbsp; // Swift 4

缥缈止盈

您应将一侧留空,因此命名为“ partial range”。let newStr = str[..<index]运算符的部分范围相同,只是将另一侧留空:let newStr = str[index...]请记住,这些范围运算符返回Substring。如果要将其转换为字符串,请使用String的初始化函数:let newStr = String(str[..<index])您可以在此处阅读有关新子字符串的更多信息。

料青山看我应如是

斯威夫特5、4用法let text = "Hello world"text[0] // Htext[...3] // "Hell"text[6..<text.count] // worldtext[NSRange(location: 6, length: 3)] // wor码import Foundationpublic extension String {&nbsp; subscript(value: Int) -> Character {&nbsp; &nbsp; self[index(at: value)]&nbsp; }}public extension String {&nbsp; subscript(value: NSRange) -> Substring {&nbsp; &nbsp; self[value.lowerBound..<value.upperBound]&nbsp; }}public extension String {&nbsp; subscript(value: CountableClosedRange<Int>) -> Substring {&nbsp; &nbsp; self[index(at: value.lowerBound)...index(at: value.upperBound)]&nbsp; }&nbsp; subscript(value: CountableRange<Int>) -> Substring {&nbsp; &nbsp; self[index(at: value.lowerBound)..<index(at: value.upperBound)]&nbsp; }&nbsp; subscript(value: PartialRangeUpTo<Int>) -> Substring {&nbsp; &nbsp; self[..<index(at: value.upperBound)]&nbsp; }&nbsp; subscript(value: PartialRangeThrough<Int>) -> Substring {&nbsp; &nbsp; self[...index(at: value.upperBound)]&nbsp; }&nbsp; subscript(value: PartialRangeFrom<Int>) -> Substring {&nbsp; &nbsp; self[index(at: value.lowerBound)...]&nbsp; }}private extension String {&nbsp; func index(at offset: Int) -> String.Index {&nbsp; &nbsp; index(startIndex, offsetBy: offset)&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP