Swift Tour(Swift一览)
Swift Tour
传统表明,新语言中的第一个程序应在屏幕上打印“Hello,world”字样。在Swift中,这可以在一行中完成:
print("Hello,world")
如果你用C或Objective-C编写代码,这个语法看起来很熟悉-在Swift中,这行代码是一个完整的程序。您无需为输入/输出或字符串处理等功能导入单独的库。在全局范围编写的代码用作程序的入口点,因此您不需要main()函数。您也不需要在每个语句的末尾写分号。
Simple Values(值)
使用“let”定义一个常量,使用“var”定义一个变量
1、常量、变量的定义
//define a variable value.
var myVariable = 42
myVariable = 50
//define a constant value.
let myConstant = 42
2、为常量、变量(隐式/显式)指定类型
//隐式定义整型类型
let implicitInteger = 70
//隐式定义Double
let implicityDouble = 70.0
//显式定义Double
let explicityDouble:Double = 70
3、值永远不会隐式转换为其他类型。如果需要将值转换为其他类型,请显式创建所需类型的实例。
出现错误的示例
let label = "The width is"
let width = 94
let widthLabel = label + width
修正后的示例
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
此处敲黑板、划重点(Swift此处与其他语言的区别)
1、在Swift错误示例(label+width是错误的)
let label = "The width is"
let width = 94
let widthLabel = label + width
2、在Kotlin示例中(label+width是正确的)
val label = "This is label"
val width = 40
val widthLabel = label + width
println(widthLabel)
3、在Java示例中(label+width是正确的)
final String label = "This is label of java language";
final int width = 90;
final String widthLabel = label + width;
字符串处理
1、在字符串中包含值:在括号中写入值,并在括号前写入反斜杠->(variable)
例如:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
2、占用多行的字符串,使用:"""
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit"
"""
print(quotation)//result:I said "I have 3 apples."And then I said "I have 8 pieces of fruit"
创建数组和字典
使用方括号[]创建数组和字典,并通过在括号中写入索引或键来访问他们的元素,最后一个元素后面允许逗号。
1、创建数组、添加数组元素、修改数组元素、查询数组元素
//创建数组
var shoppingList = ["catfish","water","tulips"]
//空数据的数组
var emptyList = [String]()
//修改数据
shoppingList[1] = "bottle of water"
print("shopping :\(shoppingList)")//shopping :["catfish", "bottle of water", "tulips"]
//添加数据
shoppingList.append("appended element")
print("shopping index 1 :\(shoppingList[1])")//shopping index 1 :bottle of water
print("shopping :\(shoppingList)");//shopping :["catfish", "bottle of water", "tulips", "appended element"]
2、创建字典、添加字典元素、修改字典元素、查询字典元素
//创建空数据的字典
var emptyDictionary = [String:String]()
//创建带有数据的字典
var shoppingDictionary = [
"One":"first",
"Two":"second",
"Three":"third"
]
print("shoppingDictionary:\(shoppingDictionary)")//shoppingDictionary:["Three": "third", "One": "first", "Two": "second"]
//修改字典
shoppingDictionary["One"] = "modify element"
print("shoppingDictionary:\(shoppingDictionary)")//shoppingDictionary:["Three": "third", "One": "modify element", "Two": "second"]
//添加数据
shoppingDictionary["Append"] = "append"
print("shoppingDictionary:\(shoppingDictionary)")//shoppingDictionary:["Three": "third", "Append": "append", "One": "modify element", "Two": "second"]
Control Flow(控制流)
使用If和Switch制作条件语句
使用for-in,while,repeat-while进行循环
条件或循环变量周围的括号是可选的。
let individualScores = [75,43,203,87,12]
var teamScore = 0
for score in individualScores{
if score > 50{
teamScore += 2
}else{
teamScore += 1
}
}
print("teamScore:\(teamScore)")
处理可选值(可能为空的值/nil)
1、使用if和let一起处理可能为空(nil)的值
var optionalString: String? = "Hello"
print(optionalString == nil)
// Prints "false"
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
//let name 定义一个不为nil的属性
//optionalName可为nil类型的属性
if let name = optionalName {
greeting = "Hello, \(name)"
}else{
greeting = "default value"
}
print(greeting)//Hello, John Appleseed
2、使用??运算符提供默认值(??类似于Kotlin中?:)
/*
使用??运算符提供默认值(类似于Kotlin中?:)
*/
let nickName:String? = nil
let fullName:String = "John appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
print(informalGreeting)//Hi John appleseed
3、Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber","watercress":
print("That would 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.");
}
//Prints "Is it a spicy red pepper"
在匹配的switch case中执行代码后,程序推出switch语句。程序不会继续下一种情况,因此不需要在每个案例代码的末尾明确地中断交换机(与Java语言不同:不需要break)
4、Iterate dictionary(遍历字典)
/*
创建字典(key,value)
*/
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
//iterate
for (key,numbers) in interestingNumbers{
for number in numbers{
if(number > largest){
largest = number
}
}
}
print("largest:\(largest)")//largest:25
5、使用while 和 repeat 循环
while loop(while循环)
var n = 2
while n < 100{
n *= 2
}
print("n:\(n)")//n:128
repeat while(repeat while循环,类似Java的do while)
var m = 2
repeat{
m *= 2
}while m < 100
print("m:\(m)")//m:128
6、区间
开区间(使用..<省略其上限值)
/*
0-开区间(不取端点)
*/
var total = 0
for i in 0..<4{
total += i
print("i:\(i)")//0,1,2,3
}
print("total:\(total)")//total:6
闭区间(使用...取端点/上限的值)
/*
0-闭区间(取端点)
*/
total = 0
for i in 0...4{
total += i
print("i:\(i)")//0,1,2,3,4
}
print("total:\(total)")//total:10
想要查看更多、更详细有料干货点击我https://pdliuw.github.io/
未完待续。。。