I've taken this over to Swift Users from Swift Evolution.
I think you'd want to handle the exceptional case first, as it provides an
opportunity for early exit before processing normal behavior. In such case,
consider using a guard rather than an if:
guard !names.isEmpty else { print("No names"; return }
for name in names { ... }
Flipping the two tests allows you to use an existing if-else without changing
the language, although there's really nothing that the `else` is adding here:
if names.isEmpty { ... }
else for name in names { ... }
-- E
> On Feb 1, 2017, at 10:31 AM, Saagar Jha via swift-evolution
> <[email protected]> wrote:
>
> If you’re fine with a couple extra characters, you can use .isEmpty:
>
> for name in names {
> // do your thing
> }
> if names.isEmpty {
> // do whatever
> }
>
> It’s a bit more typing, but I feel it makes your intentions more clear.
>
> Saagar Jha
>
>> On Feb 1, 2017, at 8:48 AM, Chris Davis via swift-evolution
>> <[email protected] <mailto:[email protected]>> wrote:
>>
>> Hi,
>>
>> Often when I’m programming I stumble upon this scenario:
>>
>> I have a list of items that may or may not be empty - if it’s full, I do one
>> thing, if it’s empty I do something else, my code looks like this:
>>
>> class Example_1
>> {
>> let names = ["Chris", "John", "Jordan"]
>>
>> /// Loop over names, if no names, print no names
>> func run()
>> {
>> for name in names
>> {
>> print(name)
>> }
>>
>> if names.count == 0
>> {
>> print("no names")
>> }
>> }
>> }
>>
>> let exampleOne = Example_1()
>> exampleOne.run()
>>
>> However, Personally, I would find it more pleasing to write something like
>> this:
>>
>> class Example_2_Proposed
>> {
>> let names:[String] = []
>>
>> /// Loop over names, if no names, print no names
>> func run()
>> {
>> for name in names
>> {
>> print(name)
>> } else {
>> print("no names")
>> }
>> }
>> }
>>
>> let exampleTwo = Example_2_Proposed()
>> exampleTwo.run()
>>
>> The difference here is a “for-else” type syntax where if there were no items
>> in the array it would simply fall through to the else statement.
>>
>> What would be the pros/cons of introducing such syntax?
>>
>> Is there’s a way of doing something similar in swift already?
>>
>> Thanks
>>
>> Chris
>>
>>
>>
>>
>> _______________________________________________
>> swift-evolution mailing list
>> [email protected] <mailto:[email protected]>
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> _______________________________________________
> swift-evolution mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-evolution
_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users