Break A Number Up To An Array of Individual Digits

后端 未结 5 1933
陌清茗
陌清茗 2020-12-02 00:32

If I have the integer 123 and I want to break the digits into an array [1,2,3] what is the best way of doing this? I have messed around with this a lot and I have the follo

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 01:07

    My take for Swift 2:

    var x = 123
    var digits = String(x).characters.map { Int(String($0))! } // [1,2,3]
    

    It is more explicit about the characters, so I think it is quite readable.

提交回复
热议问题