2
let myArray = Array(arrayLiteral: userIDs)
let newArray = myArray.map{$0 as! UInt}

以下错误是什么意思?

从“设置?” 到不相关的类型 'UInt' 总是失败

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

4

2 回答 2

3

如果userIDsis 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 不保留元素的类型。

于 2016-04-25T12:07:00.780 回答
0

如果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
于 2016-04-25T11:53:31.583 回答