Swift常用语法示例代码
Posted brave-sailor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift常用语法示例代码相关的知识,希望对你有一定的参考价值。
此篇文章整理自我以前学习Swift时的一些练习代码,其存在的意义多是可以通过看示例代码更快地回忆Swift的主要语法。
如果你想系统学习Swift或者是Swift的初学者请绕路,感谢Github上The Swift Programming Language
开源翻译的中文版,感谢极客学院wiki提供的PDF版本。
代码和PDF版本上传至Github,有兴趣的可以下载下来试试。
SwiftTour
Base
var str = "Hello, World!"
print(str)
// 变量用var声明,常量用let声明,变量类型自动推断
// 可在变量后声明类型,用冒号分隔
var myVariable = 42
let myConstant = 42
myVariable = 50
let explictDouble: Double = 60
// 值永远不会被隐式转换为其他类型,需要转换必须采用显式转换
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"
// []用来创建数组或字典
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic"
]
occupations["Jayne"] = "Public Relations"
// 创建一个空数组或者字典
let emptyArray1 = [String]()
let emptyDictionary1 = [String: Float]()
let emptyArray2: [String] = []
let emptyDictionary2: [String: Float] = [:]
// 控制流,if和switch用于选择,for-in,for,while和repeat-while用于循环
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
// 由于不支持隐式转换,条件必须是一个布尔表达式
// 一般采用可选值配合if和let,处理值缺失判断
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello"
if let name = optionalName {
greeting = "Hello, \(name)"
}
// Switch支持任意类型的数据以及各种比较操作
let vegetable = "red pepper"
switch vegetable {
case "celery" :
print("Add some raisins and make ants on a log")
case "cucumber", "watercress" :
print("That woould make a good tea sandwich")
case let x where x.hasSuffix("pepper") :
print("Is it a spicy \(x)?")
default :
print("Everything tastes good in soup")
}
// 使用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 numberGroup: String = "Null"
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
numberGroup = kind
}
}
}
print(numberGroup, largest)
// while循环
var n = 2
while n \< 100 {
n = n *