[swift-evolution] [pre-proposal] Automatic unwrapper boolean properties using unless keyword

Charles Srstka cocoadev at charlessoft.com
Thu Mar 31 17:04:36 CDT 2016


What I often do is use ?? to provide a default (usually false).

if myList?.isEmpty ?? false {
    print(“Empty”)
} else {
    print(“Not empty”)
}

The other thing you can do, of course, is to use a ‘where’ statement:

if let list = myList where list.isEmpty {
    print(“Empty”)
} else {
    print(“Not empty”)
}

Charles

> On Mar 31, 2016, at 4:54 PM, Guilherme Torres Castro via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello,
> 
> This is a Idea I got from Objetive-C, where nil is evaluate no false, this feature can keep the code clean. For example:
> 
> if (![myList isEmpty]) { ... }
> Will evaluate true or false even if myList is nil.
> I know that Swift is not Design to work like Objetive-C, but sometimes this make the code cleaner.  
> 
> Example:
> if !myList?.isEmpty { print("Ok") }
> This is much more cleaner and easy to read than:
> 
> if !(myList != nill && mylist!.isEmpty) { print("Ok") }
> Moreover the tip from the Xcode (when you type the  lead user to generate wrong code when you type this code :
> 
> if !((myList?.isEmpty)) != nil { print("Ok") }
> As you can see the suggestion made by the Xcode will not work, because event if the list is empty the expression will return true.
> 
> My ideia is to use some special syntax that permit optional to be evaluate to boolean expression. Those syntax may be like in ruby <http://www.tutorialspoint.com/ruby/ruby_if_else.htm>. 
> 
> 
> code if condition
> So the code from the example will be:
> 
> print ("Ok") if !myList?.isEmpty
> Or using the unless keyword:
> 
> unless myList?.isEmpty print("not empty") else print "empty"
> 
> I didn't spent much time thinking about the syntax keyword, because I want to know first if you will consider a great addition to the language, if so, we can work on details and a formal proposal.
> 
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160331/fe7b8cd5/attachment.html>


More information about the swift-evolution mailing list