gpt4 book ai didi

swift - 如何在 Swift 中将 *正数* 数字转换为数字数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:58:34 35 4
gpt4 key购买 nike

我想将一个正数转换成相应的数字列表——数字也应该是整数。

转换时,比如1024,应该返回[1,0,2,4]

最佳答案

在 Swift 4.1 或更高版本中

let number = 1024
let digits = String(number).compactMap { Int(String($0)) }
print(digits) // [1, 0, 2, 4]

在 Swift4 中

let number = 1024
let digits = String(number).flatMap { Int(String($0)) }
print(digits) // [1, 0, 2, 4]

在 Swift2 和 Swift3 中

let number = 1024
let digits = String(number).characters.flatMap { Int(String($0)) }
print(digits) // [1, 0, 2, 4]

关于swift - 如何在 Swift 中将 *正数* 数字转换为数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27736317/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com