ios - 使 Swift 数组符合协议(protocol)

标签 ios arrays swift protocols

假设某些项目可以出现在 Feed 中,只要它们实现了 Feedable 协议(protocol)定义的必要属性。我们还假设 Photo 对象是 feed-worthy:

extension Photo: Feedable { }

是否可以说这些照片的 Array 也可能是 Feedable

extension [Photo] : Feedable

或者我是否总是需要某种包装对象(例如 PhotoAlbum)来符合 Feedable

编辑

重申一下,我很好奇是否可以只制作 Photo 对象数组 Feedable。不制作任何内容类型 FeedableArray,不制作 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/

相关文章:

ios - 限制版本 iOS - 没有最低版本

ios - NSInvalidArgumentException,原因 : 'Storyboard doesn' t contain a view controller with identifier 'SomeController'

php - mysql WHERE IN数组字符串/用户名

ios - MDCTextInputController 错误消息覆盖输入的文本

arrays - 如果检测到特定字符串,如何删除多个数组中的索引

php - 重新排列数组索引 Eloquent Laravel

php - HTTPS POST 工作成功,但变量为空

swift - 无法将类型 'Generic<String>' 的值转换为预期的参数类型 'Generic<Any>'

ios - PDF 到 Apple 报亭

ios - 在 Sprite 工具包中将文本写成一个圆圈(swift)