无法在Swift中创建符合协议的数组

前端之家收集整理的这篇文章主要介绍了无法在Swift中创建符合协议的数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下协议和符合它的类:
  1. protocol Foo{
  2. typealias BazType
  3.  
  4. func bar(x:BazType) ->BazType
  5. }
  6.  
  7.  
  8. class Thing: Foo {
  9. func bar(x: Int) -> Int {
  10. return x.successor()
  11. }
  12. }

当我尝试创建一个foos的数组时,我得到一个奇怪的错误

  1. var foos: Array<Foo> = [Thing()]

Protocol Foo can only be used as a generic constraint because it has
Self or associated type requirements.

好的,所以它只能被使用,如果它有一个关联的类型要求(它做),但由于某些原因这是一个错误? WTF?

我不知道我完全明白编译器试图告诉我什么

假设我们可以把一个Thing的例子放在数组foos中,会发生什么?
  1. protocol Foo {
  2. typealias BazType
  3.  
  4. func bar(x:BazType) -> BazType
  5. }
  6.  
  7. class Thing: Foo {
  8. func bar(x: Int) -> Int {
  9. return x.successor()
  10. }
  11. }
  12.  
  13. class AnotherThing: Foo {
  14. func bar(x: String) -> String {
  15. return x
  16. }
  17. }
  18.  
  19. var foos: [Foo] = [Thing()]

因为AnotherThing也符合Foo,所以我们也可以把它放在foos中.

  1. foos.append(AnotherThing())

现在我们从foos中随机抓取一个foo.

  1. let foo = foos[Int(arc4random_uniform(UInt32(foos.count - 1)))]

我要调用方法栏,你能告诉我,我应该发送一个字符串或一个整数到bar吗?

foo.bar(“foo”)或foo.bar(1)

斯威夫特不能.

所以它只能用作一般的约束.

什么场景需要这样的协议?

例:

  1. class MyClass<T: Foo> {
  2. let fooThing: T?
  3.  
  4. init(fooThing: T? = nil) {
  5. self.fooThing = fooThing
  6. }
  7.  
  8. func myMethod() {
  9. let thing = fooThing as? Thing // ok
  10. thing?.bar(1) // fine
  11.  
  12. let anotherThing = fooThing as? AnotherThing // no problem
  13. anotherThing?.bar("foo") // you can do it
  14.  
  15. // but you can't downcast it to types which doesn't conform to Foo
  16. let string = fooThing as? String // this is an error
  17. }
  18. }

猜你在找的Swift相关文章