Search code examples
swiftinheritancesuperclass

Object inherit from NSObject causes error Property 'self._username' not initialized at super.init call


I create UserModel object inherit from NSObject I have problem with override init() in give me error because of "Property 'self._username' not initialized at super.init call". can someone told me how to fix it ? also should I always inherit from NSObject ?

class UserModel:NSObject
{
    let _username:String
    let _password:String
    let _isAuthenticated:Bool
    let _isManager:Bool

    init(username:String = "",password:String = "" ,isAuthenticated:Bool = false,isManager:Bool = false)
    {
        self._username = username
        self._password = password
        self._isAuthenticated = isAuthenticated
        self._isManager = isManager
    }


    override init() {
        super.init()
    }


}

Solution

    1. You absolutely do not have to always inherit from NSObject!

    class UserModel { ... } is perfectly fine as well

    1. The error arises because when you try to call super.init self has to be properly set up. And after the init() is finished your class members do not have any values! Both is not allowed for non-optional types.

    Solution: remove the init() and maybe even the NSObject inheritance:

    class UserModel {
        let _username : String
        let _password : String
        let _isAuthenticated : Bool
        let _isManager : Bool
    
        init(username : String = "", password : String = "", isAuthenticated : Bool = false, isManager : Bool = false) {
            self._username = username
            self._password = password
            self._isAuthenticated = isAuthenticated
            self._isManager = isManager
        }
    }
    

    Sidenote: why do your variables have a leading underscore?