enumeration - Swift issue with example -
i'm new swift , learning book called the swift programming language. in book there example:
enum rank: int { case ace = 1 case two, three, four, five, six, seven, eight, nine, ten case jack, queen, king func simpledescription() -> string { switch self { case .ace: return "ace" case .jack: return "jack" case .queen: return "queen" case .king: return "king" default: return string(self.rawvalue) } } }
and here part don't understand:
if let convertrank = rank(rawvalue: 3){ let description = convertrank.simpledescription() }
i tried change code above this:
let convertrank = rank(rawvalue: 3) let description = convertrank.simpledescription()
basically, have removed if
statement, error occurs: value of optional 'rank?' not unwrapped; did mean use '!' or '?'?
why have use if
statement? , don't understand error message say.
if let
special structure
in swift allows check if optional holds value, , in case – unwrapped value.
in case:
if let convertrank = rank(rawvalue: 3){ let description = convertrank.simpledescription() }
the if let
structure unwraps rank(rawvalue: 3)
(i.e. checks if there’s value stored , takes value) , stores value in convertrank
constant. can use convertrank
inside first branch of if
. notice inside if
don’t need use ?
or !
anymore.
in second case:
let convertrank = rank(rawvalue: 3) let description = convertrank.simpledescription()
you can unwrap convertrank
way:
let description = convertrank!.simpledescription()
trying use
!
access non-existent optional value triggers runtime error. make sure optional contains non-nil value before using!
force-unwrap value.
but below code work same if let
:
let description = convertrank?.simpledescription()
and program not crash if convertrank
nil
.
more explanation:
Comments
Post a Comment