DEV Community

Naveen Ragul B
Naveen Ragul B

Posted on • Updated on

Swift Basics

  • Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development.

DataTypes

  • Swift provides datatype such as
  1. Int
  2. Double
  3. Float
  4. Bool
  5. String
  • 3 primary collection types -
  1. Array
  2. Set
  3. Dictionary

Variables - to store and refer to these values.
example :

var currentLoginAttempt : Int = 0
Enter fullscreen mode Exit fullscreen mode

Constant - For variable whose value doesn't change.
example :

let maximumNumberOfLoginAttempts : Int = 10
Enter fullscreen mode Exit fullscreen mode
  • tuples - store group of values
  • optional types - handles the absence of a value

Type Annotations

provide a type annotation when you declare a constant or variable
example :

var welcomeMessage: String
Enter fullscreen mode Exit fullscreen mode

DataTypes

Int

Integers - whole numbers with no fractional component.
Swift provides - signed and unsigned integers in 8, 16, 32, and 64 bit forms

Range for signed int : -2^(n-1) to (2^(n-1))-1
Range for unsigned int : 0 to (2^n )- 1

Floating-Point Numbers

Numbers with a fractional component.

Swift provides two signed floating-point number types:

  1. Double represents a 64-bit floating-point number.
  2. Float represents a 32-bit floating-point number.

Double - precision of at least 15 decimal digits
Float - 6 decimal digits.


Type Inference

Type inference enables a compiler to deduce the type of a particular expression automatically by examining the values you provide.

example :

let pi = 3.14159  // pi is inferred to be of type Double
Enter fullscreen mode Exit fullscreen mode

If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context:

example :

let anotherPi = 3 + 0.14159  // inferred as type Double
Enter fullscreen mode Exit fullscreen mode

Numeric Literals

Integer literals can be written as:

  • A decimal number, with no prefix
  • A binary number, with a 0b prefix
  • An octal number, with a 0o prefix
  • A hexadecimal number, with a 0x prefix

example :

let decimalInteger = 17           // 17 in decimal
let binaryInteger = 0b10001       // 17 in binary
let octalInteger = 0o21           // 17 in octal
let hexadecimalInteger = 0x11     // 17 in hexadecimal
Enter fullscreen mode Exit fullscreen mode

Floating-point literals

Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix).
Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase e and for hexadecimal floats indicated by an uppercase or lowercase p

example :

1.25e2 means 1.25 x 102, or 125.0.
1.25e-2 means 1.25 x 10-2, or 0.0125.

0xFp2 means 15 x 22, or 60.0.
0xFp-2 means 15 x 2-2, or 3.75.

The rules for combining numeric constants and variables are different from the rules for numeric literals.
i.e.

let pi = 3 + 0.14159. //Correct

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = three + pointOneFourOneFiveNine  //Compilation Error
let pi = Double(three) + pointOneFourOneFiveNine  //Correct
Enter fullscreen mode Exit fullscreen mode

--

Type Aliases

Type aliases define an alternative name for an existing type. It is useful when you want to refer to an existing type by a name thats contextually more appropriate

example :

typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min // it is 0 now
Enter fullscreen mode Exit fullscreen mode

Tuples

Tuples group multiple values into a single compound value. The values within a tuple can be of any type.

example :

let http404Error = (404, "Not Found") //type (Int, String)
Enter fullscreen mode Exit fullscreen mode

You can name the individual elements in a tuple, when defined

example :

let http200Status = (statusCode: 200, description: "OK")
Enter fullscreen mode Exit fullscreen mode

use the element names to access the values of those elements:
example :

print("The status code is \(http200Status.statusCode)")
Enter fullscreen mode Exit fullscreen mode

Optionals

use optionals in situations where a value may be absent.
optional variable without a default value is automatically set to nil, but not constant

forced unwrap an optional value using !

example :

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
if convertedNumber != nil {
    print("convertedNumber : \(convertedNumber!).")
}

Enter fullscreen mode Exit fullscreen mode

Trying to use ! to access a nonexistent optional value triggers a runtime error

Optional Binding
use optional binding to find out whether an optional contains a value, and if so store it in a variable or constant

example :

if let actualNumber = Int(possibleNumber) {
    print("The string has an integer value of \(actualNumber)")
} else {
    print("The string couldn't be converted to an integer")
}
// "The string has an integer value of 123"
Enter fullscreen mode Exit fullscreen mode

Constants and variables created with optional binding in an if statement are available only within the body. In contrast, in guard statement, it is available in the lines of code that follows that

Implicitly Unwrapped Optionals
an optional will always have a value, after that value is first set.

let possibleNumber = "123"
let convertedNumber : Int! = Int(possibleNumber)
let number : Int = convertedNumber // ! - not needed
Enter fullscreen mode Exit fullscreen mode

Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point.


Basic Operators

  • Assignment Operator ( = )
  • Compound Assignment Operators ( += , -= etc )
  • Arithmetic Operators(+, -, *, /)
  • Remainder Operator ( % )
  • Unary Minus Operator ( + )
  • Unary Plus Operator( - )
  • Comparison Operators ( <, >, <=, >= , == , !=)
  • Identity operators (=== and !==)
  • Ternary Conditional Operator ( ?: )
  • Nil-Coalescing Operator ( ?? ) - unwraps optional value if it contains else return default value example :
let defaultColorName = "red"
var userDefinedColorName: String?
var colorNameToUse = userDefinedColorName ?? defaultColorName  // "red"
Enter fullscreen mode Exit fullscreen mode
  • Range Operators
  • Closed Range( a...b )
  • Half Open Range( a..<b )
  • One-Sided Ranges (...a , a...)
  • Logical Operators (!, &&, ||)

??, &&, || - uses short-circuit evaluation

Top comments (0)