0
1

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 1 year has passed since last update.

if var

if var ・・・と 書けることをご存知ですか?
 

オプショナル型をアンラップする場合にif let ・・・と書きますが、if var ・・・もアンラップします。
違いは、受け取る”変数”がミュータブル(書き換え可能)だということです。

”変数”と書いた時点で ミュータブル(mutable) ですね。
イミュータブル(immutable) なら"定数"と書きますから・・・

let optInt: Int? = 10

if let int = optInt {
    print(int)  // 10
}

if var int = optInt {
    print(int)  // 10
    int = 20
    print(int)  // 20
}

for var

for var ・・・と 書けることをご存知ですか?
 

意味は同じで、 ”変数”(ミュータブル)に受け取ります。

for var a in 0 ..< 10 {
    a = 0
    print(a)  // always 0
}

でも、for let ・・・とは 書けません。

for let a in 0 ..< 10 {
// 'let' pattern cannot appear nested in an already immutable context
}

『すでにイミュータブルだから被せるな』的に怒られます。

おまけ

for x: 型 in ・・・と、型名を指定できることをご存知ですか?
 

左辺の型と違う型の定数(変数)で受け取りたい場合に指定します。
もちろん、for varとの組み合わせも可能です。

for x: UInt8 in 0 ..< 10 {
    print(type(of: x)) // UInt8
}


しかし、キャストできない型を書くと、何かしらのエラーになります。

for x: UInt8 in -10 ..< 10 {
//Negative integer '-10' overflows when stored into unsigned type 'UInt8'
}

次のようにCharacterで受け取りたいですが、エラーになります。

for x: Character in 0 ..< 256 {
//Cannot convert sequence element type 'Int' to expected type 'Character'
}

extension Character {
    init(_ int: Int) { self = Character(Unicode.Scalar(int)!) }
}

Intを引数に取るCharacterイニシャライザを定義していてもエラーです。
イニシャライザを呼ぶわけではなく、あくまで『キャストできる型に限る』ということです。



当然ですが、左辺のSequenceArray<Character>に変換してやれば、普通にCharacterで受け取れます。

for x in (0 ..< 256).map(Character.init) {
    if x.isCurrencySymbol { print(x) }
}
// $
// ¢
// £
// ¤
// ¥


 

おまけ の おまけ

let,varwhileを組み合わせて、
while let 定数 = while var 変数 = とも書けます。

var optInt: Int? = 10

while let int = optInt {      }
while var int = optInt {      }

使い道が思い浮かびませんが、知っていると役に立つ場面があるかも・・・


Swiftって面白い言語ですね。

以上です。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?