LoginSignup
102
106

More than 5 years have passed since last update.

Swiftの文法だけ先に学ぶ

Last updated at Posted at 2014-06-02

WWDC2014、おなかいっぱいですね。やっぱり最も注目したのは新言語 Swift でしょうか。ということで、iBooks の 「The Swift Programming Language」を読んでおべんきょうします。

なお、私は英語はなんとなく読める程度なので、間違っている可能性は大いにあります。

Hello, world

println("Hello, World")

行末にセミコロンがいらない言語ですね。
ダブルクォーテーションで括ってるけど、シングルじゃないのか。

定数/変数

var myVariable = 42
myVariable = 50
let myConstant = 42

キャメルケースがお作法かしら。
varで変数宣言、letで定数宣言、と

let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

値から型を判別してくれてますね。例になってる変数名に使われているimplicitは暗黙、explicitは明示の意です。
明示的にはlet 変数名: 型 = 値と。

型の変換は暗黙では行わないので、型変換が必要な場合は自分で指定する必要がある…

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

この例だとwidthはIntegerのため、Stringに変換してlabelと文字列の結合をしてますね。

文字列中の変数呼び出し

私はPHPerなのでその例でいきますが…

$hoge = 100;
$fuga = "hoge is $hoge";

これで展開されます。Swiftの場合、

var hoge = 100
var fuga = "hoge is \(hoge)"

バックスラッシュ+括弧ですね。括弧内は式も可。

配列/連想配列

配列はブラケットを使う

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Realtions"

ケツカンマが許されてますね、なんとすばらしい。

空の配列を作る方法。

let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

上では型を明示的にしていますが、型を推測できるのであれば、

shoppingList = []

として、空のブラケットだけで宣言できます

制御構文

if

変数周りの次は制御構文っていうのはどの言語も同じですね。

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
teamScore

for~inがありますね。便利。ifがすごいわかりやすい。

ifの式は、Booleanを返すものでなければならない、と。
例えば上の例でいくと if score {~~} はエラーになる。

定義されてない値で動かそうとするために、ifletを一緒に使うことができ、この値はオプションとして表される???
ちょっとこのへん英語がよくわからない
オプションは値が入っているか、値が見当たらないことを示すためnilが入っている

var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "Chatii"
var greeting = "Hello"

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

例文読んでもイマイチわかんないな…。続ける。

EXPERIMENT

Change optionalName to nil. What greeting do you get? Add an else clause that sets a different greeting if optionalName is nil.

抜粋:: Apple Inc. “The Swift Programming Language”。 iBooks. https://itun.es/jp/jEUH0.l

optionalNamenilにしたらgreetingはどうなるか?
optionalNameがnilの場合、異なるgreetingをセットするelseを加える。

???何をいってるのかわかってない

switch

let vegetable = "red pepper"
switch vegitable {
case "celery":
    let comment = "~~~"
case "cucumber", "watercress":
    let comment = "~~~"
case let x where x.hasSuffix("pepper"):
    let comment = "\(x)"
default:
    let comment = "default comment"

breakがなく、複数にあてたいときはカンマ区切りでOK、と

102
106
2

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
102
106