Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic in Swift
// Find index position of item using Generic
func genericFindItem() {
let names = ["A", "B", "C", "D", "E"]
if let result = self.findItem(of: "D", in: names) {
print(result)
}
}
func findItem<T: Equatable>(of foundItem: T, in items: [T]) -> Int? {
for(index, item) in items.enumerated() {
if item == foundItem {
return index
}
}
return nil
}
// Pass value as array in Generic
func genericPassArray() {
printArray(array: ["1", "2", "3", "4"])
printArray(array: [1, 2, 3, 4])
printArray(array: [1.1, 1.2, 1.3, 1.4])
}
func printArray<T>(array: [T]) {
print(array)
}
// Usage of Generic in Struct
func genericRandom() {
let randomIntegers = RandomContainer(items: [1, 2, 3, 4, 5, 6, 7])
print(randomIntegers.getRandom())
let randomStrings = RandomContainer(items: ["a", "b", "c", "d", "e"])
print(randomStrings.getRandom())
}
struct RandomContainer<T> {
var items = [T]()
func getRandom() -> T {
let randomIndex = Int(arc4random_uniform(UInt32(items.count)))
return items[randomIndex]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment