0

SO I have two models; Contact and Group, and am archiving/unarchiving their data through NSCoder. Consider this:

class Contact
{
    var id: Int = default_value
    var name: String = ""
    var number: String = ""

    init?(Id:Int, Name:String, Number:String)
    {
        self.id = Id
        self.name = Name
        self.number = Number
        super.init()
        if Id == default_value{
            return nil
        }
    }

    // MARK: NSCoding
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeInteger(id, forKey: "id")
        aCoder.encodeInteger(name, forKey: "name")
        aCoder.encodeBool(number, forKey: "number")
    }

    required convenience init?(coder aDecoder: NSCoder)
    {
        let Id = aDecoder.decodeIntegerForKey("id")
        let Name = aDecoder.decodeIntegerForKey("name")
        let Number = aDecoder.decodeBoolForKey("number")
        self.init(Id:Id, Name:Name, Number:Number)
    }
}

This goes really fine, but when I try to use contact in my group model, it just messes up bad = gives this error "Cannot assign Value of type Contact to Contact?";

class group
{
    var id: Int = default_value
    var contact = Contact?.self //wont let me declare a Contact

    init?(Id:Int, cont:Contact)
    {
        self.id = Id
        self.contact = cont    //Cannot assign Value of type Contact to Contact?
        super.init()
        if Id == default_value{
            return nil
        }
    }

    // MARK: NSCoding
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeInteger(id, forKey: "id")
        aCoder.encodeInteger(contact, forKey: "contact")
    }

    required convenience init?(coder aDecoder: NSCoder)
    {
        let Id = aDecoder.decodeIntegerForKey("id")
        let Cont = aDecoder.decodeIntegerForKey("contact")
        self.init(Id:Id, cont:Cont)
    }
}

Please tell me what should I do as i don't have all the parameters to initialise contacts as a whole. Thank you in advance :)

Mohsin Khubaib Ahmed
  • 1,008
  • 16
  • 32

1 Answers1

1

You variable declaration should be

var contact: Contact

This essentially says that the group class should have a non-optional variable of type Contact, which means you have to set this variable to a non-nil Contact during initialisation.

stefandouganhyde
  • 4,494
  • 1
  • 16
  • 13
  • Perfect! Thank you for the answer. Also if you can give the link to the official documentation where this is stated, would be a huge plus :) – Mohsin Khubaib Ahmed May 10 '16 at 11:54
  • 1
    Documentation-wise, I guess this would be the best bit: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID212 – stefandouganhyde May 10 '16 at 14:39