avatarAvijit Nagare

Summary

The provided web content is an educational article that introduces Swift programming language, highlighting its features such as safety, modernity, performance, and interoperability with Objective-C, while also covering basic Swift concepts like variables, constants, type safety, tuples, and concurrency with actors.

Abstract

The article "Let’s become Swift Friendly" serves as a primer for developers interested in learning about Apple's Swift programming language. It outlines Swift's advantages over Objective-C, including improved speed, type safety, and ease of understanding. The author emphasizes Swift's support for modern programming paradigms, such as international language support, Unicode, and concurrency, as well as its robust package manager. Safety features, such as the mandatory initialization of variables and the use of optionals to handle nil values, are underscored. The article also delves into the basics of Swift syntax, including the declaration of variables and constants, the use of comments, and the flexibility around semicolons. It explains Swift's type system, numeric literals, type inference, and integer conversion, while also discussing the language's strong type safety. The concept of tuples is introduced

Hi there!! hope you are doing well.

Designed by Auther.

Sometimes we missed to read small-small things which could help us while coding. In this read you may find some concepts which you may not get chance to read it.

Let’s become Swift Friendly:

After objective c Apple released a new development language called “Swift”. They provided tools in Xcode to convert Objective C code to Swift code and guidelines to use Objective C code into Swift and vice-versa. Swift language is better than Objective-C in terms of speed, type safety, easy to understand,

Morden:

Support international languages, emoji, Unicode, UTF-8 base encoding, ARC, concurrency with less code, generics, tuples, high level functions (map, filters), error handling using try catch.

Safety:

Swift variables are always initialized before use and cannot be “nil” at compile time itself. Other nil cases are handled using concepts called “optional”.

Fast and Powerful:

Built to support fast LLVM compiler technology and support to morden hardware.

Package Manager:

Used to build, run, package, test, swift library and executable to distribute your code.

Objective C interoperability:

Objective died? no. There are numerous projects still using Objective-C. Full access and support to objective c code.

Swift Basics:

Swift is a programming language for all Apple OS such as iOS, macOS, watchOS, tvOS. Swift provides its own version of the fundamental type you see in Objective-C, C language.

Ex. Swift Int similar to Objective-C integer

Swift String similar to Objective-C NSString.

Variables:

Variable values can be changed later in the program. Ex. var counter = 0

counter += 1 // counter is 1 now.

Constants:

Constants whose value can’t be changed once initialized.

Ex. let pi = 3.14
pi = 0 // compile time error.

You can declare a variable name the same as a reserved keyword using backticks but try to avoid it.

Comments:

Swift supports both single line and multiline comments.

// this is single line comment

/* This is multiline comment
This is another line
*/

Nested multiline comment allowed in swift which is not allowed in C language.

/* line 1
/* line 2 */
*/

Semicolon:

Swift doesn’t need to write ; at the end of each line.

Ex. Objective -C int a = 0; semicolon required.

Swift var a = 0 //semicolon not required.

Integer:

They are whole integer numbers with no fractions.

Ex. 45, -34

They are signed and unsigned integers in 8(Int8), 16(Int16), 32, 64 bit form.

UInt :

Are unsigned Int and they have the same size as platform native word size.

Ex. On a 32-bit platform, UInt size is UInt32. Same for 64-bit platforms.

Floating point number:

They are numbered with fractional components i.e. decimal points. Ex. 3.14, -353. Swift Double supports 64-bit numbers, and they support precision 15 decimal digits. Float supports 32-bit numbers with 6 decimal digit precision.

Type safety:

Swift is type safe language. It enables you to be clear on types used in code. Say, left hand side type matched with right hand side type

Ex. var a, b: String // Both are string type
a == b //Swift allows equity check on if both left and right side variables are the same type.

var c: Int
a == c // this comparison is not allowed as "a" is String type and "c" is Int type.

Type inference:

Process of knowing variable type automatically when compiling code is known as type inference.

Ex. Consider variable declaration:

var counter = 0 // From value 0 swift knows type Int
let pi = 3.14 // 3.14 is Double value so, swift knows type of "pi" would be Double.
let firstName = "John" // "John" is string value, firstName is String type.

If you try, let result = 3.14 + 2 swift evaluate expression and assign most appropriate precise type ex. Double in this case, as Double will show value more correctly.

Numeric literal:

Integer literal can be written in various forms ex. Binary(0b), Hexadecimal(0x), Octal(0o), for decimal no prefix.

Ex. Below are values of number 17 in different literal forms.

let decimalInteger = 17
let binaryInteger = 0b10001
let octalInteger = 0o21
let hexadecimalInteger = 0x11

Floating-point literal decimal can have an optional exponent (indicated by “e”) and a hexadecimal must have an exponent (indicated by “p”).

Ex.

2.12e2 same as 2.12x10², or 212.0
2.12e-2 means 2.12x10^-2 or 0.0212

