Search code examples
swiftreduceambiguous

Why is one expression ambiguous and the other not?


The following code works

let evens = [1,2,2,3,4,5,6,6,7].reduce(Set<Int>()) { (var set: Set<Int>, int: Int) -> Set<Int> in

        if (true) {

        set.insert(int)

        }

    }

...but the compiler thinks this is ambiguous?

let evens = [1,2,2,3,4,5,6,6,7].reduce(Set<Int>()) { (var set: Set<Int>, int: Int) -> Set<Int> in

        set.insert(int)

    }

Bug report?


Solution

  • The following code works

    No, it doesn't:

    :; swift
    "crashlog" and "save_crashlog" command installed, use the "--help" option for detailed help
    "malloc_info", "ptr_refs", "cstr_refs", and "objc_refs" commands have been installed, use the "--help" options on these commands for detailed help.
    Welcome to Apple Swift version 2.1 (700.1.101.6 700.1.76). Type :help for assistance.
      1> let evens = [1,2,2,3,4,5,6,6,7].reduce(Set<Int>()) { (var set: Set<Int>, int: Int) -> Set<Int> in 
      2.  
      3.         if (true) { 
      4.  
      5.         set.insert(int) 
      6.  
      7.         } 
      8.  
      9. }   
    evens: Set<Int> = {}
    repl.swift:9:1: error: missing return in a closure expected to return 'Set<Int>'
    }
    ^
    

    In both cases, the problem is that you haven't returned anything, but you need to return something of type Set<Int>:

    let evens = [1,2,2,3,4,5,6,6,7].reduce(Set<Int>()) { (var set: Set<Int>, int: Int) -> Set<Int> in
        if (true) {
            set.insert(int)
        }
        return set
    }
    

     

    let evens = [1,2,2,3,4,5,6,6,7].reduce(Set<Int>()) { (var set: Set<Int>, int: Int) -> Set<Int> in
        set.insert(int)
        return set
    }