Divided operation in Swift

后端 未结 1 1163
长情又很酷
长情又很酷 2020-12-07 05:23

Why i get error constantly on that?

 var rotation:Float= Double(arc4random_uniform(50))/ Double(100-0.2)

Actually i try this one too:

相关标签:
1条回答
  • 2020-12-07 05:42

    Swift has strict rules about the whitespace around operators. Divide '/' is a binary operator.

    The important rules are:

    • If an operator has whitespace around both sides or around neither side, it is treated as a binary operator. As an example, the + operator in a+b and a + b is treated as a binary operator.
    • If an operator has whitespace on the left side only, it is treated as a prefix unary operator. As an example, the ++ operator in a ++b is treated as a prefix unary operator.
    • If an operator has whitespace on the right side only, it is treated as a postfix unary operator. As an example, the ++ operator in a++ b is treated as a postfix unary operator.

    That means that you need to add a space before the / or remove the space after it to indicate that it is a binary operator:

    var rotation = Double(arc4random_uniform(50)) / (100.0 - 0.2)
    

    If you want rotation to be a Float, you should use that instead of Double:

    var rotation = Float(arc4random_uniform(50)) / (100.0 - 0.2)
    

    There is no need to specify the type explicitly since it will be inferred from the value you are assigning to. Also, you do not need to explicitly construct your literals as a specific type as those will conform to the type you are using them with.

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