【发布时间】: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])
}
}
【问题讨论】:
-
我知道如何用 Int 来做,但不知道如何用 AnyObject 来做
-
哦,bugs.swift.org/browse/SR-128的状态不是最新的吗?你是怎么用 Int 做的?
-
CC-Dog 的回答:stackoverflow.com/a/27731101/1530581
-
谢谢。您为什么不使用该解决方案或发布您尝试时遇到的错误?
标签: swift arguments nsattributedstring