如何使用 Swift 插入带有可选参数的 Sqlite 3

How to insert into Sqlite with optional parameters using Swift 3

我有这个 class 和一些可选属性:

class Address {
    var Id: Int64
    var AddressType: Int64
    var AddressStatus: Int64
    var Address1: String?
    var Address2: String?
    var City: String?
    var State: String?
    var Zip: String?
    var Country: String?
    var Latitude: Double?
    var Longitude: Double?
}

我正在尝试插入 Sqlite 数据库,如下所示:

let insert = table.insert(or: .replace, Id <- item.Id, AddressType <- item.AddressType, AddressStatus <- item.AddressStatus, Address1 <- item.Address1?, Address2 <- item.Address2?, City <- item.City?, State <- item.State?, Zip <- item.Zip?, Country <- item.Country?, Latitude <- item.Latitude?, Longitude <- item.Longitude?)

但是我得到这个构建错误:

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

如果我使用'!'它会构建,但是当我 运行:

时出现此错误
unexpectedly found nil while unwrapping an Optional value

我还是 Swift 的新手,但据我所知,我不想使用 '!'当值可以为零时,正确吗?

我不确定我做错了什么。

使所有 class 属性常量(用 let 声明)并使它们成为非可选的,添加一个必需的 init() 和所有地址属性参数。顺便说一句,Swift 约定以小写字母开始您的 vars 命名。注意:除非有要求,否则您应该使用 Int 而不是 Int64。关于属性的可选性,您可以在初始化时为它们分配一个默认值。顺便说一句,除非你需要让你的对象持久化(符合 NSCoding 标准),否则最好使用结构:

struct Address {
    let id: Int
    let addressType: Int
    let addressStatus: Int
    let address1: String
    let address2: String
    let city: String
    let state: String
    let zip: String
    let country: String
    let latitude: Double?
    let longitude: Double?
    init(id: Int, addressType: Int, addressStatus: Int, address1: String = "", address2: String = "", city: String = "", state: String = "", zip: String = "", country: String = "", latitude: Double = nil, longitude: Double = nil) {
        self.id = id
        self.addressType = addressStatus
        self.addressStatus = addressStatus
        self.address1 = address1
        self.address2 = address2
        self.city = city
        self.state = state
        self.zip = zip
        self.country = country
        self.latitude = latitude
        self.longitude = longitude
    }
}

因此您可以按如下方式创建新对象地址:

let address1 = Address(id: 1, addressType: 2, addressStatus: 3)
let address2 = Address(id: 2, addressType: 3, addressStatus: 4, address1: "Any Address", latitude: 22.0, longitude: 43.0)   // You don't need to add all parameters as long as you keep them in the same order as your initializer

address2.latitude   // 22.0