什么是 Swift 中的桥接转换,如以下警告所示:Conditional downcast from 'Data?' to 'CKRecordValue is a bridging conversion

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

Swift 中的桥接转换是什么? "bridging" 是什么意思?

我在以下代码中收到一条警告,我在其中标记了一条注释“//警告”:

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

警告说:

Conditional downcast from 'Data?' to 'CKRecordValue' (aka '__CKRecordObjCValue') is a bridging conversion; did you mean to use 'as'?

我也有使用桥接转换的代码:

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?

其中 privateEntityInstance.media 是可选的,privateMedia 也是可选的。该代码是否有效,以便 CoreData 将保存媒体属性的适当值,无论它是 NSObject 还是 nil?

  • as? CKRecordValue 是有条件的向下转换(从不太具体的类型到更具体的类型)
  • as CKRecordValue? 是桥接转换(例如从具体类型到协议或从 Swift 类型到它的 Objective-C 对应类型)。这是编译器期望的语法。

然而在Swift5中Data符合CKRecordValueProtocol所以你可以写

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

建议始终优先使用密钥订阅 record["field"] 而不是 setObject:forKey:,因为后者需要将桥接转换为对象,例如

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

并且不要注释比实际类型(非可选)更差的类型(可选)Data? Data