接受带有可选参数的 JSON 的 Swift 3 init 方法

标签 swift

根据 Leo Dabus 在这里的出色建议 How to insert into Sqlite with optional parameters using Swift 3 ,我修改了我的类以允许可选参数。但是,我有一个方便的方法(如下所示),它接受一个 JSON 字符串来初始化对象。但是,如果您查看最底部的 self.init,它需要我添加“!”到可选参数。据我了解,这是不正确的,因为这些参数可以为零。有没有好的方法来处理这个问题? 谢谢!!!

class Address : BaseEntity {

    var Id: Int
    var AddressType: Int
    var AddressStatus: Int
    var Address1: String
    var Address2: String
    var City: String
    var State: String
    var Zip: String
    var Country: String
    var Latitude: Double
    var Longitude: Double

    init(id: Int, addressType: Int, addressStatus: Int, address1: String = "", address2: String = "", city: String = "", state: String = "", zip: String = "", country: String = "", latitude: Double = 0, longitude: Double = 0, isDeleted: Bool, created: Date? = nil, createdBy: Int = 0, modified: Date? = nil, modifiedBy: Int = 0) {
        self.Id = id
        self.AddressType = addressType
        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
        super.init(isDeleted: isDeleted, created: created, createdBy: createdBy, modified: modified, modifiedBy: modifiedBy)
    }

    convenience init?(json: [String: Any]) {

        guard let id = json["Id"] as? Int,
            let addressType = json["AddressType"] as? Int,
            let addressStatus = json["AddressStatus"] as? Int,
            let isDeleted = json["IsDeleted"] as? Bool
            else {
                return nil
        }

        let address1 = json["Address1"] as? String
        let address2 = json["Address2"] as? String
        let city = json["City"] as? String
        let state = json["State"] as? String
        let zip = json["Zip"] as? String
        let country = json["Country"] as? String
        let latitude = json["Latitude"] as? Double
        let longitude = json["Longitude"] as? Double

        let date = Foundation.Date()
        let created = date.dateFromJson(json: json["Created"] as? String)
        let createdBy = json["CreatedBy"] as? Int
        let modified = date.dateFromJson(json: json["Modified"] as? String)
        let modifiedBy = json["ModifiedBy"] as? Int

        self.init(id: id, addressType: addressType, addressStatus: addressStatus, address1: address1!, address2: address2!, city: city!, state: state!, zip: zip!, country: country!, latitude: latitude!, longitude: longitude!, isDeleted: isDeleted, created: created, createdBy: createdBy!, modified: modified, modifiedBy: modifiedBy!)
    }
}

最佳答案

除了我对命名约定的评论外,没有必要使您的属性可变。你应该看看“??”零合并运算符:

class 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
    }
    init?(json: [String: Any]) {
        guard
            let id = json["Id"] as? Int,
            let addressType = json["AddressType"] as? Int,
            let addressStatus = json["AddressStatus"] as? Int,
            let isDeleted = json["IsDeleted"] as? Bool
            else {
                return nil
        }
        self.id = id
        self.addressType = addressType
        self.addressStatus = addressStatus
        self.address1 = json["Address1"] as? String ?? ""
        self.address2 = json["Address2"] as? String ?? ""
        self.city = json["City"] as? String ?? ""
        self.state = json["State"] as? String ?? ""
        self.zip = json["Zip"] as? String ?? ""
        self.country = json["Country"] as? String ?? ""
        self.latitude = json["Latitude"] as? Double
        self.longitude = json["Longitude"] as? Double

        print(isDeleted)
        // call super.init here
    }
}

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
print(address1.id)         // 1
print(address1.address1)   // "" empty String
print(address2.latitude ?? "nil")   // 22.0
print(address2.longitude ?? "nil")   // 43.0

关于接受带有可选参数的 JSON 的 Swift 3 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41879186/

相关文章:

ios - ScrollView 在 subview 的顶部添加空间 xcode 6 Swift

ios - UIImageView:如何显示缩放图像?

swift - 线程 1 : exc_bad_instruction(code=exc_i386_invop, 子代码 = 0x0)/ fatal error :索引超出范围

Swift - 无法将类型 'UnsafePointer<Any>' 的值转换为预期的参数类型 'UnsafePointer<_>'

swift - 在 NSOperation 中使用 UICollectionView 的引用

ios - 导航错误swift 3

Swift:如何确定应用程序文件夹?

ios - Swift:可以应用于按钮的磨砂玻璃效果?

swift - 在风景中使用相机的图像选择器无法正常工作 (SwiftUI)

objective-c - Swift 中的 Objective-C id 的等价物是什么?