[swift-evolution] Add an implicit return nil if function reaches end before return explicitly called

Logan Sease lsease at gmail.com
Wed Jun 22 14:44:59 CDT 2016


I believe Swift should no longer require an explicit return on all functions and instead do an implicit nil return if the function reaches the end of its control flow and has an optional return type.

This could be useful to keep code clean and compact, by only having to write code for cases that our function handles and just returning nil otherwise automatically.


Consider:

func toInt(string : String?) -> Int?
{
	if let s = string
	{
		return s.intValue
	}

	//Make this return implicitly happen instead of requiring it.
	//return nil 
}



This also very much goes along with the implicit return within a guard statement that I have seen proposed. Here:

func toInt(string: String?) -> Int?
{
	guard let s = string else {
		 //this could be implicitly returned using the same logic, since the guard means we have reached the end of our code path without returning
		//return nil 
	}
	return s.toInt()
}


These methods could be re-written as so:

This could allow us to write the examples below much cleaner
func toInt(string : String?) -> Int?
{
	if let s = string
	{
		return s.toInt()
	}
}

func toInt(string: String?) -> Int?
{
	guard let s = string else {} 
	return s.toInt()
}

// it would be even cooler if we could omit the else {} and make them not it return by default. But that’s another thing all together
func toInt(string: String?) -> Int?
{
	guard let s = string
	return s.toInt()
}


Thanks for reading my first post to the Swift open source discussion board!
-Logan




More information about the swift-evolution mailing list