Swift array.map 将 NSNumber 转换为 UInt

Swift array.map conver NSNumber to UInt

let myArray = Array(arrayLiteral: userIDs)
let newArray = myArray.map{[=12=] as! UInt}

下面的错误是什么意思?

Cast from 'Set?' to unrelated type 'UInt' always fails

我想将从 NSSet 创建的数组转换为使用 UInt 而不是数字的数组。

如果 userIdsNSSet,则 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 )
}

这在 playground 中产生:

1
__NSSetI
__NSCFNumber
__NSCFNumber
__NSCFNumber
UInt
UInt
Uint

如果 userIDsSet<NSNumber> 那么执行 Array(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([=11=]) } 

在您发表评论后更新

如果你有 Foundation 的 NSSet 而不是 Swift 的 Set,你可以这样做:

let userIDs = NSSet(array: nums)
let myArray = userIDs.map { [=12=] as! NSNumber }
let newArray = myArray.map { UInt([=12=]) }

我们必须将 NSSet 的内容向下转换为 NSNumber,因为 NSSet 不保留元素的类型。