Contents

Swift Data Types

In any programming language, data types are crucial for determining the type of data stored in a variable. In Swift, variables are used to store data, and their type determines what kind of data they hold. This helps the operating system allocate appropriate memory and ensures that only the correct type of data is stored. For instance, an integer variable can only hold integer values, not strings. Swift supports the following primary data types:
Int, String, Float, Double, Bool, and Character.

Integer and Floating-Point Numbers

Integers are whole numbers that can be positive, negative, or zero. They do not contain fractional components. In programming, integers are classified as:

  • Unsigned integers (UInt): Zero or positive numbers.
  • Signed integers (Int): Can include negative numbers.

Swift provides integers in various bit sizes: 8-bit, 16-bit, 32-bit, and 64-bit. The naming convention follows a pattern similar to C. For example:

  • A signed 16-bit integer is represented as Int16.
  • An unsigned 8-bit integer is represented as UInt8.
Integer Bounds

The following table shows the minimum and maximum values for each integer type:

Integer TypeMinMax
UInt80255
UInt16065,535
UInt3204,294,967,295
UInt64018,446,744,073,709,551,615
Int8-128127
Int16-32,76832,767
Int32-2,147,483,6482,147,483,647
Int64-9,223,372,036,854,775,8089,223,372,036,854,775,807

Swift also provides two additional types:

  • Int: Platform-native integer, equivalent to Int32 on 32-bit platforms and Int64 on 64-bit platforms.
  • UInt: Platform-native unsigned integer, similar to UInt32 or UInt64 depending on the platform.
Finding Minimum and Maximum Values

Swift allows us to find the bounds of integer types using the .min and .max properties. Here’s an example:

Example:

				
					print("Integer Type        Min                    Max")
print("UInt8           \(UInt8.min)         \(UInt8.max)")
print("UInt16          \(UInt16.min)        \(UInt16.max)")
print("UInt32          \(UInt32.min)        \(UInt32.max)")
print("UInt64          \(UInt64.min)        \(UInt64.max)")
print("Int8            \(Int8.min)          \(Int8.max)")
print("Int16           \(Int16.min)         \(Int16.max)")
print("Int32           \(Int32.min)         \(Int32.max)")
print("Int64           \(Int64.min)         \(Int64.max)")

				
			

Output:

				
					Integer Type        Min                    Max
UInt8               0                     255
UInt16              0                     65535
UInt32              0                     4294967295
UInt64              0                     18446744073709551615
Int8               -128                   127
Int16              -32768                 32767
Int32              -2147483648            2147483647
Int64              -9223372036854775808   9223372036854775807

				
			
Floating-Point Numbers

Floating-point numbers can represent both integers and numbers with fractional components. Swift provides two types of floating-point numbers:

TypeBit SizeDecimal Precision
Double64-bitUp to 15 decimal places
Float32-bitUp to 6 decimal places

These numbers can represent values like: 5.67, 0.0, 12345.6789, etc.

Examples

				
					// Using Double
var largeDecimal: Double = 12345.6789012345
print("Double value is:", largeDecimal)

// Using Float
var smallDecimal: Float = 5.6789
print("Float value is:", smallDecimal)

				
			

Output:

				
					Double value is: 12345.6789012345  
Float value is: 5.6789  

				
			

Strings in Swift

Strings in Swift are collections of characters. For example, "Hello, World!" is a string. Swift strings are Unicode-compliant and case-insensitive. They are encoded using UTF-8, which defines how Unicode data is stored in bytes.

In Swift, strings are a fundamental data type and are often implemented as an array of characters. They can also represent more general collections or sequences of data elements.

Creating a String

Strings in Swift can be created using string literals, the String keyword, or the String initializer.

Syntax:

				
					var str: String = "Hello, Swift!"
var str2 = "Swift Programming"

				
			

Examples:

				
					// String creation using string literal
var greeting = "Welcome to Swift Programming"
print(greeting)

// String creation using String instance
var message = String("This is an example")
print(message)

// String creation using String keyword
var note: String = "Enjoy Coding"
print(note)

				
			

Output:

				
					Welcome to Swift Programming  
This is an example  
Enjoy Coding  

				
			
