从Swift中的超类访问子类属性

时间:2015-03-15 11:32:57

标签: ios swift

我是编程新手,需要一些Swift继承方面的帮助。我正在创建一个购物车类型的应用程序,用于在我的业务中创建报价。我有一个产品类,其中包含特定产品类型的子类,因此我可以为它们提供自定义属性。我有一个购物车类,我可以传递产品类和所需的数量。

我的问题是,一旦我创建了产品并将其传递到购物车中,我想访问我的子类中的属性,但我无法弄清楚如何实现这一点。请帮忙?这是我的代码。

我的产品类

class ProductItem: NSObject {

var productCode:String!
var productDescription:String!
var manufacturerListPrice:Double!
}

产品子类

class DigitalHandset: ProductItem {

var digitalPortsRequired:Int!

init(productCode: String, listPrice: Double){
    super.init()
    super.productCode = productCode
    super.manufacturerListPrice = listPrice
    super.productDescription = ""

    self.digitalPortsRequired = 1
    }
}

购物车类

public class bomItems: NSObject {

    var quantity:Int
    var productItem:ProductItem

    init(product: ProductItem, quantity: Int) {
        self.productItem = product
        self.quantity = quantity
    }
}

测试类

class testModelCode{
    var system = MasterSystem() // This class holds my array of cart items (BOM or Bill Of Materials) 
    var bomItem1 = bomItems(product: DigitalHandset(productCode: "NEC999", listPrice: 899), quantity: 8)

func addToSystem() {
    system.billOfMaterials.append(bomItem1) //I have a system class that holds an array for the cart items.
    //At this point I want to access a property of the Digital Handset class but it appears that I can not. 
    //Can anyone point me in the right direction to allow this. 
    //The following is what is not working. 
    bomItem2.DigitalHandset.digitalPortsRequired
}

1 个答案:

答案 0 :(得分:0)

如果bomItem2的类型为ProductItem,则需要将其向下转换为DigitalHandset,以便访问DigitalHandset的属性。执行此操作的安全方法是使用条件向下转发as?以及可选的绑定if let语法:

if let digitalHandset = bomItem2 as? DigitalHandset {
    // if we get here, bomItem2 is indeed a DigitalHandset
    let portsRequired = digitalHandset.portsRequired
} else {
    // bomItem2 is something other than a DigitalHandset
}

如果要检查多个类,switch语句就派上用场了:

switch bomItem2 {
case digitalHandset as DigitalHandset:
    println("portsRequired is \(digitalHandset.portsRequired)")
case appleWatch as AppleWatch:
    println("type of Apple Watch is \(appleWatch.type)")
default:
    println("hmmm, some other type")
}