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

CosynPa v_ds_dt at 163.com
Mon Jan 25 04:34:50 CST 2016


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?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160125/8b3b2468/attachment.html>


More information about the swift-users mailing list