GVKun编程网logo

使用Swift 4中的JSONDecoder时,丢失的键可以使用默认值而不是必须是可选属性吗?

17

本文将介绍使用Swift4中的JSONDecoder时,丢失的键可以使用默认值而不是必须是可选属性吗?的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些

本文将介绍使用Swift 4中的JSONDecoder时,丢失的键可以使用默认值而不是必须是可选属性吗?的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于12.5 Swift可选属性与构造方法、ios – Swift 2.0中的动态可选属性、ios – Swift问题中的JSONModel、ios – 使用swift Xcode 6的默认标签栏项目颜色的知识。

本文目录一览:

使用Swift 4中的JSONDecoder时,丢失的键可以使用默认值而不是必须是可选属性吗?

使用Swift 4中的JSONDecoder时,丢失的键可以使用默认值而不是必须是可选属性吗?

Swift
4添加了新Codable协议。当我使用JSONDecoder它时,似乎要求类的所有非可选属性Codable在JSON中具有键,否则会引发错误。

使类的每个属性都是可选的似乎是不必要的麻烦,因为我真正想要的是使用json中的值或默认值。(我不希望该属性为零。)

有没有办法做到这一点?

class MyCodable: Codable {    var name: String = "Default Appleseed"}func load(input: String) {    do {        if let data = input.data(using: .utf8) {            let result = try JSONDecoder().decode(MyCodable.self, from: data)            print("name: \(result.name)")        }    } catch  {        print("error: \(error)")        // `Error message: "Key not found when expecting non-optional type        // String for coding key \"name\""`    }}let goodInput = "{\"name\": \"Jonny Appleseed\" }"let badInput = "{}"load(input: goodInput) // works, `name` is Jonny Applessedload(input: badInput) // breaks, `name` required since property is non-optional

答案1

小编典典

我更喜欢的方法是使用所谓的DTO-数据传输对象。它是一个结构,符合Codable并表示所需的对象。

struct MyClassDTO: Codable {    let items: [String]?    let otherVar: Int?}

然后,您只需使用该DTO初始化要在应用程序中使用的对象。

 class MyClass {    let items: [String]    var otherVar = 3    init(_ dto: MyClassDTO) {        items = dto.items ?? [String]()        otherVar = dto.otherVar ?? 3    }    var dto: MyClassDTO {        return MyClassDTO(items: items, otherVar: otherVar)    }}

这种方法也是不错的选择,因为您可以按自己的意愿重命名和更改最终对象。很明显,比手动解码需要更少的代码。此外,通过这种方法,您可以将网络层与其他应用程序分开。

12.5 Swift可选属性与构造方法

12.5 Swift可选属性与构造方法

/**

可选属性与构造方法

*/

class CreditCard {

let cardNumber: UInt32

init(number: UInt32) {

self.cardNumber = number

}

}

// 可选值存储属性可以在构造方法中不进行初始化。默认为nil

// 当然我们也可以在构造方法中进行初始化。

class Human {

let name: String

var age: Int

// 对于一个人来讲,可能有信用卡,也可能没有信用卡。因此声明为可选值类型。

var card: CreditCard?

init(name: String,age: Int) {

self.name = name

self.age = age

// self.card = CreditCard.init(number: 98675548)

}

}

var perosn = Human.init(name: "xiaozhang",age: 10)

perosn.age = 11

ios – Swift 2.0中的动态可选属性

ios – Swift 2.0中的动态可选属性

我已经看过这篇文章 Optional dynamic properties in Swift,但我不想在NSObject中包装该类.这只是关于Realm数据库我没有nil属性,但我认为这是一个很好的方式来建模我的数据库.在可以在 https://realm.io/docs/swift/latest/中找到的Realm文档中,它表示支持选项.这是我的

dynamic var complete: Bool? = nil

这是我的

错误

Property cannot be marked dynamic because its type cannot be represented in Objective-C

我知道这是与上面的帖子相同的代码和错误,但我很好奇,如果Realm文档说它支持它,他们还有另一种解决方法吗?

解决方法

来自 supported types和 optional properties的文档.

String,NSDate,NSData and Object properties can be optional. Storing optional numbers is done using 07002.

RealmOptional supports Int,Float,Double,Bool,and all of the sized versions of Int (Int8,Int16,Int32,Int64).

因此,使用标准的swift语法很好地支持String,NSDate,NSData和Object类型的选项.

对于使用RealmOptional完成的其他数字类型(例如Bool).然后,要使用此RealmOptional类型的变量,您可以访问其value属性,该属性是一个可选的,表示您的基础值.

// deFinition (defined with let)
let complete = RealmOptional<Bool>()  // defaults to nil
// usage
complete.value = false  // set non-nil value
...
complete.value = nil    // set to nil again

ios – Swift问题中的JSONModel

ios – Swift问题中的JSONModel

我试图使用 JSONModel将json映射到 Swift中的模型.

如果模型没有属于JSONModel子类的属性,则一切正常.

所以在示例中这是有效的,并且它成功映射了属性:

class Person: JSONModel {

