Search code examples
swiftargumentsnsattributedstring

How to pass parameter of AnyObject... to function which parameter need AnyObject


I'am using function of

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

arguments: AnyObject...

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

Update:

When I use code bellow:

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

It will give error:

Use of unresolved identifier 'NSAttributedString(attributes:format:_:)'

Update:(Temp Solution)

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

Solution

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

    The full call becomes unsafeBitCast(NSAttributedString.init(attributes:format:_:), to: Function.self)

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

    Playgrounds screenshot