[swift-users] How to express an optional is always not nil under certain conditions

zhaoxin肇鑫 owenzx at gmail.com
Mon Jan 25 08:14:23 CST 2016


You can write.

func bar() {
       if xxx {
           switch yyy {
           case .c1:
               doSomething1()
           case .c2:
*               guard let foo= someOptional else { fatalError("someOptional
should never be nil here!") }*
*               doSomethingWithValue(foo) *
           }
       } else {
           doSomething2()
       }
   }

zhaoxin

On Mon, Jan 25, 2016 at 6:34 PM, CosynPa via swift-users <
swift-users at swift.org> wrote:

> For example, I have a function that set some optional value:
>
>     func foo() {
>        if xxx {
>            switch yyy {
>            case .c1:
>                someOptional = nil
>            case .c2:
>                someOptional = 5
>            }
>        } else {
>            someOptional = nil
>        }
>    }
>
> Later I want to do something with the optional value. And I know the
> optional is always not nil when xxx is satisfied and yyy is in c2 case, so
> I just use force unwrapping.
>
>    func bar() {
>        if xxx {
>            switch yyy {
>            case .c1:
>                doSomething1()
>            case .c2:
>                doSomethingWithValue(someOptional !) // force unwrapping,
> not very good
>            }
>        } else {
>            doSomething2()
>        }
>    }
>
> But this is not very good, since you can't tell from the code why the
> optional is not nil, and if the function foo is changed, you are not aware
> of the fact that the force unwrapping is no longer valid. So is there some
> better solution?
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160125/38dfb2f8/attachment.html>


More information about the swift-users mailing list