Search code examples
swiftstringfunctionreturntuples

Why does Swift accept code that should return a tuple, but instead returns a string?


In the following code, I would expect Xcode not to accept because I'm using a string as the return value in the body of the code instead of a tuple. But for some reason, Xcode doesn't return an error. Why is that?

func test(name: String) -> (String) {
    return name
}

Solution

  • There's special treatment for tuples of 0 or 1 element. As far as the type system is concerned:

    • () is equivalent to Void()
    • (T) is equivalent to T