Swift语言学习1--简单语法

来源:互联网 发布:厦门流程优化招聘 编辑:程序博客网 时间:2024/05/17 04:15


// Playground - noun: a place where people can play

import Cocoa

// 用let创建一个常量,var创建一个变量,类型一致,当要明确指明变量类型的时候可以用冒号:
// 变量
var myVariable = 42
myVariable = 50
// 常量
let myConstant = 42

// 模糊指明类型 交给系统自行判断
let implicitInteger = 70
let implicitDouble = 70.0
// 明确指明类型
let explicitDouble: Double = 70
let explicitFloat: Float = 70

// 变量不会自动转换成其他类型,如果需要进行明确说明
let label = "The Width is "
let width = 94
// 如果不进行强转 会出现类型不匹配的错误
let widthLabel = label + String(width)

// 在字符串中包含变量:把变量写在圆括号中,再在圆括号前加上\
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples"
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

// 用[]创建数组和字典,访问里面的元素的时候用索引或者key
var shoppingList = ["catfish","water","tulips","bluepaint"];
shoppingList[1]
shoppingList[1] = "bottle of water"

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

// 创建空字典和数组,用初始化语法
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

// 如果类型信息可以判断,也可以像这样子定义空数组和空字典,还可以作为函数参数
shoppingList = []


// 控制流
// 用if,switch作为选择语句,用for-in,for,while,do-while作为循环语句。圆括号内写条件或者循环变量,但这个也可以省略。主体部分用大括号不能省略
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
teamScore

// 在if语句中,判断条件必须是一个Boolean表达式让if和let一块使用来表示可能是空值的情况,这些值都是可选的,这些可选的值(optional value)可以用特定的值或者nil来标明值确实丢失。在一个类型后面写一个问号?来标记是可选的值
var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "John Appleseed"
optionalName == nil
var greeting = "Hello"
if let name = optionalName {
    greeting = "Hello, \(name)"
}
// 如果optional value是nil,条件是false,大括号里面的语句就不执行。否则optional value就被unwrapped并且在let后转成常量,使得unwrapped的值在代码块中可以使用


// switch语句许多类型 执行过程中只要有匹配就会跳出程序,因此不需要break
let vegetable = "red pepper"
switch vegetable {
case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber","watercress":
    let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
    let vegetableComment = "Is it a spicy \(x)?"
default:
    let vegetableComment = "Everything tastes good in soup."
}

// 使用for-in提供字典的键值对遍历字典中每个item
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
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest


// 使用while重复代码块直到条件改变
var n = 2
while n < 100 {
    n = n * 2
}
n

var m = 2
do {
    m = m * 2
} while m < 100
m

// 也可以用.. 代替索引范围
var firstLoop = 0
for i in 0..5 {
    firstLoop += i
}
firstLoop

var secondLoop = 0
for var i = 0; i < 3; i++ {
    secondLoop += 1
}
secondLoop





















0 0