Ios Swift:类型必须实现协议,并且是给定类的子类

Ios Swift:类型必须实现协议,并且是给定类的子类,ios,objective-c,inheritance,swift,protocols,Ios,Objective C,Inheritance,Swift,Protocols,在Objective-C中,可以将类型定义为给定类的类型并实现协议: - (UIView <Protocol> *)someMethod; -(UIView*)方法; 这说明someMethod返回的值是实现给定协议的UIView。有没有办法在Swift中执行类似的操作?您可以这样做: protocol SomeProtocol { func someMethodInSomeProtocol() } class SomeType { } class SomeOtherTy

在Objective-C中,可以将类型定义为给定类的类型并实现协议:

- (UIView <Protocol> *)someMethod;
-(UIView*)方法;

这说明
someMethod
返回的值是实现给定协议的
UIView
。有没有办法在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
}
protocol-SomeProtocol{
func someMethodInSomeProtocol()
}
类SomeType{}
类SomeOtherType:SomeType,SomeProtocol{
func someMethodInSomeProtocol(){}
}
类SomeOtherType:SomeType,SomeProtocol{
func someMethodInSomeProtocol(){}
}
func somethod(条件:Bool)->T{
变量someVar:T
如果(条件){
someVar=SomeOtherType()作为T
}
否则{
someVar=someOtherType()作为T
}
someVar.someMethodInSomeProtocol()
将someVar返回为T
}

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

此处类似的问题:此处也类似,谢谢。在这种情况下,在某种方法中,如果我这样做:
var v:T;v=MyView()
,我收到一个错误“MyView不能转换为T”,即使MyView是一个
类MyView:UILabel,Protocol
。如果在返回的末尾添加“as T”,它也可以工作。我会更新答案的。谢谢,这样更好。在实现该方法时,我仍然存在以下问题:
func-someMethod()->T{var-someVar:T-someVar.someMethodInSomeProtocol()您的协议实际定义了'someMethodInSomeProtocol()吗“?如果我在协议中有这个定义并在类中实现,那么我就不会得到你的错误。是的,它得到了。但是在我的例子中,someVar的类型是t
func-someMethod(条件:Bool)->t{var-someVar:t如果(条件){someVar=SomeOtherType()作为t}else{someVar=SomeOtherType()as T}someVar.someMethodInSomeProtocol()返回someVar as T}