Re: More elegance than a long if/else
Re: More elegance than a long if/else
- Subject: Re: More elegance than a long if/else
- From: Quincey Morris <email@hidden>
- Date: Fri, 10 Mar 2017 14:32:15 -0800
On Mar 10, 2017, at 08:24 , Bryan Vines <email@hidden> wrote:
>
> Would integer division work better than the modulus operator?
It would certainly work better in the sense that division is the right operator and modulus is the wrong one!
Regarding the original question, I would add that there’s a decent argument to be made that keeping a long series of cases is clearer in intent and methodology than a concise but somewhat obscure calculation. In that case, though, I would just set an imageName variable inside the “if” statement, and retrieve the UIImage afterwards. (That keeps the contents of the “if” to simple statements that the compiler can easily optimize, whereas creating the image in each case is a method call that blocks some optimizations.)
Also, a “switch” statement would be cleaner than an “if”, since it has less boilerplate, and this kind of range testing can be done in Swift, though the mechanism isn’t obvious till you see it:
> switch (batteryLevel)
> {
> case _ where batteryLevel >= 90: imageName = "10"
> case _ where batteryLevel >= 80: imageName = “9"
> …
> default: imageName = "0”
> }
> let image = UIImage (named: imageName)
My guess is that the Swift compiler can optimize code like this very nicely.
Finally, I’d point out that anyone who cared about numerical correctness might say that the entire solution is “wrong” because the cutoff points are in the wrong place. If you’re trying to indicate battery level in 10% increments, it seems more correct to represent 89 and 90 values both as 90%, rather than as 90% and 100% respectively, as the code seems to suggest. But that’s a different issue.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden