简体   繁体   English

什么是 Swift 中的桥接转换,如以下警告所示:来自“数据”的条件向下转换? 到 'CKRecordValue 是一个桥接转换

[英]What is a bridging conversion in Swift as in the following warning: Conditional downcast from 'Data?' to 'CKRecordValue is a bridging conversion

What is a bridging conversion in Swift?什么是 Swift 中的桥接转换? What does "bridging" mean? “桥接”是什么意思?

I get a warning in the following code where I marked with a comment saying "// warning":我在以下代码中收到警告,其中我用注释标记“// 警告”:

import UIKit
import CloudKit

let int: UInt8 = 1
let data: Data? = Data([int])
let record: CKRecord = CKRecord(recordType: "record_type")
record.setObject(data as? CKRecordValue, forKey: "field") // warning

The warning says:警告说:

Conditional downcast from 'Data?'来自“数据?”的有条件的向下转型to 'CKRecordValue' (aka '__CKRecordObjCValue') is a bridging conversion;到 'CKRecordValue'(又名 '__CKRecordObjCValue')是一个桥接转换; did you mean to use 'as'?你的意思是用'as'吗?

I also have code that uses a bridging conversion:我也有使用桥接转换的代码:

import Foundation
import CoreData


extension Vision {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Vision> {
        return NSFetchRequest<Vision>(entityName: "Vision")
    }

    @NSManaged public var media: NSObject?

}

private var privateEntityInstance: Vision
private var privateMedia: Data? = nil

privateEntityInstance.media = privateMedia as NSObject?

where privateEntityInstance.media is an optional and privateMedia is also an optional.其中 privateEntityInstance.media 是可选的,privateMedia 也是可选的。 Would that code work, so that CoreData will save the appropriate value of the media attribute whether it be an NSObject or a nil?该代码是否有效,以便 CoreData 保存媒体属性的适当值,无论它是 NSObject 还是 nil?

  • as? CKRecordValue as? CKRecordValue is conditional downcast (from a less specific to a more specific type) as? CKRecordValue是有条件的向下转换(从不太具体到更具体的类型)
  • as CKRecordValue? is a bridging conversion (for example from a concrete type to a protocol or from a Swift type to its Objective-C counterpart) .是一种桥接转换(例如从具体类型到协议或从 Swift 类型到它的 Objective-C 对应物)。 This is the syntax the compiler expects.这是编译器期望的语法。

However in Swift 5 Data conforms to CKRecordValueProtocol so you can write但是在 Swift 5 Data符合CKRecordValueProtocol所以你可以写

let int: UInt8 = 1
let data = Data([int])
let record = CKRecord(recordType: "record_type")
record["field"] = data

It's recommended to prefer always Key Subscription record["field"] over setObject:forKey: because the latter requires the bridge cast to an object eg建议始终使用 Key Subscription record["field"]不是setObject:forKey:因为后者需要将桥转换为对象,例如

let data = Data([int]) as NSData // or as CKRecordValue
...
record.setObject(data, forKey: "field")

And don't annotate a worse type (optional) Data?并且不要注释更糟糕的类型(可选) Data? than the actual type (non-optional) Data .比实际类型(非可选) Data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM