当前位置: 动力学知识库 > 问答 > 编程问答 >

Overriding a property in a swift class which is defined initially in a Obj-c superclass

问题描述:

Although I fully appreciate it's bad practice for strongly typed implementations, I have a some generic code that needs to be changed in a subclass. The getters and setters in the obj-c code deals with id typed values so it is expecting more generalised values.

// objc

@interface A

@property NSNumber* foo;

@end

// swift subclass

class B : A {

var foo: String?

}

Is there anyway to define a property is Swift so that it replaces entirely the superclass property?

The loosely typed nature of Obj-c with the (id) type allows some flexibility, that is closed down in swift.

网友答案:

This is not possible. You can override the property to provide different behavior, but changing the type violates OO design and thus doesn't compile.

To override a property:

override var foo: NSNumber! {
  get { return NSNumber(int: 5) }
  set { }
}

Edit: Why does this break OO?

The reason is that by inheriting from A, you promise to act like an A. Imagine what would happen if you had a function like this:

func doStuff(obj: A) {
   print("Foo / 2: \(Float(obj.foo.integerValue) / 2.0)")
}

What would happen if you tried to submit an instance of B here? In a strongly-typed, compiled language, this can't be reconciled. In a dynamic language, this would result in a runtime error.

I'll also mention Liskov Substitution Principle:

Substitutability is a principle in object-oriented programming that states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., an object of the type T may be substituted with its subtype object of the type S) without altering any of the desirable properties of that program (correctness, task performed, etc.)

This is more of a guideline that says you shouldn't break existing behavior of methods and procedures that operate on your superclass, just because you subclassed. But the same is true for structure, it's just the compiler enforcing this rather than being a guideline.

分享给朋友:
您可能感兴趣的文章:
随机阅读: