Overriding a stored property in Swift

前端 未结 10 813
鱼传尺愫
鱼传尺愫 2020-11-30 00:10

I noticed that the compiler won\'t let me override a stored property with another stored value (which seems odd):

class Jedi {
    var lightSaberColor = \"Bl         


        
10条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 00:35

    Swift does not allow you to override a variable stored property Instead of this you can use computed property

    class A {
        var property1 = "A: Stored Property 1"
    
        var property2: String {
            get {
                return "A: Computed Property 2"
            }
        }
    
        let property3 = "A: Constant Stored Property 3"
    
        //let can not be a computed property
        
        func foo() -> String {
            return "A: foo()"
        }
    }
    
    class B: A {
    
        //now it is a computed property
        override var property1: String {
    
            set { }
            get {
                return "B: overrode Stored Property 1"
            }
        }
    
        override var property2: String {
            get {
                return "B: overrode Computed Property 2"
            }
        }
        
        override func foo() -> String {
            return "B: foo()"
        }
    
        //let can not be overrode
    }
    
    func testPoly() {
        let a = A()
        
        XCTAssertEqual("A: Stored Property 1", a.property1)
        XCTAssertEqual("A: Computed Property 2", a.property2)
        
        XCTAssertEqual("A: foo()", a.foo())
        
        let b = B()
        XCTAssertEqual("B: overrode Stored Property 1", b.property1)
        XCTAssertEqual("B: overrode Computed Property 2", b.property2)
        
        XCTAssertEqual("B: foo()", b.foo())
        
        //B cast to A
        XCTAssertEqual("B: overrode Stored Property 1", (b as! A).property1)
        XCTAssertEqual("B: overrode Computed Property 2", (b as! A).property2)
        
        XCTAssertEqual("B: foo()", (b as! A).foo())
    }
    

    It is more clear when compare with Java, where a class field can not be overrode and does not support polymorphism because is defined in compile time(run efficiently). It is called a variable hiding[About] It is not recommended to use this technics because it is hard to read/support

    [Swift property]

提交回复
热议问题