Swift: Cannot assign to immutable expression of type 'AnyObject?!'

前端 未结 2 899
情话喂你
情话喂你 2021-02-19 02:53

I searched, but I didn\'t find a familiar answer, so...

I am about to program a class to handle parse methods like updating, adding, fetching and deleting.



        
2条回答
  •  無奈伤痛
    2021-02-19 03:05

    In swift a lot of types are defined as structs, which are immutable by default.

    I had the same error doing this :

    protocol MyProtocol {
        var anInt: Int {get set}
    }
    
    class A {
    
    }
    
    class B: A, MyProtocol {
        var anInt: Int = 0
    }
    

    and in another class :

    class X {
    
       var myA: A
    
       ... 
       (self.myA as! MyProtocol).anInt = 1  //compile error here
       //because MyProtocol can be a struct
       //so it is inferred immutable
       //since the protocol declaration is 
       protocol MyProtocol {...
       //and not 
       protocol MyProtocol: class {...
       ...
    }
    

    so be sure to have

    protocol MyProtocol: class {
    

    when doing such casting

提交回复
热议问题