Get nth character of a string in Swift programming language

后端 未结 30 1968
一整个雨季
一整个雨季 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:45

    Swift 4.2 or later

    Range and partial range subscripting using String's indices property

    As variation of @LeoDabus nice answer, we may add an additional extension to DefaultIndices with the purpose of allowing us to fall back on the indices property of String when implementing the custom subscripts (by Int specialized ranges and partial ranges) for the latter.

    extension DefaultIndices {
        subscript(at: Int) -> Elements.Index { index(startIndex, offsetBy: at) }
    }
    
    // Moving the index(_:offsetBy:) to an extension yields slightly
    // briefer implementations for these String extensions.
    extension String {
        subscript(range: Range) -> SubSequence {
            let start = indices[range.lowerBound]
            return self[start..) -> SubSequence {
            let start = indices[range.lowerBound]
            return self[start...indices[start...][range.count]]
        }
        subscript(range: PartialRangeFrom) -> SubSequence {
            self[indices[range.lowerBound]...]
        }
        subscript(range: PartialRangeThrough) -> SubSequence {
            self[...indices[range.upperBound]]
        }
        subscript(range: PartialRangeUpTo) -> SubSequence {
            self[..

    Thanks @LeoDabus for the pointing me in the direction of using the indices property as an(other) alternative to String subscripting!

提交回复
热议问题