Define a typealias for the whole project - swift

In which file can I define a typealias that works in the whole project, etc.
typealias S = String

the typealias works the same way as variables. If you want to be global put it outside the class scope at any file.

typealias is use to aliasing the existing Data Types. Its access scope is same as a variable, if its declared in side the block like class, struct, protocol etc then its visibility also remains inside that block only. it can not be used outside to declare a new variables of that type.

Related

Global var vs Shared Instance swift

What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.
A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:
var bar = Bar()
You would then be able to access the instance from anywhere, like this:
bar
bar.foo()
A shared instance, or singleton, looks like this:
class Bar {
static var shared = Bar()
private init() {}
func foo() {}
}
Then you can access the shared instance, still from anywhere in the module, like this:
Bar.shared
Bar.shared.foo()
However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:
var bar2 = Bar()
var bar3 = Bar()
However, using a singleton (shared instance), the initialiser is private, so trying to do this...
var baaar = Bar()
...results in this:
'Bar' initializer is inaccessible due to 'private' protection level
That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.
If you want more information about this, there's a great article by KrakenDev here.
Singleton (sharing instance)
Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app.
The dispatch_once function, which executes a block once and only once for the lifetime of an app.
Global variable
Apple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.

Stopping reference variables changing the value of the original variable

I am assigning the value of a custom class to another variable. Updating the value of the new variable is affecting the value of the original variable. However, I need to stop the reference variable from updating the original variable.
Here's a basic representation of what's happening:
var originalVariable = CustomClass()
originalVariable.myProperty = originalValue
var referenceVariable = originalVariable
referenceVariable.myProperty = updatedValue
print("\(originalVariable.myProperty)") //this prints the ->updatedValue<- and not the ->originalValue<-
I've tried wrapping the referenceVariable in a struct to make it a value type but it hasn't solved the problem.
I've found information regarding value and reference types but I haven't been able to find a solution.
My question in a nutshell: How do I stop an update to a reference variable from updating the original variable that it got its value assigned from?
Thanks in advance.
The whole point of reference semantics (as used by classes) is that all variables point to the same (i.e., they reference the same) object in memory. If you don't want that behaviour, you should use value types (Struct, Enum, Array...) or create copies of your object.
If CustomClass implements the NSCopying protocol you can do:
var referenceVariable = originalVariable.copy()
If it doesn't, you'll have to find some other way to copy it or implement the protocol yourself.
Wrapping the class in a struct will just make two different structs each containing a different reference to the same object.

Swift: Classes are reference types?

I wanted to know why can't you hold instances of a class in a variables -> why does it have to be a reference. That's a bit problematic because if I want to store a object in a two variables it any changes made to the object will change the values of my variables. Is there a way around it ?
thanks,
you can use struct instead of class because structures pass by value
Why Choose Struct Over Class?

Swift: class func .... why use this instead of func when creating a method inside a class?

I'm new to coding, apologies for dumb question.
Am following a tutorial to build a note taking app using Swift in Xcode.
Within a class definition I have been defining methods using the keyword func myMethod etc. At one point the instructor decides to define a Class method (within the existing class) using class func myMethod.
Why would you do this?
Thanks in advance for any feedback.
By defining a class method it means that you don't need an instance of that class to use the method. So instead of:
var myInstance: MyClass = MyClass()
myInstance.myMethod()
You can simply use:
MyClass.myMethod()
The static (class) function is callable without needing an instance of the class available; it may be called without having to instantiate an object.
This can be useful for encapsulation (avoiding placing the function in the global namespace), or for operations that apply to all objects of a given class, such as tracking the total number of objects currently instantiated.
Static functions can be used to define a namespaces collection of related utility functions:
aDate = Utils.getDate()
aTime = Utils.getTime()
Another common use is for the singleton pattern, where a static function is used to provide access to an object that is limited to being instantiate only once:
obj = MySingleton.getInstance()
obj.whatever()
One answer is namespacing. If a function is only relevant to a certain class there is no need to declare the function globally.
This is Swift's take on static methods:
Static methods are meant to be relevant to all the instances of a class (or no instances) rather than to any specific instance.
An example of these are the animation functions in UIView, or the canSendMail function from MFMailComposeViewController.

Static variable in ObjectiveC

Static variables are variables allocated statically at compile time. My doubt is for what purpose some variables are declared statically? I didn't have used any static variable in my code till now. From the apple code http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.html
in securityWrapper.m, there is a line
static SecKeyWrapper * __sharedKeyWrapper = nil;
what is the use of statically allocating __sharedKeyWrapper here?
I have seen the use of static key word in so many codes. So kindly explain the use and benefits when static keyword.
Thanks in advance.
That file global is a singleton, used for sharing an instance of a class.
The reason it's static in Objective-C is internal linkage. In practice, this means the variable can not be seen outside the file it is declared in. If another file declares a variable with the same name, they're two different variables.
Keep in mind that the way Objective-C instances work, the instance won't actually be allocated automatically. Rather, you have a pointer to the instance. The code will still have to do something like:
if ( !_sharedKeyWrapper ) {
_sharedKeyWrapper = [[SecKeyWraper alloc] initBlahBlah];
}
See links for more.
When you define a new class of objects, you can decide what instance
variables they should have. Every instance of the class will have its
own copy of all the variables you declare; each object controls its own
data.
However, you can't prescribe variables for the class object; there are
no "class variable" counterparts to instance variables. Only internal
data structures, initialized from the class definition, are provided for
the class. The class object also has no access to the instance variables
of any instances; it can't initialize, read, or alter them.
Therefore, for all the instances of a class to share data, an external
variable of some sort is required. Some classes declare static variables
and provide class methods to manage them. (Declaring a variable static
in the same file as the class definition limits its scope to just the
class-and to just the part of the class that's implemented in the file.
Unlike instance variables, static variables can't be inherited by
subclasses.)
Static variables help give the class object more functionality than just
that of a "factory" producing instances; it can approach being a
complete and versatile object in its own right. A class object can be
used to coordinate the instances it creates, dispense instances from
lists of objects already created, or manage other processes essential to
the application. In the case when you need only one object of a
particular class, you can put all the object's state into static
variables and use only class methods. This saves the step of allocating
and initializing an instance.
Also static variables are initialized once. You can use static variables in recursive calls. Simple Example Factorial.