Get nth character of a string in Swift programming language

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

    If you see Cannot subscript a value of type 'String'... use this extension:

    Swift 3

    extension String {
        subscript (i: Int) -> Character {
            return self[self.characters.index(self.startIndex, offsetBy: i)]
        }
    
        subscript (i: Int) -> String {
            return String(self[i] as Character)
        }
    
        subscript (r: Range) -> String {
            let start = index(startIndex, offsetBy: r.lowerBound)
            let end = index(startIndex, offsetBy: r.upperBound)
            return self[start..) -> String {
            let start = index(startIndex, offsetBy: r.lowerBound)
            let end = index(startIndex, offsetBy: r.upperBound)
            return self[start...end]
        }
    }
    

    Swift 2.3

    extension String {
        subscript(integerIndex: Int) -> Character {
            let index = advance(startIndex, integerIndex)
            return self[index]
        }
    
        subscript(integerRange: Range) -> String {
            let start = advance(startIndex, integerRange.startIndex)
            let end = advance(startIndex, integerRange.endIndex)
            let range = start..

    Source: http://oleb.net/blog/2014/07/swift-strings/

提交回复
热议问题