enum Hotel{
case hotelName: "Raddisson"
case hotelCost: 200
case offer: 0.02
}
How should assign the multiple types in the enum?
Unfortunately this is not possible to have cases of an enum of different types. An enum can have some raw type
, but that type is same for all the cases. Below is the example of enum having raw type String
enum Hotel: String {
case hotelName: "Raddisson"
case hotelCost: "200"
case offer: "0.02"
}
You should use a struct here, for example:
struct Hotel {
let hotelName: String
let hotelCost: NSDecimalNumber
let offer: NSDecimalNumber
}
To have an enum with multiple values you could do this using associated values:
enum Hotel {
case standard(name: String, cost: NSDecimalNumber, offer: NSDecimalNumber)
case extended(name: String, cost: NSDecimalNumber, offer: NSDecimalNumber, discount: NSDecimalNumber)
}
An example of how to extract the values from the above enum is:
let hotel = Hotel.standard(name: "Hotel", cost: 50, offer: 10)
if case let Hotel.standard(name, cost, offer) = hotel {
print (name, cost, offer)
}
switch hotel {
case let .standard(name, cost, offer):
print (name, cost, offer)
case let .extended(name, cost, offer, discount):
print (name, cost, offer, discount)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.