Linear Search is the process of finding the index of given element in the given array
Let’s starts with naive approach
let nums = [1,2,3,4,5]let numToFind = 5for i in 0..<nums.count {
if numToFind == nums[i] {
print("Found at \(i)")
}
}// prints Found at 4
Above code prints the index of the element if it present in the list of nums
Take Away
- Variables in swift are declared using
var
keyword - Constants in swift are declared using
let
keyword - All types of arrays follows Arrays structure which has
count
property that returns number of elements in the Collection
Using Extension
Extensions are powerful features in Swift, where we can define functions and properties that can be used by variables/constants of same type
extension Array where Element:Equatable {
func indexOf(_ num:Element) -> Int {
for i in 0..<self.count{
if self[i] == num {
return i
}
}
return -1
}
}let indexOfOne = nums.indexOf(1)
// prints 0let indexOfNinetyNine = nums.indexOf(99)
// prints -1
However, return -1 is not obvious if we use the index to process some other task. Here comes, Optionals to the Rescue. Rewriting the above code using Optionals.
extension Array where Element:Equatable {
func indexOf(_ num:Element) -> Int? {
for i in 0..<self.count{
if self[i] == num {
return i
}
}
return nil
}
}let indexOfOne = nums.indexOf(1)
// prints Optional(0)let indexOfNinetyNine = nums.indexOf(99)
// prints nil
We can unwrap and get the value of optionals using !
operator as indexOfOne!
unwrapping nil values throws errors
Take Away:
1. where
clause is a Generic Concept in Swift. Above snippet can be referred as Any array that has Equatable type of contents can access indexOf function.
2. Optionals are used to mitigate potential null values and safely handling them
Functions in Swift:
- Functions in Swift starts with
func
keyword followed by open and close parenthesis - Between parenthesis functions define parameters they operate on.
- Each parameter can have two names, first name is referred by calling function and second name is referred inside the function
func increment(by num:Int)
- First name shall be ignore used
_
sign(Don’t Care) - Then follows arrow mark and return type of the function
func increment(by num:Int)->Int{
return 5+num
}let fivePlusOne = increment(by : 1)
Thanks for Reading.
Pls provide suggestion in the comments section if any.