本文介绍了如何传递AnyObject的参数...以功能哪个参数需要AnyObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

NSAttributedString(attributes: [String : AnyObject]?, format: String, arguments: AnyObject...)

我想自定义一个常规函数以在上面调用此函数.所以我需要发送参数

And I want to customize an general function to call this function above. So I need to send parameter

但是此参数在我的自定义函数中将变为[AnyObject].如何解决?

But this parameter will become [AnyObject] in my customize function. How to fix it?

更新:

当我使用以下代码时:

typealias Function = ([String : AnyObject]?, String, [AnyObject]) -> NSAttributedString
let myAttributedString = unsafeBitCast(NSAttributedString(attributes:format:_:) , Function.self)

它将给出错误:

更新:(临时解决方案)

我得到了一个临时解决方案,虽然很难看,但对我来说已经足够了.

I get an temp solution which is ugly but works just enough for me.

// NOTE: here arguments may be String or NSAttributedString
private func getAttributedString(withFormat format: String, _ arguments: AnyObject..., withUnderLine: Bool = false) -> NSAttributedString {
    var attributes = [NSFontAttributeName: #someFont,
                     NSForegroundColorAttributeName: #someColor]
     if withUnderLine {
          attributes[NSStrikethroughStyleAttributeName] = NSUnderlineStyle.StyleSingle.rawValue
     }

     switch arguments.count {
         case 0:
             return NSAttributedString(attributes: attributes, format: format)
         case 1:
             return NSAttributedString(attributes: attributes, format: format, arguments[0])
         case 2:
             return NSAttributedString(attributes: attributes, format: format, arguments[0], arguments[1])
         case 3:
             return NSAttributedString(attributes: attributes, format: format, arguments[0], arguments[1], arguments[2])
         case 4:
             return NSAttributedString(attributes: attributes, format: format, arguments[0], arguments[1], arguments[2], arguments[3])
         default:
             assert(arguments.count <= 4)
             return NSAttributedString(attributes: attributes, format: format, arguments[0], arguments[1], arguments[2], arguments[3])
         }
     }

推荐答案

如果要引用初始化程序,则应使用NSAttributedString.init(attributes:format:_:)

If you are referencing the initializer, you should use NSAttributedString.init(attributes:format:_:)

完整呼叫变为unsafeBitCast(NSAttributedString.init(attributes:format:_:), to: Function.self)

我刚刚在iPad上的Swift Playgrounds中尝试过类似的操作:

I've just tried something similar in Swift Playgrounds on iPad:

这篇关于如何传递AnyObject的参数...以功能哪个参数需要AnyObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:38