20

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"
7
  • 1
    let str: StaticString = "\(part1)\(part2)" is this what you need Commented Mar 23, 2017 at 10:47
  • 2
    @InderKumarRathore Actually the result is the same "Cannot convert value of one type to another" Commented Mar 23, 2017 at 10:51
  • 1
    I read the documentation and it says StaticString : A string type designed to represent text that is known at compile time. Commented Mar 23, 2017 at 10:56
  • 1
    Because of above constraint I don't think you can have dynamic text in it Commented Mar 23, 2017 at 10:57
  • 6
    The os_log API expects StaticString messages. It would be nice to be able to log dynamic messages. Commented Jun 19, 2018 at 12:24

3 Answers 3

14

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Michael, but I am really interested in a generic hack way to do this sort of conversion.
"String concatenation happens at runtime." was key to satisfy my search (w/ an upvote, though i'd love a reference for it ;).
13

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

Comments

5

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.