Swift:用于可选下标的可选链接 [英] Swift: Optional chaining for optional subscripts

查看:83
本文介绍了Swift:用于可选下标的可选链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个let map : [String: String]let key: String?.

最简单的访问map[key]的方式是什么(如果我有key则返回String?,如果没有的话则返回None)?

What is the most concise way to access map[key] (and get back a String? if I had a key and None if I did not)?

推荐答案

let value = key.flatMap { map[$0] }

使用

/// Returns `nil` if `self` is nil, `f(self!)` otherwise.
@warn_unused_result
public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?

struct Optional中的方法.

或者,您可以将其包装到自定义下标方法中

Alternatively, you can wrap that into a custom subscript method

extension Dictionary {
    subscript(optKey : Key?) -> Value? {
        return optKey.flatMap { self[$0] }
    }
}

和简单地写

let value = map[key]

为避免与常规"下标方法混淆,并进行 意图让代码的读者更加清楚,您可以定义 具有外部参数名称的下标方法:

To avoid confusion with the "normal" subscript method, and to make the intention more clear to the reader of your code, you can define the subscript method with an external parameter name:

extension Dictionary {
    subscript(optional optKey : Key?) -> Value? {
        return optKey.flatMap { self[$0] }
    }
}

let value = map[optional: key]

这篇关于Swift:用于可选下标的可选链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