4bottiglie 4bottiglie - 5 months ago 10
Swift Question

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?

Answer

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()
    }
}
Comments