ios - Swift:类型必须实现协议(protocol)并且是给定类的子类

标签 ios objective-c inheritance swift protocols

<分区>

在 Objective-C 中,您可以将类型定义为属于给定类并实现协议(protocol):

- (UIView <Protocol> *)someMethod;

这表明 someMethod 返回的值是一个实现给定协议(protocol) ProtocolUIView。有没有办法在 Swift 中执行类似的操作?

最佳答案

你可以这样做:

protocol SomeProtocol {
  func someMethodInSomeProtocol()
}

class SomeType { }

class SomeOtherType: SomeType, SomeProtocol {
  func someMethodInSomeProtocol() { }
}

class SomeOtherOtherType: SomeType, SomeProtocol {
  func someMethodInSomeProtocol() { }
}

func someMethod<T: SomeType where T: SomeProtocol>(condition: Bool) -> T {
  var someVar : T
  if (condition) {
    someVar = SomeOtherType() as T
  }
  else {
    someVar = SomeOtherOtherType() as T
  }

  someVar.someMethodInSomeProtocol()
  return someVar as T
}

这定义了一个函数,该函数返回类型为“SomeType”和协议(protocol)为“SomeProtocol”的对象,并返回符合这些条件的对象。

关于ios - Swift:类型必须实现协议(protocol)并且是给定类的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25825988/

相关文章:

python 类的子类或实例

ios - Swift 3 Xcode 8 中的 FileManager 和 urlsForDirectory 错误

ios - 全局 HTTP 代理内部如何工作?

ios - Xcode 返回链接器错误 "library not found for -lFirebaseAuth"

ios - 我如何在 Objective-C 中模拟这个 curl 语句?

objective-c - OCUnit应用程序测试: Trying to test UIPageControl numberOfPages == NSArray count

ios - Swift:动态填充 numberOfSectionsInTableView 和 numberOfRowsInSection

objective-c - 如何将 NSString 转换为 C 字符串?

c++ - 确保派生类构造函数必须调用特定的基类方法

c++ - 如何创建抽象类成员?