Get nth character of a string in Swift programming language

后端 未结 30 1963
一整个雨季
一整个雨季 2020-11-22 01:26

How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

var string = \"Hello, world!\"

var firstChar = string[         


        
30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:58

    Xcode 11 • Swift 5.1

    You can extend StringProtocol to make the subscript available also to the substrings:

    extension StringProtocol {
        subscript(_ offset: Int)                     -> Element     { self[index(startIndex, offsetBy: offset)] }
        subscript(_ range: Range)               -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) }
        subscript(_ range: ClosedRange)         -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) }
        subscript(_ range: PartialRangeThrough) -> SubSequence { prefix(range.upperBound.advanced(by: 1)) }
        subscript(_ range: PartialRangeUpTo)    -> SubSequence { prefix(range.upperBound) }
        subscript(_ range: PartialRangeFrom)    -> 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]
        }
    }
    

    Testing

    let test = "Hello USA 

提交回复
热议问题