Swift-3
struct Book {
var title: String
var description: String
var price: Float
}
I have Book structure which I want to initialize from dictionary
var book: Book? = ["Title": "Harry Poter", "Description": "Fantasy Novel", "Price": 190]
Is it possible to do in Swift?
Try to make suitable init() as Martin says for your structure and use it according to your requirement:
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With