2

I had created the sample application for testing the failable initializers. When I extends the NSObject then I am getting the below error.

1) Property 'self.userName' not initialized at super.init call.
2) Immutable value 'self.userDetails' may only be initialized once.
3) Immutable value 'self.userName' may only be initialized once.

Please find the below code and screenshot for the same.

class User: NSObject {

    let userName: String!
    let userDetails: [String]?

    init?(dictionary: NSDictionary) {
        super.init()

        if let value = dictionary["user_name"] as? String {
            self.userName = value
        }
        else {
            return nil
        }

        self.userDetails = dictionary["user_Details"] as? Array
    }        
}

Screenshot

enter image description here

Ramkrishna Sharma
  • 6,961
  • 3
  • 42
  • 51

2 Answers2

1

All properties must initialised before super.init()

Nil must be returned from the failable initialiser after super.init(). This restriction should be removed in Swift 2.2

Correct implementation would be:

class User: NSObject {

    let userName: String!
    let userDetails: [String]?

    init?(dictionary: NSDictionary) {
        if let value = dictionary["user_name"] as? String {
            self.userName = value
        } else {
            self.userName = nil
        }

        self.userDetails = dictionary["user_Details"] as? Array

        super.init()

        if userName == nil {
            return nil
        }

        else if userDetails == nil {
            return nil
        }
    }
}
Silmaril
  • 4,241
  • 20
  • 22
1
import Foundation

let dictionary = ["user_name": "user", "user_Details":[1,2,3]]

class User: NSObject {

    var userName: String?
    var userDetails: [String]?

    init?(dictionary: NSDictionary) {
        super.init()
        if let value = dictionary["user_name"] as? String {
            self.userName = value
        }
        else {
            return nil
        }

        self.userDetails = dictionary["user_Details"] as? Array
    }        
}

let c = User(dictionary: dictionary)
dump(c)
/*
▿ User
  ▿ Some: User #0
    - super: <__lldb_expr_31.User: 0x7fe372f15860>
    ▿ userName: user
      - Some: user
    - userDetails: nil
*/
user3441734
  • 16,722
  • 2
  • 40
  • 59