Fittoburst Fittoburst - 1 year ago 90
Swift Question

Swift assert with string parameters

Why in Swift is this legal...

assert( false, "Unexpected diagnosis: \(diagnosis)" );

whereas this is not?

let assertString = "Unexpected diagnosis: \(diagnosis)"
assert( false, assertString );

In the second snippet, I get the error...

Cannot invoke 'assert' with an argument list of type '(BooleanLiteralConvertible, String)

Surely, the second parameter is a string in both cases.

Answer Source

Second paramter of assert is declared as either message: @autoclosure () -> Str or _ message: StaticString. I guess "Unexpected diagnosis: \(diagnosis)" is treated as expression and picked up by @autoclosure, while assertString is simply a String variable that cannot be converted to closure or StaticString.

StaticString can be made only with:

static func convertFromExtendedGraphemeClusterLiteral(value: StaticString) -> StaticString
static func convertFromStringLiteral(value: StaticString) -> StaticString

I guess this explains why swift manual has note that you cannot use string interpolation in assert() as there is no support for StringInterpolationConvertible.