首页 > 解决方案 > 无法使用“String”类型的参数为“[NSAttributedString.Key: Any]”类型的值下标

问题描述

我正在为 iOS 13 / Swift 5 更新我的应用程序并遇到此错误。我不是 100% 确定如何解决它。有任何想法吗?

@objc override open var tintColor: UIColor? {
    didSet {

        #if swift(>=4.2)
        var textAttributes = [NSAttributedString.Key : Any]()
        let foregroundColorKey = NSAttributedString.Key.foregroundColor
        #elseif swift(>=4)
        var textAttributes = [NSAttributedStringKey : Any]()
        let foregroundColorKey = NSAttributedStringKey.foregroundColor
        #else
        var textAttributes = [String:Any]()
        let foregroundColorKey = NSForegroundColorAttributeName
        #endif

        textAttributes[foregroundColorKey] = tintColor

        #if swift(>=4)

            if let attributes = convertFromOptionalNSAttributedStringKeyDictionary(titleTextAttributes(for: .normal)) {

                for (key, value) in attributes {
                    #if swift(>=4.2)
                    textAttributes[key] = value
                    #else
                    textAttributes[NSAttributedStringKey.init(key)] = value
                    #endif
                }
            }

        #else

            if let attributes = titleTextAttributes(for: .normal) {
                textAttributes = attributes
            }
        #endif

        setTitleTextAttributes(textAttributes, for: .normal)
    }
}

它抛出的错误是这样的:

Cannot subscript a value of type '[NSAttributedString.Key : Any]' with an argument of type 'String'

在此处输入图像描述

标签: iosswiftxcodeswift5

解决方案


当您textAttributes在 Swift 4.2 版本中下标时,请检查您使用key的类型是String. 您想在下标之前初始化NSAttributedString.Keyusing 。所以而不是:keytextAttributes

textAttributes[key] = value

你想做:

textAttributes[NSAttributedString.Key(key)] = value

推荐阅读