[英]Can not execute method from another class by delegate?
I am using swift 5.1 and do not know if the swift version make it impossible.我正在使用 swift 5.1,不知道 swift 版本是否使它成为不可能。
I created class in swiftA.swift and SwiftB.swift and I want to execute method in SwiftA.swift.我在 swiftA.swift 和 SwiftB.swift 中创建了类,我想在 SwiftA.swift 中执行方法。
swiftA.swift: swiftA.swift:
class MySchoolA : CaculateADelegate {
func executeCaculate(_ MyClass,caculateTheNumber index:Int) -> Int {
return 80
}
}
and in the swiftB.swift并在 swiftB.swift
protocol CaculateADelegate: AnyObject {
func executeCaculate(_ MyClass,caculateTheNumber index:Int) -> Int
}
class MyClassB {
weak var delegate:CaculateADelegate?
init(){
let num = delegate?.executeCaculate(self,0)
}
}
the variable num is always nil, where is wrong?变量 num 始终为零,哪里错了?
thank you.谢谢你。
in init
of class B the delegate is nil
在 B 类的
init
中,委托nil
weak var delegate:CaculateADelegate?
So if you do所以如果你这样做
let bC = MyClassB() // here it's nil
bC.delegate = self // here it has a value
-- ——
So to work you can do like this by sending the delegate in init
所以为了工作,你可以通过在
init
发送委托来做到这一点
class MySchoolA : CaculateADelegate {
func executeCaculate(_ ff:MyClassB,caculateTheNumber index:Int) -> Int {
return 80
}
}
protocol CaculateADelegate: AnyObject {
func executeCaculate(_ ff:MyClassB,caculateTheNumber index:Int) -> Int
}
class MyClassB {
weak var delegate:CaculateADelegate?
init(_ del:CaculateADelegate){
self.delegate = del
let num = delegate?.executeCaculate(self,caculateTheNumber: 0)
print(num)
}
}
Test this测试这个
MyClassB(MySchoolA()) // will print 80
You're not refrencing delegate to self in swiftA.swift.您没有在 swiftA.swift 中将委托引用到 self 。
In class swiftA.swift you have instance of swiftB class at that time do swiftB.delegate = self and implement protocols in swiftA class在 swiftA.swift 类中,您当时有 swiftB 类的实例,请执行swiftB.delegate = self并在 swiftA 类中实现协议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.