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?
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.
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.
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.
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.
Self
into your protocolprotocol Prot1 {
func returnMyself() -> Prot1
}
protocol Animal {
func mySelf() -> Self
}
class Feline: Animal {
func mySelf() -> Self {
return self
}
}
class Cat: Feline { }
Feline().mySelf() // Feline
Cat().mySelf() // Cat
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
protocol ReadableInterval { }
class Interval: ReadableInterval { }
protocol ReadableEvent {
associatedtype IntervalType: ReadableInterval
func getInterval() -> IntervalType
}
class Event: ReadableEvent {
typealias IntervalType = Interval
func getInterval() -> Interval {
return Interval()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With