Get nth character of a string in Swift programming language

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

    Swift 5.3

    I think this is very elegant. Kudos at Paul Hudson of "Hacking with Swift" for this solution:

    @available (macOS 10.15, * )
    extension String {
        subscript(idx: Int) -> String {
            String(self[index(startIndex, offsetBy: idx)])
        }
    }
    
    

    Then to get one character out of the String you simply do:

    var string = "Hello, world!"
    
    var firstChar = string[0] // No error, returns "H" as a String
    

提交回复
热议问题