是否可以指定类型参数符合Swift中原始约束的泛型类型的值?

时间:2018-02-14 01:34:58

标签: swift generics types

最近,我在Swift中遇到了以下问题。

编辑:这是一个更具体的例子。我们正在努力提供挑战服务,向用户提出一系列随机挑战。

protocol PreferencesProtocol: Codable {
    var backgroundColorHex: String? { get set };
    init();
}
class Preferences: PreferencesProtocol {
  var backgroundColorHex: String?;
  required init() {
    instantSuccessFeedback = true;
    backgroundColorHex = "#FFFFFF";
  }
}
class ExerciseDescription<PreferencesType: Preferences>: ExerciseDescriptionProtocol {
  static var preferencesType: PreferencesType.Type {
    return PreferencesType.self;
  }

  class var internalName: String {
    get{
      fatalError("\(String(describing: type(of: self)))Exercise must have a unique internal name");
    }
  }
  // Will be overridden
  class func getViewController(initialPreferences: PreferencesType) -> ExerciseViewController<PreferencesType> {
    return ExerciseViewController<PreferencesType>(initialPreferences: initialPreferences);
  }

  private init() {}
}

我们有一些练习与偏好和描述匹配

class MatchingPreferences: Preferences {
  var cardCount: Int = 5;
}

class MatchingDescription: ExerciseDescription<MatchingPreferences> {
  typealias PreferenceType = MatchingPreferences;
  override class func getViewController(initialPreferences: MatchingPreferences) -> ExerciseViewController<MatchingPreferences> {
    return MatchingViewController(initialPreferences: initialPreferences);
  }
  override class var internalName: String{
    return "matching";
  }
}

我们希望将即将到来的练习存储在调度程序服务中:

struct FakeScheduleService {
  static var currentExerciseDescriptions: [ExerciseDescription<Preferences>.Type] {
    return [MatchingDescription.self]
  }
  static var nextExerciseDescription: ExerciseDescription<Preferences>.Type {
    return MatchingDescription.self;
  }

  static var rewardDuration: Int {
    return 200;
  }
}

我们的想法是能够从JSON对象创建这些首选项对象,然后按计划启动练习,同时不强制练习强制转换他们的首选项。

0 个答案:

没有答案