Swift Reference
declaring variable
var str = "Hello"
declaring constant
let str ="hello"
str = "world" // this wont compile constant cannot reassign
data types
Int , Double, Bool, String, Character
String equality check
empty check
str.isEmpty
double equal ==
this check identical caharacter in same order. simple capital cases checked here
.contains
check substring found or not
if condition
same as java. but && can check using , in swift
var x = 10
if x != 9, x != 10 , x != 6 {
print("aaa")
}else {
print("bbb")
}
output = bbb
optionals ? !
variable without initialize and use throw compile time error
//var y // swift is type safety. so cannot use without type
//var y = 10 // this is ok. type is int
//var y : Int
//print(y) // this return errr because no value
var y : Int?
//print(y) // this print nil
//print(y!) // this is error. beacause cannot use nil value because of optional
var z = y // this is fine. but assign nil value to z. this may cause crash
//var z2 = y! // ! use to wrap z2 as int. this raise error because nill value
// so have to check nill. two ways
if y != nil {
// var z2 = y // without unwrapping z is not idetified as INT
// var k = z2 + 5 // so without z2 type raise error
var z3 = y! // Wrap using ! to Int value
var k2 = z3 + 5 // now z3 is Int . so run fine
}
// second way. best way
if let y2 = y {
print(y2)
}
** so in my knowledge optional is use to make app without crash due to nil value. we have to use if let for optional variables and else part to handle nil values
declaring function
func funcName( name : String, lastname : String){
print("my name is \(name) \(lastname)")
}
2nd way
func aa(x1 var1:String, x2 var2 :String){
print ("hello v\(var1) df \(var2)")
}
aa(x1: "dd", x2: "sdasd")
invoke function
funcName(name: "thu",lastname: "wijre")
invoke. function without variable name
define function parameter with underscore
func abc(_ name:String){
print (name)
}
abc( "dsfdsf"). // no need to add variable name when invokint if uderscore used
function with default parameter values
func abc(_ name:String, age : Int = 10){
print ("\(name) sdfdf \(age)")
}
abc( "dsfdsf")
function return value
func returnInt(x1 :Int, x2 :Int) ->Int{
return x1+x2
}
print (returnInt(x1: 10, x2: 20))
enum
like enum in java. same concept
enum CompassPoint {
case north, east, south, west
}
usage
let compassHeading: CompassPoint = .west
switch compassHeading {
case .north:
print("I am heading north")
structures
structures are same as classes but no inhertance in structures.
struct xx{
var x2=10
func printX(){
print(x2)
}
}
var a1 = xx()
//let a1 = xx() // this cannot be done. constant cannot assign properties. because next line trye to assign x2 value.
a1.printX()
a1.x2 = 89
a1.printX()
this is OK
let b1 = xx().x2
print(b1)
let b2 = xx(x2: 50)
print(b2)
Initializers
“All Swift types come with an initializer, which is similar to a function that returns a new instance of the type. The default initializer is init().”
var string = String.init() // ""
var integer = Int.init() // 0
var bool = Bool.init() // false”
this is short version
var string = String() // ""
var integer = Int() // 0
var bool = Bool() // false”
Memberwise initializer
struct Person {
var name: String
func sayHello() {
print("Hello, there!")
}
}
let person = Person(name: "Jasmine")
initialize multiple values
struct Temperature {
var celsius: Double
init(celsius: Double) {
self.celsius = celsius
}
init(fahrenheit: Double) {
celsius = (fahrenheit - 32) / 1.8
}
}
let currentTemperature = Temperature(celsius: 18.5)
let boiling = Temperature(fahrenheit: 212.0)
print(currentTemperature.celsius)
print(boiling.celsius)
mutating methods
in cases need to update values using instance methods rather than using above init methods u need to use mutating keyword
struct test{
var x : Int = 0
mutating func increment(){
x = x+1
}
mutating func incrementByVal(by val : Int){
x = x+val
}
func printx(){ // here no updation. so no need mutating keyword
print(x)
}
}
var a = test()
a.increment()
a.incrementByVal(by: 5)
a.printx()
same class declarion is here
class test1{
var x : Int = 0
func increment(){
x = x+1
}
func incrementByVal(by val : Int){
x = x+val
}
func printx(){
print(x)
}
}
var a1 = test1()
a1.increment()
a1.incrementByVal(by: 5)
a1.printx()
computed properties
property to perform a calculation to return value use this way
struct temp{
var celcius :Double
var farenhite : Double {
return celcius + 32
}
}
let b1 = temp(celcius: 24)
print(b1.farenhite)
Property Observers
Swift allows to get previous value when set a new value. willset and didset keywords used
here two more keywords, newValue oldValue
struct test{
var x :Int = 10{
willSet{
print("new val \(newValue)")
}
didSet{
print("Old val \(oldValue)")
}
}
}
var x = test()
x.x = 9
output
new val 9
Old val 10
static veriables and methods
struct test{
static var x :Int = 10;
static func m(){
print("m")
}
}
print(test.x)
test.m()
** static vars cannot use in when instantiated
var aa = test()
aa.x = 20 // this cannot done. error
copying
assign a structer to a variable and again changed structer may not changed previous assigned value
struct test{
var x :Int = 10;
static func m(){
print("m")
}
}
var t = test()
var t2 = t
t.x = 20
print(t.x)
print( t2.x)
output
20,10
self
self refers to the current instance of the object. like this in java
Variable Properties
if assigned structer instance to a constant you cannot change structer variable too
struct test{
var x :Int = 10;
}
let t = test()
t.x = 3. // this is compile error
create class
same as above discussed structer. only difference is classes can iherited.
in same file you cannot use class and structer using same name. :)
class A{
var x="etstwrwrt";
func printx(){
print(x)
}
func A(){
print ("df")
}
}
instantite class
let a = A()
a.printx()
a.A()
aa(x1: "wq", x2: "ere")
Constructor
not like in java. constructor no need class name. just require init keyword
class A{
init() {
print ("A1")
}
func A(){// this is not a contructor. work as normal function
print ("A2")
}
}
var x = A()
x.A()
Inheritance
same as in java
class A{
var x :Int = 10
}
class B : A{. // inherit class A (use : )
func printXInB(){
print(x)
}
}
var x = B()
x.printXInB()
override
only functions can override, not varibles. sholud use override keyword
class A{
var x :Int = 10
func printX(){
print(x)
}
}
class B : A{
override var x : Int = 90. // this is not allowed
var x : Int = 90 // this is not allowed
override func printX(){ // functions can override using override keyword
var x : Int = 90. // this is ok. initialization inside function
x = 80. // this change function variable
print(x)
}
}
super
use super keyword to override super class variables
class A{
var x : Int = 10
init(x : Int) {
self.x = x
print(x)
}
}
class B :A{
init() {
super.init(x: 20)
}
}
var b = B()
reference
in structer we discuss this in copy section. but in class when we instance a class it store in memory. when we copy the referenct to another variable it also refer same memory location. but in structer when copy instance it create another memory location. so in classes newly refence var update class var or constant it will change both reference var values
class A{
var x : Int = 10
}
var a = A()
var a2 = a
a2.x = 20
print(a.x). // output as 20
class ot structure
Because classes and structures are so similar, it can be hard to know when to use classes and when to use structures for the building blocks of your program.
As a basic rule, you should start new types as structures until you need one of the features that classes provide.
Start with a class when you're working with a framework that uses classes or when you want to refer to the same instance of a type in multiple places.
when you need to maintain stable identity (want to get updated value rather than copied) use classes
protocol. - seems like interfaces in java
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
creating variable
var varname : String {
get
}
every variable sholud mark inside curly bracket with get or set (get means readonly var and set means write. get set means read and write)
protocol testp{
var x : Int {
get set. // var as getter and setter. cannot only setter. but can only getter
}
func printx() // need to overrite in inherited classes or structs
}
class A : testp{
func printx() {
print("dd")
}
var x : Int {
get{
return 10
}
set (newVal){
print(newVal) // setter happen here. enter anythig when set value. but cannot assign like this x = newVal
}
}
}
let a1 : A = A()
print(a1.x) // print 10
a1.printx() // print dd
a1.x = 98 // print 98
extension
extensions is add new functionality to anything
extension String {
func sayHello(){
print("hello")
}
}
var str = "hi"
str.sayHello()
///////////////////////
extension Int{
func square() -> Int {
return (self * self)
}
}
var x = 8
print(x.square())
//////////////////////
class User {
var firstname = "hello"
var lastname = "swift"
}
extension User{
// var fullname : String = firstname + " " + lastname // cannot use variables in extensions
func getFullname() -> String {
return firstname + " " + lastname
}
}
var bob = User()
print (bob.getFullname())
closure
this is work same as functions but these has noname and no func keyword, and also very short
func adding (x : Int, y :Int) -> Int{
return x + y
}
print(adding(x: 5, y: 6))
var addClosure : (Int, Int) -> (Int) = { x, y in
return x + y
}
//shortestway
var addClosure2 : (Int, Int) -> (Int) = {
return $0 + $1 // can use param order with $ sign
}
print(addClosure(5,6))
print(addClosure2(5,6))
//var addClosure : (firstParamType, SecondParamTyoe) -> (ReturnType) = { FirstParamRefereName, secondParamRefereName in
// return x + y // operation
//}
// without parameters
// normal way
func printHello () -> String{
return "hello"
}
// with closure
var helloClosure : () -> (String) = {
return "hello"
}
print(printHello())
print(helloClosure())
collections
Arrays
var x : [Int] = [2] // declare array
x [0] = 12
var y : Array<Int> = [2] // declare array
y[0] = 23
var z = [Int] () // declare array
z = [2]
z[0] = 8
var a1 = [Int] (repeating : 0 , count : 100) // declare array with 100 zeros
print(a1[20])
var x1 = ["abc", "cde", "dfds"] // can contains only single type
var x2 : [Any] = ["abc", "cde", "dfds",10] // can caontaint any type
var x3 : [String] = ["abc", "cde", "dfds"] // can contain only String type
print(x[0])
//print(y[0])
print(x1[0])
x1.insert("bbb", at : 0) // insert item dynamically. here at value sholud inside array length.
print(x1[0])
Dictionary
dictionary is a associated key with a value. key is unique. dictionay arrange as alphabatically order to search easy
var ff = ["a" : 100, "b" : 45]
//var ff = ["a" : "ttt", "b":45] // this is compile error, cannot contain different types
print(ff["a"])
var x1 = Dictionary<String,Int>()
x1.updateValue(120, forKey: "xx")
print(x1["xx"])
var a1 : [String : Int] = [:] // initialize empty dictionary
a1.updateValue( 134, forKey: "aa") // key and value
print(a1["aa"])
Loops
for loop
for i in 1...5 { // included 5 also here
print("xx \(i)")
}
var x1 = ["a","b","c"]
for c in x1 {
print(c)
}
for letter in "abcd".characters{
print(letter)
}
// index with value
for (index,letter) in "abcd".characters.enumerated(){
print("\(index) \(letter)")
}
// output
//0 a
//1 b
while loop
var x = 0
while x < 3
{
print(x)
x = x+1
}