@@ -79,8 +79,10 @@ extension CKDecoderKeyedContainer {
79
79
private func decodeCKRecordValue< T> ( _ value: CKRecordValue , forKey key: Key ) throws -> T where T: Decodable {
80
80
81
81
if let asset = value as? CKAsset {
82
- let data = try Data ( contentsOf: asset. fileURL)
83
- return data as! T
82
+ guard let data = try Data ( contentsOf: asset. fileURL) as? T else {
83
+ throw CKCodableError ( . typeMismatch, context: [ " Error: " : " Couldn't convert Data value to \( String ( describing: T . self) ) " ] )
84
+ }
85
+ return data
84
86
}
85
87
86
88
if let assets = value as? [ CKAsset ] {
@@ -89,11 +91,18 @@ extension CKDecoderKeyedContainer {
89
91
let data = try Data ( contentsOf: $0. fileURL)
90
92
datas. append ( data)
91
93
}
92
- return datas as! T
94
+ guard let castedDatas = datas as? T else {
95
+ throw CKCodableError ( . typeMismatch, context: [ " Error: " : " Couldn't convert [Data] value to \( String ( describing: T . self) ) " ] )
96
+ }
97
+ return castedDatas
93
98
}
94
99
95
100
if let locationValue = value as? CLLocation {
96
- return " \( locationValue. coordinate. latitude) ; \( locationValue. coordinate. longitude) " as! T
101
+ let locationStringValue = " \( locationValue. coordinate. latitude) ; \( locationValue. coordinate. longitude) "
102
+ guard let locationValue = locationStringValue as? T else {
103
+ throw CKCodableError ( . typeMismatch, context: [ " Error: " : " Couldn't convert String value to \( String ( describing: T . self) ) " ] )
104
+ }
105
+ return locationValue
97
106
}
98
107
99
108
if let locationsValues = value as? [ CLLocation ] {
@@ -102,11 +111,17 @@ extension CKDecoderKeyedContainer {
102
111
let value = " \( $0. coordinate. latitude) ; \( $0. coordinate. longitude) "
103
112
locations. append ( value)
104
113
}
105
- return locations as! T
114
+ guard let castedLocations = locations as? T else {
115
+ throw CKCodableError ( . typeMismatch, context: [ " Error: " : " Couldn't convert [String] value to \( String ( describing: T . self) ) " ] )
116
+ }
117
+ return castedLocations
106
118
}
107
119
108
- return value as! T
120
+ guard let decodableValue = value as? T else {
121
+ throw CKCodableError ( . typeMismatch, context: [ " Error: " : " Couldn't convert \( value) value to \( String ( describing: T . self) ) " ] )
122
+ }
109
123
124
+ return decodableValue
110
125
}
111
126
112
127
private func decodeSingleReference< T> ( _ reference: CKRecord . Reference , type: T . Type ) throws -> T where T: Decodable {
0 commit comments