Skip to content

Instantly share code, notes, and snippets.

@kashiftriffort
Last active May 6, 2020 05:44
Show Gist options
  • Save kashiftriffort/c91f29459954a11c2315204e7559de67 to your computer and use it in GitHub Desktop.
Save kashiftriffort/c91f29459954a11c2315204e7559de67 to your computer and use it in GitHub Desktop.
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