gpt4 book ai didi

ios - 从 Swift 中的父类(super class)访问子类属性

转载 作者:行者123 更新时间:2023-11-28 09:12:00 25 4
gpt4 key购买 nike

我是编程新手,需要一些有关 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
}

最佳答案

如果 bomItem2ProductItem 类型,您需要将其向下转换为类型 DigitalHandset 才能访问 DigitalHandset 的属性。执行此操作的安全方法是使用条件向下转换 as? 以及可选的绑定(bind) 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")
}

关于ios - 从 Swift 中的父类(super class)访问子类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com