Skip to content

[SR-1789] Swift can't infer types in generic methods that reuse part of the struct/class' parameters #44398

@swift-ci

Description

@swift-ci
Previous ID SR-1789
Radar None
Original Reporter robotlolita (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug, LanguageFeatureRequest, TypeChecker
Assignee None
Priority Medium

md5: 0101359cc12f70fff9f02db7121d39ee

is duplicated by:

relates to:

Issue Description:

The following code fails because Swift can't infer the types:

struct Product<A, B> { 
    let left: A 
    let right: B 
     
    func map<C>(f: (A) -> C) -> Product<C, B> { 
        return Product(left: f(left), right: right) 
    } 
}

Running this results in the following type error:

error: repl.swift:6:23: error: '(left: C, right: B)' is not convertible to '(left: A, right: B)'
        return Product(left: f(left), right: right)
                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

What I Expected

Given that the return value for the generic type says Product<C, B>, that's what I would have expected Swift to infer the type as, in which case the code should type check. But instead Swift is inferring it as Product<A, B>.

A different❓ type inference error occurs when you have a tuple for the values there instead of the values in separated fields. In this case, Swift infers the tuple to be (_, _).

struct Product<A, B> { 
    let values: (A, B)
     
    func map<C>(f: (A) -> C) -> Product<C, B> { 
        let (a, b) = values
        return Product(values: (f(a), b))
    } 
} 
error: repl.swift:6:32: error: cannot convert value of type '(C, B)' to expected argument type '(_, _)'
        return Product(values: (f(a), b))
                               ^~~~~~~~~

In both cases I expected the code to type check correctly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    TypeResolverbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfexpressionsFeature: expressionsgenericsFeature: generic declarations and typesswift 6.0swift evolution proposal neededFlag → feature: A feature that warrants a Swift evolution proposaltype checkerArea → compiler: Semantic analysistype inferenceFeature: type inferenceunexpected errorBug: Unexpected error

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions