I create a enum like the following and I try to use the fromRaw() function.
enum Test : Int {
case a = 1
case b, c
func description() -> String{
switch self {
case .a:
return "a"
default:
return String(self.toRaw())
}
}
}
It works in the situation I use like this. The bvalue.description() gives me the result "2".
if let bvalue = Test.fromRaw(2) {
bvalue.description()
}
But when I try to use it without If statement, like the following. It gives me a wrong notification on the second line said "Invalid use of '()' to call a value of a non-function type String."
let bvalue = Test.fromRaw(2)
bvalue.description()
I was confused. What is the difference within If or without If statement? Why the second way cannot work? What type is this fromRaw() function returned?
The .fromRaw()
method returns an optional value of your enumeration. So instead of bvalue
having type Test
, it has type Test?
. In order to access its value you need to either unwrap it with an if let...
like your example or force the unwrapping with the !
operator:
bvalue!.description()
Note that if the .fromRaw()
call failed, you'll get a runtime error. Try this to see it:
let bvalue = Test.fromRaw(5) // 5 is out of bounds, bvalue == nil
bvalue!.description() // runtime error: Can't unwrap Optional.None
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments