timbucktieu
timbucktieu

Reputation: 39

Difference of using `:` and `as` in Swift when specifying variable type in Swift?

Following a few different tutorials on Swift and noticed this difference. Are there cases where the two lines function differently, or is this more of a style preference?

var newString:NSString = "Test String"

and

var newString = "Test String" as NSString

Upvotes: 0

Views: 220

Answers (2)

The difference is that in the first case, you declare the variable to be of type NSString, and hence it will be of type NSString, initialized with a string literal. (Either it's that the compiler performs an implicit conversion from the swift String type to NSString, or the literal itself is type-less – I'm not actually sure about this one.)

In the second case, you are not declaring the type of the variable explicitly. Instead, you perform an explicit conversion from the String literal to NSString, so the initializing expression itself has type NSString. Hence, type inference will tell the compiler that the type of the variable is also NSString.

The overall outcome of the two cases should be similar (if not identical modulo the cost of actual conversions, if any).

Upvotes: 4

matt
matt

Reputation: 535086

There is no functional difference in this situation. It's merely the difference between a variable type explicitly declared in the variable declaration and a variable type implicitly inferred from the initial value. Either way, this variable gets a type, which is what matters.

(There are other situations, however, where the explicit declaration is necessary.)

Upvotes: 0

Related Questions