Reputation: 988
I'm working with a collection view, and I'm trying to make a array of tuples, containing the reuse identifier, the cell's type, and the function to call to set up the cell in tableView(_:cellForItemAt:)
.
So far so good, except for the function. Xcode complains in the array's declaration that it
"Cannot convert value of type '(AddASpotInfoVC) -> (UICollectionViewCell) -> UICollectionViewCell' to expected element type '(UICollectionViewCell) -> UICollectionViewCell'
AddASpotInfoVC
is the view controller's class. Here's the array's initialization itself:
typealias cellFunc = (_ aCell: UICollectionViewCell) -> UICollectionViewCell
let reuseIdentifiers: [(String, UICollectionViewCell.Type, cellFunc)] = [
("AddASpotInfoPicCell", AddASpotInfoPicCell.self, picCellFunc),
("AddASpotInfoNameCell", AddASpotInfoNameCell.self, nameCellFunc),
("AddASpotInfoDescCell", AddASpotInfoDescCell.self, descCellFunc),
("AddASpotInfoTagsCell", AddASpotInfoTagsCell.self, tagCellFunc)]
And all the functions in the array (for now) are in an extension of the view controllers' class (not that it should be relevant, I think...) and look like this
func picCellFunc(aCell: UICollectionViewCell) -> UICollectionViewCell {
return aCell
}
So, what am I doing wrong in my array's initialization?
Upvotes: 1
Views: 493
Reputation: 2361
If your functions are not using any state, it does make sense to make them class or static methods like Adamsor suggests.
But if you do want your methods to read/write any variables in your viewController instance, you can use a lazy var for the tuple array, and reference the methods using self, like this:
lazy var reuseIdentifiers: [(String, UICollectionViewCell.Type, cellFunc)] = [
("AddASpotInfoPicCell", AddASpotInfoPicCell.self, self.picCellFunc),
("AddASpotInfoNameCell", AddASpotInfoNameCell.self, self.nameCellFunc),
("AddASpotInfoDescCell", AddASpotInfoDescCell.self, self.descCellFunc),
("AddASpotInfoTagsCell", AddASpotInfoTagsCell.self, self.tagCellFunc)]
Upvotes: 1
Reputation: 770
Function implementation can depend on other variables. So it requires you to declare functions as static. Use:
static func picCellFunc (aCell: UICollectionViewCell) -> UICollectionViewCell
Inside your array use:
AddASpotInfoVC.picCellFunc
Edit: You can also move array initialisation code into one of your functions or initialisers.
Upvotes: 2