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

James Froggatt james.froggatt at me.com
Wed Jun 22 15:36:07 CDT 2016


Welcome, Logan.

Functions currently return the empty tuple, ‘()’, by default. Void is a typealias to the empty tuple type. It is also possible to write ‘return ()’ explicitly, rather than just ‘return’. (This is generally a detail of the language, so may be unfamiliar)

It is unclear in your proposal as it stands which (if any) a function returning ‘()?’ would use as its default: (), or nil?
Would the ‘nil’ keyword still be required when writing return explicitly?

While this does match behaviour present in other parts of the language, and I see the benefit of having implicit returns in this otherwise straightforward case, I'm struggling to decide as to whether this is worth the extra complexity of having two orthogonal implicit return mechanisms.

------------ Begin Message ------------ 
Group: gmane.comp.lang.swift.evolution 
MsgID: <4AC6F31E-9E46-47B3-8CAE-B5EDD04043D5 at gmail.com> 

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


_______________________________________________
swift-evolution mailing list
swift-evolution at swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


------------- End Message ------------- 



From James F


More information about the swift-evolution mailing list