3

I want to achieve this

if let large = imageLinks.large {

    if !large.isEmpty {

        result = large
    }
}

in a single if statement, something like this (this does not compiles)

if let large = imageLinks.large where !large.isEmpty {

    result = large       
}

Is it possible?

emenegro
  • 6,901
  • 10
  • 45
  • 68

3 Answers3

6

It 's not yet possible. With the actual Version of swift the if let statement is pretty poor.

But with Swift 1.2 (it will be available in Xcode 6.3). You will be able to do this:

(SWIFT 1.2)

if let large = imageLinks.large where !large.isEmpty {

    result = large       
}

But now you cannot. You can do something like:

if  imageLinks.large != nil && !imageLinks.large!.isEmpty {
   result = large!;
}

Note: Swift use "Lazy Evaluation" If the first part imageLinks.large != nil is false it will not Evaluate the second part, so it will not crash.

But I don't found this solution beautiful (too much force unwrapping).

LastMove
  • 2,482
  • 1
  • 15
  • 25
6

In swift 4.4, generics to the rescue \o/

public extension Optional where Wrapped == String {
    var isEmptyOrNil: Bool { (self ?? "").isEmpty }
}

usage

if nameField.text.isEmptyOrNil {
    //doSomething...
}
Jakub Truhlář
  • 20,070
  • 9
  • 74
  • 84
sachadso
  • 848
  • 9
  • 10
1

In Swift 1.1

If you don't like force unwrapping, you can:

if let large = imageLinks.large?.isEmpty == false ? imageLinks.large : nil {
    result = large
}

It's not so beautiful anyway :(

rintaro
  • 51,423
  • 14
  • 131
  • 139