简体   繁体   中英

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.

I created class in swiftA.swift and SwiftB.swift and I want to execute method in SwiftA.swift.

swiftA.swift:

class MySchoolA : CaculateADelegate {
func executeCaculate(_ MyClass,caculateTheNumber index:Int) -> Int {
    return 80
 }
}

and in the 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?

thank you.

in init of class B the delegate is 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

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.

In class swiftA.swift you have instance of swiftB class at that time do swiftB.delegate = self and implement protocols in swiftA class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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