Przeglądaj źródła

Swap String(bytes:encoding:)! for String(decoding:as:)

Avoids the force unwraps that were needed before.

From the comment in https://github.com/apple/swift-protobuf/issues/1730#issuecomment-2466138248.
Thomas Van Lenten 1 rok temu
rodzic
commit
b164ab273a

+ 1 - 1
Sources/SwiftProtobuf/JSONEncoder.swift

@@ -73,7 +73,7 @@ internal struct JSONEncoder {
 
     internal var stringResult: String {
         get {
-            String(bytes: data, encoding: String.Encoding.utf8)!
+            String(decoding: data, as: UTF8.self)
         }
     }
 

+ 1 - 1
Sources/SwiftProtobuf/Message+JSONAdditions.swift

@@ -32,7 +32,7 @@ extension Message {
             return try m.encodedJSONString(options: options)
         }
         let data: [UInt8] = try jsonUTF8Bytes(options: options)
-        return String(bytes: data, encoding: .utf8)!
+        return String(decoding: data, as: UTF8.self)
     }
 
     /// Returns a `SwiftProtobufContiguousBytes` containing the UTF-8 JSON serialization of the message.

+ 1 - 1
Sources/SwiftProtobuf/Message+JSONArrayAdditions.swift

@@ -31,7 +31,7 @@ extension Message {
         options: JSONEncodingOptions = JSONEncodingOptions()
     ) throws -> String where C.Iterator.Element == Self {
         let data: [UInt8] = try jsonUTF8Bytes(from: collection, options: options)
-        return String(bytes: data, encoding: .utf8)!
+        return String(decoding: data, as: UTF8.self)
     }
 
     /// Returns a `SwiftProtobufContiguousBytes` containing the UTF-8 JSON serialization of the messages.

+ 1 - 1
Sources/SwiftProtobuf/TextFormatEncoder.swift

@@ -37,7 +37,7 @@ internal struct TextFormatEncoder {
     private var indentString: [UInt8] = []
     var stringResult: String {
         get {
-            String(bytes: data, encoding: String.Encoding.utf8)!
+            String(decoding: data, as: UTF8.self)
         }
     }
 

+ 1 - 1
Tests/SwiftProtobufTests/TestHelpers.swift

@@ -373,7 +373,7 @@ extension PBTestHelpers where MessageTestType: SwiftProtobuf.Message & Equatable
 
             do {
                 let encoded: [UInt8] = try decoded.jsonUTF8Bytes()
-                let encodedString = String(bytes: encoded, encoding: String.Encoding.utf8)!
+                let encodedString = String(decoding: encoded, as: UTF8.self)
                 do {
                     let redecoded = try MessageTestType(
                         jsonUTF8Bytes: encoded,