3
2

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のきほん

Last updated at Posted at 2018-03-06

(随時更新)
公式のSwift Development Resourcesを参考にしています。

単純な変数

変数と定数

varを使えば変数、letを使えば定数を定義できる。

var hogeVariable = 1
let hogeConstant = 2

型について

変数や定数に代入される値によって暗黙的(implicitly)に型が予測される。

var implicitInt = 2
    -> Int型
var implicitDouble = 7.0
    -> Double型

明示的(explicitly)に型を宣言する場合、「:(セミコロン)」をつかってvar 変数名: 型名とする。

var explicitFloat: Float = 4
    -> Float型

変数の型を確認する方法

type(of: )を使用する。

(dynamicTypeやString(describing: )は使わない)
var hoge = "notHoge"
print(type(of: hoge))
    -> String

型変換は暗黙的に行われない

一度宣言した変数の値をあとから異なる型に変換したい場合は、明示的に変換したい型のインスタンスを作る必要がある。

var label = "Width is "
var width = 100

print(label + width)
    -> error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'

print(label + String(width))
    -> "Width is 100"

文字列の中に数値型の値を入れる場合、インスタンスを生成しなくても「(バックスラッシュ)」をつかって\(変数名)とする方法もある。

var apples = 3
var pineapples = 2

var appleSum = "I have \(apples) apples."
    -> "I have 3 apples"
var fruitSum = "I have \(apples + pineapples) pieces of fruit."
    -> "I have 5 pieces of fruit."

複数行の文字列を扱う方法

「”(ダブルクォーテーション)」を3つ並べて""" 文字列 """と囲ってあげる。

var mailContent = """
Hi,bro.
It has been a long time.
How is everything?
"""

辞書型と配列

配列と辞書型の宣言には「 」を使い、要素にアクセスするにはインデックスやキーを[ ]内に書く。
コンマは最後の要素のあとにも書くことができる。

var shoppingArray = ["banana", "milk", "nuts", "salmon",]
    ->["banana", "milk", "nuts", "salmon"]
print(shoppingArray[2])
    -> "nuts"

var presidentsDictionary = [
    "Shinzo": "Japan",
    "Trump": "America",
    "Putin": "Russia"
    ]
    ->["Shinzo": "Japan","Trump": "America", "Putin": "Russia"]
print(presidentsDictionary["Shinzo"])
    -> "Japan"

空の配列と辞書

空の配列や辞書型の変数を宣言する場合は、初期化する構文を使う。

var emptyArray = [String]()
    -> []
var emptyDictionary = [String: Float]()
    -> []

配列と辞書型の変数がすでに宣言されていて、型が明らかな場合は以下の方法で空にすることが可能。

var shoppingArray = ["banana", "milk", "nuts", "salmon"]
shoppingArray = []
    -> [] //Array<String>

var presidentsDictionary = ["Shinzo": 63, "Trump": 71, "Putin": 65]
presidentsDictionary = [:]
    -> [:] //Dictionary<String, Int>

処理の操作

ifswitchを使えば条件分岐、for-inwhilerepeat-whileを使えばループ処理ができる。
処理を記述する部分は**「{ }(中括弧)」**で囲う。

let memberScore = [5, 7, 3, 9]
var teamScore = 0

for score in memberScore {
    if score > 5 {
        teamScore += 2
    } else {
        teamScore += 1
    }
}

print(teamScore)
    -> 6

if文

ifの条件式は常に論理式

暗黙的に0と比較しようとif 変数 {…}と書くとエラーになる。

var hogeScore = 100
if hogeScore {
    print("Not safety")
}
    -> error: 'Int' is not convertible to 'Bool'

ifとletでオプショナル型の表現(Optional Binding)

オプショナル型の変数は「値が含まれている」、「nil」のどちらもいける両刀使い。
オプショナル型の変数を宣言するには型の後ろに「?」をつける。

var optionalString: String? = "I'm opptional!"
print(optionalString == nil)
    ->false

ifとlet(varでも可能)を組み合わせることで変数に値があるか、欠けている(nil)かで条件分岐。
オプショナル型変数に値が含まれていればアンラップされた値が変数に代入され、変数がnilならfalseとなって処理はスキップされる。

変数に値がある場合

var userName: String? = "Sota"
var greeting = "Hello!"

if let name = userName {
    greeting = "Hello, \(name)"
}

print(greeting)
    -> Hello, Sota

変数に値がない(nil)場合

var userName: String?
var greeting = "Hello!"

if let name = userName {
    greeting = "Hello, \(name)"
}

print(greeting)
    -> Hello!

オプショナル型にデフォルト値を与える

??オペレータを使うことで値がnilの場合のデフォルト値を与えることができる。

var userName: String? = nil
let anonymName: String = "Nanashi"
var greeting = "Hi \(userName ?? anonymName)"

print(greeting)
    -> Hi Nanashi

Switch文

Switchはあらゆる値、比較演算に対応している。
defaultケースを設定しないと「網羅的でない」としてエラーになる。
where句を使いlet 変数 where 条件式 (var 変数でもok)とすることで、特定の条件を指定して処理を行うことも可能。
(.hasSuffix()メソッドは、引数の文字列が変数内の文字列の「末尾」に含まれていればTrueを返す)

import Foundation //.hasSuffixのためにインポート

var userJob = "Unemployed"
switch userJob {
    case "Office Worker":
        print("Soso")
    case "Entreprenuer", "Investor": //カンマ区切りでor
        print("Money Happy Pesron")
    case let x where x.hasSuffix("employed”):
        print("Are you Unemployed?")
    default:
        print("Enter your Job!")
}
    -> "Are you Unemployed?"
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?