Quick extension for selected class instance

In the Objective-C category, you can enter the advanced feature introduced by category methods by including the category header in your class.

It seems that all Swift extensions are automatically entered without importing. How do you achieve the same in Swift?

For example:

extension UIView { // only want certain UIView to have this, not all // similar to Objective-C, where imported category header // will grant the capability to the class func extraCapability() { } } 
+7
swift swift2 swift-extensions category
source share
3 answers

Define a protocol to use as an option so that extensions are available or not:

 protocol UIViewExtensions { } 

then define the extension for the protocol, but only for subclasses of UIView (otherwise this will not work):

 extension UIViewExtensions where Self: UIView { func testFunc() -> String { return String(tag) } } 

The class defined for the protocol will also have the extension:

 class A: UIView, UIViewExtensions { } A().testFunc() //has the extension 

And if it is not defined for the protocol, it will also not have an extension:

 class B: UIView {} B().testFunc() //execution failed: MyPlayground.playground:17:1: error: value of type 'B' has no member 'testFunc' 

UPDATE

Since protocol extensions do not fulfill class polymorphism , if you need to redefine functions, the only thing I can come up with is a subclass:

 class UIViewWithExtensions: UIView { override func canBecomeFocused() -> Bool { return true } } UIViewWithExtensions().canBecomeFocused() // returns true 

it can also be combined with an extension, but I don’t think it would make sense anyway.

+8
source share

You can make extensions private for a particular class by adding private before the extension, for example:

 private extension UIView { func extraCapability() { } } 

This means that it can only be used in this particular class. But you need to add this to every class that requires this extension. As far as I know, there is no way to import the extension as you can in Obj-c

+2
source share

Note Private access in Swift is different from private access in most other languages, because its scope is in the attached source file, and not in the attached ad. This means that the type can access any private objects that are defined in the same source file as it is, but the extension cannot access these types of private members if it is defined in a separate source file.

According to Apple, it ’s not visible here that you can make extensions private in separate files.

You can create a private extension in the same source file.

0
source share

All Articles