0

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 ?

Goktug
  • 855
  • 1
  • 8
  • 21

1 Answers1

0

Change this code -

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

to this code -

 func clone() -> AnyObject {
    return Circle( radius : self.radius )
 }
Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31