    var name: Nsstring?
    var gender: Nsstring?

}

但是,如果我将JSONModel子类设置为City,则此属性未初始化,并且当我稍后尝试访问city属性时它会崩溃应用程序(我可以成功访问person.name和person.gender,但是在person.city上它崩溃了任何信息):

class Person: JSONModel {

    var name: Nsstring?
    var gender: Nsstring?
    var city: City? // City is JSONModel subclass
}

如果它是JSONModel子类,看起来JSONModel不能映射/解析属性.
有没有人经历过这个并解决了它?

解决方法

JSONModel在Swift中不起作用,这就是你遇到问题的原因.从 JSONModel readme:

NB: Swift works in a different way under the hood than Objective-C.
Therefore I can’t find a way to re-create JSONModel in Swift.
JSONModel in Objective-C works in Swift apps through CocoaPods or as
an imported Objective-C library.

您可能能够在某些边缘情况下使用它 – 但唯一可靠的方法是使用它,通过编写Objective C代码并使用这些Objective C类.如果你想做纯Swift,你应该看看其他库,如Argo和其他一些库.

ios – 使用swift Xcode 6的默认标签栏项目颜色

ios – 使用swift Xcode 6的默认标签栏项目颜色

环境:
– Xcode 6 beta 4
– Swift语言
– iOS标签应用程序(默认xCode项目)

如何将标签的默认灰色更改为其他? (优选全球)

就我的研究而言,我需要以某种方式将每个标签的图像渲染模式更改为原始渲染模式,但我不知道如何

解决方法

每个(默认)标签栏项由文本和图标组成。通过指定外观,全局更改文本颜色很容易:

// you can add this code to you AppDelegate application:didFinishLaunchingWithOptions: 
// or add it to viewDidLoad method of your TabBarController class
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.magentaColor()],forState:.normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()],forState:.Selected)

与图像情况有点复杂。您无法在全局范围内定义其外观。您应该在TabBarController类中重新定义它们。添加代码到以下TabBarController类的viewDidLoad方法:

for item in self.tabBar.items as [UITabBarItem] {
    if let image = item.image {
        item.image = image.imageWithColor(UIColor.yellowColor()).imageWithRenderingMode(.AlwaysOriginal)
    }
}

我们知道UIImage类中没有imageWithColor(…)方法。所以这里是扩展实现:

// Add anywhere in your app
extension UIImage {
    func imageWithColor(tintColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size,false,self.scale)

        let context = UIGraphicsGetCurrentContext() as CGContextRef
        CGContextTranslateCTM(context,self.size.height)
        CGContextScaleCTM(context,1.0,-1.0);
        CGContextSetBlendMode(context,.normal)

        let rect = CGRectMake(0,self.size.width,self.size.height) as CGRect
        CGContextClipToMask(context,rect,self.CGImage)
        tintColor.setFill()
        CGContextFillRect(context,rect)

        let newImage = UIGraphicsGetimageFromCurrentimageContext() as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

imageWithColor是从这个答案借来的:http://stackoverflow.com/a/24545102/3050466

今天的关于使用Swift 4中的JSONDecoder时,丢失的键可以使用默认值而不是必须是可选属性吗?的分享已经结束,谢谢您的关注,如果想了解更多关于12.5 Swift可选属性与构造方法、ios – Swift 2.0中的动态可选属性、ios – Swift问题中的JSONModel、ios – 使用swift Xcode 6的默认标签栏项目颜色的相关知识,请在本站进行查询。

本文标签: