Reputation:
I just started learning Swift by following the Apple documentation. Here is an example from documentation.
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
I have query on printing statement. I dont get it that \(names[i])
,
can somebody please explain?
I know string interpolation also some (for in)
loop too when we loop through each item.
but I don't understand \(names[i])
Upvotes: 2
Views: 1160
Reputation: 981
When you put a number in brackets like this: names[3], it means you want the value in the names array from the 3rd position. Remember arrays start with 0 so the 3rd position would be the fourth number in the array list.
The i means you want the number in there to change for each loop. So the first time the loop runs it will run like names[0] and then the second time it runs it will run like names[1] and it will continue like this until the loop completes.
The \names[i] means your putting a variable in the middle of a string. So if you wanted to print a normal string you would use "this is a string" but if you wanted to print a string with a variable in the middle you could do this:
let variable = "long variable"
Print("this is a string with a \(variable)")
And it would print out: this is a string with a long variable
EDIT: if you want to print each value of array on separate line there are two ways to do it.
The first is:
For item in names
{
Print(item)
}
Or you can do:
For i in 0..<names.count
{
Print(names[i])
}
Upvotes: 1