问题
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