LoginSignup
5
5

More than 5 years have passed since last update.

Swiftでジェネリッククラスを書いてみた

Posted at

どこかの記事でclassはジェネリックを使えないみたいなことを書いてあったのでためしに書いてみた。

Stack.swift
class Stack<T> {
    var array : T[] = T[]()

    func count() -> Int {
        return array.count
    }

    func push(item: T) {
        array += item
    }

    func pop() {
        if(array.count > 0){
            array.removeLast()
        }
    }

    func top() -> T? {
        if(array.count > 0){
            return array[array.count - 1]
        }
        return nil
    }
}

var stack = Stack<Int>()

stack.push(1)
stack.push(2)
stack.push(3)

println(stack.top())
stack.pop()
println(stack.top())
stack.pop()
println(stack.top())
stack.pop()
println(stack.top())

これをコンソールで実行した結果が下記。

3
2
1
nil

classでもジェネリックは書けるようです。
というメモ。

5
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5