5
5

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のOptionalでこれできますか? に挑戦

Last updated at Posted at 2015-02-10

こちらに挑戦してみました。
Optional.mapを使いたかったのでQ3, 4あたりは簡潔かどうかは怪しいですが。。。

playground
// Playground - noun: a place where people can play

import UIKit

func Q1() {
    
    func ans(a: Int?) -> Int? {
        return a.map { $0 * $0 }
    }
    
    println(ans(2))
    println(ans(nil))
}

func Q2() {
    
    func ans(s: String?) -> Int? {
        return s?.toInt()
    }
    
    println(ans("2"))
    println(ans("a"))
    println(ans(nil))
}

func Q3() {
    
    func safeSqrt(x: Double) -> Double? {
        return x < 0.0 ? nil : sqrt(x)
    }
    
    func ans(x: Double?) -> Double? {
        return x.map(safeSqrt) ?? nil
    }
    
    println(ans(4))
    println(ans(0))
    println(ans(-4))
    println(ans(nil))
}

func Q4() {
    
    func ans(#a: Int?, #b: Int?) -> Int? {
        return a.map { a0 in b.map { b0 in a0 + b0 } } ?? nil
    }
    
    println(ans(a: 1, b: 2))
    println(ans(a: nil, b: 2))
    println(ans(a: 1, b: nil))
    println(ans(a: nil, b: nil))
}

func Q5() {
    
    func ans(a: Int?) {
        a.map(println)
    }
    
    ans(1)
    ans(nil)
    ans(2)
}

println("\nQ1")
Q1()
println("\nQ2")
Q2()
println("\nQ3")
Q3()
println("\nQ4")
Q4()
println("\nQ5")
Q5()

Q1
Optional(4)
nil

Q2
Optional(2)
nil
nil

Q3
Optional(2.0)
Optional(0.0)
nil
nil

Q4
Optional(3)
nil
nil
nil

Q5
1
2
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?