Skip to content

Commit 38659e6

Browse files
committed
use switch instead of casting to protocol
1 parent 1152aa4 commit 38659e6

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

Sources/FoundationEssentials/JSON/JSONEncoder.swift

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,12 +1216,12 @@ private extension __JSONEncoder {
12161216
return .number(decimal.description)
12171217
} else if !options.keyEncodingStrategy.isDefault, let encodable = value as? _JSONStringDictionaryEncodableMarker {
12181218
return try self.wrap(encodable as! [String:Encodable], for: additionalKey)
1219-
} else if let array = value as? _JSONDirectArrayEncodable {
1219+
} else if let directArrayEncodable = _asDirectArrayEncoding(value, for: additionalKey) {
12201220
if options.outputFormatting.contains(.prettyPrinted) {
1221-
let (bytes, lengths) = try array.individualElementRepresentation(encoder: self, additionalKey)
1221+
let (bytes, lengths) = try directArrayEncodable.individualElementRepresentation(encoder: self, additionalKey)
12221222
return .directArray(bytes, lengths: lengths)
12231223
} else {
1224-
return .nonPrettyDirectArray(try array.nonPrettyJSONRepresentation(encoder: self, additionalKey))
1224+
return .nonPrettyDirectArray(try directArrayEncodable.nonPrettyJSONRepresentation(encoder: self, additionalKey))
12251225
}
12261226
}
12271227

@@ -1246,6 +1246,43 @@ private extension __JSONEncoder {
12461246
return encoder.takeValue()
12471247
}
12481248

1249+
func _asDirectArrayEncoding<T: Encodable>(_ value: T, for additionalKey: (some CodingKey)? = _CodingKey?.none) -> _JSONDirectArrayEncodable? {
1250+
switch value {
1251+
case let array as [Int8]:
1252+
array
1253+
case let array as [Int16]:
1254+
array
1255+
case let array as [Int32]:
1256+
array
1257+
case let array as [Int64]:
1258+
array
1259+
case let array as [Int128]:
1260+
array
1261+
case let array as [Int]:
1262+
array
1263+
case let array as [UInt8]:
1264+
array
1265+
case let array as [UInt16]:
1266+
array
1267+
case let array as [UInt32]:
1268+
array
1269+
case let array as [UInt64]:
1270+
array
1271+
case let array as [UInt128]:
1272+
array
1273+
case let array as [UInt]:
1274+
array
1275+
case let array as [String]:
1276+
array
1277+
case let array as [Float]:
1278+
array
1279+
case let array as [Double]:
1280+
array
1281+
default:
1282+
nil
1283+
}
1284+
}
1285+
12491286
@inline(__always)
12501287
func getEncoder(for additionalKey: CodingKey?) -> __JSONEncoder {
12511288
if let additionalKey {

0 commit comments

Comments
 (0)