I would not use a String
extension here because the return is of type (String) -> String
which is not the same as type String
and the extension will not allow you to cast its type. I assume you chose an extension to make it globally accessible but there are other options. You can make the function itself global (which I don't find attractive), you can make the function static
within a regular class
or struct
, you can make the struct
static
, you can do the singleton pattern, you can store the function in the app delegate and call it there--you have a list of options to make properties and methods "global".
Because all that this method does is take a String
and convert it into a modified String
, no need for singleton, and so I would most likely create a global class with static properties.
class Globals {
static func iconName(_ identifier: String) -> String {
return "slickDaddy"
}
}
let icon = Globals.iconName("myIconName")
var iconSize = icon.size(withAttributes: [NSAttributedStringKey.backgroundColor: UIColor.blue])
print(iconSize) // prints (58.01953125, 13.8)
You can call this method from anywhere in the app. Certainly consider all of the other iterations I mentioned above and use the one that suits you best. Furthermore, even if you could do this in an extension, I personally wouldn't. This is a business method used in very special cases, not a method that modifies the style of a String
that is used all over the app (which is what I think extensions should be primarily used for).