Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 234
Fittoburst Avatar asked Oct 01 '14 09:10

Fittoburst


1 Answers

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.

like image 149
Kirsteins Avatar answered Oct 13 '22 18:10

Kirsteins