2017-08-02 57 views
0

我正在創建一個小圖書館,用來自某人姓名的首字母創建一個圖像。我有一個類和類FUNC實際工作class func imageWith(name: String?, textColor: UIColor = .white) -> UIImage?我以前從未使用過class func,我通常會用static我想知道是否有可能與class func imageWith(name: [String]?, textColor: UIColor = .white) -> UIImage?在swift中重載'class func'

任何幫助重載函數,將不勝感激。

+0

我期望會工作。你試過了嗎? –

+2

再看一遍,有一件可能令人討厭的事情是,如果您嘗試爲「name」參數傳遞nil,則它會變得模糊不清。你的圖書館的客戶必須通過「零作爲字符串?」或「無[String]?」。也許你可以讓陣列版本不可選?傳遞一個空數組往往和傳遞零一樣好。 –

+0

另一種選擇是使用[variadic parameters](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html),它們允許一個或多個值作爲單個值傳遞論據。缺點是[它們不允許將現有數組作爲參數傳遞](https://stackoverflow.com/a/24024724/1305067),稱爲splatting。 – paulvs

回答

0

你得到的錯誤信息是由於在Swift 3中,Objective-C運行時隱式提供了方法,Objective-C不支持重載。有兩種方法可以解決這個問題:

  1. 升級到Swift 4,它刪除了隱式的@objc推斷。

或:

  • @nonobjc添加到一個或兩個FUNC聲明。
  • 0

    這是一個Objective-C轉換問題。

    Objective-C在調用方法時沒有類的強制類型區分,所以你不能擁有同名的方法。

    斯威夫特在哪裏看到

    class func imageWith(name: String?, textColor: UIColor = .white) -> UIImage?

    class func imageWith(name: [String]?, textColor: UIColor = .white) -> UIImage?

    Objective-C中看到

    +(id)imageWithName: (id) name andTextColor: (id) textColor

    +(id)imageWithName: (id) name andTextColor: (id) textColor

    解決方案:

    所有您實際需要做的事情是修改您的命名,例如.e.g。

    class func imageWith(names: [String]?, textColor: UIColor = .white) -> UIImage?

    這將導致在Objective-C看到

    +(id)imageWithNames: (id) names andTextColor: (id) textColor