繁体   English   中英

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

[英]Accessing a subclass property from a super class in 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
}

如果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")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM