SE-0328: Structural opaque result types

I’m struggling to understand what this would enable. An argument of type some P1 is strictly less useful than an argument of (existential) type P1. Values of subtypes can already witness supertypes, so a value of type S can already be passed as an argument of type P1. Therefore there is no reason to ever create a temporary value of an opaque type.

I am pleased to see this proposal come to review. It lifts some restrictions in the use of opaque types and, as such, fits very well with the direction of Swift. As I'm not a Rustacean, I can't say I have extensive experience with the corresponding feature in Rust, but based on my limited understanding I think it compares favorably. I have thought about this topic at some length and studied both the original pitch and this revision.

Looking at this with fresh eyes after some time (and having not re-examined my prior opinions in the pitch phase), I do have some thoughts about the detailed design which may have evolved since prior--

Syntax for optionals

I very much appreciate the rationale behind requiring the parens in spelling (some P)?. Indeed, it is unimpeachable that this is the clearest possible spelling. However, the following points (which I agree with--and I think would be generally agreed upon) give me pause:

...a user's first instinct might be to write some P? . This latter syntax is moderately less verbose, and is, in fact, unambiguous...

...since P? is never a correct constraint, it would be possible to (and in fact this proposal's implementation does) provide a "fix it" to the user which suggests that they change some P? to (some P)?.

True, the fix-it certainly minimizes the burden to users. However, I'd argue that whenever there's a spelling for something that's both intuitive and always unambiguous (a rarity), anything required on top of that surely has to be, by the same token, unnecessary ceremony.

I'm not sold on the argument that some has to bind less tightly than ? just because -> and & do: Swift already goes through contortions for operators such as try for user ergonomics. And indeed, we admit that users' intuition here doesn't require some to bind less tightly.

That said, it is easier to add a special rule than to take one away, so I would be content with leaving the rules as-is for now and circling back to this at a later time if our expectations are proved out that users will widely expect to be able to write some P? without parens.

Higher order functions

This idea of features being easier to add later than to take away leads me to the proposed syntax as it applies here:

Consider the function func f() -> (some P) -> () . The closure value produced by calling f has type (some P) -> () , meaning it takes an opaque result type as an argument. That argument has some concrete type, T , determined by the body of the closure. [Emphasis mine.]

This decision should be considered in the context of generalized some syntax, which we are likely to implement in the future.

I think it's important to spell out that consideration. It took me some time in another conversation (thanks to @ensan-hcl, as I recall) to appreciate the issue here:

The "generalized some syntax" which is mentioned specifically in Future Directions would have (some P) -> () as a shorthand for a generic constraint, equivalent to <T: P>(T) -> ()—that is, the caller of the closure would determine the concrete type.

However, in the case of the closure returned by f discussed above, (some P) -> () actually means (T) -> <T: P>() (to use the "fully generalized reverse generics" syntax also mentioned in Future Directions)—which is to say, the callee (i.e., the closure) determines the concrete type.

There has been some disagreement in that prior conversation about which of these scenarios should be endowed with the spelling of (some P) -> (), but for certain they cannot both be, since they mean very different things. For this reason, if this proposal were to be accepted as written allowing higher order functions declared func f() -> (some P) -> (), it would make the proposal's own future direction impossible due to ambiguity.

I don't think we have to resolve the disagreement here (although I happen to agree with the proposal's future direction). It would suffice to disallow such higher order functions with opaque types, just as the proposal suggests as an alternative, since it is difficult (usually impossible) to actually call the returned closure anyway and it would be of limited use. We could then resolve the question regarding "generalized some syntax" at a later time, and indeed we could still allow the use of higher order functions returning possibly uncallable closures at a later time when "fully generalized reverse generics" are made possible.

This course of action would be consistent with that line of thinking that it is easier to add features later than to remove them, allowing currently unsettled questions to be settled later rather than foreclosing them for the limited purpose of allowing higher order functions to return usually uncallable closures.


Generally +1 except for the same concern that @xwu expressed above, about higher-order functions. I don't usually comment on swift evolution threads but this one jumped out at me when reading the proposal.

