【问题标题】:Swift extension on RawRepresentable has no accessible initializerRawRepresentable 上的 Swift 扩展没有可访问的初始化程序
【发布时间】:2016-03-02 07:28:55
【问题描述】:

我正在尝试为我的 FieldIdentifiable 协议创建一个扩展,仅当实现它的枚举具有 Int 的 RawValue。唯一的问题是return FieldIdItem(rawValue: newValue) 行一直显示此错误:

'Self.FieldIdItem' cannot be constructed because it has no accessible initializers

这是一个 Swift 错误还是我遗漏了什么?

enum SignUpField: Int, FieldIdentifiable {
  case Email = 0, Password, Username

  typealias FieldIdItem = SignUpField
}

protocol FieldIdentifiable {
  typealias FieldIdItem

  func next() -> FieldIdItem?
  func previous() -> FieldIdItem?
}

extension FieldIdentifiable where Self: RawRepresentable, Self.RawValue == Int {

  func next() -> FieldIdItem? {
    let newValue: Int = self.rawValue+1
    return FieldIdItem(rawValue: newValue)
  }

  func previous() -> FieldIdItem? {
    return FieldIdItem(rawValue: self.rawValue-1)
  }
}

【问题讨论】:

    标签: swift generics enums swift-extensions swift-protocols


    【解决方案1】:

    extension FieldIdentifiable where Self: RawRepresentable, Self.RawValue == Int { ... }
    

    Self 的关联类型 FieldIdItem 不是(必然) RawRepresentable,这就是为什么

    FieldIdItem(rawValue: newValue)
    

    不编译。你可以通过添加额外的约束来解决这个问题:

    extension FieldIdentifiable where Self: RawRepresentable, Self.RawValue == Int,
    Self.FieldIdItem : RawRepresentable, Self.FieldIdItem.RawValue == Int { ... }
    

    但是,如果 next()previous() 方法实际上应该 返回相同类型的实例,那么你就不需要 完全关联类型,并且可以在协议中使用Self作为返回类型:

    enum SignUpField: Int, FieldIdentifiable {
        case Email = 0, Password, Username
    }
    
    protocol FieldIdentifiable {
    
        func next() -> Self?
        func previous() -> Self?
    }
    
    extension FieldIdentifiable where Self: RawRepresentable, Self.RawValue == Int {
    
        func next() -> Self? {
            return Self(rawValue: self.rawValue + 1)
        }
    
        func previous() -> Self? {
            return Self(rawValue: self.rawValue - 1)
        }
    }
    

    还要注意约束

    Self.RawValue == Int
    

    可以稍微放松一下

    Self.RawValue : IntegerType
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      相关资源
      最近更新 更多