0

This is my LoginData Model Class:

class LoginData
{
    var sessionToken : String!
    init(fromJson json: JSON!)
    {
    if json == nil
     {
      return 
     }
    sessionToken = json["Session_Token"].stringValue
   }
}

I want to create instance for the class in the below class:

  class Confirm
{
 var modelobj = model()
   // If I used to create instance I got error like this( **Missing argument for parameter 'fromJson' in call**) and how to create instance for this class

}
GuganReddy
  • 33
  • 5
  • Try like this `var objLoginData = LoginData(fromJson: json)` [For more info](http://www.tutorialspoint.com/swift/swift_initialization.htm) – Chandan Jul 12 '16 at 15:58
  • 1
    That's a very confusing design of the initializer. Either create a failable initializer (`init?(...`) returning `nil` on failure or check the JSON before creating the instance and use non-optional types. – vadian Jul 12 '16 at 16:04
  • If I try like this var objLoginData = LoginData(fromJson: json),I need to declare the json....@Chandan Prajapati – GuganReddy Jul 12 '16 at 16:13
  • @GuganReddy, you have to pass the parameter of JSON type to create an instance of LoginData because you are using parametrize initializer. and no default initializer is there used by the compiler. just add one more initializer like `init(){ }` manually then you can initialize like `var objLoginData = LoginData()` Thanks – Chandan Jul 12 '16 at 16:50

1 Answers1

1

As others have mentioned, this initializer should be failable. sessionToken no longer needs to be an implicitly unwrapped optional (String!). I've also formatted the code to Swift's convention.

class LoginData {
    var sessionToken: String

    init?(fromJson json: JSON) {
        guard let sessionToken = json["Session_Token"].stringValue else {
            return nil
        }

        self.sessionToken = sessionToken
    }
}

then instantiate it with:

guard let loginData = LoginData(fromJson: someJson) else {
    //Initializer failed. Recover from error here.
    //Must break, return, or call @noreturn function
}

//use loginData

You must call the initializer with the json parameter, because there is no initializer that exists with no parameters.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • That doesn't compile because `stringValue` of the `SwiftyJSON` library is non-optional – vadian Jul 12 '16 at 17:10
  • @vadian Oh okay. Could you edit it accordingly, please? – Alexander Jul 12 '16 at 17:14
  • Sorry, I don't edit code in other's posts fundamentally and it's difficult in this case because according to the OP's request the passed JSON is supposed to be optional. – vadian Jul 12 '16 at 17:19