let myArray = Array(arrayLiteral: userIDs)
let newArray = myArray.map{$0 as! UInt}
以下错误是什么意思?
从“设置?” 到不相关的类型 'UInt' 总是失败
我想将创建的数组转换为NSSet
数组UInt
而不是数字。
如果userIDs
is Set<NSNumber>
then doingArray(arrayLiteral: userIDs)
不会从集合内容创建数组,它会创建一个包含集合本身的数组。
删除arrayLiteral
初始化:
let num1 = NSNumber(integer: 33)
let num2 = NSNumber(integer: 42)
let num3 = NSNumber(integer: 33)
let nums = [num1, num2, num3] // [33, 42, 33]
let userIDs = Set(nums) // {33, 42}
let myArray = Array(userIDs) // [33, 42]
然后你可以映射到任何你想要的:
let newArray = myArray.map{ UInt($0) }
在您发表评论后更新
如果你有 Foundation 的 NSSet 而不是 Swift 的 Set,你可以这样做:
let userIDs = NSSet(array: nums)
let myArray = userIDs.map { $0 as! NSNumber }
let newArray = myArray.map { UInt($0) }
我们必须将 NSSet 的内容向下转换为 NSNumber,因为 NSSet 不保留元素的类型。
如果userIds
是 a NSSet
,则myArray
其中有一个类型为 的元素NSSet
。不过,您可以映射用户 ID。
let userIDs: NSSet = NSSet(array: [ NSNumber(int:1), NSNumber(int:2), NSNumber(int:3) ] )
let myArray = Array(arrayLiteral: userIDs )
print( myArray.count) // returns 1
print( myArray[0].dynamicType)
let newArray = userIDs.map { x -> UInt in
print(x.dynamicType)
return x as! UInt
}
for x in newArray {
print( x.dynamicType )
}
这在操场上产生:
1
__NSSetI
__NSCFNumber
__NSCFNumber
__NSCFNumber
UInt
UInt
Uint