Swift - Enum的相关值或扩展

时间:2015-04-28 09:48:42

标签: swift enums associated-object associated-types computed-values

关于swift enum的一般问题。

我想创建一个“icon”的枚举,并将一个值“关联”到enum case

enum Icon {
  case plane
  case arrow
  case logo
  case flag
}

我想为枚举值创建一个关联的图像。 还有与枚举值相关联的颜色

因此,例如,如果可以做类似的事情:

extension Icon.plane {
  var image = {
    get {
       return UIImage("plane.png")
    }
  }
  var color = {
    get {
       return UIColor.greenColor()
    }
  }
}


var image = Icon.arrow.image // the image associated to the enum
var color = Icon.arrow.color // the color associated to the enum

这类事可能吗?

4 个答案:

答案 0 :(得分:28)

不幸的是,您无法根据枚举情况定义静态属性,但您可以使用计算属性和enum Icon { case plane case arrow case logo case flag var image: UIImage { switch self { case .plane: return UIImage(named: "plane.png")! case .arrow: return UIImage(named: "arrow.png")! case .logo: return UIImage(named: "logo.png")! case .flag: return UIImage(named: "flag.png")! } } var color: UIColor { switch self { case .plane: return UIColor.greenColor() case .arrow: return UIColor.greenColor() case .logo: return UIColor.greenColor() case .flag: return UIColor.greenColor() } } } // usage Icon.plane.color 为每种情况返回值:

$(".tweet-content").bind("keydown", function(){
    var tweetlength = $(".tweet-content").html().length;
    $(".char-count").html(126-tweetlength);
});

答案 1 :(得分:6)

使用带有关联值的枚举结合switch语句,您可以非常灵活。第一个例子:

enum Icon {
    case plane(img:UIImage, col:UIColor)
    case arrow(img:UIImage, col:UIColor)
    case logo(img:UIImage, col:UIColor)
    case flag(img:UIImage, col:UIColor)

    var values:(img:UIImage,col:UIColor) {
        switch self {
        case let .plane(image, color):
            return (image,color)
        case let .arrow(image, color):
            return (image,color)
        case let .logo(image, color):
            return (image,color)
        case let .flag(image, color):
            return (image,color)
        }
    }
}



var a = Icon.plane(img: UIImage(named: "image.png")!, col: UIColor.blueColor())

a.values.col
a.values.img

和第二个例子:

enum Icon {
    case plane(img:UIImage, col:UIColor)
    case arrow(img:UIImage, col:UIColor)
    case logo(img:UIImage, col:UIColor)
    case flag(img:UIImage, col:UIColor)

    var img:UIImage {
        switch self {
        case let .plane(image, color):
            return image
        case let .arrow(image, color):
            return image
        case let .logo(image, color):
            return image
        case let .flag(image, color):
            return image
        }
    }

    var col:UIColor {
        switch self {
        case let .plane(image, color):
            return color
        case let .arrow(image, color):
            return color
        case let .logo(image, color):
            return color
        case let .flag(image, color):
            return color
        }
    }
}



var a = Icon.plane(img: UIImage(named: "image.png")!, col: UIColor.blueColor())

a.col
a.img

无需扩展。如果你真的想要静态值,你可以这样做:

struct MyIcon {
    static let plane = Icon.plane(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
    static let arrow = Icon.arrow(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
    static let logo = Icon.logo(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
    static let flag = Icon.flag(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
}

MyIcon.arrow.col

可能比将固定的文字值放在switch语句中更整洁。

答案 2 :(得分:2)

更清晰易读

enum Icon {
    case plane
    case arrow
    case logo
    case flag

    var image: UIImage {
        return value.image
    }

    var color: UIColor {
        return value.color
    }

    private var value: (image: UIImage, color: UIColor) {
        switch self {
        case .plane: return (UIImage(named: "plane.png")!, UIColor.green)
        case .arrow: return (UIImage(named: "arrow.png")!, UIColor.green)
        case .logo: return (UIImage(named: "logo.png")!, UIColor.green)
        case .flag: return (UIImage(named: "flag.png")!, UIColor.green)
        }
    }
}

// Use
Icon.plane.image
Icon.plane.color

答案 3 :(得分:1)

更短更安全的代码:

public static void fileWrite (String [] [] finalArray, String fileName) throws IOException {
/*
* Purpose: To create a new file and write the data. 
* Parameters: String array,  file name
* Return: Null
* */

try {
  //Writing Declerations
  FileWriter fw = new FileWriter(fileName, true);
  BufferedWriter bw = new BufferedWriter(fw);
  PrintWriter pw = new PrintWriter(bw);

  //Header in file
  ArrayList <String> arrHeading = new ArrayList<String>(1);
  arrHeading.add("Location"); arrHeading.add("Collect Date");
  arrHeading.add("Month");

  //Header, adds all the different parameters, by checking if there is a new parameter, then adding it to the array list
  for (int i = 0; i<finalArray.length; i++){
    int counter = 0; 
    for (int k = 0; k < arrHeading.size(); k++){
      if (finalArray[i][3] != arrHeading.get(k)){ // If the parameter exists
       counter += 1;
      }
      if (finalArray[i][3] == arrHeading.get(k)){ // If the parameter does not exist
       counter -= 1;
      }
    }
    if (counter == arrHeading.size()){ // Add a new heading
      arrHeading.add(finalArray[i][3]);
    }
  }

   // Prints heading into file
  for (int i = 0; i < arrHeading.size(); i++){
    pw.print(arrHeading.get(i) + ",");
  }

  // Printing data
  //How many days/locations are there
  ArrayList <String> arrDate = new ArrayList<String>(0);
  ArrayList <String> arrLocation = new ArrayList<String>(0);
  ArrayList <String> arrMonth = new ArrayList<String>(0);
  for (int i = 0; i <finalArray.length; i++){
    int counter = 0;
    for (int k = 0; k < arrDate.size(); k++){
      if (finalArray[i][1] != arrDate.get(k).toString()){
        counter +=1;
      }
    }
    if (counter == arrDate.size()){
      arrLocation.add(finalArray[i][0]);
      arrDate.add(finalArray[i][1]);
      arrMonth.add(finalArray[i][2]);
      System.out.println(finalArray[i][1]);
    }
  }

  //Create the cleaned version of the array
  String [] [] arrClean = new String [arrDate.size()] [arrHeading.size()];

  //Places dates,months,locations into the clean array
  for (int i = 0; i < arrDate.size(); i++){
    arrClean[i][0] = arrLocation.get(i).toString() ;
    arrClean[i][1] = arrDate.get(i).toString() ; 
    arrClean[i][2] = arrMonth.get(i).toString() ;
  }

  //Checks for position of parmname and places values
  for (int i = 0; i < arrClean.length; i++){
    for (int j = 0; j < arrHeading.size(); i++){
      //First check which date the values must fall under;
      if (finalArray[i][1] == arrClean[i][1]){
        System.out.println("got here");
        if (finalArray[i][3] == arrHeading.get(j).toString()){
          arrClean[i][j] = finalArray[i][4];
          System.out.println("got here!");
        }
      }
    }
  }
  pw.write(arrClean[1][4]);

  //Close
  pw.flush(); 
  pw.close(); 

  System.out.println("Record Saved");
}
catch (Exception E){
   System.out.println( "Record not Saved. Check that the file is closed.");
}  

}