1

How to append custom class object to an array in Swift? Below is my code, but it shows error.

Error:

"Cannot assign value of '()' to type [PhotoVC]"

Code:

var photoVCs = [PhotoVC]()
for index in 0 ..< photos.count {
    if let vc = getPhotoController(index) {
        photoVCs = photoVCs.append(vc)
    }
}

func getPhotoController(index: Int) -> PhotoVC? {
    if index < 0 || index == NSNotFound {
        return nil
    }
    else if index == photos.count {
        return nil
    }

    let PhotoVCID = "PhotoVCID"
    if let storyboard = storyboard,
        pageVC = storyboard.instantiateViewControllerWithIdentifier(PhotoVCID) as? PhotoVC {
        pageVC.photoName = photos[index]
        pageVC.photoIndex = index
        return pageVC
    }
    return nil
}

I should be able to do it, but what's the problem?

1 Answer 1

7

append does not return anything. Remove the assignment:

photoVCs = photoVCs.append(vc) // wrong
photoVCs.append(vc)            // ok
Sign up to request clarification or add additional context in comments.

1 Comment

append inserts the object into the collection. There isn't need to assign the collection again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.