为什么一个表达式含糊不清而另一个表达式不含糊?

时间:2015-11-19 01:37:11

标签: swift reduce ambiguous

以下代码可以使用

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)

        }

    }

...但编译器认为这是不明确的?

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)

    }

错误报告?

1 个答案:

答案 0 :(得分:1)

  

以下代码可以使用

不,它没有:

:; 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>'
}
^

在这两种情况下,问题是你没有返回任何内容,但你需要返回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
}