"This decision should be considered in the context of generalized some syntax, which we are likely to implement in the future" sounds good to me (that's in "Alternatives considered"), but it seems like that should mean we don't allow (some P) -> () yet, to avoid that later discussion being overly constrained by source breakage.

I see the argument (paraphrased) "we shouldn't prevent stuff just because we think it's mostly useless" from the same section, but I don't see explicitly the counterargument, "perhaps we should prevent this particular stuff to reserve space we know we need for later decision-making." The proposal should certainly make that decision-making visible in "Alternatives considered", and I hope it can be reversed.

  • Is the problem being addressed significant enough to warrant a change to Swift?
  • Does this proposal fit well with the feel and direction of Swift?

Yes, both in itself and as part of the larger effort to broaden and smoothen all the generic-related type features.

  • If you have used other languages or libraries with a similar feature, how do you feel that this proposal compares to those?


  • How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Read carefully

Dropping by to share that I just had someone looking to adopt swift list this as one of the blockers in a design they were trying out and they very really excited to see this pitched :slight_smile:

Read through myself as well and looks great, looking forward to this limitation be lifted!


That is certainly an important point re the usual relative precedence of unary operators.

On the other hand, one could make a persuasive counterargument that this doesn’t have to hold—and shouldn’t—for non-symbolic unary operators:

Obviously, Swift isn’t a natural human language, nor do its operators exactly parallel math operators, but where possible we prefer fluent APIs and operators with behaviors that don’t run counter to their elementary school usages, for readability, intuitiveness, etc.

Therefore, consider, given the following natural language phrase:

How’s it going?

The only natural parsing is “(How’s it going)?” and not “How’s it (going?)”. By the same token, some P? reads naturally as (some P)?, and would not read naturally as some (P?) even if it were supportable. Perhaps we just need to adopt the Spanish punctuation rules: ¡some P! :upside_down_face:

Thank you for the precise summary of previous conversation (here). I appreciate it :bowing_man:

I think we should consider that the addition of T<some P> will increase the number of functions that takes reverse generic argument. For example, consider Array<some Numeric>. Calling append method must require reverse generic argument.

var array: Array<some Numeric> = [0, 1, 2, 3]
// it requires reverse generic argument

With more examples of reverse generic argument, this proposal will strengthen the argument that some P should be used for reverse generic arguments, even if we rule out to use bare some P in argument position.

Again, I don’t think this is the thread to discuss that topic, but for clarity, I’m not sure I understand why this is a “reverse generic argument”:

The underlying element type is fully determined by the type of array, which is passed in as self by the caller.


FWIW, I disagree. The whitespace disparity to me strongly indicates that the ? binds to the P rather than to some P. I suspect I could eventually train myself to read it otherwise, and yes I can reason through why the some (P?) reading is nonsense, but it would introduce a slight cognitive load when parsing that form, and I don't see a great reason why it needs to be allowed simply because we can parse it unambiguously in the compiler.


I don't aim to discuss that, neither.

About the word 'reverse generic argument' is a bit confusing, sorry. I wanted to express 'it behaves as if taking reverse generic argument (or, opaque argument type)'.

I just mentioned that, if the number of reverse generic argument like behaviors increases, people will found it more strange that func foo(value: some P) takes generic argument. I tried to show that forbidding (some P) -> ABC and adopting this proposal isn't 'keeping unsettled' but makes situation changed a bit.

Maybe the simplest example is the next code. No one but the callee determines the argument type.

typealias Closure<T> = (T) -> ()
let closure: Closure<some P> = { ... }
1 Like

I‘m very much +1 on this proposal, as it closes a gap in the current language.

However I want to add something about functions with a signature of (some P) -> (). Maybe I‘m wrong, but the current discussion seems to forget that there are actually already such functions in the current version of Swift (and btw they’re quite awkward to work with, as many simple things don’t work like they normally do).
Consider the following example:

func foo() -> some BinaryInteger { 5 }

let bar = foo() // type of bar is 'some BinaryInteger'

let baz = bar.isMultiple(of:) // type of baz is '(some BinaryInteger) -> Bool

print(baz(7)) // prints '2'

These function types however are not like normal function types. For example we cannot write them in our code (e.g. as a type annotation):

let baz2: (some BinaryInteger) -> Bool = baz
// Error: 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions

But this type clearly exists:

let baz3: (Int) -> Bool = baz
// Error: Cannot convert value of type '(some BinaryInteger) -> Bool' to specified type '(Int) -> Bool'

I think we should sort out relatively quickly, what some P in a parameter position actually means, because it basically already exists but isn't fully usable yet...


Thanks for this insight; it prompted me to realize that the distinction between a type parameter and an opaque type already exists today with regular type parameters, and it has made me more confident in the design choices made in this proposal.

Writing (some P) -> Bool in a type annotation is exactly what the proposal unlocks, and your example compiles with the flag to enable this feature. As you rightly point out, opaque types in structural positions are not really new with this proposal; this proposal merely allows you to spell them in source.

Today, and with this proposal, a value that contains an opaque type some P always means the underlying type has already been inferred using the callee's return value (or an initializer expression in the case of stored properties and local variables). You don't know what that underlying type is, and you can only interact with the type through the interface promised by the protocol constraint (hence the terminology opaque).

Allowing the use of some P in the types of parameter declarations to mean an implicit type parameter conforming to the protocol that gets substituted by the caller doesn't muddle that rule; it only changes where the type parameter is opened and substituted. It is still the case that when you have a value whose type contains some P, that is an opaque type that already has an underlying type. When you reference or call a function whose signature contains some P in parameter position, some P is a type parameter that is immediately substituted with the underlying type (which could be inferred from an argument provided to a call, a contextual type for a function reference, etc).

The rules here are exactly the same as explicit type parameters, e.g. <T>. When you have a value whose type contains T, that type has an underlying type that is opaque to you. You may have seen this type referred to on the forums or in the compiler codebase as an "archetype", but it's the same concept as an opaque type. It is only in the interface of a generic type or function that T means a type parameter. In expressions, T is always an opaque type/archetype.


I'm positive to the feature and how it has been proposed in its entirety.

+1 to the spelling (some P)?. Users should be able to naively replace T? with its unsugared counterpart Optional<T> without incurring in non functioning code. some P? wouldn't be able to be replaced with some Optional<P>.

+1 to having (some P) -> A to always follow the "type gets chosen by the callee" rule, even if it implies the existence of almost non-callable functions.

Isn't the quoted sentence in direct disagreement with the rule? Why would opaque parameter types be substituted by the caller, resulting in having (some P) -> A to be equivalent to <T: P>(T) -> A? Did I misunderstand?

1 Like

Parameter declaration is the key phrase. I specifically meant this (which, to be clear, is just a future direction):

protocol P {}
struct S: P {}

func generic(value: some P) { ... } // equivalent to `generic<T: P>(value: T)`

generic(value: S()) // implicit type parameter `some P` is substituted with `S`

Whenever you have an expression that contains some P as a parameter type, e.g. (some P) -> Void the type parameter has already been substituted somewhere else.

1 Like

It may not muddle that specific formulation of the rule, but it's also the case that the behavior today, and even moreso under SE-0328, satisfies the rule:

If some P appears anywhere in a declaration, the underlying type for that opaque type is chosen by the author of the declaration.

This formulation of the rule would be violated if some P came to mean a caller-provided type parameter.

IMO, it would be highly confusing for some P in parameter position to mean two different things. If we think we would (or might) want some P to signify an implicit caller-side type parameter, then I think we should disallow some P in parameter position as part of SE-0328. If we're not ready to decide that question, then I agree with @xwu that we should simply disallow it for now and revisit once we are ready to discuss that issue in a targeted manner.


Yes, I agree with this assessment.

It's really important to make a distinction between "parameter position" in a function declaration vs function type. This proposal doesn't allow opaque types in parameter declarations, so that's fine, we can debate that later :slightly_smiling_face: If we explicitly disallow function types having opaque types in parameter position, that's a source breaking change that I don't think we should make as part of this proposal (it's possible for such a type to be inferred today as @Zollerboy1 demonstrates above, but spelling out this type in source is currently an error)

