Swift ui issues

off-topic

(Kishore) #1

Hello! I am new to swift. I created a sign up page. There is an error in the line where I define the function namely ‘saveitem’. And because of that I am getting build failed. Also I am not able to access main story board. Kindly help.

import UIKit
import CoreData

class SignUpController: UIViewController {

@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    
}


@IBAction func signUpAction(_ sender: Any) {
    
    if emailField.text != "" {
        let toastView = ToastView()
        toastView.showAddedTo(view: self.view, message: "Email Id cannot be empty")
        return
    }
    
    if passwordField.text != "" {
        let toastView = ToastView()
        toastView.showAddedTo(view: self.view, message: "Password cannot be empty")
        return
    }
    
    if userNameField.text != "" {
        let toastView = ToastView()
        toastView.showAddedTo(view: self.view, message: "Username cannot be empty")
        return
    }
    
    saveItem(dict: NSMutableDictionary(dictionary: ["userName":userNameField.text,"email":emailField.text,"password":passwordField.text]))
}

func saveItem(dict: NSMutableDictionary){
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    //**Note:** Here we are providing the entityName **`Entity`** that we have added in the model
    let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
    let myItem = NSManagedObject(entity: entity!, insertInto: context)
    print(myItem)
    myItem.setValuesForKeys(dict as! [String : Any])
    
    do {
        try context.save()
    }
    catch{
        print("There was an error in saving data")
    }
}

#2

Hi! Welcome to the swift forums. :)
It would be very helpful if you said what error you are getting. After copy-pasting your code into an empty project the only error I can see is the missing } at the end and usage of things that aren't defined in the code you sent us.


(Kishore) #3

The error is - expression implicitly coerced from ‘String?’ To ‘Any’


(Kishore) #4

Kindly help, if you need any extra information, tell me exactly what you need??


#5

This is a warning, not an error. Warnings can be ignored if you want, they just warn you that something is fishy (but still valid).

What it warns you about is that userNameField.text etc are String? aka Optional<String> which means that there could be string there, or they could be nil. nil is an equivalent of null or None from other languages.

What do you want to do when it is nil? Xcode fixits suggest three options when you click the warning:
08

What you want though is to unwrap your optionals in your checks earlier in the method (guard is designed for that):

    @IBAction func signUpAction(_ sender: Any) {
        guard let emailText = emailField.text, emailText != "" else {
            let toastView = ToastView()
            toastView.showAddedTo(view: self.view, message: "Email Id cannot be empty")
            return
        }
        guard let passwordText = passwordField.text, passwordText != "" else {
            let toastView = ToastView()
            toastView.showAddedTo(view: self.view, message: "Password cannot be empty")
            return
        }
        guard let usernameText = userNameField.text, usernameText != "" else {
            let toastView = ToastView()
            toastView.showAddedTo(view: self.view, message: "Username cannot be empty")
            return
        }

        saveItem(dict: NSMutableDictionary(dictionary: ["userName":usernameText,"email":emailText,"password":passwordText]))
    }

(Kishore) #6

Thank you so much for the reply. I now understand that I can ignore them. I tried to run it as an app, but I am not able to get the desired output. For example, I would like new user to register in the app. But, when I type new credentials and press signup, it says ‘ Email Id cannot be empty‘. Can you kindly explain me what I am doing wrong here?


#7

You show a toast when email is not an empty string. You probably want to change your condition to == ""


(Stern) #8

Few comments.

It's preferable to use !someString.isEmpty than comparing to the empty string. Same for other containers; use isEmpty, not count != 0.

UITextField.text says it returns a String? but it really doesn't. It will never return nil. But it is safe to assign nil to it. Weird huh? This is a semantic not supported by swift. There is no half-optional.

Unwrapping UITextField.text is a waste of time. Simplest is just to force unwrap.
if userName.text!.isEmpty { \\ userName cannot be empty blah blah blah


#9

Is it documented anywhere that .text will never return nil?

While it may be okay in this specific circumstance, we shouldn't teach people that the best way to deal with optionals is to force unwrap them, because 99% of the time it is a bad advice.


(Stern) #10

I don't think it's documented but there's plenty of discussion of this on SO etc.

Your code is fine and frankly I've not settled on a single best way to deal with this issue. I usually use the nil coalescing operator rather than unwrap like you show.