如何使用Swift 3将可选参数插入到Sqlite中

时间:2017-01-26 03:45:57

标签: swift3 sqlite.swift

我的这个类有一些可选属性:

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的新手,但据我所知,我不想使用'!'当值可以为零时,是否正确?

我不确定我在这里做错了什么。

1 个答案:

答案 0 :(得分:2)

创建所有类属性常量(使用let声明)并使它们成为非可选项,并使用所有Address属性参数添加必需的init()。顺便说一下,使用小写字母开始你的vars命名是Swift惯例。注意:除非是必需的,否则应使用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