Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a StaticString into String at runtime?

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
like image 767
David Andreoletti Avatar asked Sep 25 '17 03:09

David Andreoletti


2 Answers

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.

like image 123
Hamish Avatar answered Oct 01 '22 20:10

Hamish


This should work:

let fileName : StaticString = #file
let currentFile : String = "\(fileName)"

(Swift 4)

like image 34
HixField Avatar answered Oct 01 '22 18:10

HixField