Reputation: 6451
I'm trying to do the following in a playground to assign an enum type based on a string, but getting an error in the changeType function. How can I get this to work properly?
enum TransactionType {
case purchase,charge
case deposit,payment
func description() -> String {
switch self {
case .purchase:
return "purchase"
case .charge:
return "charge"
case .deposit:
return "deposit"
case .payment:
return "payment"
}
}
func typeFromString(value:String) -> TransactionType {
switch value {
case "charge":
return .charge
case "deposit":
return .deposit
case "payment":
return .payment
default:
return .purchase
}
}
}
class Tester {
var transactionType = TransactionType.purchase
func changeType() {
transactionType = TransactionType.typeFromString("charge")
}
}
var tester = Tester()
print(tester.transactionType.description())
tester.changeType()
print(tester.transactionType.description())
Upvotes: 3
Views: 7927
Reputation: 72760
The solution is simpler than you think:
enum TransactionType : String {
case purchase = "purchase", charge = "charge"
case deposit = "deposit", payment = "payment"
}
class Tester {
var transactionType = TransactionType.purchase
func changeType() {
transactionType = TransactionType.fromRaw("charge")!
}
}
var tester = Tester()
print(tester.transactionType.toRaw())
tester.changeType()
print(tester.transactionType.toRaw())
The trick is to set a raw value of String
type, which defines the type associated to each enum case.
More info Raw Values in Enumerations
Upvotes: 3
Reputation: 80265
You can define the typeFromString
method as static in order to avoid complications with optional values. After all, it just contains constants anyway. Simply add the word static
before the func
definition.
static func typeFromString(value:String) -> TransactionType {
Upvotes: 1