Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Cant I return Void directly in a function

In test1(), it can return Void which returned by test() successfully. But in test2(), error throws. Why?

//: 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
}
like image 602
LK Yeung Avatar asked Jan 06 '16 04:01

LK Yeung


2 Answers

Void is a type, so it cannot be returned. Instead you want to return the representation of Void, which is an empty tuple.

Therefore, try this instead, and this will compile:

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

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

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

test1()

For more information about why an empty tupple can be returned in a function that expects to return Void type, search for void in the following link: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

like image 87
Jorge Torres Avatar answered Oct 01 '22 02:10

Jorge Torres


In test1() you are not returning Void, your return is the function test() that returns void itself;

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.
}

I hope this would help!

like image 31
Jessica Avatar answered Oct 01 '22 04:10

Jessica