如何使用枚举(在结构中定义)作为字典的键?

时间:2016-11-25 12:29:13

标签: swift

我有以下代码:

struct TestStruct2 {
    let field1: String
    let field2: Int

    enum TestEnum2 {
        case Value1
        case Value2
    }

}

    let dic2 = Dictionary<TestStruct2.TestEnum2, TestStruct2>()
    let dic3 = [TestStruct2.TestEnum2 : TestStruct2]()

dic2成功运作。

但是dic3会返回编译错误:

 (Type of expression is ambiguous without more context)

我不明白为什么。任何想法?

1 个答案:

答案 0 :(得分:1)

正如@Hamish在评论中提到的,这是一个编译器错误。您已经展示了一种使用长格式的解决方法:

typealias

第二种解决方法是为嵌套类型创建typealias TestStruct2Enum2 = TestStruct2.TestEnum2 let dic3 = [TestStruct2Enum2 : TestStruct2]()

typealias

第三种解决方法是创建整个字典的typealias Test2Dict = [TestStruct2.TestEnum2 : TestStruct2] let dic4 = Test2Dict()

[:]

第四种解决方法是明确指定类型并使用let dic5: [TestStruct2.TestEnum2 : TestStruct2] = [:] 字面值初始化字典:

let dic6 = [:] as [TestStruct2.TestEnum2 : TestStruct2]

最后的解决方法是将文字转换为类型:

function my_custom_theme_style(){

    $bodyColor = get_option('boon_body_color');
    $paragraphColor = get_option('boon_paragraph_color');

    return 'body{
    color: ' . $bodyColor . ' !important;
    }
    p{
    color: ' . $paragraphColor . ' !important;
    }';
}

function add_custom_style(){
    echo '<style type="text/css">';
    echo my_custom_theme_style();
    echo '</style>';
}

add_action('wp_enqueue_scripts', 'add_custom_style');
相关问题