Swift exclamation mark before a text

ⅰ亾dé卋堺 提交于 2019-12-02 23:33:13

问题


This tutorial I am currently working on says I have to disable the Save Button until the text field has some value in it. Here is the code:

saveButton.isEnabled = !text.isEmpty

Does the exclamation mark before text.isEmpty mean that the save button is enabled is the text is not empty same way that != mean not equal to? I know exclamation mark means force unwrap, but I thought you put the exclamation mark after the text. BTW(I have tested it and it works as the tutorial says so)


回答1:


The exclamation mark is both a postfix operator (and as you said is the the force unwrap operator used this way) and a prefix operator. The latter is the boolean negation, so when text is the empty string, text.isEmpty is true and negating it with an exclamation mark before gives !text.isEmpty which is false, disabling the save button.




回答2:


The exclamation mark before text.isEmpty called Logical NOT operator, it inverts the boolean value.

saveButton.isEnabled = !text.isEmpty

means that if text is empty, the saveButton will not be enabled, and vice versa.

To make it more clear, if we tried to translate it as an if-statement, it should be as:

if text.isEmpty {
    saveButton.isEnabled = false
} else {
   saveButton.isEnabled = true
}


来源:https://stackoverflow.com/questions/52525681/swift-exclamation-mark-before-a-text

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