[swift-evolution] Proposal: for loops with return values

Jim Dovey jimdovey at apple.com
Tue Jan 19 12:19:03 CST 2016


> On Jan 19, 2016, at 7:08 AM, Craig Cruden via swift-evolution <swift-evolution at swift.org> wrote:
> 
> i.e. the Swift way of doing things that comes to mind (equivalent) would be:
> 
> let host: String? = “host”
> let port: Int? = “80”
> 
> let inetAddress = InetSocketAddress?
> if let host = host, port = port {
>   inetAddress = InetSocketAddress(host, port)
> }
> else {
>   inetAddress = nil
> }
> 
> Just wondering if there was a cleaner way - because to me that just looks ugly.

You can always wrap it in a (nicely inline-able) function for cleanliness:

func makeAddr(host: String?, port: Int?) -> InetSocketAddress? {
	guard let h = host, p = port else { return nil }
	return InetSocketAddress(host: h, port: p)
}

// … somewhere else …
let host: String? = getHost()
let port: Int? = getPort()

guard let inetAddress = makeAddr(host, port) else { throw SocketError(EADDR) }

Cheers,
-Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160119/a4d1f682/attachment.html>


More information about the swift-evolution mailing list