allenlinli
allenlinli

Reputation: 2154

How to append custom object to an array in Swift?

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?

Upvotes: 1

Views: 2761

Answers (1)

Code Different
Code Different

Reputation: 93161

append does not return anything. Remove the assignment:

photoVCs = photoVCs.append(vc) // wrong
photoVCs.append(vc)            // ok

Upvotes: 7

Related Questions