0

This code works in Playground, but I get a compile error when I define this in my project in Xcode 7.2

Here is my Playground screenshot https://goo.gl/yJ4Q75

Error is: method does not override any method in the super class

public class A {
    private func myUnavailableMethod() {
        print("A. private func myUnavailableMethod()")
    }
}

public class B : A {  
    override func myUnavailableMethod() {
        print("B. func myUnavailableMethod()")
    }
}

Motivation to this Playground was an error when trying to override a method, compiler was complaining as "Not available"

class MySFSafariViewController: SFSafariViewController {
    override init() {

    }
}

---- FOUND HOW THEY MARKED a method as unavailable.

When jumping to the Objective C declaration.

@interface SFSafariViewController : UIViewController

/*! @abstract The view controller's delegate */
@property (nonatomic, weak, nullable) id<SFSafariViewControllerDelegate> delegate;

****- (instancetype)init NS_UNAVAILABLE;****
jcalloway
  • 1,155
  • 1
  • 15
  • 24

2 Answers2

1

The meaning of private/internal/public is different in Swift compared to some other languages.

IF and it is an IF you have your classes as two separate files in the project, then it's pretty clear.

private - scope is visibility is the file that holds the code
internal - scope of visibility is the namespace
public - scope of visibility is full access from anywhere 

In Xcode Playground their are both in one file so the method is visible to class B.

Earl Grey
  • 7,426
  • 6
  • 39
  • 59
  • so is there a way to mark the method as "not visibile at all to anything outside of the class"? I tried internal, and it behaved the same as private in the Playground – jcalloway Feb 28 '16 at 23:47
  • nope, the only way to keep it "class-private" like you describe is have it as a "sole occupant of the file" and that will make the method de-facto invisible to anybody else. – Earl Grey Feb 28 '16 at 23:55
  • Ok so to extend this further, I was seeing an error in the following code, and was trying to simulate it in Playground. – jcalloway Feb 29 '16 at 00:01
  • So the motivation behind this was an Error I was seeing in the following snippet. This causes an error "cannot override init which has been marked unavailable. So how did they do that ? "class MySFSafariViewController: SFSafariViewController { override init() { }" – jcalloway Feb 29 '16 at 00:01
0

The myUnavailableMethod of class A is private, therefore it can't be overridden. Change the method declaration to be internal by removing the private keyword.

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143