Bad Swift Things We Do Because We Can

I give you nested computed properties in functions:

import Foundation

func f() {
	var s: String { return "\(Date())" }
	print(s)
	sleep(2)
	print(s)
}

f()

Yeah.

Today’s is courtesy of Mike Ash.

6 Comments

  • You can even add willSet/didSet in a local variable. Handy if, for example, you want to update an NSProgress every few thousand iterations (to avoid locking costs in NSProgress) from within a hot and long-running loop.

  • MAGIC!

  • How about putting them in a loop 😉


    import Foundation

    for _ in 1...5 {
    var s: String { return "\(Date())" }

    print(s)
    sleep(2)
    print(s)
    }

  • It works great using the 8.3.2 toolchain, but it crashes the playground if you try to use the latest 2017-04-24 (a) toolchain.

  • If it’s legal, why is it a Bad Thing?

  • why is it bad thing??