//
// main.swift
// hello
//
// Created by 小强 on 15/12/5.
// Copyright © 2015年 小强. All rights reserved.
//
import Foundation
let implicitInteger = 70
let implicitDoubule = 70.0
let explicitDouble:Double = 70
print(explicitDouble);
// 练习1
// 创建一个常量,并显式指定类型为Float并指定初始值为4
let constFloat: Float = 4;
print(constFloat);
/*******************************************************/
let label = "The width is ";
let width = 94;
let widthLabel = label + String(width);
print(widthLabel);
// 练习2
// 删除以上代码中最后一行的String,错误提示是什么
// 错误提示:Binary operator '+' cannot be applied to operands of type 'String' and 'int'
var array:Array<Int> = [Int](); // 声明一个空数组
var shoppingList = ["catfish", "water", "tulipa", "blue paint"];
print(shoppingList[0]);
var occupations = [
"Malcolm": "Catain",
"Kaylee": "Mechanic",
];
print(occupations["Kaylee"]);
// 控制流
let individualScores = [75, 43, 103, 87, 12];
var teamScore = 0;
for score in individualScores
{
if (score > 50){
teamScore += 3;
} else {
teamScore += 1;
}
}
print (teamScore);
/*var optionalString: String? = "Hello";
optionalString = nil;
var optionalName: String? = "John Appleseed";
var greeting = "Hello!";
if let name = optionalName // 此处不能添加括号
{
greeting = "Hello,\(name)";
}
print(greeting);*/
// 练习3 把 optionalName 改成 nil,greeting 会是什么?添加一个 else 语句,
// 当 optionalName 是 nil 时,给 greeting 赋一个不同的值
var optionalString: String? = "Hello";
optionalString = nil;
var optionalName: String? = nil;
var greeting = "Hello!";
if let name = optionalName // 此处不能添加括号
{
greeting = "Hello,\(name)";
} else {
greeting = "你好"
}
print(greeting);
let vegetable = "red pepper";
switch (vegetable)
{
case "celery":
let vegetableComment = "Add some rais and make ant on log.";
break;
case "cucumber","watercress":
let vegetableComment = "That would make a good tea sandwich.";
break;
case let x where x.hasSuffix("pepper"):
let vegetableCommrent = "Is it a spicy \(x)?"
default:
let vegetbaleComment = "Everything tastes good in soup."
}
// 练习4 删除 default 语句,看看会有什么错误?
// 错误提示:Switch must be exhaustive, consider adding a default clause
// 使用 for-in 来遍历字典,需要两个变量来表示每个键值对
let interestingNumbers = ["Prime":[2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square":[1, 4, 9, 16, 25],
];
var largest = 0;
var largestKind: String = ""; // 添加一个变量来记录哪种类型的数字是最大的
for (kind, numbers) in interestingNumbers
{
for (number) in numbers
{
if (number > largest)
{
largest = number;
largestKind = kind;
}
}
}
print(largest);
print(largestKind);
// 练习5 添加另一个变量来记录哪种类型的数字是最大的。
// 示例代码,如上所示。