Why use T! instead of T as function parameter and return type?

Viewed 50

In JavaScriptCore, I saw most of functions declared T! as parameter type and return type. Since T! assumes non-nil when pass in and return, why not just declare T as type?

e.g.

func evaluateScript(_ script: String!) -> JSValue!

why not just

func evaluateScript(_ script: String) -> JSValue
1 Answers

This indicates that an ObjC API has not yet been audited for nullability, and does not have nullability annotations applied. Without nullability annotations, the compiler doesn't know whether the values are optional or not. The default behavior in that case is to make them all ! types, and leave the question to the caller (the only other possible approach would be to make everything ? types, which would be extremely inconvenient to work with).

When Apple annotates the header, the ! will go away.

In the meantime, it's up to you to check the documentation to ensure the return values cannot be nil before using them directly.

In this particular case, the underlying JSEvaluateScript can in fact return nil:

@result The JSValue that results from evaluating script, or NULL if an exception is thrown.

So you do need to check it. There's just no way for the compiler to know that currently.

Related