Inline if condition with nil in swift

安稳与你 提交于 2019-12-12 06:12:19

问题


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"


来源:https://stackoverflow.com/questions/30392878/inline-if-condition-with-nil-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!