N.echizen N.echizen - 1 month ago 13
iOS Question

Swift - Class has no initializer

I am trying to pass a variable to another view via code. When a user clicks on a table view data my app passes the table data to the next view. But I am getting a "class has no initialisers" on my second screen:

Table view calling 2nd screen on click:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("editFriend") as! EditFriendViewController

self.presentViewController(nextViewController, animated: true, completion: nil)

nextViewController.friend = friendArray[indexPath.row];
}


2nd screen code:

import UIKit
import CoreData

class EditFriendViewController: UIViewController {

var friend: Friends

@IBOutlet weak var fName: UITextField!
@IBOutlet weak var lName: UITextField!
@IBOutlet weak var mobile: UITextField!
@IBOutlet weak var gender: UIPickerView!
@IBOutlet weak var address: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

fName.text = friend.firstName!;
lName.text = friend.lastName!;
mobile.text = friend.mobile!;
address.text = friend.address!;
}


}

Answer

That's because you have defined a property without initialise it in your init() method. If you need a property to init in somewhere else instead of init method, eg. viewDidLoad. That is very common in ViewController. So you need to define the property as implicitly unwrapped optional, that means, you need to declare friend as Friends! instead of Friends, or if you need the property to be optional, then declare it as Friend?

import UIKit
import CoreData

class EditFriendViewController: UIViewController {
    var friend: Friends!  // declare friend as implicitly unwrapped optional, you are responsible to assign any value to it before using it
    ....

    override func viewDidLoad() {
       super.viewDidLoad()
       friend = Friend() // Assign a value to friend property
    }
}
Comments