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
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 e.g.
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
.