问题描述
注意: 请参阅LeoDabus的答案以获取有关Swift 4和Swift5的正确实现。
Xcode 11•Swift 5.1
您可以扩展StringProtocol以使下标也可用于子字符串:
extension StringProtocol {
subscript(_ offset: Int) -> Element { self[index(startIndex, offsetBy: offset)] }
subscript(_ range: Range<Int>) -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) }
subscript(_ range: ClosedRange<Int>) -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) }
subscript(_ range: PartialRangeThrough<Int>) -> SubSequence { prefix(range.upperBound.advanced(by: 1)) }
subscript(_ range: PartialRangeUpTo<Int>) -> SubSequence { prefix(range.upperBound) }
subscript(_ range: PartialRangeFrom<Int>) -> SubSequence { suffix(Swift.max(0, count-range.lowerBound)) }
}
extension LosslessstringConvertible {
var string: String { .init(self) }
}
extension BidirectionalCollection {
subscript(safe offset: Int) -> Element? {
guard !isEmpty, let i = index(startIndex, offsetBy: offset, limitedBy: index(before: endindex)) else { return nil }
return self[i]
}
}
测试中
let test = "Hello USA 解决方法
如何获得字符串的第n个字符?我尝试[]
没有成功的bracket()访问器。
var string = "Hello,world!"
var firstChar = string[0] // Throws error
错误:“下标”不可用:无法对带Int的字符串进行下标,请参见文档注释以进行讨论