Convert a String to an array of characters swift 2.0

后端 未结 3 1279
南旧
南旧 2020-12-17 16:16

I need to convert a string into an array of characters. This work in Swift 1.2 and lower but doesn\'t since Swift 2.0

var myString = \"Hello\"
Array(myString         


        
相关标签:
3条回答
  • 2020-12-17 17:01

    You have to use the characters property of String since it is no longer a SequenceType:

    var myString = "Hello"
    let charactersArray = Array(myString.characters)
    
    0 讨论(0)
  • 2020-12-17 17:06

    First, use the characters property of String struct :

    let str = "Hello World"
    var charView = str.characters
    

    You get an CharacterView instance. To access to an element of charView, you have to use String.CharacterView.Index. If you want to convert this to an array of String, do this :

    let str = "Hello World"
    var arr = str.characters.map { String($0) }
    

    Now, you have an array of type [String] :

    arr[0] // => "H"
    
    0 讨论(0)
  • 2020-12-17 17:07
    var myString = "Hello"
    let characters = [Character](myString.characters)  // ["H","e","l","l","o"]
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题