return语句报错:无法将[AnyHashable : Any]?转为[UINib.OptionsKey : Any]?
问题解决:类型不匹配导致的转换错误
报错的核心原因是参数类型不匹配:你定义的optionsOrNil参数类型是[AnyHashable : Any]?,但UINib.instantiate(withOwner:options:)方法要求的options参数类型是[UINib.OptionsKey : Any]?,Swift无法自动在这两个字典类型之间做隐式转换。
直接修改代码中的参数类型即可解决问题,修改后的代码如下:
// // Created by Stevoo 10/17/2022 // From: https://github.com/mac-cain13/R.swift.Library // License: MIT License // import Foundation import UIKit public extension NibResourceType { /** Instantiate the nib to get the top-level objects from this nib - parameter ownerOrNil: The owner, if the owner parameter is nil, connections to File's Owner are not permitted. - parameter options: Options are identical to the options specified with -[NSBundle loadNibNamed:owner:options:] - returns: An array containing the top-level objects from the NIB */ public func instantiate(withOwner ownerOrNil: Any?, options optionsOrNil: [UINib.OptionsKey : Any]? = [:]) -> [Any] { return UINib(resource: self).instantiate(withOwner: ownerOrNil, options: optionsOrNil) } }
补充说明
如果你的代码需要兼容旧版本的调用(比如传入[AnyHashable: Any]类型的参数),可以在调用UINib.instantiate时显式转换类型:
return UINib(resource: self).instantiate(withOwner: ownerOrNil, options: optionsOrNil as? [UINib.OptionsKey : Any])
但这种方式不如直接统一参数类型严谨,建议优先使用第一种修改方案。
内容的提问来源于stack exchange,提问作者Stephen Botta
相关产品推荐
相关产品推荐

