LoginSignup
4
1

More than 5 years have passed since last update.

SwiftTourをさっと読む ~ Simple Values ~

Last updated at Posted at 2018-06-11

SwiftTourをさっと読む ~ Simple Values ~

Swiftの勉強を始めたので公式のA Swift Tourをさっと読んでみました。
今回はSimple Valuesをさらっとまとめました。というかそのまんまだけど。

バージョンは4.2です。

標準出力

標準出力
  print("Hello World")

変数宣言・定数宣言

変数

変数宣言
  var myVariable = 42
  myVariable = 50

定数

定数宣言
  let myConstant = 42

定数のため、再代入は不可

定数への再代入はエラー
  let myConstant = 42
  myConstant = 3 // ←これはエラーになる

型を指定して宣言

型を指定して宣言
  var myVariable:Int = 42
  let myConstant:Int = 5

型変換

型変換
  // 変換先の型(変換する値)
  let intVal = 10
  let strVal = String(intVal)

初期値がない、あるいは不足している場合でも型を宣言すればコンパイラが推論を行ってくれる

型推論による型変換
  var myVariable1 = 42 // Intの42
  var myVariable2:Double = 42 // Doubleの42.0

暗黙的に型変換は行われないので明示的に書く必要がある

明示的に変換する必要がある
  let label = "The width is "
  let width = 94
  let widthLabel = label + String(width) // "The width is 94"
  // let widthLabel = label + width これはエラーになる

文字列操作

文字列内における値参照

文字列内における値参照
  let name = "Taro"
  let message = "Hello, \(name)"

複数行の文字列

複数行の文字列
  let ppap = """
  I have a pen
  I have an apple
  uh!
  apple-pen
  """

配列と辞書

配列

配列
  var shoppingList = ["catfish", "water", "tulips", "blue paint"]
  print(shoppingList[1]) // "water"
  shoppingList[1] = "bottle of water"
  print(shoppingList[1]) // "bottle of water"

辞書

辞書
  var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
  ]
  print(occupations.count) // 2
  occupations["Jayne"] = "Public Relations"
  print(occupations.count) // 3
  print(occupations["Malcolm"]) // Optional("Captain")

空の配列・空の辞書

空の配列・空の辞書
  shoppingList = []
  occupations = [:]

型推論が可能な場合に限り利用可能

型推論ができない場合はエラー
  var shoppingList = [] // ←これはエラーになる
  var occupations = [:] // ←これはエラーになる

型を指定すれば可能

型指定を行い空を入れる
  var shoppingList:[String] = []
  var occupations:[String:String] = [:]

おわり

他の言語を経験していれば難しいことはなさそうですね。
何か間違いがあればご指摘お願い致します。

おしまい。

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