Swift-3
struct Book {
var title: String
var description: String
var price: Float
}
我有我想从字典初始化的书籍结构
var book: Book? = ["Title": "Harry Poter", "Description": "Fantasy Novel", "Price": 190]
在 Swift 中可以做到吗?
尝试按照 Martin 所说的为您的结构制作合适的 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!)