Same datatype multiple variable declaration in swift

后端 未结 2 1240
抹茶落季
抹茶落季 2021-02-01 14:33

in objective-c we can declare variable like -NSString *a,*b,*c;

in swift there a way to declare same datatype multiple variable variable rather than doing l

相关标签:
2条回答
  • 2021-02-01 15:15

    Swift has an odd design decision here. Placing a type on a variable affects all previous non-explicitly typed variables in a multi-line definition. Same for constants.

    These two lines are equivalent (a, b and c are Double):

    var a, b, c: Double
    var a: Double, b: Double, c: Double
    

    And these two are equivalent (a and b are Int, while c and d are Double):

    var a, b: Int, c, d: Double
    var a: Int, b: Int, c: Double, d: Double
    
    0 讨论(0)
  • 2021-02-01 15:16

    You can declare multiple constants or multiple variables on a single line, separated by commas:

    var a = "", b = "", c = ""
    

    NOTE

    If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

    Type Annotations:

    You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:

    var red, green, blue: Double
    

    NOTE

    It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference.

    Documentation HERE.

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