一个可用的init方法的实例

时间:2016-07-10 12:23:04

标签: swift binding conditional optional initializer

这是我的代码:

struct Book{
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

init?(title: String, author: String, price: String, pubDate: String){
    guard let title = title, let author = author else { // error here
        return nil
    }

    self.title = title
    self.author = author
    self.price = price
    self.pubDate = pubDate
}

}

我的错误说条件绑定的初始化程序必须没有选项类型'字符串' 我的问题是,为什么我会得到这个错误,如果我正确理解了guard语句,我应该只在else之前传递非Optional属性,在大括号之后传递可选的属性,就像我在这里完成的那样

3 个答案:

答案 0 :(得分:0)

你可以使用guard作为可选变量来解包预期数据或者早期无法从函数或循环返回。你也不需要使所有参数都是可选的。还有其他原因会导致初始化失败。< / p>

答案 1 :(得分:0)

我建议你完全放弃 failable init 。您的结构包含titleauthor,它们不是可选,因此请让初始化程序反映出来。除非他们能提供标题和作者,否则不要让他们尝试创作一本书。

其他两个属性是可选。我建议您在初始值设定项中为这些提供默认值nil,这样您的用户就可以最灵活地创建Book

struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

    init(title: String, author: String, price: String? = nil, pubDate: String? = nil) {
        self.title = title
        self.author = author
        self.price = price
        self.pubDate = pubDate
    }
}

let book1 = Book(title: "The Hitchhiker's Guide to the Galaxy", author: "Douglas Adams")
let book2 = Book(title: "The Shining", author: "Stephen King", price: "20.00")
let book3 = Book(title: "Little Women", author: "Louisa May Alcott", price: "15.99", pubDate: "1868")
let book4 = Book(title: "Harry Potter", author: "J. K. Rowling", pubDate: "1997")

如果您真的希望能够传递nil任何内容,但如果他们没有提供titleauthor则会失败,那么请使用{{1解包guardtitle,否则失败并返回author

nil

答案 2 :(得分:-1)

struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

    init?(dict: [String : String]){
        guard let title = dict["title"], let author = dict["author"] else {
            return nil
        }
        let price = dict["price"]
        let pubDate = dict["pubDate"]

        self.title = title
        self.author = author
        self.price = price
        self.pubDate = pubDate
    }
}