无法将 SomeObject 类型的值分配给 SomeObject?

Cannot assign Value of type SomeObject to SomeObject?

所以我有两个模型;通过 NSCoder 联系和分组,并 archiving/unarchiving 他们的数据。考虑一下:

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)
    }
}

这真的很好,但是当我尝试在我的组模型中使用联系人时,它只是搞砸了 bad = 给出了这个错误 "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)
    }
}

请告诉我我应该怎么做,因为我没有所有参数来整体初始化联系人。提前谢谢你:)

你的变量声明应该是

var contact: Contact

这实质上是说组 class 应该有一个类型为 Contact 的非可选变量,这意味着您必须在 Contact 期间将此变量设置为非零 Contact初始化。