【问题标题】:How to pass parameter of AnyObject... to function which parameter need AnyObject如何将 AnyObject... 的参数传递给需要 AnyObject 的参数
【发布时间】:2017-02-03 03:40:19
【问题描述】:

我正在使用

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

我想自定义一个通用函数来调用上面的这个函数。所以我需要发送参数

参数:AnyObject...

但是这个参数在我的自定义函数中会变成[AnyObject]。如何解决?

更新

当我使用下面的代码时:

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

会报错:

使用未解析的标识符'NSAttributedString(attributes:format:_:)'

更新:(临时解决方案)

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

// 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])
         }  
     }

【问题讨论】:

标签: swift arguments nsattributedstring


【解决方案1】:

如果你引用初始化器,你应该使用NSAttributedString.init(attributes:format:_:)

完整的通话变成unsafeBitCast(NSAttributedString.init(attributes:format:_:), to: Function.self)

我刚刚在 iPad 上的 Swift Playgrounds 中尝试过类似的东西:

【讨论】:

  • 啊哈,太棒了!
  • 你在哪里找到的?我在文档中没有找到任何内容,也许我没有正确的键进行搜索。谢谢。
  • 我依稀记得有一些像[1, 2, 3].map(String.init)这样的例子说明初始化器可以这样引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多