1

The following method calculates the percentage using two variables.

func casePercentage() {
        let percentage = Int(Double(cases) / Double(calls) * 100)
        percentageLabel.stringValue = String(percentage) + "%"
}

The above method is functioning well except when cases = 1 and calls = 0. This gives a fatal error: floating point value can not be converted to Int because it is either infinite or NaN

So I created this workaround:

func casePercentage() {
    if calls != 0 {
        let percentage = Int(Double(cases) / Double(calls) * 100)
        percentageLabel.stringValue = String(percentage) + "%"
    } else {
        percentageLabel.stringValue = "0%"
    }
}

This will give no errors but in other languages you can check a variable with an .isNaN() method. How does this work within Swift2?

2

1 Answer 1

0

You can "force unwrap" the optional type using the ! operator:

calls! //asserts that calls is NOT nil and gives a non-optional type

However, this will result in a runtime error if it is nil.

One option to prevent using nil or 0 is to do what you have done and check if it's 0.

The second is option is to nil-check

if calls != nil

The third (and most Swift-y) option is to use the if let structure:

if let nonNilCalls = calls {
    //...
}

The inside of the if block won't run if calls is nil.

Note that nil-checking and if let will NOT protect you from dividing by 0. You will have to check for that separately.

Combining second and your method:

//calls can neither be nil nor <= 0
if calls != nil && calls > 0
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.