Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift:Class cannot be declared public because its Super class is internal

I am trying to declare the class as public as shown below

class RewardsAndRedemptionModel:BaseObject {
var rewardHistory :[RewardHistoryModel]!
}

This is where i am trying to make the class public but i could not.

public class RewardHistoryModel :BaseObject  {
 var rewardValue : String!
 var recordedByName : String!
 var rewardFor : String!
}

Even i read the documentations available on Internet i couldn't get it please help me out.

like image 886
Sam Avatar asked Dec 07 '16 07:12

Sam


2 Answers

The compiler tells you that you can't make it public because the super class is internal. The compiler isn't lying, you know.

No subclass can be more accessible than its super class. Why? Think about it this way, a subclass has all the properties and members that its super class has. If this restriction didn't exist, then access modifiers will not be as useful anymore. You have an internal class. Someone else subclasses your internal class and declare it as public. Now encapsulation is broken. Things that you don't want to be accessed can now be accessed through the subclass.

In other words, if a subclass is more accessible than its super class, then the access modifier of the super class loses effect. That's why the compiler has this restriction: to remind you that what you're writing can make the super class' access modifier lose effect. You're probably doing the wrong thing.

To fix the problem, declare BaseClass and its super classes as public.

like image 172
Sweeper Avatar answered Oct 24 '22 02:10

Sweeper


Swift 3

You need to declare the access level of the RewardHistoryModel & BaseObject class & their internal members like functions or variables as public or open (open is available in swift 3).

public class BaseObject {
   // set member of this class as public that you want to access outside (Project/Framework Level)
}

public class RewardHistoryModel :BaseObject  {
// set members as public or open  - // open is available in swift 3.
 public (or open) var rewardValue : String! 
 public (or open) var recordedByName : String!
 public (or open) var rewardFor : String!
}

As stated in the documentation (The Swift Programming Language - Access Control) :

A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used.

Classes are declared as internal by default, so you have to add the public keyword to make them public.

A similar rule exists for functions as well.

A function cannot have a higher access level than its parameter types and return type, because the function could be used in situations where its constituent types are not available to the surrounding code.

like image 31
Krunal Avatar answered Oct 24 '22 00:10

Krunal