Swift协议扩展 [英] Swift protocol extension
问题描述
非常感谢文章关于在实例化 UIViewController
或 UIStoryboard
时摆脱使用字符串的问题。
Very much appreciated the article about getting rid of using strings when instantiating UIViewController
or UIStoryboard
.
尽管有一点我想改变行为。
我没有在此处使用情节提要枚举类来获取情节提要,而是希望此处的类型符合协议。
Though there is one point where I wanted to change the behavior. Instead of giving a Storyboard enum into the class method for getting a storyboard, I wanted a type here that conforms to a protocol.
extension UIStoryboard {
class func storyboard(storyboard: StoryboardRepresentable, bundle: NSBundle? = nil) -> UIStoryboard {
return UIStoryboard(name: storyboard.storyboardName, bundle: bundle)
}
}
protocol StringRawRepresentable: RawRepresentable {
typealias RawValue = String
var rawValue: String { get }
}
protocol StoryboardRepresentable {
var storyboardName: String { get }
}
extension StoryboardRepresentable where Self: StringRawRepresentable {
var storyboardName: String {
return self.rawValue
}
}
enum SomeOtherEnum: String, StoryboardRepresentable {
case BlaMain
case BlaSub
case BlaSomeThing
var storyboardName: String { return self.rawValue }
}
有了这个(假设您有一些使用此实现的有趣模块),模型本身可以具有符合StoryboardRepresentable的新枚举类型,而不是具有集中式枚举有关所有正在使用的情节提要,从而产生依赖性。
With that (given you have several moduls interesting in using this implementation) the models themselves could have new enum types conforming to StoryboardRepresentable instead of having a centralized enum with knowledge about all storyboards in use and thus creating a dependency.
这是我的问题。尽管我已经在扩展中实现了storyboardName,但是当我在SomeOtherEnum上删除storyboardName时,却遇到了编译器错误,抱怨不符合协议!?
And here is my problem. Though I have implemented the storyboardName in the extension, I got a compiler error complaining about non-protocol conformance when I remove the storyboardName on SomeOtherEnum!?
推荐答案
extension UIStoryboard {
class func storyboard(storyboard: StoryboardRepresentable, bundle: NSBundle? = nil) -> UIStoryboard {
return UIStoryboard(name: storyboard.storyboardName, bundle: bundle)
}
}
protocol StoryboardRepresentable {
var storyboardName: String { get }
}
extension StoryboardRepresentable where Self: RawRepresentable, Self.RawValue == String {
var storyboardName: String {
return self.rawValue
}
}
enum SomeOtherEnum: String, StoryboardRepresentable {
case BlaMain
case BlaSub
case BlaSomeThing
}
StoryboardRepresentable
现在可以应用于任何 String
,但不要键入 Int
。
StoryboardRepresentable
can now be applied to any enum of type String
but not to type Int
.
这篇关于Swift协议扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!