Swift: My Convenience init does not see the normal init

时间:2015-07-31 20:42:46

标签: ios swift init

I am trying to create a convenience init for my class: User. I've done this before for another class, and - to create it again - I have used the same code, just differed for my User class.

Here is my User class:

import Foundation

class User {
    //Database Variables
    let userID: String?
    let firstName: String?
    let lastName: String?
    let password: String?
    let emailID: String?
    let dob: String? //timestamp
    let picture: String? //URL?
    let location: Location?
    let sex: String?

convenience init(data: [[String: AnyObject]]) {
    self.init(userID: String(data["user_id"]!), firstName: String(data["first_name"]!), lastName: String(data["last_name"]!), password: String(data["password"]!), emailID: String(data["email"]!), dob: String(data["dob"]!), picture: String(data["picture"]!), location: Location(String(data["street"]!), String(data["city"]!), String(data["state"]!), String(data["zip"]!), String(data["country"]!)), sex: String(data["sex"]!))
}

init (userID: String, firstName: String, lastName: String, password: String, emailID: String, dob: String, picture: String, location: Location, sex: String) {
    self.userID = userID
    self.firstName = firstName
    self.lastName = lastName
    self.password = password
    self.emailID = emailID
    self.dob = dob
    self.picture = picture
    self.location = location
    self.sex = sex
}

However, Swift doesn't see the self.init method. I am getting a Could not find an overload for init that accepts the supplied arguments

What is wrong?

4 个答案:

答案 0 :(得分:1)

您正在传递便利init数组Dictionary [[String : AnyObject]] 你的意思是只传递Dictionary: [String : AnyObject]吗?

答案 1 :(得分:1)

除了彼得所说的字典数组之外, 创建Location对象

Location(String(data["street"]!), String(data["city"]!), String(data["state"]!), String(data["zip"]!)

错误,因为缺少参数名称。 假设你的其他代码是 Swift 2 ,它应该是

Location(streetAddress: String(data["street"]!), city: String(data["city"]!), state: String(data["state"]!)

答案 2 :(得分:0)

在easy init中的self.init(...)之后按Enter键。如果参数正确,它将删除错误。

答案 3 :(得分:0)

首先,我认为您的声明是错误的,当您应该声明一个普通数组时,您声明了一个数组数组。

错:

convenience init(data: [[String: AnyObject]])

正确:

convenience init(data: [String: AnyObject])

之后,你必须传递这样的参数:

self.init(userID: (data["user_id"] as! String).....

我希望我能帮助你:)。