如何在数组中获取枚举的索引

时间:2017-05-29 10:15:33

标签: swift enums

我需要更新存储在Enum中的Array的关联值。如何在不知道其索引的情况下访问正确案例的单元格?

enum MessageCell {
    case from(String)
    case to(String)
    case subject(String)
    case body(String)
}

var cells = [MessageCell.from(""), MessageCell.to(""), MessageCell.subject(""), MessageCell.body("")]

let recipient = "John"

// Hardcoded element position, avoid this
cells[1] = .to(recipient)

// How to find the index of .to case
if let index = cells.index(where: ({ ... }) {
    cells[index] = .to(recipient)
}

4 个答案:

答案 0 :(得分:5)

使用if case来测试闭包中的enum个案.to,如果找到则返回true,否则返回false

if let index = cells.index(where: { if case .to = $0 { return true }; return false }) {
    cells[index] = .to(recipient)
}

这是一个完整的例子:

enum MessageCell {
    case from(String)
    case to(String)
    case subject(String)
    case body(String)
}

var cells: [MessageCell] = [.from(""), .to(""), .subject(""), .body("")]

if let index = cells.index(where: { if case .to = $0 { return true }; return false }) {
    print(".to found at index \(index)")
}

输出:

.to found at index 1

答案 1 :(得分:3)

作为使用index(where:)的替代方法,您可以使用与for循环的模式匹配,以便迭代与给定大小写匹配的元素的索引,然后只需{{1}在第一场比赛中:

break

答案 2 :(得分:1)

以下是如何解决此问题的简化演示,以便您了解其工作原理:

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("activity result","coming" + String.valueOf(requestCode)+ contentFileUri);
//        View popupView = getActivity().getLayoutInflater().inflate(R.layout.popup_add_snag, null);
//        LinearLayout attachLayout = (LinearLayout)popupView.findViewById(R.id.attachLayout);
//        ImageView photoImageicon = (ImageView)popupView.findViewById(R.id.imageicon);

        try{
//            if (resultCode == Constants.RESULT_OK){
                if(contentFileUri !=null) {
                    Log.d("fileuri", contentFileUri.toString());
                    String attachmentType = "IMAGE";
//                        mAdapter.attachmentType=attachmentType;
                    photoImageIcon.setVisibility(View.VISIBLE);
                    // attachLayout.setVisibility(View.INVISIBLE);
                    Toast.makeText(getActivity().getApplicationContext(), R.string.successfull_image, Toast.LENGTH_SHORT).show();
                    Log.d("fileuri", contentFileUri.toString());

                    InputStream inputStream =   getContext().getContentResolver().openInputStream(contentFileUri);

在你的情况下:

var arr = ["a", "b"] // a, b
if let index = arr.index(where: { $0 == "a" }) {
    arr[index] = "c"
}
print(arr) // c, b

答案 3 :(得分:0)

试试这个:

if let index = cells.index(where: { (messageCell) -> Bool in
            switch messageCell
            {
            case .to(let x):
                return x == recipient ? true : false
            default:
                return false
            }
        })
        {
            cells[index] = .to(recipient)
        }