如何从子类访问属性?

时间:2019-01-03 00:53:31

标签: swift class inheritance subclass

我在从子类访问属性时遇到问题。我定义了超类,然后创建了从超类继承的子类。我在子类中初始化了我的超类。

我有一个叫做Box的课。在此类中,我有一个称为Offer的属性,其类型为OfferType。

var Offer:OfferType?

比我已经创建了OfferType类,并在其中设置了一些属性。

class OfferType {

    var Name: String?
    var Image: UIImage?
    var Description: String?

    init(Name: String, Image: UIImage, Description: String) {
        self.Name = Name
        self.Image = Image
        self.Description = Description   
    }
}

比我创建了OfferType的3个子类

class Discount: OfferType {

    var Quantity: Int?

    init() {
        super.init(Name: "Discount", Image: UIImage(named: "Discount")!, Description: "nice")
    }   
}

class FreeShipping: OfferType  {

    var From: String?
    var To: String?

    init() {
        super.init(Name: "FreeShiping", Image: UIImage(named: "FreeShipping")!, Description: "lalaa")
    }   
}

class BoGoF: OfferType {

    lazy var SecondProduct = String()

    init() {
        super.init(Name: "BoGoF", Image: UIImage(named: "BoGoF")!, Description: "boh")
    }    
}

现在,在将子类分配为BOX类中的属性Offer之后,我尝试获取子类的属性。

我做不到,Xcode给我的唯一选择就是访问超类(OfferType)的属性

我需要访问属性Discount of subclass Discount。

这是我要访问属性的地方

首先,我将子类分配给Box类中的属性

newBox.Offer =折扣

现在我正在尝试获取Discount的属性,但它并没有提供给我

newBox.Offer。 Just Here

我尝试投射它,但是没有用

enter image description here

我的班级newbox是这样定义的

enter image description here

这就是Box类的定义方式

Class Box

1 个答案:

答案 0 :(得分:0)

您的newBox实例可能具有定义为offer的{​​{1}}属性。

即使您将OfferType的实例放在Discount属性中,编译器也无法知道,因为您已经告诉编译器offer将包含一个offer。它无法知道将包含在其中的特定 OfferType

您必须将OfferType强制转换为所需的类型。建议您研究offeras。这是一个示例:

is

这里的if let discount = newBox.offer as? Discount { print("Discount Quantity is \(discount.quantity)") } 关键字基本上告诉编译器以下内容:

  

as?newBox.offer的一种吗?如果是这样,则返回   返回nil。