Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 578
4bottiglie Avatar asked Jun 14 '16 15:06

4bottiglie


People also ask

What is protocol conformance in Swift?

Any type that satisfies the requirements of a protocol is said to conform to that protocol. In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

Can a protocol inherit from a class Swift?

In Swift, protocols can inherit from one or more additional protocols. Let's see how and why to use it. Here we have a User protocol, this protocol will be getting bigger each time we add a new User requirement into it.

What is difference between protocol and class Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

Are protocols value types in Swift?

Swift only has a total of six types: These consist of the four Named types or Nominal types: protocol: Value type (but can be reference types) struct: Value type. enum: Value type.


1 Answers

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()
    }
}
like image 175
Luca Angeletti Avatar answered Nov 02 '22 14:11

Luca Angeletti