可失败的 init 方法的实例

instance of a failable init method

这是我的代码:

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
}

}

我的错误是条件绑定的初始化程序必须具有选项类型而不是 'String' 我的问题是,为什么我会收到此错误,如果我正确理解 guard 语句,我应该只在 else 之前传入非可选属性,在大括号之后传入可选属性,就像我在这里所做的那样。

你可以只对可选变量使用 guard 来解包预期的数据或早期失败 return 从函数或 loops.Also 你不需要使所有参数 optional.There 也是其他原因可能导致初始化失败。

我建议您完全放弃 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 就会失败,那么请使用 guard 解包 titleauthor,否则失败并 return nil:

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

// These all return nil
let book5 = Book()
let book6 = Book(title: "War and Peace")
let book7 = Book(author: "Ray Bradbury")
let book8 = Book(title: "Pride and Prejudice", price: "40.00", pubDate: "1813")
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
    }
}