Reputation: 540
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
Reputation: 59536
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()
}
}
Upvotes: 8
Reputation: 21147
protocol Prot1
{
associatedtype T
func returnMyself() -> T
}
class MyClass : Prot1
{
typealias T = MyClass
func returnMyself() -> T
{
return self
}
}
Upvotes: 3