简体   繁体   中英

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? 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; did you mean to use '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. Would that code work, so that CoreData will save the appropriate value of the media attribute whether it be an NSObject or a nil?

  • as? CKRecordValue as? CKRecordValue is conditional downcast (from a less specific to a more specific type)
  • 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) . This is the syntax the compiler expects.

However in Swift 5 Data conforms to CKRecordValueProtocol so you can write

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

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

And don't annotate a worse type (optional) Data? than the actual type (non-optional) Data .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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