假设某些项目可以出现在 Feed
中,只要它们实现了 Feedable
协议(protocol)定义的必要属性。我们还假设 Photo
对象是 feed-worthy:
extension Photo: Feedable { }
是否可以说这些照片的 Array
也可能是 Feedable
?
extension [Photo] : Feedable
或者我是否总是需要某种包装对象(例如 PhotoAlbum
)来符合 Feedable
?
编辑
重申一下,我很好奇是否可以只制作 Photo
对象数组 Feedable
。不制作任何内容类型 Feedable
的 Array
,不制作 Feedable
本身的数组 Feedable
(两者都是如果您需要,我们会在下面提供解决方案)。
换句话说,一个解决方案(我怀疑是否存在)允许我定义一个类型为 Feedable
的变量,结果如下:
var feedable: Feedable
//photo is feedable, so this is fine
feedable = Photo() //ok
//arrays of photos are feedable
let photo1 = Photo()
let photo2 = Photo()
feedable = [photo1, photo2]
//arrays of other things are not
feedable = ["no", "dice"] //nope
//even if the contents of an array are themselves Feedable, that's not sufficient. E.g. Video is Feedable, but Array of Videos is not.
let video1 = Video()
let video2 = Video()
feeble = video1 //fine
feedable = [video1, video2] //nope
也许 this gist (当然不会编译)更清楚地显示了意图。
最佳答案
您可以通过这种方式实现您的目标:
swift 4:
protocol Feedable {
func foo()
}
extension String: Feedable {
func foo() {
}
}
extension Array: Feedable where Element: Feedable {
func foo() {
}
}
// or in more generic way to support Array, Set and other collection types
extension Collection: Feedable where Element: Feedable {
func foo() {
}
}
关于ios - 使 Swift 数组符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323356/