[swift-evolution] [Idea] Use optionals for non-optional parameters
Justin Jia
justin.jia.developer at gmail.com
Wed Aug 17 12:55:33 CDT 2016
> On Aug 17, 2016, at 11:59 PM, Tino Heth <2th at gmx.de> wrote:
>
>
>> Let’s discuss something else. Actually there is an easy fix: make all functions accept optionals. I think this is a really bad idea
> Indeed.
> I don't think there is a good motivation to change the status quo:
> You can't "sugar away" everything; sometimes, you just have to write a line of code that does what you want.
> As you can "if let" convert as many optionals as you like in a single statement, it really doesn't hurt that much.
>
> The precondition stuff looks exactly like guard inside the function to me… what's the benefit of that?
It won't change the original function. It's like adding a new function. It won't affect the original function. For example: if view is non optional then the function won't throw.
func addSubview(_ view: UIView?) throw
func addSubview(_ view: UIView)
It's only a very rough idea. But this is not limited to checking nil. *Maybe* in the future we can achieve something like this:
----
func randomInt() -> Int { }
precondition count > 0 else { return nil }
func getCellSize(forItemsInRow count: Int) -> CGSize { }
let numberOfCells = randomInt()
let cellSize = getCellSize(forItemsInRow: numberOfCells) // cellSize is optional, since numberOfCells can be smaller or equal to zero
let cellSize = getCellSize(forItemInRow: 4) // cellSize is non optional, since 4 > 0
----
Even this:
----
func randomPositiveInt() -> Int { }
postcondition > 0 else { fatalError() }
precondition count > 0 else { return nil }
func getCellSize(forItemsInRow count: Int) -> CGSize { }
let numberOfCells = randomPositiveInt()
let cellSize = collectionView.getCellSize(forItemsInRow: numberOfCells) // cellSize is non-optional, since numberOfCells is always positive
----
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160818/7a64a4fa/attachment.html>
More information about the swift-evolution
mailing list