Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift]カウンタクラスを作ってみた[暇つぶし]

Last updated at Posted at 2014-06-14

Infinite loop in getterという記事をみて、カウンタクラス(整数を順番にかえすだけのクラス)を作ってみたくなったので作ってみた。

正攻法

とりあえず、正攻法で以下のように書いた。

Counter.swift
class BaseCounter {
    var __counter = 0

    var counter: Int {
        get {
            return __counter++
        }
    }
    
}

let c = BaseCounter()

println(c.counter)
println(c.counter)
println(c.counter)
println(c.counter)

まあそれなりに動くのだが、

c.__counter = 0

とか、カウンタの値を外側から直接書き換えられるのがイマイチ。
(privateとか出来ないのかな…?)

クロージャ

そこで、クロージャ(関数閉包)を使って書き換えてみたのが以下。

Counter.swift(その2)
class Counter {
    
    func CountUp() -> (() -> Int) {
        var count = 0
        func c() -> Int {
            return count++
        }
    
        return c;
    }

    let f : (() -> Int)?
    
    init(){
        f = CountUp()
    }
    
    var counter : Int {
        get {
            return f!()
        }
    }
}

let c = Counter()

println(c.counter)
println(c.counter)
println(c.counter)
println(c.counter)
println(c.counter)

これでも、

c.f!()

のように、クロージャに直接アクセスは可能だが、カウンタをゼロに戻すことは出来ないからいい……ことにしておく。

追記:無名関数

どうにかして、もっと短くかけないか頑張ってみた。
無名関数の後ろに()をつけられることに気づいたので、ちょっと短くできた。

Counter.swift(その3)
class Counter {
    let f = { () -> (() -> Int) in
        var count = 0
        func c() -> Int {
            return count++
        }
        return c;
    }()
    
    var counter : Int {
        get {
            return f()
        }
    }
}


let c = Counter()

println(c.counter)
println(c.counter)
println(c.counter)
println(c.counter)
println(c.counter)
2
3
5

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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?