var declaration with type vs without

前端 未结 1 1241
梦如初夏
梦如初夏 2021-01-28 11:34

What is the difference between this

var a = ClassA()

and this

var a: ClassA = ClassA()

Why do one vs the othe

1条回答
  •  北海茫月
    2021-01-28 11:54

    I'm not a Swift developer but I'm fairly certain that it operates in the same way as languages like C# in this regard.

    In the first case, the type of the variable is inferred from the type of the expression used to initialise it. Your a variable is thus of type ClassA and can thus refer to any object that is that type or is derived from it. In the second case, you are specifying that the variable is type ClassA explicitly rather than allowing it to be inferred.

    In that second case, the annotation is redundant because the specified type is the same as that which would be inferred anyway. If those types were different though, then it would be worthwhile, e.g.

    var a: BaseType = DerivedType()
    

    In this case, the variable is being initialised with an object that is one type but the variable is specified to be a type that is more general.

    If you are declaring a variable without initialising it then you need an annotation too, because there is no initialising expression from which to infer the variable's type.

    0 讨论(0)
提交回复
热议问题