Allen Lin Allen Lin - 6 months ago 8
Swift Question

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?

Answer

append does not return anything. Remove the assignment:

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