简体   繁体   English

Swift-参数必须符合协议且检查为kindOf的函数

[英]Swift - Function where parameter must conform to protocol and check is kindOf

I have an OrderBook with expected and completed orders; 我有一个包含预期和已完成订单的OrderBook; both of which are array of Ints. 两者都是Ints数组。

I want to have an 'add' order function which is generic and works for both the expected and completed class; 我想要一个通用的“添加”订购功能,适用于预期的和已完成的类;

Both classes follow a protocol. 这两个类都遵循协议。

I wish to make a function call where the object passed in must conform to a protocol; 我希望在传入的对象必须符合协议的情况下进行函数调用; not only that I want to check that the order is kindOf class. 我不仅要检查顺序是否为kindOf类。

protocol EntryProtocol {
    var value: Int { get set }
}

class OrderBook {
    var existingOrders: [ExistingOrder] = [ExistingOrder]()
    var completedOrders: [CompletedOrder] = [CompletedOrder]()

    func add<C1: Any>(order: C1) where C1: EntryProtocol {

        print (order is ExistingOrder.Type) // returns false
        print (order is CompletedOrder.Type)  // returns false

        // i want to do a switch here
    }
}

class ExistingOrder: EntryProtocol {
    var value : Int

    init(value: Int) {
        self.value = value
    }

    // .. other methods
}



class CompletedOrder: EntryProtocol {
    var value : Int

    init(value: Int) {
        self.value = value
    }

    // .. other methods
}


var orderBook: OrderBook = OrderBook()

let howMany = 4

for _ in 1...howMany {
    let value = 3 // this is a random number (1-6)
    let order = ExistingOrder.init(value: value)
    orderBook.add(order: order)
}

print (orderBook.existingOrders)
print (orderBook.completedOrders)

In my swift playground, the add() function always returns false when I check to see whether it is a ExistingOrder or CompletedOrder 在我快速的操场上,当我检查它是ExistingOrder还是CompletedOrder时,add()函数始终返回false。

How do I make a function where the parameter must conform to a protocol; 我如何在参数必须符合协议的情况下创建函数? then check that the object passed in via parameter is of a certain type? 然后检查通过参数传入的对象是否具有某种类型?

Many thanks 非常感谢

the answer is to use order is ExistingOrder , crediting @rmaddy then check the return if let order = order as? ExistingOrder 答案是使用order is ExistingOrder ,将@rmaddy记入贷方,然后检查if let order = order as? ExistingOrder if let order = order as? ExistingOrder , crediting @dan if let order = order as? ExistingOrder ,记入@dan

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

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