Search code examples
swiftlet

Is there any particular resource that demonstrates which values can be inferred in Swift?


For instance:

let myConstant = 4

The value of the constant above can be inferred

How do we know if a value can be inferred or not?


Solution

  • Generally, the type of x can be inferred if the type of value that expression will evaluate can be known:

    let x = <expression>
    

    In your example, 4, an integer literal, is evaluated to be an Int, so myConstant's type is inferred to be Int.

    Another example:

    func f() -> String { return "Foo" }
    let x = f()
    

    The type of x can be inferred because we know the type that f will return by looking at its declaration, a String.

    For more complicated expressions, this still holds true. The compiler will look at the types that each subexpression evaluates to and do an analysis to figure out what type the expression will evaluate to eventually.

    However, sometimes this cannot be done:

    func f<T>() -> T? { return nil }
    let x = f()
    

    f can return any type but you haven't specified any. T is not known so the return type of f is not known, so x's type cannot be inferred.