4bottiglie
4bottiglie

Reputation: 540

Swift Protocol Function: returning the same type of conforming class

I want to know if something java-like (or c++) can be done in Swift:

I have a protocol:

protocol Prot1 {
   func returnMyself() -> Prot1
}

And a class conforms the protocol Prot1. Can I force the return type of the function returnMyself() to be the same type of the class like below?

class MyClass: Prot1 {
   public func returnMyself() -> MyClass {
      return self
   }
}

Is it possible?

Upvotes: 6

Views: 1830

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59536

Just use Self into your protocol

protocol Prot1 {
   func returnMyself() -> Prot1
}

Here's an example

protocol Animal {
    func mySelf() -> Self
}

class Feline: Animal {
    func mySelf() -> Self {
        return self
    }
}

class Cat: Feline { }

Feline().mySelf() // Feline
Cat().mySelf() // Cat

About protocol extensions

You can also use Self inside a protocol extension like this

protocol Animal {}

extension Animal {
    func mySelf() -> Self {
        return self
    }
}

Now a class just need to conform to Animal like this

class Feline: Animal { }
class Cat: Feline { }
class Dog: Animal {}

and automatically gets the method

Feline().mySelf() // Feline
Cat().mySelf() // Cat
Dog().mySelf() // Dog

Update

protocol ReadableInterval { }

class Interval: ReadableInterval { }

protocol ReadableEvent {
    associatedtype IntervalType: ReadableInterval
    func getInterval() -> IntervalType
}

class Event: ReadableEvent {
    typealias IntervalType = Interval
    func getInterval() -> Interval {
        return Interval()
    }
}

Upvotes: 8

Daniel Klöck
Daniel Klöck

Reputation: 21147

protocol Prot1
{
    associatedtype T
    func returnMyself() -> T
}

class MyClass : Prot1
{
    typealias T = MyClass
    func returnMyself() -> T
    {
        return self
    }
}

Upvotes: 3

Related Questions