0

I have A class. And its subclass B. I need to override type of its property. Also that will be ok to to change a protocol. How can I do that?

class A {
 var property: String (or SomeProtocolA)
}

class B: A {
 var property: Int (or SomeProtocolB)
}

Maybe its possible to add support second protocol for property in subclass?

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
  • 1
    You can't. http://stackoverflow.com/questions/24094158/overriding-superclass-property-with-different-type-in-swift – Code Different Jun 16 '16 at 19:52
  • One rule of OO inheritance is that B is substitutable for A -- meaning if I think I have an A, but really have a B, it's ok. B can do everything A can do and hare no extra requirements. So B.property needs to be String or behave like String. – Lou Franco Jun 16 '16 at 19:56
  • In your real example, does SomeProtocolB inherit from SomeProtocolA? – Lou Franco Jun 16 '16 at 19:57

2 Answers2

0

You can't, and this is indicative of poor design.

Suppose Class A had a function:

class A {
    var property: String (or SomeProtocolA)

    func getMyString() -> String {
        return property
    }
}

and now class B inherits it, whilst "overwriting" property:

class B : A {
    var property: Int(or SomeProtocolB)

    // func getMyString() -> String { //inherited from superclass
    //    return property //type error, expected String, returning Int
    //}
}
Alexander
  • 59,041
  • 12
  • 98
  • 151
0

You can do this, but in VERY limited situations. The only ways that this is allowed is under the following circumstances:

  1. The property must be get only.
  2. The overriding type must be a subclass of the original type (so no struct, protocol or enum).

Here is an example overriding with strings:

class A {
    var property: NSString {
        return ""
    }
} 

class B: A {
    override var property: NSMutableString {
        return NSMutableString(string: "")
    }
} 
keithbhunter
  • 12,258
  • 4
  • 33
  • 58