Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialize a structure with a dictionary in Swift? [duplicate]

Tags:

swift

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?

like image 369
manismku Avatar asked Sep 15 '25 06:09

manismku


1 Answers

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!)
like image 74
Salman Ghumsani Avatar answered Sep 17 '25 03:09

Salman Ghumsani