UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 13 - Using Opaque return type instead of `Self` with extension

Forums > 100 Days of SwiftUI

The square() Function in the extension below uses the Self keyword to allow having different return type that conforms to the same Numeric protocol.

extension Numeric {
    func squared() -> Self {
        self * self
    }
}

So, if we are looking to return different types that conforms to the same Numeric protocol, why we don't use Opaque return type instead like this?``

extension Numeric {
  func square() -> some Numeric {
    return self * self
  }
}

PS: I experimented in Xcode and the code works fine with opaque return type also.

2      

You could do it that way, but what would be the point? Opaque return types are used to hide the return type from the caller because the specific return type ultimately doesn't matter at the call site.

But here you know what type squared is returning because you call it on a specific variable. You are always returning the same type it was called on. If you call squared on a Double, you'll get a Double back; if you call it on an Int, you'll get an Int back; etc.

The square() Function in the extension below uses the Self keyword to allow having different return type that conforms to the same Numeric protocol.

No, it returns the same type it was called on, not a different type. If squared is called on a Double, then Self is Double; if it's called on an Int, then Self is Int, etc. Using Self indicates "I'm returning the same type that the method was called on", whereas some Numeric indicates "I'm returning some kind of thing that conforms to Numeric, but you don't need to know exactly what it is". It just so happens that in this specific case some Numeric ends up being the same as Self, which is why it works.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.