[英]Can not execute method from another class by delegate?
我正在使用 swift 5.1,不知道 swift 版本是否使它成为不可能。
我在 swiftA.swift 和 SwiftB.swift 中创建了类,我想在 SwiftA.swift 中执行方法。
swiftA.swift:
class MySchoolA : CaculateADelegate {
func executeCaculate(_ MyClass,caculateTheNumber index:Int) -> Int {
return 80
}
}
并在 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)
}
}
变量 num 始终为零,哪里错了?
谢谢你。
在 B 类的init
中,委托nil
weak var delegate:CaculateADelegate?
所以如果你这样做
let bC = MyClassB() // here it's nil
bC.delegate = self // here it has a value
——
所以为了工作,你可以通过在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)
}
}
测试这个
MyClassB(MySchoolA()) // will print 80
您没有在 swiftA.swift 中将委托引用到 self 。
在 swiftA.swift 类中,您当时有 swiftB 类的实例,请执行swiftB.delegate = self并在 swiftA 类中实现协议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.