Reputation: 5593
I'm doing the A Swift Tour.
One:
I'm not getting the Generics
functions logic. Its for Design Patterns
? And the explanation on the tour looks very short and unclear.
Two:
In this pice of code for creating a generic function,
func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes { //im not getting this line (?)
result.append(item)
}
return result
}
repeatItem("knock", numberOfTimes:4)
I do not understand this syntax very well, what means _
, ..
, and <
in the same line, why is used?
Upvotes: 2
Views: 5232
Reputation: 2469
for _ in 0..<numberOfTimes {
(something)
}
Is equivalent to:
for(var nameForWhichIdontCare = 0; nameForWhichIDontCare < numberOfTimes {
(something)
}
So:
_
is used in places where a name is required but you dont care, so basically discarding the name from the beginning.
..<
is a range up to a number.
...
is a range up to and including a number.
Upvotes: 0
Reputation: 7906
_
, ..
, and <
are not part of the generics.
_
is just an non-name for a parameter that is never used.
usually you would put a variable name like i
there and use it in the block but as you are just doing something a certain number of times you are not really using the index.
..<
is a shorthand for the range between the start value and the end value. 1..<5
would then generate the range 1,2,3,4
there is also a range shorthand ...
that gives you the last value 5
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner. Generics
Upvotes: 6
Reputation: 93161
Consider the old school for
loop in C:
for var i = 0; i < numberOfTimes; i++ {
result.append(item)
}
Yuck, a lot of code just to repeat result.append(item)
for numberOfTimes
! Swift has a shorthand syntax: a..<b
means "iterate from a to less than b" so your for
loop can be rewritten as:
for i in 0..<numberOfTimes {
result.append(item)
}
But then you don't use i
inside the body of the loop either. All you want is to repeat it numberOfTimes
. So you don't care what name the iterator takes: i
, x
or z
. Hence you don't even need to declare it, just replace it with a _
:
for _ in 0..<numberOfTimes {
result.append(item)
}
Upvotes: 2
Reputation: 3253
When you don't use a variable anywhere else, you can use an underscore. So if you're looping over some range of numbers, and you're not using the index, then you can use a _
. It's just syntax sugar.
The 0..<4
means means start counting at 0, and count up to 4-1=3. You can include the last number using 0...4
, which would mean *start counting at 0, and count up to 4`.
for i in 0..<4 {
print(i)
} // prints 0, 1, 2, 3
While,
for i in 0...4 {
print(i)
} // prints 0, 1, 2, 3, 4
Upvotes: 2