Git Hub
коротко

Swift: Generics (Дженерики)

12 января 2017, 14:09

Пример Generics в функции

class GenericsDemo {
    class func swap<T>(_ a: inout T,_ b: inout T){
        let temp = a
        a = b
        b = temp
    }
}

var n1 = 100
var n2 = 200

GenericsDemo.swap(&n1, &n2)

var s1 = "s1"
var s2 = "s2"

print("s1=\(s1) <-> s2=\(s2)")
GenericsDemo.swap(&s1, &s2)
print("swap\ns1=\(s1) <-> s2=\(s2)")

Genereics в типах

protocol Container {
   typealias ItemType
   mutating func append(item: ItemType)
   var count: Int { get }
   subscript(i: Int) -> ItemType { get }
}

struct TOS<T>: Container {
   // original Stack<T> implementation
   var items = [T]()
   mutating func push(item: T) {
      items.append(item)
   }
   
   mutating func pop() -> T {
      return items.removeLast()
   }

   // conformance to the Container protocol
   mutating func append(item: T) {
      self.push(item)
   }
   
   var count: Int {
      return items.count
   }

   subscript(i: Int) -> T {
      return items[i]
   }
}

var tos = TOS<String>()
tos.push("Swift")
println(tos.items)

tos.push("Generics")
println(tos.items)

tos.push("Type Parameters")
println(tos.items)

tos.push("Naming Type Parameters")
println(tos.items)
Поделиться
Популярное