What is the use of static keyword if let keyword used to define constants/immutables in swift?
I will break them down for you:
var
: used to create a variablelet
: used to create a constantstatic
: used to create type properties with eitherlet
orvar
. These are shared between all objects of a class.
Now you can combine to get the desired out come:
static let key = "API_KEY"
: type property that is constantstatic var cnt = 0
: type property that is a variablelet id = 0
: constant (can be assigned only once, but can be assigned at run time)var price = 0
: variable
So to sum everything up var and let define mutability while static and lack of define scope. You might use static var
to keep track of how many instances you have created, while you might want to use just var
for a price that is different from object to object. Hope this clears things up a bit.
Example Code:
class MyClass{
static let typeProperty = "API_KEY"
static var instancesOfMyClass = 0
var price = 9.99
let id = 5
}
let obj = MyClass()
obj.price // 9.99
obj.id // 5
MyClass.typeProperty // "API_KEY"
MyClass.instancesOfMyClass // 0
What is the difference between let and static let ?
fooValue
is an instance property. There's one separate fooValue
per every instance (object) of the Foo
class.
barValue
is a static property. There's one shared barValue
that belongs to the class.
Here's a more concrete example. Suppose I had this class:
class Human {
static let numberOfLimbs = 4
let name: String
}
What would you expect to happen if I asked you what the name of a Human is? I.e. Human.name
. Well, you wouldn't be able to answer me, because there's no one single name of all humans. Each human would have a separate name. You could however, tell me the number of limbs humans have, (Human.numberOfLimbs
), which is (almost) always 4.
What is the purpose of using static on a constant in a Swift structure?
It has multiple applications, including but not limited by the following:
1) To give a constant separate namespace, if constants have same names.
struct A {
static let width: Int = 100
}
struct B {
static let width: Int = 100
}
print(A.width)
print(B.width)
2) Static constants are 'lazy' by design, so if you are about to use lazy-behaved global constant, it might be handy to put it in a structure.
3) To show your coworkers that constant is applicable to specific domain where given structure is used.
4) Organize your configuration in sections:Theme.Layout.itemHeight
or Label.Font.avenirNext
When to use static constant and variable in Swift?
When you define a static var/let into a class (or struct), that information will be shared among all the instances (or values).
Sharing information
class Animal {
static var nums = 0
init() {
Animal.nums += 1
}
}
let dog = Animal()
Animal.nums // 1
let cat = Animal()
Animal.nums // 2
As you can see here, I created 2 separate instances of Animal
but both do share the same static variable nums
.
Singleton
Often a static constant is used to adopt the Singleton pattern. In this case we want no more than 1 instance of a class to be allocated.
To do that we save the reference to the shared instance inside a constant and we do hide the initializer.
class Singleton {
static let sharedInstance = Singleton()
private init() { }
func doSomething() { }
}
Now when we need the Singleton
instance we write
Singleton.sharedInstance.doSomething()
Singleton.sharedInstance.doSomething()
Singleton.sharedInstance.doSomething()
This approach does allow us to use always the same instance, even in different points of the app.
There is any difference between the static property and static function in Swift
In the var t = { }()
syntax: the { }
is a function that returns a value, and the ()
is calling that function once to set the initial value of the variable t
. You can change t
to something else later, because it's a var
. That syntax is like var a = 42
but instead of 42 you set it to the result of running a function, like: { return 42 }()
but that function isn't run every time you read (or write) the value t
The getURLSessionConfigurationDefault() -> URLSessionConfiguration
is always creating a new instance of something and returning that new instance - the result of the function.
How exactly does the let keyword work in Swift?
let
is a little bit like a const
pointer in C. If you reference an object with a let
, you can change the object's properties or call methods on it, but you cannot assign a different object to that identifier.
let
also has implications for collections and non-object types. If you reference a struct
with a let
, you cannot change its properties or call any of its mutating func
methods.
Using let
/var
with collections works much like mutable/immutable Foundation collections: If you assign an array to a let
, you can't change its contents. If you reference a dictionary with let
, you can't add/remove key/value pairs or assign a new value for a key — it's truly immutable. If you want to assign to subscripts in, append to, or otherwise mutate an array or dictionary, you must declare it with var
.
(Prior to Xcode 6 beta 3, Swift arrays had a weird mix of value and reference semantics, and were partially mutable when assigned to a let
-- that's gone now.)
What is the difference between `let` and `var` in Swift?
The let
keyword defines a constant:
let theAnswer = 42
The theAnswer
cannot be changed afterwards. This is why anything weak
can't be written using let
. They need to change during runtime and you must be using var
instead.
The var
defines an ordinary variable.
What is interesting:
The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once.
Another strange feature:
You can use almost any character you like for constant and variable
names, including Unicode characters:
let = "dogcow"
Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329
Community Wiki
Because comments are asking for adding other facts to the answer, converting this to community wiki answer. Feel free edit the answer to make it better.
Differences Objective-C const and let Swift in terms of run and compile time
Let means once assigned the value can’t be changed. The compiler will enforce that. An expression like “let now=Date()” can’t be determined at compile time but at compile time you can disallow reassigning to “now”.. “let pi = 3.141” can be determined at compile time, enabling optimisations and that is like C’s const
Note for reference types (classes) let means the assigned object will continue to be the same object, it doesn’t mean the object itself can’t or doesn’t change.
Related Topics
Convert a Swift Array of String to a to a C String Array Pointer
Swift 5: What's 'Escaping Closure Captures Mutating 'Self' Parameter' and How to Fix It
Reference to Property in Closure Requires Explicit 'Self.' to Make Capture Semantics Explicit
Fixing Nsurlconnection Deprecation from Swift 1.2 to 2.0
How to Use Contains Within a Swift Array Extension
Reading Data into a Struct in Swift
Why Is the Shorthand Argument Name $0 Returning a Tuple of All Parameters
Swift: Failing to Copy Files to a Newly Created Folder
Swift: Setting an Optional Property of a Protocol
Aws Cognito Swift Credentials Provider "Logins Is Deprecated: Use Awsidentityprovidermanager"
Pass Variables from One Viewcontroller to Another in Swift
How to Add Material to Modelentity Programatically in Realitykit