Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Optional皆伝

touyou
October 29, 2016

 Optional皆伝

http://qiita.com/koher/items/c6f446bad54442a28bf4
この記事を参考にSwiftのOptional型についてまとめさせていただきました。

touyou

October 29, 2016
Tweet

More Decks by touyou

Other Decks in Programming

Transcript

  1. ⟃♴ך״ֲז儗ծ֮ז׋ז׵וֲ剅ֹתַׅ ˖ B*OU ָ֮׷הֹծBך⦼׾✳⛦׃׋ְկ׋׌׃ծBָOJMך㜥さכOJM׾䖤׋ְկ ˖ BSSBZ<*OU> ָ֮׷הֹծBSSBZך剑ⴱך銲稆׾《䖤׃׋ְկ׋׌׃ծBSSBZָOJMַծ 剑ⴱך銲稆ָ㶷㖈׃זְ"SSBZָ瑞ך㜥さכOJM׾䖤׋ְկؼٝز<*OU>כSTU *OU הְֲفٗػذ؍׾䭯אկSTUכ剑ⴱך銲稆ָ㶷㖈׃זְ㜥さכOJM׾鵤ׅկ

    ˖ Y%PVCMF ָ֮׷הֹծYך䎂倯呎׾鎘皾׃׋ְկ׋׌׃ծYָOJMת׋כ頾ך侧ך㜥 さכOJM׾䖤׋ְկזֶծTRSU׾㸜Ⰻח׃׋頾ך侧׾床ׅהOJM׾鵤ׅꟼ侧 TBGF4RSU%PVCMF%PVCMF ָ֮׷׮ךה׃ג罋ִג葺ְկ ˖ B*OU הC*OU ָ֮׷הֹծB C׾鎘皾׃׋ְկ׋׌׃ծBַCָOJMך㜥さחכ OJM׾䖤׋ְկ
  2. ٌشس⵱ ˖ 'PP Y BU.BQ G G Y  ˖

    GPPBU.BQ\'PP  ^GPP ˖ GPPBU.BQ\G  BU.BQ H ^GPPBU.BQ G BU.BQ H
  3. 䭁䓸ך⢽ extension Optional { public func reduce<U>(_ initial: U, combine:

    (U, Wrapped) -> U) -> U { switch self { case .none: return initial case .some(let value): return combine(initial, value) } } public func filter(_ includeElement: @escaping (Wrapped) -> Bool) -> Wrapped? { return flatMap { includeElement($0) ? $0 : nil } } public func forEach(_ action: (Wrapped) -> ()) { reduce(()) { action($1) } } }
  4. ⟃♴ך״ֲז儗ծ֮ז׋ז׵וֲ剅ֹתַׅ ˖ B*OU ָ֮׷הֹծBך⦼׾✳⛦׃׋ְկ׋׌׃ծBָOJMך㜥さכOJM׾䖤׋ְկ ˖ BSSBZ<*OU> ָ֮׷הֹծBSSBZך剑ⴱך銲稆׾《䖤׃׋ְկ׋׌׃ծBSSBZָOJMַծ 剑ⴱך銲稆ָ㶷㖈׃זְ"SSBZָ瑞ך㜥さכOJM׾䖤׋ְկؼٝز<*OU>כSTU *OU הְֲفٗػذ؍׾䭯אկSTUכ剑ⴱך銲稆ָ㶷㖈׃זְ㜥さכOJM׾鵤ׅկ

    ˖ Y%PVCMF ָ֮׷הֹծYך䎂倯呎׾鎘皾׃׋ְկ׋׌׃ծYָOJMת׋כ頾ך侧ך㜥 さכOJM׾䖤׋ְկזֶծTRSU׾㸜Ⰻח׃׋頾ך侧׾床ׅהOJM׾鵤ׅꟼ侧 TBGF4RSU%PVCMF%PVCMF ָ֮׷׮ךה׃ג罋ִג葺ְկ ˖ B*OU הC*OU ָ֮׷הֹծB C׾鎘皾׃׋ְկ׋׌׃ծBַCָOJMך㜥さחכ OJM׾䖤׋ְկ
  5. ♧菙涸鍑瘶 // 1൪ var result: Int? if let a0 =

    a { result = a0 * a0 } else { result = nil } // or result = a == nil ? nil : a! * a!
  6. ♧菙涸鍑瘶 // 2൪ if let array0 = array { if

    let first = array0.first { result = first } else { result = nil } } else { result = nil } // Int??ʹͳΔ͚Ͳ... var result2: Int?? = array.map { $0.first }
  7. ♧菙涸鍑瘶 // 3൪ if let x0 = x { resultDouble

    = safeSqrt(x0) } else { resultDouble = nil } // Double??ʹͳΔ͚Ͳ... let result3: Double?? = x.map { safeSqrt($0) } // ??Λ࢖͏ resultDouble = x.map { safeSqrt($0) } ?? nil
  8. ♧菙涸鍑瘶 // 4൪ if let a0 = a { if

    let b0 = b { result = a0 + b0 } else { result = nil } } else { result = nil } // Int??ʹͳΔ͚Ͳ... result2 = a.map { a0 in b.map { b0 in a0 + b0 } }