使Swift数组符合协议

Ben*_*ard 9 arrays protocols ios swift

假设某些项目可以出现在a中Feed,只要它们实现Feedable协议定义的必要属性即可.我们还要说这个Photo对象是值得的:

extension Photo: Feedable { }
Run Code Online (Sandbox Code Playgroud)

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

extension [Photo] : Feedable
Run Code Online (Sandbox Code Playgroud)

或者我是否总是需要某种包装对象,例如a PhotoAlbum,以符合Feedable

编辑

为了重新迭代,我很好奇我是否只能制作Photo对象数组Feedable.不制作Array任何内容类型Feedable,而不是制作一个Feedables本身的数组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
Run Code Online (Sandbox Code Playgroud)

也许这个要点(当然没有编译)更明确地表明了意图.

Vit*_*nko 10

您可以通过以下方式实现您的目标:

斯威夫特 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() {    
    }
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ael -5

我没有在操场上尝试过,但也许你可以简单地制作一个 Feedable 数组:

var myPhotosArray = [Feedable]()
Run Code Online (Sandbox Code Playgroud)

然后,所有实现 Feedable 协议的内容都将被允许出现在数组中。如果您只需要一个照片数组,您仍然可以对 Photo 对象进行子类化以创建 FeedablePhoto 对象。

在 Playground 中尝试一下,而不是在没有测试的情况下就投反对票。严重的是 3 票反对,没有任何理由和解释......

import UIKit

protocol Tree: class {
  func grow()
}

class BigTree: Tree {
  internal func grow() {
    print("Big tree growing")
  }
}

class SmallTree: Tree {
  internal func grow() {
    print("Small tree growing")
  }
}

class Car {
  //not a tree
}

var manyTrees = [Tree]()

manyTrees.append(BigTree())
manyTrees.append(SmallTree())
manyTrees.append(Car()) //This makes an error "Car doesn't conform to expected type 'Tree'"
Run Code Online (Sandbox Code Playgroud)