[英]How to access same propety from different class without type casting in swift
I have 2 class which have same number of properties with same name. 我有2个类,它们具有相同数量的同名属性。 I want to access property without type casting. 我想访问没有类型转换的属性。
class A : NSObject {
var amount : Int = 10
}
class B : NSObject {
var amount : Int = 20
}
Now I want to double the value of amount property like this 现在我想要像这样加倍amount属性的值
main() {
let classA : A()
print(doubleValue(classA))
let classB : B()
print(doubleValue(classB))
}
func doubleValue(myClass:AnyObject) -> Int {
return myClass.amount * 2
}
Please suggest how can I achieve this. 请建议我如何实现这一目标。
This is exactly what protocol are used for. 这正是协议的用途。 Let us call this new protocol Amountable
and add the amount
property. 让我们将这个新协议Amountable
并添加amount
属性。
protocol Amountable {
var amount: Int { get set }
}
If you want to provide a default implementation for doubleValue()
you can event use protocol extension as follows: 如果要为doubleValue()
提供默认实现,则事件可以使用协议扩展,如下所示:
extension Amountable {
mutating func doubleValue() {
self.amount *= 2
}
}
Finally, let your classes conform to the protocol: 最后,让您的类符合协议:
class ClassA: Amountable {
// Implementation of classA here
}
class ClassB: Amountable {
// Implementation of classB here
}
objectA = ClassA()
objectA.doubleValue()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.