Swift options with string options

Why is this a legal right in Swift ...

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

then how is it not?

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

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

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

Of course, the second parameter is a string in both cases.

+6
source share
2 answers

The second parameter, assert, is declared as message: @autoclosure () -> Str or _ message: StaticString . I believe that "Unexpected diagnosis: \(diagnosis)" treated as an expression and @autoclosure , and assertString is just a String variable that cannot be converted to a closure or StaticString .

StaticString can only be done with

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

I suppose this explains why the quick guide notes that you cannot use string interpolation in assert() since StringInterpolationConvertible no support for StringInterpolationConvertible .

+4
source

quotation mark documentation:

... ( assert() ) Performs the traditional C-style statement with an optional message. Use this function for internal health checks that are active during testing but do not affect delivery code performance. To check for invalid use in build versions, see precondition(_:_:file:line:) .

and I tested Xcode 8, precondition(_:_:file:line:) works fine with formatted strings. eg:.

 precondition(userId.lengthOfBytes(using: .ascii) > 0, "\(userId) is invalid for DBManager.id") 
0
source

Source: https://habr.com/ru/post/976095/


All Articles