nayem
nayem

Reputation: 7605

Early return from a function which has a return type of [String] in Swift 3

I have a function which returns an Array of String if some conditions are met. But I want to have the early return functionality in my function. Something like this:

func fetchPerson() -> [String] {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return nil
    }
    .......
    .......
}

But I'm facing issues like:

Nil is incompatible with return type '[String]'

I tried writing only return statement. But it fails too. What to do?

Edit: 1

What if I just want to return back from this function without any value. Just back to the line where the call to this function happened. Something like:

func fetchPerson() -> [String] {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return //return to the line where function call was made
    }
    .......
    .......
}

Upvotes: 0

Views: 617

Answers (1)

Nirav D
Nirav D

Reputation: 72460

You can solved this error two ways.

  • Either change return type to [String]? from [String] means make return type optional.

    func fetchPerson() -> [String]? {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return nil
        }
        .......
        .......
    }
    
  • Either Change return statement to return [] from return nil means return empty array.

    func fetchPerson() -> [String] {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return []
        }
        .......
        .......
    }
    

Upvotes: 1

Related Questions