I have UICollectionView with cells: Image, Text, or Image+Text.
class ParentCell: UICollectionViewCell {
class ImageCell: ParentCell {
class TextCell: ImageCell { }
}
class TextCell: ParentCell { }
}
func createTextCellId(classPrefix: ParentCell.Type) -> String {
return String(reflecting: classPrefix.TextCell)
}
Why Swift erases nested type?
// CORRECT: ParentCell.TextCell
createTextCellId(classPrefix: ParentCell.self)
// INCORRECT: ParentCell.TextCell
createTextCellId(classPrefix: ParentCell.ImageCell.self)
Another functions do not work:
func createTextCellId<ParentCellType: ParentCell>(classPrefix: ParentCellType.Type) -> String {
return String(reflecting: classPrefix.TextCell)
}
That's not how Swift works.
classPrefix.TextCell
in your code will always mean theTextCell
declared inParentCell
, not the one inImageCell
.To do this kind of dynamically resolution of types, you would need a protocol:
Then you can do:
Then your design could be:
Note that
ParentCell
cannot conform toTextCellProviding
. Otherwise the same problem happens again - i.e.ParentCell
decides whatTextCell
should be, for all its subclasses, and its subclasses can't change that.Example:
Also consider whether you actually need
ParentCell
. If all the common functionalities can be (and makes sense to be) implemented with extensions onTextCellProviding
, consider doing that instead.