Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

ios - Divided operation in Swift

Why i get error constantly on that?

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

Actually i try this one too:

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

thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...