swift: declare public variable - ios

class XYActivity: UIActivity,YouTubeHelperDelegate
{
var youTubeHelper:YouTubeHelper
var uploadURL: String!
override init() {
self.youTubeHelper = YouTubeHelper()
}
override func activityType() -> String? {
return nil
}
//
}
I want to make uploadURL public, That is, to be assigned in other class.
When I add public infront of var uploadURL:String! it suggest me to make it as internal. I wanna make it public. Please help

In order to make it public, the class must be declared as public.
By default the modifier is internal, which makes classes, methods and properties not explicitly declared as private available anywhere in the current module.
If your project consists of an app only, then you probably don't need public - internal has the same effect. If you are developing a framework instead, and need that property accessible from code in other modules, then you need to declare the entire class and the exposed methods/properties as public.
Suggested reading: Access Control
Excerpt describing default access levels:
All entities in your code (with a few specific exceptions, as described later in this chapter) have a default access level of internal if you do not specify an explicit access level yourself. As a result, in many cases you do not need to specify an explicit access level in your code.
and access levels for single-target apps:
When you write a simple single-target app, the code in your app is typically self-contained within the app and does not need to be made available outside of the app’s module. The default access level of internal already matches this requirement. Therefore, you do not need to specify a custom access level. You may, however, want to mark some parts of your code as private in order to hide their implementation details from other code within the app’s module.

You can make it public if the class that contains it is also public, so change that according to it.

JuST ADD a keyword "public" at start this will make it public in the app.

Very neatly explained on docs.swift.org

Related

How to create a common property in swift4

I need a common property in my project so that I can use or share it thought out the application.
I have tried many solutions but didn't work.
I think it would make many things simple and reusable.
You can use Extension
as documented in
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID383
you can change previously defined classes properties
example
extension UIColor {
class var customGreen: UIColor {
let darkGreen = 0x008110
return UIColor.rgb(fromHex: darkGreen)
}
}
Make use of the iOS Design pattern "Singleton".
Its uses only one reference for a class and the same property will get reflected where ever you are using it throughout the app.
Reference : https://thatthinginswift.com/singletons/
You can create a lightweight "namespace" by declaring a public struct or enum. Then, simply add your static vars and you can safely share it.
As an added benefit, you get thread-safety for free. (Static stored property initializers are thread-safe.)
public enum SharedConstants {
public static var id = "MyID"
public static var hashCode = 12345678
}
By the way, extensions are great if you want to enhance an existing type. Type extensions let you add new functionality to a type without modifying its original code.
Yet, if all you need is a common shared property, extensions may not be the best choice.

swift - extending PieChartView

I have the following code but i'm facing some issues, maybe related to 'open' keyword.
class CustomPieChartView: PieChartView
{
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
_xAxis = nil
self.highlighter = PieHighlighter(chart: self)
}
}
initialize is marked internal inside PieChartView
According to the Swift documentation you cannot access internal members of frameworks (they must be marked open).
Internal access enables entities to be used within any source file
from their defining module, but not in any source file outside of that
module. You typically use internal access when defining an app’s or a
framework’s internal structure.
...
Open class members can be overridden by subclasses within the module
where they’re defined, and within any module that imports the module
where they’re defined.
The maintainer(s) of Charts may not want that method to be overridden but since it's open source perhaps you/someone can attempt to have that changed if there is a good reason or use case.

How to properly use class extensions in Swift?

