Goktug Goktug - 1 year ago 45
Swift Question

Methods in Protocols

I am very new to protocol oriented programming ,so my question may be very easy.

I intend to define a Cloneable protocol which has a clone() method. This method returns the object whose contents are same as contents of the object which invoke clone() method. Thus, return type of clone() method must adjust to the class adopting Cloneable protocol.

protocol Cloneable{

func clone() -> AnyObject
}


public final class Circle : Cloneable{


private var radius : Double
private var area : Double
private var perimeter : Double


public init( radius : Double ){
self.radius = radius
area = PI * radius * radius
perimeter = 2 * PI * radius
}

public convenience init(){
self.init( radius : 1.0 )
}

func clone() -> Circle{
return Circle( radius : self.radius )
}
}


I get error that Class Circle does not conform to Cloneable protocol.
It wants me to change AnyObject with Circle. If I do that, How can this protocol be used for all classes ?

Answer Source

Change this code -

func clone() -> Circle{
   return Circle( radius : self.radius )
}

to this code -

 func clone() -> AnyObject {
    return Circle( radius : self.radius )
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download