How to express an optional is always not nil under certain conditions


(CosynPa) #1

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?


(Zhao Xin) #2

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@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@swift.org
https://lists.swift.org/mailman/listinfo/swift-users