Search code examples
swiftswift-playground

Issue using protocol to connect two classes in swift language


I use playground and try to get message "show : Hello" in below simple code. However, nothing shows, but there is no compiler error. I don't where the problem is.

protocol showSome{
   func show(str:String)
}
class client: showSome{
   var s: server?
   init(){
       s = server(str: "Hello", delegate: self)
   }    
   func setup(){
       let server = s!
       server.service()       
   }    
   func show(str: String) {
       println("show: \(str)")
   }
}
class server{
   let delegate: showSome?
   let str: String
   init(str: String, delegate: showSome){
       self.delegate = delegate
       self.str = str
   }
   func service(){
       let d = delegate!
       d.show(str)
   }
}

var c = client()
c.setup()

Solution

  • Your code works for me. You have to open the timeline if you are in a playground to see the output go println()

    open timeline

    btw: by conventions class names are using CamelCase with an initial big letter.