2015-03-15 4 views
0

Я новичок в программировании и нуждаюсь в некоторой помощи с наследованием в Swift. Я создаю приложение типа cart для создания котировок в моем бизнесе. У меня есть класс продукта с подклассом для определенных типов продуктов, поэтому я могу предоставить им пользовательские свойства. У меня есть класс корзины, где я могу пройти в классе продукта и требовать qty.Доступ к свойству подкласса из суперкласса в 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 
} 

ответ

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") 
} 
+0

Это потрясающе , Большое спасибо. Я играл с downcast, но не мог заставить его работать, ваше решение отлично работало. Благодаря! – Barnsy