開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta
- Swift (プログラミング言語)
Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 7(Types, Equality, Conversion and All That Jazz: Serious types))、SHARPEN YOUR PENCIL(p.293)をSwiftで考えてみる。
SHARPEN YOUR PENCIL(p.293)
コード(Xcode)
main.swift
// // main.swift // sample293 // // Created by kamimura on 8/25/14. // Copyright (c) 2014 kamimura. All rights reserved. // import Foundation func f<T>(a:[T?]) { for x in a { print("x = \(x), ") if x { println("true") } else { println("false") } } } var a:String? = "" var b:String? = "a" var c:String? = nil var d:String? var strs:[String?] = [a, b, c, d] f(strs) var e:Int? = 0 var f:Int? = 1 var g:Int? = 10 var h:Int? = nil var i:Int? var ints:[Int?] = [e, f, g, h, i] f(ints) var j:[Int]? = [] var k:[Int]? = [0] var l:[Int]? = nil var m:[Int]? var arrays:[[Int]?] = [j, k, l, m] f(arrays) var n:Dictionary<String, Int>? = [:] var o:Dictionary<String, Int>? = ["a":1] var p:Dictionary<String, Int>? = nil var q:Dictionary<String, Int>? var dictionaries:[Dictionary<String, Int>?] = [n, o, p, q] f(dictionaries) var r:Bool? = true var s:Bool? = false var t:Bool? = nil var u:Bool? var booleans:[Bool?] = [r, s, t, u] f(booleans) print("s = \(s), !s = \(!s): ") if !s { if s! { print("true") } else { print("false") } } println() print("s = \(s), s != nil = \(s! != nil):") if s != nil { if s { print("true") } else { print("false") } } println() if s != nil && s { println("true") } else { println("false") } println("t = \(t), t == nil = \(t == nil)")
入出力結果(Console Output)
x = Optional(""), true x = Optional("a"), true x = nil, false x = nil, false x = Optional(0), true x = Optional(1), true x = Optional(10), true x = nil, false x = nil, false x = Optional([]), true x = Optional([0]), true x = nil, false x = nil, false x = Optional([:]), true x = Optional(["a": 1]), true x = nil, false x = nil, false x = Optional(true), true x = Optional(false), true x = nil, false x = nil, false s = Optional(false), !s = false: s = Optional(false), s != nil = true:true true t = nil, t == nil = true Program ended with exit code: 0
Optionalの場合、falseでもtrueになるのが、まだ慣れなくて不思議な感じ。
0 コメント:
コメントを投稿