Swift-3
struct Book {
var title: String
var description: String
var price: Float
}
我有Book结构,我想从字典
初始化var book: Book? = ["Title": "Harry Poter", "Description": "Fantasy Novel", "Price": 190]
可以在Swift中做到吗?
答案 0 :(得分:2)
尝试为您的结构制作合适的init(),如马丁所说,并根据您的要求使用它:
struct Book {
var title: String
var description: String
var price: Int
}
extension Book {
init(book : Dictionary<String,Any>){
title = book["Title"] as? String ?? ""
description = book["Description"] as? String ?? ""
price = book["Price"] as? Int ?? 0
}
}
let dict = ["Title": "Harry Poter", "Description": "Fantasy Novel", "Price": 190] as [String : Any]
var book: Book? = Book(book: dict)
print(book!)