In Swift, I have historically used extensions to extend closed types and provide handy, logic-less functionality, like animations, math extensions etc. However, since extensions are hard dependencies sprinkled all over your code-base, I always think three times before implementing something as an extension.
Lately, though, I have seen that Apple suggests using extensions to an even greater extent, e.g. implementing protocols as separate extensions.
That is, if you have a class A that implement protocol B, you end up with this design:
class A {
// Initializers, stored properties etc.
}
extension A: B {
// Protocol implementation
}
As you enter that rabbit-hole, I started seeing more extension-based code, like:
fileprivate extension A {
// Private, calculated properties
}
fileprivate extension A {
// Private functions
}
One part of me likes the building-blocks you get when you implement protocols in separate extensions. It makes the separate parts of the class really distinct. However, as soon as you inherit this class, you will have to change this design, since extension functions cannot be overridden.
I think the second approach is...interesting. Once great thing with it is that you do not have to annotate each private property and function as private, since you can specify that for the extension.
However, this design also splits up stored and non-stored properties, public and private functions, making the "logic" of the class harder to follow (write smaller classes, I know). That, together with the subclassing issues, makes me halt a bit on the porch of extension wonderland.
Would love to hear how the Swift community of the world looks at extensions. What do you think? Is there a silverbullet?
This is only my opinion, of course, so take what I'll write easy.
I'm currently using the extension-approach in my projects for few reasons:
The code is much more clean: my classes are never over 150 lines and the separation through extensions makes my code more readable and separated by responsibilities
This is usually what a class looks like:
final class A {
// Here the public and private stored properties
}
extension A {
// Here the public methods and public non-stored properties
}
fileprivate extension A {
// here my private methods
}
The extensions can be more than one, of course, it depends on what your class does. This is simply useful to organize your code and read it from the Xcode top bar
It reminds me that Swift is a protocol-oriented-programming language, not an OOP language. There is nothing you can't do with protocol and protocol extensions. And I prefer to use protocols for adding a security layer to my classes / struct. For example I usually write my models in this way:
protocol User {
var uid: String { get }
var name: String { get }
}
final class UserModel: User {
var uid: String
var name: String
init(uid: String, name: String) {
self.uid = uid
self.name = name
}
}
In this way you can still edit your uid and name values inside the UserModel class, but you can't outside since you'll only handle the User protocol type.
I use a similar approach, which can be described in one sentence:
Sort a type's responsibilities into extensions
These are examples for aspects I'm putting into individual extensions:
A type's main interface, as seen from a client.
Protocol conformances (i.e. a delegate protocol, often private).
Serialization (for example everything NSCoding related).
Parts of a types that live on a background thread, like network callbacks.
Sometimes, when the complexity of a single aspect rises, I even split a type's implementation over more than one file.
Here are some details that describe how I sort implementation related code:
The focus is on functional membership.
Keep public and private implementations close, but separated.
Don't split between var and func.
Keep all aspects of a functionality's implementation together: nested types, initializers, protocol conformances, etc.
Advantage
The main reason to separate aspects of a type is to make it easier to read and understand.
When reading foreign (or my own old) code, understanding the big picture is often the most difficult part of diving in. Giving a developer an idea of a context of some method helps a lot.
There's another benefit: Access control makes it easier not to call something inadvertently. A method that is only supposed to be called from a background thread can be declared private in the "background" extension. Now it simply can't be called from elsewhere.
Current Restrictions
Swift 3 imposes certain restrictions on this style. There are a couple of things that can only live in the main type's implementation:
stored properties
overriding func/var
overidable func/var
required (designated) initializers
These restrictions (at least the first three) come from the necessity to know the object's data layout (and witness table for pure Swift) in advance. Extensions can potentially be loaded late during runtime (via frameworks, plugins, dlopen, ...) and changing the type's layout after instances have been created would brake their ABI.
A modest proposal for the Swift team :)
All code from one module is guaranteed to be available at the same time. The restrictions that prevent fully separating functional aspects could be circumvented if the Swift compiler would allow to "compose" types within a single module. With composing types I mean that the compiler would collect all declarations that define a type's layout from all files within a module. Like with other aspects of the language it would find intra file dependencies automatically.
This would allow to really write "aspect oriented" extensions. Not having to declare stored properties or overrides in the main declaration would enable better access control and separation of concerns.
I hate it. It adds extra complexity and muddies the use of extensions, making it unclear on what to expect that people are using the extensions for.
If you're using an extension for protocol conformance, OK, I can see that, but why not just comment your code? How is this better? I don't see that.

The use of private keyword in Swift and their use in protocols?

I'm building an iOS app where i want to make a protocol (Which by my understanding is the equivalent of java interfaces) for my model, to use for Unit Testing purposes.
In Java you typically want to encapsulate your values in a model and make them accessible through getters and setters only.
How can i ensure this encapsulation in Swift with protocols, where i can't use the private keyword for properties.
My model is setup something like this:
class model {
private var property: Int = 5
func getProperty() -> Int {
return property
}
func setProperty(newValue: Int) {
self.property = newValue
}
}
And i want my protocol to look something like this:
protocol modelProtocol {
private var property: Int { get set }
}
My problem is that i can't declare my properties private, is this just a thing in Swifts access control (I've read they have private, internal and public) that you don't use private properties that much or is there an equivalent to Java's way of handling interfaces and private variables?
(Note: I'm using Xcode 7 and swift 2.0 if that matters)
I don't think that you can have private properties and public Getters and Setters with Swift code, as the getters and setters cannot have a higher access control than the property. For unit testing purposes you can access any internal entity using the #testable attribute as shown in the documentation below.
Access Levels for Unit Test Targets
When you write an app with a unit test target, the code in your app needs to be made available to that module in order to be tested. By default, only entities marked as public are accessible to other modules. However, a unit test target can access any internal entity, if you mark the import declaration for a product module with the #testable attribute and compile that product module with testing enabled.
I do not think you would be able to declare private properties within a protocol, you may need to use a base class instead with internal properties and extend that class. I am still fairly new to protocols myself, but I believe they are mainly used to ensure code conforms to that protocol as in... it provides that functionality or those methods.
References Used:
Swift Access Control
Swift Properties
Swift unit testing access

A pragmatic view on private vs public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!

Resources