通用RawRepresentable协议属性

时间:2017-03-30 17:17:59

标签: ios swift struct enums protocols

我希望写一个protocol,它将与各种测量结构一起使用。这些结构中的每一个都有自己的单位枚举,用于定义用于比较的单位类型:

public enum TestUnits: Double {
  case foo = 100.0
  case var = 1000.0
}

所有枚举都是Double类型并符合RawRepresentable。我正在寻找一种方法来创建一个通用协议属性,每个Struct可以设置自己的单位枚举进行比较和格式化:

protocol UnitMeasuable {

   var measurementType : SOMETHING<RawRepresentable> { get} 

   func someFormattingFunc(type: measurementType) -> String
}

我只是不清楚如何声明measurementType以便它将由单个结构设置。

由于

1 个答案:

答案 0 :(得分:0)

在这种情况下,我会有两个选择。

#在协议上使用associatedtype

    #include <iostream>
    using namespace std;

    int elapsed_time(int entry_time, int exit_time)
    {
    int total = 0;
    total = (exit_time / 100) * 60 + (exit_time % 100) - (entry_time / 100) * 60
            + (entry_time % 100);
    return total;
    } // returns elapsed time in total minutes

    double parking_charge(int total_minutes)
    {
      int charge;

      if (total_minutes <= 30)
        charge = 0;

      else if (120 > total_minutes < 30)
        charge = (3 + (0.05 * total_minutes));

      else
        charge = (8 + (0.10 * total_minutes));

    } // returns parking charge
    void print_results(double charge)
    {
       cout << "The charge of parking was: " << charge;
    }

    int main()
    {  
      double charge,minutes;
        int entry_time,exit_time;   
      cout << "What was the entry time? (Enter in 24 hour time with no colon) ";
      cin >> entry_time;

      cout << "What was the exit time? (Enter in 24 hour time with no colon) ";
      cin >> exit_time;

     minutes=elapsed_time(entry_time,exit_time);

     charge=parking_charge(minutes);  

     print_results( charge);

    }

或忘记变量(我认为没有理由你应该拥有该属性,但我真的不知道你的计划是什么)并在函数中使用泛型。

 protocol UnitMeasuable {
 associatedtype Something where Something: RawRepresentable

   var measurementType: Something { get} 
   func someFormattingFunc(type: Something) -> String
}

希望这有帮助!