LoginSignup
5
5

More than 5 years have passed since last update.

力試し:SwiftのOptionalでこれできますか? にチャレンジ

Last updated at Posted at 2015-02-10

サクッとやってみました(Swift 1.1)

元記事はこちらです。
http://qiita.com/koher/items/627a90017e3d4be1dd5b

まずはシンプルなカスタムオペレータを定義します。

infix operator >>> { associativity left }
public func >>><T, U>(optional: T?, f: T -> U?) -> U? {
    if let x = optional {
        return f(x)
    } else {
        return nil
    }
}

次にそれを使って問題を解決します。

// 1.
func function1(x: Double?) -> Double? {
    return x >>> { sqrt($0) }
}
println("1. ---")
println(function1(nil))
println(function1(2.0))

// 2.
func function2(x: String?) -> Int? {
    return x?.toInt()
}
println("2. ---")
println(function2(nil))
println(function2("10"))

// 3.
func safeSqrt(x: Double) -> Double? {
    return x < 0.0 ? nil : sqrt(x)
}

func function3(x: Double?) -> Double? {
    return x >>> safeSqrt
}
println("3. ---")
println(function3(nil))
println(function3(-2.0))
println(function3(2.0))

// 4.
func function4(a: Int?, b: Int?) -> Int? {
    return a >>> { a in
        b >>> { b in
            a + b
        }
    }
}
println("4. ---")
println(function4(nil, nil))
println(function4(nil, 2))
println(function4(1, nil))
println(function4(1, 2))

// 5.
func function5(a: Int?) {
    if let a = a {
        println(a)
    }
}
println("5. ---")
function5(nil)
function5(2)
function5(nil)
function5(1)

出力

1. ---
nil
Optional(1.4142135623731)
2. ---
nil
Optional(10)
3. ---
nil
nil
Optional(1.4142135623731)
4. ---
nil
nil
nil
Optional(3)
5. ---
2
1

はい、完全に

functional programming in swift
http://www.objc.io/books/

から得たものをほとんどそのまま書いているだけです。すみません。

5
5
0

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