Generics
Generic Collections
Arrays are generic collections, so helper functions can preserve the element type they receive.
Work with element type
generic_collections.swift
func repeated<T>(_ value: T, count: Int) -> [T] {
var output: [T] = []
for _ in 0..<count {
output.append(value)
}
return output
}
let repeatCount =
let values = repeated("go", count: repeatCount)
let summary = values.joined(separator: ",")
print(summary)
func repeated<T>(_ value: T, count: Int) -> [T] {
var output: [T] = []
for _ in 0..<count {
output.append(value)
}
return output
}
let repeatCount =
let values = repeated("go", count: repeatCount)
let summary = values.joined(separator: ",")
print(summary)
func repeated<T>(_ value: T, count: Int) -> [T] {
var output: [T] = []
for _ in 0..<count {
output.append(value)
}
return output
}
let repeatCount =
let values = repeated("go", count: repeatCount)
let summary = values.joined(separator: ",")
print(summary)
generic collection
Generic collection helpers describe a relationship between the element type and the returned value.