Swift 2、NSDictionary有什么变化?

In Swift 2, what changed in NSDictionary?

在 Swift 2 中,NSDictionary(objects, forKeys) (Objective-C: dictionaryWithObjects:forKeys:) 创作中到底发生了什么变化?

Apple's prerelease documentation 特别没用,因为只有 Obj-C 代码。尽管提供的代码片段有轻微但明显的变化,但我不会说 obj-c,并且到目前为止还没有理解这些变化。

这是给你们的一些代码:

videoDataOutput.videoSettings = NSDictionary(objects: NSNumber(kCVPixelFormatType_32BGRA), forKeys: (kCVPixelBufferPixelFormatTypeKey))
//Working old Swift code; missing argument for parameter 'count' in call on Swift 2

+ (instancetype)dictionaryWithObjects:(NSArray *)objects
                              forKeys:(NSArray *)keys
//Old Obj-C code


+ (instancetype nonnull)dictionaryWithObjects:(NSArray<ObjectType> * nonnull)objects
                                      forKeys:(NSArray<id<NSCopying>> * nonnull)keys
//New Obj-C code

我在别处读到,nonnull 应该有助于与 Swift 的兼容性,但是 <ObjectType> 呢? id 是什么?

@更新 修复了 swift 代码从 NSDictionary(objectsAndKeys: )NSDictionary(objects: , forKeys:)

obj-c 程序员没有真正的变化。它主要用于编译器,正如您所说的 swift:

的交叉兼容性

而不是 (NSArray *) 你现在有 (NSArray<ObjectType> * nonnull) 这意味着 a) 数组不能为非空(不是 nil)和 b) 它的内容/值必须是 ObjectType 类型。

而不是 (NSArray *) 你有 (NSArray<id<NSCopying>> * nonnull) 这意味着 a) 如上所述和 b) 它的内容必须适应 NSCopying 协议。

关于 expected countobjectsAndKeys 不再存在 (docs),您必须使用其他功能。或者只是一个文字...

关于 idObjectType 的最后说明:id 指的是任何对象,您可以将每个视图或 arra 或任何东西视为 id - 它本身没有类型信息。 ObjectType 我认为指的是泛型,它意味着你在任何你想使用特定类型的地方写 ObjectType ,你还不知道类型,但是在 [=12] 的每个地方都是一样的=] 写成。

您没有使用 +dictionaryWithObjects:forKeys:,您正在使用 +dictionaryWithObjectsAndKeys:。这是两种不同的方法。 +dictionaryWithObjectsAndKeys: 不受 swift 支持。

使用 +dictionaryWithObjects:forKeys: 看起来像这样。

videoDataOutput.videoSettings = NSDictionary(objects: [NSNumber(integer: kCVPixelFormatType_32BGRA)], forKeys: [kCVPixelBufferPixelFormatTypeKey])

注意:我还需要将 NSNumber(kCVPixelFormatType_32BGRA) 更改为 NSNumber(integer: kCVPixelFormatType_32BGRA)


因为你的字典里只有一个词条,你可以用+dictionaryWithObject:forKey:.

videoDataOutput.videoSettings = NSDictionary(object: kCVPixelFormatType_32BGRA as NSNumber, forKey: kCVPixelBufferPixelFormatTypeKey as NSString)

注意 1:我使用 kCVPixelFormatType_32BGRA as NSNumber 而不是 NSNumber(integer: kCVPixelFormatType_32BGRA)

注意 2:我不得不使用 kCVPixelBufferPixelFormatTypeKey as NSString 而不是 kCVPixelBufferPixelFormatTypeKey.


我认为最简单的方法是使用 swift 的 Dictionary 文字。

videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as NSString: kCVPixelFormatType_32BGRA]

我在 XCode 7 Swift 2 中简单地使用了

output.videoSettings = [ kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32BGRA) ]

查看此项目以获取一些当前代码https://github.com/gibachan/OpenCVSample/