Same for Hexadecimal values. Hexadecimal calculated as hex number multiplied by 2^X, where X is exponent.

Ex. Number "10" is equal to "A" in hex.
0xAp2 same as 10x2² or 40
0xAp-2 same as 10x2^-2 or 2.5 //p indicates exponent in hex number system.

Integer Conversion:

Int8 variable/constant can store numbers between -128 to 127. UInt variable/constant can store numbers between 0 to 255.

Ex. let nonNegative: UInt = -1 // not allowed this declaration as UInt allows numbers between 0 to 255.
let outOfBounNumber: Int8 = Int8.max + 1 //not allowed as a number beyond the range.

You can’t add numbers if they are in different type. Ex. UInt8 and UInt16 as their number type is different.

let twoThousand: UInt16 = 2_000
let five: UInt8 = 5 
print("Two thousand and five: \(toThousand + UInt16(five))")
// We converted 5 values of UInt8 type to UInt16 type to match type then we printed addition. 
//UInt16 type has an initializer that takes UInt8.

Also, to add Double and Int

let a = 1.1 // type Double
let b = 1 // type Int
let result = Double(b) + a // 2.1
// Double() initializer accepts Int type number to have the same type as "a" double variable to perform addition.
// Or you can convert Double to Int to perform addition using Int() initializer which takes

Double value and converts to Int.

Ex. let intResult = b + Int(1.1) // intResult = 2

Boolean:

It represents logical values, true or false. Mostly Bool value used in conditional if statements.

Ex. 
if a > b {
  print("a is greater than b")
} else {
  print("b is greater than a")
}

In case of Bool type safety make sure Bool expressions are used in appropriate places. Ex. In conditional statements there should be Boolean expressions.

let nonBoolValue = 100
if nonBoolValue {
  print("This code will not compile as nonBoolValue will not evaluate to bool value.")
} 
// The if condition requires expressions which produce a boolean result.

However, the below code will work as the result is boolean.

Ex. if 2 == 2 {
  print("This code will compile")
}

Tuples:

Tuple groups multiple values of various types into a single compounded value.

Ex. let completion = (200, data, error)

You can combine as many value of different types into pair of parentheses ( ) and separated by comma. Also, you can access each value using index starting from zero.

Ex. let testTuple = (1, 3.14, "Hello", true)

You can access value “1” using testTuple.0

You can access value “3.14” using testTuple.1

You can access value “Hello” using testTuple.2

You can access value “true” using testTuple.3

You can write a function which can return a tuple.

Ex. 
func getAlertDetail() -> (title: String, message: String) {
  return ("Loosing changes", "You made some changes. Do want to leave?")
}

As, function returns a Tuple, so you can catch return value as a tuple.

let alert = getAlertDetail()
print(alert.0) // "Loosing changes"
print(alert.1) // "You made some changes. Do you want to leave?"
//Or you can get as:
let (title, message) = getAlertDetail()
print(title) // "Loosing changes"
print(message) // "You made some changes. Do you want to leave?"

You can omit some values from tuple by writing underscore (_) which you doesn’t need to use.

Ex. let (title, _) = getAlertDetail()
print(title) // "Loosing changes"

String:

Use \() to print calculated results in string format.

print(“Current page no:\(pageNumber)”) // Current page no: 0

Three double quotation marks to declare multiline comments.

"""Some
Big or Multiline
Text"""

Swift functions:

func sayHelloTo(person: String) -> String {
  return "Hello " + person
}

sayHelloTo(person: "John") // Hello John

Declare function with no argument label with _

Exercise for you: Function can be nested into another function.

Actors:

Your program can be decided into independent tasks. These tasks run independently and give the results. Sometimes these running tasks need to share information with each other. Actors (They reference type) help to do that. Unlike Classes actors allow only one task to access their mutable state at a time that means actors are thread safe.

Note: consider using actors in a multithreaded environment as they are thread safe.

actor TemperatureLogger {
  let label: String
  var measurements: [Int]
  private(set) var max: Int
  init(label: String, measurement: Int) {
    self.label = label
    self.measurements = [measurement]
    self.max = measurement
  }
}

//label and measurements property other code can access. But max is private (set) and only internal code can update it.
//While accessing actors property or method use await to mark potential suspension point.
//Ex.
let logger = TemperatureLogger(label: "Outdoors", measurement: 25)
print(await logger.max) // Prints "25"

As actors allow one task at a time for mutating states. If other code is already interacting with the logger object, this code suspends/pauses while it waits to access the property.

Sendable Type:

There are mutable states like variables, properties inside the tasks called as Concurrency domain. As these variables, properties (Concurrency domain) keep changing so they can’t be shared between each other because of thread safety (incorrect results). A type that can be shared from one concurrency domain to another is known as a sendable type.

Please do clap if you find something new and helpful in read and will see you with next article.

Swift
iOS
Basics Of Programming
Swiftui
Recommended from ReadMedium