Subscripts in swift

// subscripting an array.. array = [1, 2, 3, 5, 8, 13]

print(array[0]) // prints 1


print(array[1..4]) // 1..4 is the range from 1 to 4 without 4
print(array[1...4]) // 1...4 is the range from 1 to 4 including 4
// subscripting a dictionary..
var
dictionary = ["male": "I am a male"]
print(dictionary["male"]) // prints "I am a male"

Syntax: (This looks a lot like a Swift computed property.)

subscript (<parameters>) -> <return type> {
// the getter is required
get {
// used for subscript value declarations
}
set(newValue) { // the setter is optional
// definitions are written here
}
}
class daysofaweek {private var days = [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “saturday”]subscript(index: Int) -> String {
get {
return days[index]
}
set(newValue) {
self.days[index] = newValue
}
}
}
var p = daysofaweek()print(p[0]) // prints sundayp[0] = “Monday”print(p[0]) // prints Monday
struct subexample {
let decrementer: Int
subscript(index: Int) -> Int {
return decrementer / index
}
}
let division = subexample(decrementer: 100)

print("The number is divisible by \(division[9]) times")
print("The number is divisible by \(division[2]) times")
The number is divisible by 11 times
The number is divisible by 50 times

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

--

--

iOS and tvOS developer, dreamer, photographer 🤨

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhimuralidharan

Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