【问题标题】:Why is one expression ambiguous and the other not?为什么一种表达模棱两可,而另一种则不然?
【发布时间】:2016-02-20 23:57:05
【问题描述】:

以下代码有效

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)

    }

错误报告?

【问题讨论】:

    标签: swift reduce ambiguous


    【解决方案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&lt;Int&gt; 类型的东西:

    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
    }
    

    【讨论】:

    • 对不起,我所说的“作品”是指我没有得到那个模棱两可的错误。不敢相信我忘了回来...谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2019-05-17
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多