英文:
How can I convert an array of NSNumbers to an array of Ints?
问题
如何从NSNumber获取Int值在Swift中?或者将NSNumber数组转换为Int值的数组?
我有一个NSNumber的列表
let array1:[NSNumber]
我想从这个数组中获得一个Int值的列表
let array2:[Int] = Convert array1
英文:
How to get Int value from NSNumber in Swift? Or convert array of NSNumber to Array of Int values?
I have a list of NSNumber
let array1:[NSNumber]
I want a list of Int values from this array
let array2:[Int] = Convert array1
答案1
得分: 1
根据您的集合中是否包含非整数元素,结果会有所不同。
如果您希望仅在所有元素都是整数时保留集合:
let array2 = array1 as? [Int] ?? [] // [] 全部或无
如果您希望从集合中获取仅整数值:
let array3 = array1.compactMap { $0 as? Int } // [1, 3] 仅整数
如果您希望获取所有元素的完整值:
let array4 = array1.map(\.intValue) // [1, 2, 3] 所有值
英文:
It depends what is the expected result if there is non integer elements in your collection.
let array1: [NSNumber] = [1, 2.5, 3]
If you want to keep the collection only if all elements are integers
let array2 = array1 as? [Int] ?? [] // [] all or nothing
If you want to get only the integers from the collection
let array3 = array1.compactMap { $0 as? Int } // [1, 3] only integers
If you want the whole value of all elements
let array4 = array1.map(\.intValue) // [1, 2, 3] whole values
答案2
得分: 0
已修复此问题,只需一行代码:
let array1: [NSNumber] = [1, 2.5, 3]
let array2 = array1.compactMap { Int(truncating: $0) }
let array3 = array1.compactMap(Int.init)
它会返回一个包含整数值的数组。
array2
的结果为:[1, 2, 3]
array3
的结果为:[1, 3]
英文:
I have fixed this issue with one line of code:
let array1 : [NSNumber] = [1, 2.5, 3]
let array2 = array1.compactMap {Int(truncating: $0)}
let array3 = array1.compactMap(Int.init)
it returns an array of Int values.
Result of array2 = [1,2,3]
Result of array3 = [1,3]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论