【问题标题】:Why Cant I return Void directly in a function为什么我不能在函数中直接返回 Void
【发布时间】:2016-04-10 02:42:21
【问题描述】:

在test1()中,可以返回test()成功返回的Void。但是在 test2() 中,会抛出错误。为什么?

//: Playground - noun: a place where people can play

import UIKit
import AVFoundation

func test()->Void{
    print("Hello")
}

func test1(){//print Hello
    return test()
}

func test2(){// throw error
    return Void
}

【问题讨论】:

    标签: swift function return void


    【解决方案1】:

    Void 是一种类型,因此无法返回。相反,您希望返回 Void 的表示,它是一个空元组。

    因此,试试这个,它会编译:

    func test()->Void{
        print("Hello")
    }
    
    func test1(){//print Hello
        return test()
    }
    
    func test2()->Void{// throw error
        return ()
    }
    
    test1()
    

    有关为何在预期返回 Void 类型的函数中可以返回空元组的更多信息,请在以下链接中搜索 void:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

    【讨论】:

      【解决方案2】:

      在 test1() 中,您没有返回 Void,您的返回是返回 void 本身的函数 test();

      void function test(){
          print("Hello");
      }
      
      void function test1(){
             //print Hello
          return test();
      }
      
      /* you can not return a type
           func test2(){// throw error
                return Void; 
           } */
      
      void function test2(){
              //code or not
            return test(); //calling test function returns void.
      }
      

      我希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-09
        • 2017-08-31
        • 2012-07-01
        • 2016-12-20
        • 1970-01-01
        相关资源
        最近更新 更多