问题描述
注意: 有关 Swift 4 和 Swift 5 的正确实现,请参阅:
您可以扩展 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 个字符?我尝试了括号([]
)访问器,但没有成功。
var string = "Hello,world!"
var firstChar = string[0] // Throws error
错误:“下标”不可用:无法使用 Int 为字符串下标,请参阅文档注释以进行讨论