Why Is UITextField.text An Optional?
This is a historical thing. UITextField
does not make any difference between an empty string and a nil
string. In Objective-C there was no need to make a difference between them because you can call methods on nil
in Objective-C.
Also, there was no way in Objective-C to prevent users from assigning nil
to a property.
The resulting contract is that text
can be optional. In Objective-C that makes no difference.
In Swift there is not much we can do because UITextField.text
contract would have to change, possibly breaking lots of already written code. Note that even if nil
is never returned from the method, you can still assign nil
to reset the value.
You can find hundreds of similar situations in the old APIs.
Why does UITextFIeld return optional value in Swift?
The reason is probably because you're using shouldChangeCharactersIn
which doesn't indicate the change in the character until the second character. Ideally you want the user to be notified of the correct answer after they complete the answer and submit it, in which case you want to use something like textFieldDidEndEditing
:
class MyVC: UIViewController, UITextFieldDelegate {
let textField = UITextField()
var numberLabel: UILabel {
let label = UILabel()
label.text = "100"
return label
}
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(textField)
textField.borderStyle = .roundedRect
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.widthAnchor.constraint(equalToConstant: 200),
textField.heightAnchor.constraint(equalToConstant: 100)
])
textField.delegate = self
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
button.tag = 1
button.backgroundColor = .black
button.setTitle("Answer", for: .normal)
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.leadingAnchor.constraint(equalTo: textField.trailingAnchor),
button.widthAnchor.constraint(equalToConstant: 200),
button.heightAnchor.constraint(equalToConstant: 100)
])
}
@objc func buttonPressed(_ sender: UIButton!) {
if case let tag = sender.tag, tag == 1 {
textField.resignFirstResponder()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
//convert string into number
let input = (numberLabel.text! as NSString).integerValue
//find answer to label when added by 1111
let answer = input + 1111
print(answer)
if let numberText = Int(textField.text ?? "0") {
print("This is number text: \(numberText)")
if answer == numberText {
//if user gets answer correct
print("correct")
} else {
//if user gets answer incorrect
print("wrong")
}
}
}
}
Why does a UITextField have a .text value of Optional(Actual Text) Swift
Since your MyTextField
is an optional, you will have to unwrap the value in your text before printing it.
override func viewDidLoad() {
super.viewDidLoad()
if let text = MyTextField.text {
print(text)
}
}
Force Unwrap Optionals from UITextfield
Simply use
self.name = NameInput.text!
or
self.name = NameInput.text ?? ""
Once you use String(describing:)
the Optional(...)
text will be part of your string rather than an optional string and you won't be able to remove it.
UITextField displaying Optional() before input
In the following code:
var newString = textField.text
if newString!.characters.count == 0 {
newString = "\(newString)\(string)"
shouldMoveToNextField = true
}
Change...
newString = "\(newString)\(string)"
to....
newString = "\(string)"
Swift: How to unwrap UITextField Optional String to Float
Your calculation seems fine but it might be throwing a compiler error for setting Float
in place of String
to totalTipAmount
. You can try as follows,
@objc func sliderChange() {
guard let priceText = self.priceTextField.text, let price = Float(priceText) else { return }
totalTipAmount.text = "\(tipSlider.value * price)"
}
Why is uitextfield not outputting optional?
The default value of UITextField
is an empty string. so even if you have not typed anything the value is ""
If you want to check:
if let validPass = passwordInput.text {
print("It is not optional")
} else {
print("It is optional")
}
And you will see that output is "It is not optional"
If you want to check whether it is empty or not:
if let validPass = passwordInput.text, !validPass.isEmpty {
print("It is not optional or not empty")
}
Related Topics
Find the Tangent of a Point on a Cubic Bezier Curve
Distancefromlocation - Calculate Distance Between Two Points
Localizing Strings in iOS: Default (Fallback) Language
How to Add an Action to a Button Programmatically in Xcode
iOS 11 - Keyboard Height Is Returning 0 in Keyboard Notification
Autolayout: Add Constraint to Superview and Not Top Layout Guide
First App Update, User Data Lost (Was Stored in Documents Directory)
What Should Image Sizes Be at @1X, @2X and @3X in Xcode
Custom Uitableviewcell Programmatically Using Swift
Presenting Camera Permission Dialog in iOS 8
How to Disable Rotation in React Native
How to Use Apple's New .P8 Certificate for Apns in Firebase Console
Screenshot for Avplayer and Video
Xcode 6 Keeps Renaming My App's Directory in iOS8 Simulator After Each Run
How to Export Data to a CSV File with iOS
What Exactly Can Corebluetooth Applications Do Whilst in the Background