LoginSignup
20
18

More than 5 years have passed since last update.

Swiftで使い方がよくわからなくてググったところ

Last updated at Posted at 2014-07-05

文法系

?!の使い方がよくわからない

Swiftでは安全性のため、ある型の定数や変数にnilを代入することは禁止されている。
ある値が存在しないことを示すため変数にnilを代入可能にしたい場合には、?をつける。
?をつけた変数はOptional型と呼ばれ以下と同じ

var l: Optional<Int> = nil // var l:Int? = nil と同じ

Optional型の値からType型の値を取り出すことを、アンラップするという。
Optional型の値をアンラップするには、値のうしろに"!"を付ける。
アンラップする場合には、値が確かに存在すること(nilではないこと)を確認しなければならない。

Optional型のままだと動かない場合もあるみたい。例えば以下のコードはコンパイルエラーに。

var dict:Dictionary<String,String>? = Dictionary<String,String>()
dict["a"]="abc" //subscriptがないという理由でコンパイルエラー!

なので一度アンラップしてから触る

var dict:Dictionary<String,String>? = Dictionary<String,String>()
var dict2 = dict!
dict2["a"] = "abc"
dict = dict2 //アンラップ時は参照渡しじゃない模様

コンパイルエラーの原因は、Optional型の場合immutable(変更不可)な変数になるため
(Objective-cで言うとNSMutableDictionaryからNSDictionaryに変わるってことです。)
オブジェクトが変わるので参照渡しじゃないため再代入になるってことですね

参考:http://ja.wikipedia.org/wiki/Swift_(%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E)#Optional.E5.9E.8B

文字列処理系

文字列をTrimしたいと思った場合

var string = "      \n   "
string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

参考:http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/

その他

NSTimerでブロック構文&Swiftで使う

毎秒1秒間隔でブロック箇所の処理を実行するコード

base
[NSTimer scheduledTimerWithTimeInterval:1.0f target:[NSBlockOperation blockOperationWithBlock:^{
  NSLog(@"Timer event fired after 1.0s");
}] selector:@selector(main) userInfo:nil repeats:NO];

これをSwiftで書くと・・・・

swift版
NSTimer.scheduledTimerWithTimeInterval(1.0, target: NSBlockOperation({
    println("Timer event fired after 1.0s");
}), selector: "main" /* Selector("main") という書き方も可 */, userInfo: nil, repeats: true)

参考:http://blog.geta6.net/post/40001464316/nstimer

つづく・・・

20
18
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
20
18