TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Why can't I use an opaque return type here

Forums > 100 Days of SwiftUI

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

In this code, the return type of our squared function is Self which according to Paul, is basically self's data type. However, why can't I use opaque return type so that Swift would figure out what the return type would be on its own?

Something like this

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

3      

Because it wouldn't know what the type 'self' is - here is an explanation of the difference between 'Self' and 'self'. The 'self' is just the value, and if you don't provide the type it is just a collection of binary digits that could represent or be anything.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.