1 Like

This is my feeling as well.

However, if I am given a new rule that is as simple to understand as if some P appears anywhere in a declaration, the underlying type for that opaque type is chosen by the author of the declaration, then I'm willing to upgrade myself.

1 Like

Yeah, I get the distinction you've drawn between parameter declarations and parameter types, but I worry this is too subtle a distinction to introduce into the language model. If I'm understanding correctly it would make:

let f: (some P) -> Int = { ... }


func f(_: some P) -> Int { ... }

behave very differently with regards to generics, which, IMO, would be very undesirable.

Yeah, I'm specifically talking about the "spelling out this type in source" part. Existing situations where some P can sneak into a parameter type are pretty arcane, as evidenced by the many experienced Swift programmers here who didn't even know it was possible, myself included until a couple weeks ago!

Right now, I think it would be very difficult for users to even see this type exposed as some P. Not only would they have to perform the proper incantation to construct such a type, but even when inspecting the type of such a function, the code completion window only displays it as (in the example above) (BinaryInteger) -> Bool. An improper use of the function does result in the error:

Cannot convert value of type 'Int' to expected argument type 'some BinaryInteger'

In any case, I think that allowing users to spell some P in parameter position is a significant step, and one that there are clearly open design questions around. I suppose that the acceptance of this proposal wouldn't formally prevent the caller-side some P for parameter declarations, but I want to make it clear that I consider the current form of SE-0328 and some P as caller-side generic shorthand pretty much mutually exclusive from an ergonomic perspective.

If we accept this proposal I would argue pretty vehemently against a future proposal to imbue some P with caller-side semantics (though I'm open to being convinced that I'm overreacting :slight_smile:)


I think what @Jumhyn is agreeing with—if I may be so bold—is my feedback that we should decline as part of this proposal to make it not an error (as it is currently) to spell opaque types out in parameter position. Not making a change to Swift is, by construction, not source-breaking.

How Swift’s diagnostics currently display an inferred type for users to read can also be workshopped later if necessary, and I wouldn’t call such changes source breaking.


Right—I'm not suggesting that we adopt any source breaking behavior, only that we not be too permissive with the new spellings this proposal will allow, given that there are open questions about how such spellings might interact with potential future proposals.

1 Like

And, for clarity, neither am I in my feedback suggesting that we should disallow the inference of function types that we currently infer; this proposal is about (at least by my read) what and how we spell and my feedback is similarly about only that.

I absolutely agree that there is no reason to disallow the underlying types themselves of these usually uncallable closures—and indeed in my feedback I state explicitly that in the fullness of time we should be able to make them utterable, just perhaps not now and not with this syntax.

Terms of Service

Privacy Policy

Cookie Policy