Swift- variable not initialized before use (but it's not used)

后端 未结 4 1161
广开言路
广开言路 2020-12-20 14:21

Currently I\'ve got some swift code like this:

class C {
   let type: Type;
   var num = 0;
   init() {
       self.type = Type({ (num: Int) -> Void in
           


        
4条回答
  •  -上瘾入骨i
    2020-12-20 14:53

    This works:

    class C {
        var type: Type?;
        var num = 0;
        init() {
            self.type = Type({ (num: Int) -> Void in
                self.num = num;
            });
        }
    }
    

    I assume you knew that. But you want to know why your version isn't working.

    Now for the tricky part: for the line

    self.num = num;
    

    to work, the compiler has to pass self to inside the closure. The closure could be and probably is executed inside of the constructor of Type.

    This is as if you had written

    self.type = Type({ (self: C, num: Int) -> Void in
        self.num = num    
    });
    

    which is syntactically wrong but explains what the compiler has to do to compile your code.

    To pass this necessary instance of self to the constructor of Type, self has to be initialized. But self isn't initialized, because you are still in the constructor.

    The compiler tells you which part of self is not initialized, when you try to pass self to the constructor of Type.

    P.S.

    obviously Type knows num in your code. If you want to use let in C instead of var you could do...

    class Type {
        let num: Int
        init () {
            num = 3
        }
    }
    class C {
        let type: Type;
        var num = 0;
        init() {
            self.type = Type();
            num = type.num
        }
    }
    

    or even

    class C {
        let type: Type;
        var num: Int {
            return type.num
        }
        init() {
            self.type = Type();
        }
    }
    

    depending on whether you want num to change or not. Both examples compile without error.

提交回复
热议问题