In Swift 3, is the following conversion the right way to create a String
from a StaticString
?
let fileName : StaticString = #file
let currentFile : String = file.description
No, it's not strictly the correct way to convert a StaticString
to a String
; the value returned by description
is an implementation detail.
The simplest way to get a String
is not to add an explicit type annotation to fileName
to begin with; as it'll default to being a String
:
let fileName = #file
print(type(of: fileName)) // String
However, assuming this isn't possible in your actual use case, another option is to use StaticString
's withUTF8Buffer(_:)
method along with String
's init(decoding:as:)
initialiser in order to decode the UTF-8 code units of the static string:
let fileName: StaticString = #file
let currentFile = fileName.withUTF8Buffer {
String(decoding: $0, as: UTF8.self)
}
print(currentFile)
And, of course, you could make your own convenience initialiser for this:
extension String {
init(_ staticString: StaticString) {
self = staticString.withUTF8Buffer {
String(decoding: $0, as: UTF8.self)
}
}
}
let fileName: StaticString = #file
let currentFile = String(fileName)
print(currentFile)
But this conversion really shouldn't come up too often.
This should work:
let fileName : StaticString = #file
let currentFile : String = "\(fileName)"
(Swift 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With