![見出し画像](https://assets.st-note.com/production/uploads/images/119435880/rectangle_large_type_2_453c0401397c3271c472a309288e8e56.png?width=1200)
楽しい!Swift。 - A Swift Tour (Simple Values-2)
変数、定数に代入できるものはいろいろあります。文字、数字など
まず数字では
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
というように小数点がつくようなものがありますが、
let explicitDouble: Double = 70
のように型を明示して使うことができます。こうすることによって間違いの少ないコードになります。
"型"の代表的なものは数字(整数)を表す"Int"、文字を表す"String"などがあります。ここでは数字の中でも小数点のもの、"Double"を使っています。いろんな型があります。
この場合は浮動小数点型が使われています。
浮動小数点型とは、Float型とDouble型(精度が高い)があります。
文字と数字が混ざったものもありますがそういうときは、それぞれの一緒にコードの場合は型を合わせる必要があります。
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
String(width)
で数字を文字に変換することができます。
let widthLabel = label + String(width)
であわせて表示できつようにしています。なので出力すると
"The width is 94"
となります。これを変換しないで組み込むこともできて、
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
\(apples)
というように"\()"を使うと変数そのまま文章に入れ込むことができます。
文字を変数に代入する方法をもう一つ。
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""
出力すると
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have 8 pieces of fruit.
となります。長い文章でも"""を使うことでうまく変数に入れることができます。