Swift: Checking for the existence of a uitextfield - ios

I have a controller that will have a variable number of textfields. On a button press I want to check for the existence of, whether or not its empty, and check the character count of the input.
I'm trying the following, which works fine if homePhone exists
if homePhone?.text != ""{
if countElements(homePhone1.text) != 10{
validInput = false
validationError = "Home Phone must be 10 digits"
}
}
But when a textfield does not exist (mobile) I get a fatal error
if mobilePhone?.text != ""{
if countElements(mobilePhone.text) != 10{
validInput = false
validationError = "Mobile Phone must be 10 digits"
}
}
fatal error: unexpectedly found nil while unwrapping an Optional value
Obviously I'm not doing the check correctly, optionals and unwrapping is continually tripping me up.

You can unwrap your textfield and check if it exists:
if let mobilePhoneField = mobilePhone{
if mobilePhoneField.text != ""{
if countElements(mobilePhoneField.text) != 10{
validInput = false
validationError = "Mobile Phone must be 10 digits"
}
}
}

This will check if your optional variable is nil or not so you can safely unwrap it, actualy it will do it for you.
if let value = myOptionalVariable{
//my optionalVariable is not nill i can do whatever i want
value.text = "Yaay"
}

Related

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

I get this Error:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
When I call this function:
ViewController().textToLabel(answer: answerLabel)
I call this from a different class:
func textToLabel(answer: String){
answerLabel.text = answer //I get the error here
}
Second View Controller
import Foundation
import UIKit
class germanClass{
func forGerman(){
var answerLabel = ""
var voiceText = ""
var colorPicker = "white"
var randomNumber = arc4random_uniform(UInt32(numberOfAnswers + 1))
switch (randomNumber){
case 0...20:
answerLabel = "Ja😋"
voiceText = "Ja"
colorPicker = "green"
}
//ViewController().changeColor(color: colorPicker)
ViewController().textToLabel(answer: answerLabel)
if (voiceTextOn){
randomNumber = arc4random_uniform(UInt32(7))
if (randomNumber == 0){
if (userName != "Ich möchte wissen wie du heißt! 😉" || userName != "du"){
voiceText += userName
}
}
}
textToSpeech().siriVoice(language: "de-de", text: voiceText)
}
}
Based on what you've shown, I'd say you are sending a label where you should be sending label.text
Either send the text or send the label and define your method accordingly.
Calling ViewController().textToLabel(answer: answerLabel) will instantiate a new ViewController and call textToLabel(answer:) on it, which is probably not what you want.
If you're trying to pass data between two view controllers you will have to find some other way to do it, depending on the relationship between them.
Also, your second view controller should inherit from UIViewController (as any view controllers should).

Swift optionals nil check

So I fail to figure a 1 liner for following syntax in Swift and it is driving me nuts:
if lastProfile == nil || lastProfile.id == profile.id {
useProfile(profile)
lastProfile = profile
}
Now see I could chain it but I'd still end up with 2-3 ifs. I could pack it out but then I again end up with 2-3 ifs... Is it possible to do this in just 1 swoop?
Edit:
My colleague found an alternative (although we agree ugly):
if !(latestProfile != nil && latestProfile!.voiceId != profile.voiceId) {
}
Is there a better approach than above?
Solution is just a ? away:
if lastProfile == nil || lastProfile?.id == profile.id {
print("true")
lastProfile = profile
}
This prints "true" when lastProfile is nil or when lastProfile and profile have the same id. Otherwise it prints nothing.
If lastProfile is declared as let lastProfile: Profile? = ..., and for example id is declared as optional also you can use it as:
if let lastProfileId = lastProfile?.id {
// lastProfile is not nil and id is not nil
}
else {
// lastProfile is nil or lastProfile.id is nil
}
It is called Optional Chaining and you can read about it on swift docs.
if let recentProfile = latestProfile where recentProfile.voieId != profile.voiceId {
useProfile(profile)
lastProfile = profile
}

