How to use fromRaw () function to enumerate

I am creating an enumeration as follows, and I am trying 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 a situation that I use like that. Bvalue.description () gives me the result "2".

if let bvalue = Test.fromRaw(2) {
    bvalue.description()
}

But when I try to use it without an If statement, for example, the following. This leads me to an incorrect notification on the second line: "Invalid use of" () "to call a non-string value of type String."

let bvalue = Test.fromRaw(2)
bvalue.description()

I was confused. What is the difference inside an if statement or without if? Why can't the second method work? What type does the fromRaw () function return?

+4
source share
4 answers

.fromRaw() . bvalue, Test, Test?. , if let..., , !:

bvalue!.description()

, .fromRaw() , . , :

let bvalue = Test.fromRaw(5)   // 5 is out of bounds, bvalue == nil
bvalue!.description()          // runtime error: Can't unwrap Optional.None
+2

, fromRaw() . :

Test(rawValue: 2)
+7

, , bvalue, . , bvalue nil. if " " , . .

0

fromRaw() Test?, Test enum, be nil

, , if-let

, .

You can also force an optional value to be expanded using an operator !, as in bvalue!.description. But you should use it only in situations where it is clear that the option contains the actual value and is not nil. Using it in a situation where a value nilleads to a runtime error.

0
source

Source: https://habr.com/ru/post/1543432/


All Articles