当试图调用便利init,Swift时调用额外的参数

时间:2014-08-12 17:07:35

标签: swift

我有简单的课程:

class WmAttendee{

    var mEmail:String!
    var mName:String!
    var mType:Int!
    var mStatus:String = "0"
    var mRelationShip:String!

    init( email:String, name:String, type:Int) {
        self.mEmail = email
        self.mName = name
        self.mType = type
    }

     convenience init( email:String,  name:String,  type:Int,  status:String, relationShip:String) {
        self.init(email: email, name: name, type: type)
        self.mStatus = status
        self.mRelationShip = relationShip
    }
}

当我尝试使用5个参数测试第二个构造函数时,我得到:Extra argument 'status' in call

var att1 = WmAttendee(email: "myMail", name: "SomeName", type: 1); // OK

var att2 = WmAttendee(email: "mail2", name: "name2", type: 3, status: "2", relationShip: 3)
 // ERROR Extra argument 'status' in call

为什么呢?我想念一下吗?

谢谢,

2 个答案:

答案 0 :(得分:7)

根据您的方法签名:

convenience init( email:String,  name:String,  type:Int,  status:String, relationShip:String)

relationshipStatus应该是String,而不是Int

var att2 = WmAttendee(email: "mail2", name: "name2", type: 3, status: "2", relationShip: "3")

由于您没有为relationshipStatus传递正确的类型,编译器无法为您的方便init匹配方法签名,而是回退到默认的init(它可以找到的最接近的匹配) )触发Extra argument错误。

答案 1 :(得分:1)

您正在将错误类型的参数传递给您的函数。 '关系'必须是String类型,但是您传递的是Integer。是的,编译器错误具有误导性,但是再次迅速仍处于测试阶段。