Inline if condition with nil in swift

2019-09-17 20:14发布

问题:

I am trying to use inline if condition as follows:

topDisplay.text = topDisplay.text!.rangeOfString(".") ? "Sth for true" : "Sth for false"

The idea here is if there is "." in the topDisplay.text! then do something, if not, do something else. The method, rangeOfString, returns nil if no "." is found. So I am wondering is it possible to check nil within inline condition expression.

((btw, you might find out that I am trying to add "." button for calculator assignment in Stanford's online course, and to use only one line to implement this function as the hint describes))

回答1:

So I am wondering is it possible to check nil within inline condition expression.

Sure. rangeOfString(".") != nil is a boolean expression which can be used as the condition in the conditional expression:

topDisplay.text = topDisplay.text!.rangeOfString(".") != nil ? "Sth for true" : "Sth for false"