Multi-Line String

A multi-line string spans multiple lines and is enclosed in triple double quotes.

Syntax:

				
					"""
This is a
multi-line string
example in Swift.
"""

				
			

Example:

				
					let multilineString = """
Swift strings are versatile.
You can create multi-line strings
easily with triple quotes.
"""

print(multilineString)

				
			

Output:

				
					Swift strings are versatile.  
You can create multi-line strings  
easily with triple quotes.  

				
			
Empty String

An empty string is a string with no characters. You can create an empty string using either "" or the String() initializer.

Syntax:

				
					var emptyStr = ""
var anotherEmptyStr = String()

				
			

Example:

				
					var empty = ""
if empty.isEmpty {
    print("The string is empty.")
}

let anotherEmpty = String()
if anotherEmpty.isEmpty {
    print("This is also an empty string.")
}

				
			

Output:

				
					The string is empty.  
This is also an empty string.  

				
			
String Concatenation

Strings can be concatenated using various methods:

1. Addition Operator (+):

				
					var result = str1 + str2

				
			

2. Addition Assignment Operator (+=):

				
					result += str2

				
			

3. Append Method:

				
					str1.append(str2)

				
			

Example:

				
					let part1 = "Swift "
let part2 = "is powerful."

// Using +
var sentence = part1 + part2
print(sentence)

// Using +=
var phrase = "Learning "
phrase += "Swift is fun."
print(phrase)

// Using append()
var text = "Hello"
text.append(", Swift!")
print(text)

				
			

Output:

				
					Swift is powerful.  
Learning Swift is fun.  
Hello, Swift!  

				
			
String Comparison

Strings can be compared using the == (equal to) or != (not equal to) operators.

Syntax:

				
					string1 == string2
string1 != string2

				
			

Example:

				
					let stringA = "Swift Programming"
let stringB = "Learning Swift"

if stringA == stringB {
    print("The strings are equal.")
} else {
    print("The strings are not equal.")
}

				
			

Output:

				
					The strings are not equal.
				
			
String Length

The length of a string can be determined using the count property.

Example:

				
					let text = "Swift Language"
print("The length of '\(text)' is \(text.count).")

				
			

Output:

				
					The length of 'Swift Language' is 14.  

				
			
String Interpolation

String interpolation allows mixing variables, constants, and expressions into a string.

Syntax:

				
					let str = "Swift \(version)"

				
			

Example:

				
					let value = 42
let multiplier = 2
print("The result of \(value) times \(multiplier) is \(value * multiplier).")

				
			

Output:

				
					The result of 42 times 2 is 84.  

				
			
String Iteration

Strings can be iterated over using a for-in loop.

Example:

				
					for char in "Swift" {
    print(char, terminator: " ")
}

				
			

Output:

				
					S w i f t  
				
			
Common String Functions and Properties
NameDescription
isEmptyChecks if the string is empty.
hasPrefixChecks if the string starts with the specified prefix.
hasSuffixChecks if the string ends with the specified suffix.
countReturns the length of the string.
utf8Returns the UTF-8 representation of the string.
insert(_:at:)Inserts a value at a specified position.
remove(at:)Removes a value at a specified position.
reversed()Returns the reversed string.

Example:

				
					let sample = "Swift Language"

// Using isEmpty
print("Is string empty? \(sample.isEmpty)")

// Using hasPrefix
print("Does string start with 'Swift'? \(sample.hasPrefix("Swift"))")

// Using reversed()
print("Reversed string: \(String(sample.reversed()))")

				
			

Output:

				
					Is string empty? false  
Does string start with 'Swift'? true  
Reversed string: egaugnaL tfiwS  

				
			

String Functions and Operators in Swift

A string is a sequence of characters that can either be a literal constant or a variable. For example, "Hello World" is a string of characters. Swift strings are Unicode-correct and locale-insensitive. They support various operations like comparison, concatenation, iteration, and more.

Creating Strings in Swift

You can create strings in Swift using either a String instance or a string literal.

1. Using String() Initializer: The String() initializer creates a string instance.

Syntax:

				
					var str = String("Example String")

				
			

Example:

				
					// Using String() initializer
