如何将控制器转换为特定协议而不是 Swift 中的 class?
How to cast controller to a specific protocol instead of a class in Swift?
这是我的 protocol
:
protocol DBViewAnimationTransitioning {
var viewForAnimation: UIView? { get set }
}
内部用法示例prepareForSegue:
:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let controller = segue.destinationViewController as? DBViewAnimationTransitioning {
controller.viewForAnimation = sender as? UIView //cannot assign to to viewForAnimation in controller
}
}
投射到特定控制器时一切正常f.e。 DBFindViewController
。但我需要将其转换为特定的 protocol
而不是 class
。如何实现?
You can only check for protocol conformance (which includes is
, as
, and as?
) with an @objc protocol
.
所以解决方法很简单:
@objc protocol DBViewAnimationTransitioning {
var viewForAnimation: UIView? { get set }
}
或:
protocol DBViewAnimationTransitioning: class {
var viewForAnimation: UIView? { get set }
}
因为该协议不是专门针对 class/struct 的,所以它不能分配某些东西,因为它可能是一个结构,因为它被复制了所以没有意义。尝试通过将其声明为 protocol DBViewAnimationTransitioning : class
使其成为 class 协议
这是我的 protocol
:
protocol DBViewAnimationTransitioning {
var viewForAnimation: UIView? { get set }
}
内部用法示例prepareForSegue:
:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let controller = segue.destinationViewController as? DBViewAnimationTransitioning {
controller.viewForAnimation = sender as? UIView //cannot assign to to viewForAnimation in controller
}
}
投射到特定控制器时一切正常f.e。 DBFindViewController
。但我需要将其转换为特定的 protocol
而不是 class
。如何实现?
You can only check for protocol conformance (which includes
is
,as
, andas?
) with an@objc protocol
.
所以解决方法很简单:
@objc protocol DBViewAnimationTransitioning {
var viewForAnimation: UIView? { get set }
}
或:
protocol DBViewAnimationTransitioning: class {
var viewForAnimation: UIView? { get set }
}
因为该协议不是专门针对 class/struct 的,所以它不能分配某些东西,因为它可能是一个结构,因为它被复制了所以没有意义。尝试通过将其声明为 protocol DBViewAnimationTransitioning : class