欠如

来世は貝になりたい

Swiftの文法について復習してみるSimple Values

基本はSwift4のReferenceをベースに勉強していきます。

実行環境

IBM Swift Sandbox

swift.sandbox.bluemix.net

Swift-Ver:Swift Dev. 4.0 (Aug 15, 2017) Platform: Linux (x86_64)

About Swift Swiftについては割愛します。

A Swift Tour ツアーですね。 refarenceの学習も兼ねているので、ここから読み解いていこうと思います。

Tradition suggests that the first program in a new language should print the words “Hello, world!” on the screen. 
In Swift, this can be done in a single line:

訳:新しい言語の最初のプログラムは、画面上に “こんにちは、世界!”という単語を印刷する必要があることを示唆しています。 Swiftでは、これは1行で行うことができます(google翻訳

print(“Hello, world!”)と入力すれば“Hello, world!”と文字列が出力されます。

下記が実行結果です。

Swift Dev. 4.0 (Aug 15, 2017)
Platform: Linux (x86_64)
Linking ./.build/x86_64-unknown-linux/debug/TempCode
Hello,World!

Simple Values

Use let to make a constant and var to make a variable. 
The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. 
This means you can use constants to name a value that you determine once but use in many places.

訳: letを使って変数を作る定数とvarを作る。定数の値はコンパイル時には知る必要はありませんが、一度だけ値を代入する必要があります。 これは、定数を使用して一度決定する値の名前を指定できますが、多くの場所で使用できます。(google翻訳

var test_t = 45
      test_t = 78
let  test_h = 75

print(test_t)
print(test_h)

上記にletを使って変数を作る定数とvarを作りその後定数の値を一時的に変更しました。 実行結果は下記になります。

Linking ./.build/x86_64-unknown-linux/debug/TempCode
78
75
A constant or variable must have the same type as the value you want to assign to it. 
However, you don’t always have to write the type explicitly. 
Providing a value when you create a constant or variable lets the compiler infer its type. 
In the example above, the compiler infers that myVariable is an integer because its initial value is an integer. 

訳:

定数または変数は、割り当てたい値と同じ型でなければなりません。
ただし、必ずしも型を明示的に記述する必要はありません。
定数または変数を作成するときに値を指定すると、コンパイラはその型を推論できます。
上記の例では、コンパイラは、初期値が整数なので、myVariableは整数であると推定します。

上記に英文の場合myVariableに当たるのがvarの定数が整数であると推測します。

If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon. 

訳:

初期値が十分な情報を提供しない場合(または初期値がない場合)は、変数の後ろにコロンで区切って記述して型を指定します。
var test_Integer = 45
    //test_Double = 78.0
let practice_Double:Double = 75.9

print(practice_Double)

上記のように入力し実行すれば下記になります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
75.9

また、test_Doubleをコメントアウトは整数型のため小数点以下の数値を扱うためにはDouble型に変換しない場合エラーとなります。

Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type. 

訳:

値は暗黙のうちに別の型に変換されることはありません。値を別の型に変換する必要がある場合は、明示的に目的の型のインスタンスを作成します。

let width = 300
let color = "blue :"
let sky = color + String(width)
print(sky)

上記コードを実行すれば以下の通りになります。

Linking ./.build/x86_64-unknown-linux/debug/TempCode
blue :300

また数値+数値や文字列+文字列なら出来ますが数値と文字列と処理を行う場合数値を文字列もしくは文字列を数値に変換する必要があります。

There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (\) before the parentheses. For example:

訳:

文字列に値を含めるさらに簡単な方法があります。値をかっこで書き出し、かっこの前にバックスラッシュ(\)を書きます。
let balls = 3
let coins = 5
let ballSummary = "I have \(balls) balls."
let allSummary = "I have \(balls + coins) PRICE."

print(ballSummary)
print(allSummary)

上記のように入力し実行すれば下記になります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
I have 3 balls.
I have 8 PRICE.
Use three double quotes (""") for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quote. For example: 

訳:

複数の行を取る文字列には3つの二重引用符( "")を使います。引用符で囲まれた行の先頭にあるインデントは、閉じた引用符のインデントに一致する限り削除されます。
let balls = 3
let coins = 5
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 \(balls + coins ) pieces of fruit.
"""
print(quotation)

上記のように入力し実行すれば下記になります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
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.

There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash () before the parentheses. For example: こちらの例とは違い複数行の文字の中の文字列の中に数値を組み込む例です。

Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.

角括弧([])を使用して配列と辞書を作成し、それらの要素にアクセスするには、インデックスまたはキーを角括弧で囲みます。最後の要素の後にコンマを入れることができます。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

print(shoppingList)
print(occupations)
print(occupations["Malcolm"])

上記のように入力し実行すれば下記になります

/swift-execution/Sources/main.swift:12:7: warning: expression implicitly coerced from 'String?' to Any
print(occupations["Malcolm"])
      ^~~~~~~~~~~~~~~~~~~~~~
/swift-execution/Sources/main.swift:12:18: note: provide a default value to avoid this warning
print(occupations["Malcolm"])
      ~~~~~~~~~~~^~~~~~~~~~~
                             ?? <#default value#>
/swift-execution/Sources/main.swift:12:18: note: force-unwrap the value to avoid this warning
print(occupations["Malcolm"])
      ~~~~~~~~~~~^~~~~~~~~~~
                            !
/swift-execution/Sources/main.swift:12:18: note: explicitly cast to Any with 'as Any' to silence this warning
print(occupations["Malcolm"])
      ~~~~~~~~~~~^~~~~~~~~~~
                             as Any
Linking ./.build/x86_64-unknown-linux/debug/TempCode
["catfish", "bottle of water", "tulips", "blue paint"]
["Kaylee": "Mechanic", "Jayne": "Public Relations", "Malcolm": "Captain"]
Optional("Captain")
To create an empty array or dictionary, use the initializer syntax.

空の配列または辞書を作成するには、イニシャライザ構文を使用します。
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
print(emptyArray)
print(emptyDictionary)

上記のように入力し実行すれば下記になります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
[]
[:]
If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.

型情報が推測できる場合は、空の配列を[]、空の辞書を[:]と書くことができます。たとえば、変数に新しい値を設定したり、関数に引数を渡したりします。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
shoppingList =  []
 occupations = [:]

print( shoppingList)
print(occupations)

上記のように入力し実行すれば下記になります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
[]
[:]

長くなりそうなのでPageごとに書きます