如何获取 CIFilter 的显示名称?

How to get the displayname of a CIFilter?

我正在尝试获取 CIFilters 的显示名称列表。已找到 this site,它具有应该给出名称的常量(以及其他信息),但下面的代码不起作用。

控制台输出:

here 01
here 02
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<CIAccordionFoldTransition 0x7a672dc0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key CIAttributeFilterName.'

我的代码:

func getCIFilterName(filterName: String) -> String{
    var res = "abc"

    let fltr = CIFilter(name:filterName)
    println("here 01")
    if contains(fltr.attributes().keys, kCIAttributeFilterDisplayName){
        println("here 02")
        res = fltr.valueForKey(kCIAttributeFilterDisplayName) as String
    }
    println("here 03")

    return res
}

attributes方法returns字典。这样做要简单得多:

func getCIFilterName(filterName: String) -> String {
    var res = "abc"
    let fltr = CIFilter(name:filterName)
    if let disp = fltr.attributes()[kCIAttributeFilterDisplayName] as? String {
        res = disp
    }
    return res
}

但我不喜欢你在我们失败时返回错误值的把戏 "abc"。这就是 Optionals 的作用——让我们远离这种 "magic values" 。所以像这样重写:

func getCIFilterName(filterName: String) -> String! {
    var res : String! = nil
    let fltr = CIFilter(name:filterName)
    if let disp = fltr.attributes()[kCIAttributeFilterDisplayName] as? String {
        res = disp
    }
    return res
}

但是,不要忘记检查返回值是否为 nil,否则如果您尝试将它用于任何事情(如果它 nil),您将会崩溃。