代码之家  ›  专栏  ›  技术社区  ›  Mark A. Donohoe

能否仅扩展使用字符串作为原始值类型的RawRepresentables?

  •  2
  • Mark A. Donohoe  · 技术社区  · 8 年前

    我正在尝试编写一个扩展,该扩展基于字符串扩展枚举。我知道扩展所有枚举的方法是扩展RawRepresentable,但我希望它仅限于字符串。

    extension RawRepresentable where RawRepresentable.RawValue == String{
    
        func foo(){
    
            let myRawValue:String = self.rawValue
    
        }
    }
    

    那么,如何指定“where”子句来实现这一点呢?

    1 回复  |  直到 8 年前
        1
  •  2
  •   vacawama    8 年前

    仅扩展 RawRepresentable s基于 String s、 the where 子句是 where RawValue == String :

    extension RawRepresentable where RawValue == String {
    
        func foo() {
            let myRawValue:String = self.rawValue
            print(myRawValue)
        }
    }
    
    
    enum Flintstone: String {
        case fred, wilma, pebbles
    }
    
    Flintstone.fred.foo()  // fred