Break A Number Up To An Array of Individual Digits

后端 未结 5 1931
陌清茗
陌清茗 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条回答
  •  生来不讨喜
    2020-12-02 00:57

    I don't know if you are new to swift but let's be clear, the method where you use the map is the best for what you want to do:) There is another approach that i don't recommend cause having a good visualisation of your code structure is really important.

    import Foundation
    
    var number2 = 123
    var number3 : String = "\(number2)"
    var array : [String] = []
    var str2 = ""
    for i in number3.characters
    {
        str2.append(i)
        var string = NSString(string: "str")
        string.doubleValue
        array.append(str2)
        str2 = ""
    }
    

    cheers

提交回复
热议问题