Text: TextView vs TextField
In iOS both TextView and Textfield we are using to display text.
txtField.text = “My TextField”
txtView.text = “My TextView”
Both have same property text but behaviour is different, lets understand it together.
TextField is inherited from UIControl and text is optional here
i.e. open var text: String? // default is nil
TextView is inherited from UIScrollView and text is unWrapped here
i.e. open var text: String!
To check string is empty we use isEmpty which is directly working on text for TextView but not for TextField because it return Boolean and text is optional in TextField.
Better ways to check string in Textfield is
if textField.text == “” {
print(“Its Empty”)
}
but if you are using SwiftLint is will give warning
Empty String Violation: Prefer checking `isEmpty` over comparing `string` to an empty string literal. (empty_string)
So, to fix this we have different ways, prefer
- By giving default value
if ((textField.text ?? “”).isEmpty) {
print(“Assigned default value and checking over string”)
} - If we have to perform any logic on string then safely unwrap it
if let txt = textField.text, txt.isEmpty {
print(“Its Empty here”)
}
Thank you, Happy coding!