Is it possible to hide a Swift method (so it doesn’t appear in Xcode autocompletion and all other places) without declaring it private
?
The goal here is to make the method “unlisted” (i.e. available only if the user knows the exact name).
Is it possible to hide a Swift method (so it doesn’t appear in Xcode autocompletion and all other places) without declaring it private
?
The goal here is to make the method “unlisted” (i.e. available only if the user knows the exact name).
There aren't any attributes to control the IDE's autocompletion. Typically you would prefix such a method with _
to make it clear that it's not for general use, and to group all such methods together.
Even if such an attribute existed (and there might be one in the future), it absolutely would not hide the method in any meaningful way (since it would absolutely show up in the generated header). So the only intent here is to make it a bit more convenient on the caller by uncluttering the autocomplete list, and _
does that reasonably well.
Just for completeness, there is a way to achieve this, but you don't want to go down this road IMO. If this is an NSObject subclass, you can use dynamic dispatch. (There's no real equivalent to this in pure Swift.) You really don't want to do this, and it will generate warnings, but it is possible, and these methods won't show up in autocomplete because they're not technically visible.
class C: NSObject {
@objc private func hidden() {
print("Hidden")
}
@objc private func hiddenReturn() -> String {
return "hidden"
}
}
let c = C()
c.perform(Selector("hidden"))
let result = c.perform(Selector("hiddenReturn"))?.takeUnretainedValue() as! String
OK, now I'm on a roll of weird answers. You still don't want to do this, but the following technique actually can be useful for some things. You can pass around pointers to methods, and call them from places you wouldn't be allowed to access them directly. So, say you have some "friend" object that wants special access to some private method. Then you could return a reference to that method as part of creation. Then the Friend would be the only object that could access the special method (though Friend could pass the reference on to other objects, and then they would have access too). For example:
class C {
private func hidden() {
print("hidden")
}
fileprivate class func create() -> (C, () -> Void) {
let c = C()
return (c, c.hidden) // Return a reference to the private method
}
private init() {} // No creating us outside of create
}
class Friend {
let c: C
private let cHidden: () -> Void
init() {
(c, cHidden) = C.create()
cHidden() // Calling this function is the same as calling c.hidden()
}
}
Friend()