Swift NSCountedSet init with array bug?

喜夏-厌秋 提交于 2019-12-19 06:02:30

问题


There seems to be a bug in Swift Playground with the use of NSCountedSet.

This code works as intended

let numbers = [1,2,2,4,6,7,8,8,5,8,1]

let set = NSSet(array: numbers)

but when I try to create an NSCountedSet in the same fashion

var bag = NSCountedSet(array: numbers)

I get this error

Playground execution failed: /var/folders/bl/1tnlvfzd4mqb9gkpx0h8rxy00000gp/T/lldb/6514/playground599.swift:56:31: error: 'Int' is not identical to 'AnyObject' var bag = NSCountedSet(array: numbers)

I did try casting numbers

let nums = numbers as [AnyObject]
var bag = NSCountedSet(array: nums)

then I get this error

Playground execution failed: /var/folders/bl/1tnlvfzd4mqb9gkpx0h8rxy00000gp/T/lldb/6514/playground732.swift:58:23: error: extra argument 'array' in call var bag = NSCountedSet(array: nums)

Am I missing something here?

I can work around the problem by doing this

var bag = NSCountedSet()
for number in numbers {
    bag.addObject(number)
}

But it is not very elegant


回答1:


Update: As @carbo18 reported, this has been fixed in Xcode 6.3 beta 4.

Old answer: That definitely looks like a bug. NSCountedSet has initializers

convenience init(array: [AnyObject])
convenience init(set: NSSet)

but

let b1 = NSCountedSet(array: [])     // extra argument 'array' in call
let b2 = NSCountedSet(set: NSSet())  // extra argument 'set' in call

both fail to compile.

This was also reported in the Apple Developer Forum (https://devforums.apple.com/message/1081850#1081850), where the following workaround is given:

let numbers = [1,2,2,4,6,7,8,8,5,8,1]
let bag = NSCountedSet()
bag.addObjectsFromArray(numbers)


来源:https://stackoverflow.com/questions/29172374/swift-nscountedset-init-with-array-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!