How to use the guard instruction to determine zero after assignment?

I am trying to use the guard command to check against nil.

I am puzzled why the following allows you to slip and generate a BAD_EXEC error:

    guard let event:Event! = eventsImagesLoading.removeValueForKey(location) else {
        return
    }
    images[location] = responseData
    event!.iconImgData = images[location]

I am trying to check if the "event" is null after a method call. If so, then you just need to return. But in fact, it slips and falls on the event! .IconImageData ... line.

+1
source share
3 answers

Other answers show how to solve your problem, but don't really explain why this error occurs, so I thought I could do it.


guard let ... else, if let ..., --- , nil --- ;

var a: Int? = 5
if let b = a {
    // b unwrapped, type inferred to non-optional type Int
    print(b) // "5"
}

, a nil, b ( ) Int, nil.

b , , a . b , " " a (Int?) b (Int?), , , if let ... - .

a = nil

if let b: Int! = a {
    print(b) // "nil"
    // wups, we managed to bind a to b even though a is nil ...

    // note also this peculiarity
    print(b.dynamicType) // Optional<Int>
    let c: Int! = nil
    print(c.dynamicType) // ImplicitlyUnwrappedOptional<Int>
}

if let b: Int? = a {
    print(b) // nil
    // wups, we managed to bind a to b even though a is nil ...
}

, , b Int? () Int! ( ), b, if let ( Int?). , event (event!.iconImgData) guard let, .

, guard let ... else , eventsImagesLoading.removeValueForKey(location) nil, event ( Event!) nil .

func foo() {
    let bar : Int? = nil
    guard let _: Int! = bar else {
        print("this is surely nil")
        return

    }
    print("but an implicitly unwrapped optional will fall through")
}
foo() // "but an implicitly unwrapped optional will fall through"

, ( nil ). nil ( : nil).

, , , , guard let INFER_THIS = ... else if let INFER_THIS = ....


, ( ), .

+5

Event! Event ( 1) Event! Event ( 5).

+3
guard let event:Event = eventsImagesLoading.removeValueForKey(location) else {
        return
    }
    images[location] = responseData
    event.iconImgData = images[location]
+1
source

Source: https://habr.com/ru/post/1665658/


All Articles