var greeting = String("Welcome to Swift!")
print(greeting)

				
			

Output:

				
					Welcome to Swift!

				
			

2. Using String Literal: Double quotes are used to create string literals, similar to other programming languages.

Syntax:

				
					var str = "Hello"
var strTyped: String = "World"

				
			

Examples:

				
					// Creating strings using literals
var message = "Learning Swift is fun!"
print(message)

var typedMessage: String = "Swift Programming"
print(typedMessage)

				
			

Output:

				
					Learning Swift is fun!
Swift Programming

				
			
Multi-line Strings 

Swift supports multi-line strings using triple double quotes (""").

Syntax:

				
					Learning Swift is fun!
Swift Programming

				
			

Examples:

				
					// Multi-line string example
let paragraph = """
Welcome to Swift!
This example demonstrates
multi-line strings.
"""
print(paragraph)

				
			

Output:

				
					Welcome to Swift!
This example demonstrates
multi-line strings.

				
			
String Properties and Functions

Empty String: An empty string has no characters and a length of zero.

Example:

				
					// Creating an empty string
var emptyLiteral = ""
var emptyInstance = String()

print("Is emptyLiteral empty? \(emptyLiteral.isEmpty)")
print("Is emptyInstance empty? \(emptyInstance.isEmpty)")

				
			

Output:

				
					Is emptyLiteral empty? true
Is emptyInstance empty? true

				
			

String Length: The count property returns the total number of characters in a string.

Example:

				
					// Counting characters in a string
let text = "Swift Programming"
let length = text.count
print("The length of the text is \(length)")

				
			

Output:

				
					The length of the text is 18

				
			
String Operations

1. Concatenation: The + operator concatenates strings.

Example:

				
					// Concatenating strings
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
print("Full Name: \(fullName)")

				
			

Output:

				
					Full Name: John Doe

				
			

2. Comparison: Use == to check equality and != to check inequality.

Example:

				
					let a = "Swift"
let b = "Swift"
let c = "Python"

// Equality
print(a == b)  // true

// Inequality
print(a != c)  // true

				
			

Output:

				
					true
true

				
			
String Functions:

1. hasPrefix and hasSuffix: Check if a string starts or ends with a specific substring.

Example:

				
					let sentence = "Learning Swift"
print(sentence.hasPrefix("Learn"))  // true
print(sentence.hasSuffix("Swift")) // true

				
			

Output:

				
					true
true

				
			

2. lowercased() and uppercased(): Convert all characters in a string to lowercase or uppercase.

Example:

				
					let text = "Swift Programming"
print(text.lowercased())  // "swift programming"
print(text.uppercased())  // "SWIFT PROGRAMMING"

				
			

Output:

				
					swift programming
SWIFT PROGRAMMING

				
			

3. reversed(): Reverse the characters of a string.

Example:

				
					let word = "Swift"
let reversedWord = String(word.reversed())
print("Original: \(word)")
print("Reversed: \(reversedWord)")

				
			

Output:

				
					Original: Swift
Reversed: tfiwS

				
			

4. insert(_:at:): Insert a character at a specified position.

Example:

				
					var phrase = "Swift Programming"
phrase.insert("!", at: phrase.endIndex)
print(phrase)

				
			

Output:

				
					Swift Programming!

				
			

5. remove(at:): Remove a character at a specific index.

Example:

				
					var text = "Hello Swift!"
let index = text.index(text.startIndex, offsetBy: 6)
let removedCharacter = text.remove(at: index)
print("Modified text: \(text)")
print("Removed character: \(removedCharacter)")

				
			

Output:

				
					Modified text: Hello Sift!
Removed character: w

				
			

Data Type Conversions in Swift

Type Conversion in Swift

Type Conversion refers to the process of converting a variable or value from one data type to another. This allows instances to be checked and cast to specific class types. In Swift, type conversion is often performed during compile-time by the XCode compiler, provided the data types are compatible (e.g., integer, string, float, double).

Type conversion involves explicitly casting a value to a different data type using the desired type as a function. For instance:

				
					var stringToFloatNum: Float = Float(67891)!

				
			

Syntax:

				
					var <variable_name>: <data_type> = <convert_data_type>(<value>)

				
			

1. Convert Integer to String: This program converts an integer value to a string and displays the result with its type.

Example:

				
					import Swift

var intNumber: Int = 789

var intNumberToString: String = String(intNumber)

print("Integer Value = \(intNumber) of type \(type(of: intNumber))")
print("String Value = \(intNumberToString) of type \(type(of: intNumberToString))")

				
			

Output:

				
					Integer Value = 789 of type Int
String Value = 789 of type String

				
			

2. Convert String to Integer: This program converts a string value to an integer and displays the result with its type.

Example:

				
					import Swift

var intNum: Int = 789

var intNumToFloat: Float = Float(intNum)

print("Integer Value = \(intNum) of type \(type(of: intNum))")
print("Float Value = \(intNumToFloat) of type \(type(of: intNumToFloat))")

				
			

Output:

				
					String Value = 789 of type String
Integer Value = 789 of type Int

				
			

3. Convert String to Integer: This program converts a string value to an integer and displays the result with its type.

Example:

				
					import Swift

var string: String = "789"

var stringToInt: Int = Int(string)!

print("String Value = \(string) of type \(type(of: string))")
print("Integer Value = \(stringToInt) of type \(type(of: stringToInt))")

				
			

Output:

				
					String Value = 789 of type String
Integer Value = 789 of type Int

				
			

4. Convert Integer to Float: This program converts an integer value to a float and displays the result with its type.

Example:

				
					import Swift

var intNum: Int = 789

var intNumToFloat: Float = Float(intNum)

print("Integer Value = \(intNum) of type \(type(of: intNum))")
print("Float Value = \(intNumToFloat) of type \(type(of: intNumToFloat))")

				
			

Output:

				
					Integer Value = 789 of type Int
Float Value = 789.0 of type Float

				
			

5. Convert Float to Integer: This program converts a float value to an integer and displays the result with its type.

Example:

				
					import Swift

var floatNum: Float = 789.0089

var floatNumToInt: Int = Int(floatNum)

print("Float Value = \(floatNum) of type \(type(of: floatNum))")
print("Integer Value = \(floatNumToInt) of type \(type(of: floatNumToInt))")

				
			

Output:

				
					Float Value = 789.0089 of type Float
Integer Value = 789 of type Int

				
			

6. Convert String to Float: This program converts a string value to a float and displays the result with its type.

Example:

				
					import Swift

var string: String = "789"

var stringToFloatNum: Float = Float(string)!

print("String Value = \(string) of type \(type(of: string))")
print("Float Value = \(stringToFloatNum) of type \(type(of: stringToFloatNum))")

				
			

Output:

				
					String Value = 789 of type String
Float Value = 789.0 of type Float

				
			

Convert String to Int Swift

In Swift, you can convert a string into an integer using various methods. However, only numeric strings can be successfully converted to integers. Below are two common methods to perform this conversion.

Declaring a String Variable

A string in Swift is a collection of characters and can be declared using the String data type.

Syntax:

				
					let myVariable: String

				
			

Example:

				
					let myVariable = "Hello"

				
			
Methods for String to Integer Conversion

1. Using Int Initializer Swift provides an initializer function for integers that can convert a string to an Int. This initializer returns an optional integer. To handle non-numeric strings, you can use the nil-coalescing operator to provide a default value, such as 0.

Example:

				
					// Converting a numeric string
let myStringVariable = "25"
let myIntegerVariable = Int(myStringVariable) ?? 0
print("Integer Value:", myIntegerVariable)

// Converting a non-numeric string
let myStringVariable2 = "Hello"
let myIntegerVariable2 = Int(myStringVariable2) ?? 0
print("Integer Value:", myIntegerVariable2)

				
			

Output:

				
					Integer Value: 25
Integer Value: 0

				
			

2. Using NSString:The NSString class in Swift allows strings to be passed by reference and includes the integerValue property, which can be used to convert an NSString to an integer.

Example:

				
					import Foundation

let myString = "25"

// Converting a string to NSString and then to an integer using integerValue
let myIntegerVariable = (myString as NSString).integerValue
print("Integer Value:", myIntegerVariable)

				
			

Output:

				
					Integer Value: 25