Skip to content

Commit

Permalink
Swap String(bytes:encoding:)! for String(decoding:as:)
Browse files Browse the repository at this point in the history
Avoids the force unwraps that were needed before.

From the comment in #1730 (comment).
  • Loading branch information
thomasvl committed Nov 11, 2024
1 parent 2c22056 commit b164ab2
Show file tree
Hide file tree
Showing 5 changed files with 5 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Sources/SwiftProtobuf/JSONEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftProtobuf/Message+JSONAdditions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftProtobuf/Message+JSONArrayAdditions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftProtobuf/TextFormatEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/SwiftProtobufTests/TestHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit b164ab2

Please sign in to comment.