Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to StaticString

Tags:

string

swift

Is there a way in Swift 3.0 to get a StaticString type out of a String type which is complex?

Example (needs a conversion to work):

let aString: StaticString = "One part" + "Second part"
like image 370
Vanya Avatar asked Mar 23 '17 10:03

Vanya


3 Answers

This is not possible, because a StaticString is defined as

A simple string designed to represent text that is "knowable at compile-time". (Reference)

String concatenation happens at runtime.

I don't know what you are planing to do, but you can do something like that:

func aMethod(i: Int) -> StaticString {
    switch i {
    case 0:
        return "Simple"
    case 1:
        return "Complex"
    default:
        return "Default"
    }
}
let result = aMethod(i: 1)
print("\(type(of: result)): \(result)") // prints "StaticString: Complex"
like image 178
Michael Dorner Avatar answered Oct 20 '22 09:10

Michael Dorner


You can use format specifiers like %d or %s eg:

os_log("Successfully fetched %d recordings.", type: .info, count)
os_log("Getting recordings from %s.",
  type: .info, url.absoluteString)

for more info check here

like image 9
Alfa Avatar answered Oct 20 '22 08:10

Alfa


Depends on your actual use case, you may have some way to work it around. For example, if you are dealing with os_log, you can use %@ if you want to use Swift String instead of CVarArg.

//os_log("Compiler error with: \(string).", log: log)
os_log("This is OK: %@.", log: log, string)
like image 5
superarts.org Avatar answered Oct 20 '22 10:10

superarts.org