「Objective-C」とは全くことなる言語仕様「Swift」が登場しました。
基本はスクリプト言語仕様で理解はしやすそうですが、iOSフレームワーク・ライブラリを利用する事になるので、アプリを完成するには、結局「Xcode」「Objective-C」の知識は必須かな?
とは言え、まずは「Siwft」の文法を理解しようかと。
var name = "yoo";
let title = "Blog";
//title = "blog"; //再代入できない
let age = 20; //Int型
let version = 1.1; //Double型
let title = "blog" //String型
let tax:Float = 0.08;
let mile:Double = 100;
Stringを「"\(式)"」で連結できる。
let version = 1.1;
let versionString = "version \(version)"; // version 1.1
let yoo = ("Yohei Yoshikawa", 1975);
let (fullName, birthdayYear) = yoo;
println(fullName);
println(birthdayYear);
var yoo = (fullName: "Yohei Yoshikawa", birthdayYear: 1975);
var citis : String[] = ["Tokyo", "Osaka", "Nagoya"];
citis.append("Sapporo");
var countries = ["JPN" : "Japan", "USA" : "America"];
let oldCountry = countries.updateValue("JAPAN", forKey: "JPN");
let country = countries["JPN"];
Enumに関数を埋め込み処理できる
enum city{
case Tokyo, Osaka, Nagoya, Sapporo, Fukuoka, Yokohama, Sendai
func region() ->String {
switch self {
case .Tokyo, .Yokohama:
return "Kanto"
case .Nagoya:
return "Tokai"
case .Osaka:
return "Kansai"
case .Fukuoka:
return "Kyushu"
case .Sendai:
return "Tohoku"
default :
return ""
}
}
}
var currentCity = city.Nagoya;
println(currentCity.region());
func isAdult(age:Int) -> Bool {
if (age >= 20) {
return true;
} else {
return false;
}
}
let levels = [
"level1": [1, 2, 3, 4, 5, 6],
"level2": [7, 8, 9, 10, 11, 12],
"level3": [13, 14, 15, 16, 17],
]
for (key, level) in levels {
println(key);
for value in level {
println(value);
}
}
for i in 0..5 {
println(i);
}
for i in 0...5 {
println(i);
}
var rate = 3;
var total = 1;
for _ in 1...5 {
total *= rate;
println(total);
}
println("while");
var i:Int = 5;
while (0 <= i) {
println(i);
i--;
}
「nil」を代入可能にする
var title2:String? = "Swift";
title2 = nil;
println(title2?);
println(title2!); //nilの場合実行エラー
func calculate(price: Float , tax: Float = 3) -> Float {
let totalPrice = Float(price) * tax;
return totalPrice;
}
var string = concatString("A", "B");
println(string);
func concatString(values: String...) -> String {
var string = "";
for value in values {
string += value;
}
return string;
}
extension Double {
func km() -> Double {return self * 1.609344}
}
let mile = 100;
let km = mile.km(); //160.9344