Get nth character of a string in Swift programming language

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

    Swift's String type does not provide a characterAtIndex method because there are several ways a Unicode string could be encoded. Are you going with UTF8, UTF16, or something else?

    You can access the CodeUnit collections by retrieving the String.utf8 and String.utf16 properties. You can also access the UnicodeScalar collection by retrieving the String.unicodeScalars property.

    In the spirit of NSString's implementation, I'm returning a unichar type.

    extension String
    {
        func characterAtIndex(index:Int) -> unichar
        {
            return self.utf16[index]
        }
    
        // Allows us to use String[index] notation
        subscript(index:Int) -> unichar
        {
            return characterAtIndex(index)
        }
    }
    
    let text = "Hello Swift!"
    let firstChar = text[0]
    

提交回复
热议问题