Component separated by string crashing app swift

I have an app that converts textField input into an array of Int's by using componentSeparatedByString(",") but when i enter more than one comma in the textfield the app crashes, been trying to find a solution online but no luck, how can i fix this? I can keep it from crashing by checking for characters.first == "," ||characters.last == ",", but not consecutive commas.
enterValueLabel.text = ""
let circuits = circuitNumbersTextField.text!.componentsSeparatedByString(",")
let circuitNumbers = circuits.map { Int($0)!}
CircuitColors(circuitNumber: circuitNumbers, phaseColors: circuitPhaseColors )
if /*circuitNumbersTextField.text!.characters.first != "," || */circuitNumbersTextField.text!.characters.last != "," || (circuitNumbersTextField.text!.characters.first != "," && circuitNumbersTextField.text!.characters.last != ",")
Here's what I would do to make your code work. What is important here is the general idea, not the specific example I'm using (although it should work for you).
First, let's safely unwrap the text label:
if let text = circuitNumbersTextField.text {
}
Now that we avoid using circuitNumbersTextField.text! we know that an error wouldn't come from there.
Then we cut the sentence in components:
if let text = circuitNumbersTextField.text {
let circuits = text.componentsSeparatedByString(",")
}
We use flatMap to safely unwrap the Optionals returned by Int():
if let text = circuitNumbersTextField.text {
let circuits = text.componentsSeparatedByString(",")
let circuitNumbers = circuits.flatMap { Int($0) }
// circuitNumbers will only contain the successfully unwrapped values
}
Your code snippet:
if let text = circuitNumbersTextField.text {
let circuits = text.componentsSeparatedByString(",")
let circuitNumbers = circuits.flatMap { Int($0) }
if (circuits.first != "," && circuits.last != ",") || circuits.first != "," || circuits.last != "," {
// condition is met
} else {
// condition is not met
}
}
You can now safely use circuitNumbers in this code block without crashing.

What's the meaning of Optional("nil") in Swift?

Here is my code. If defaults did not ever save the lat, lng, then give it a lat lng.
The problem is error:
fatal error: unexpectedly found nil while unwrapping an Optional value
when using self.lat and self.lng after the code below. Every time console print out is
the saved gps is Optional("nil")
What's the meaning for Optional("nil") and the difference from Optional(nil)?
I am using Xcode 7.1 and Swift 2.
var lat : String = ""
var lng : String = ""
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.stringForKey("lat") != nil {
self.lat = defaults.stringForKey("lat")!
self.lng = defaults.stringForKey("lng")!
print ("the saved gps is \(defaults.stringForKey("lat"))")
} else {
self.lat = "34.7009333"
self.lng = "135.4942047"
print ("the init gps is \(self.lat) , \(self.lng)")
}
it show the actual value...
let digit = sender.currentTitle!
suppose your sender value is 10 then output is 10.
suppose your sender value is nil then app carsh.
it show the optional value
let digit = sender.currentTitle
suppose your sender value is 10 then output is optional("10").
suppose your sender value is nil then app is not carsh.
& display value like this optional("nil")

Checking if text fields are empty cause error in Swift 2

I am trying to check if a textbox has no value.
When I do this:
if(userEmail?.isEmpty || userPassword?.isEmpty || userPasswordRepeat?.isEmpty)
I get the following error
I tried adding "?" before the ".isEmpty" but the error won't go away
Any ideas?
Try this....
if txtEmail.text?.isEmpty == true || txtPassword.text?.isEmpty == true || txtRePassword.text?.isEmpty == true{
print("true")
}
If interested also in positive case, the following is an alternative solution for Swift 2:
let email = self.txtEmail.text where !email.isEmpty, let password = self.txtPassword.text where !password.isEmpty {
//all fields are not nil && not empty
}else{
//some field is nil or empty
}

Resources