swift不需要main作为入口,输出hello world 只需要下面一行代码
print("Hello World!")
语句结尾也不需要分号
声明变量用var,常量用let,声明后若同时赋值则不需要声明类型,编译器会根据值推测变量类型,类型确定后不能改变其类型。
var name="xiaoming" var age :Int age=10
var num:Float=1; num=1.0;
let value:String value="xiaoming" var age=10; print("my name is \(value),i am \(age) years old") print("my name is "+value+",i am "+String(age)+" years old") var str:String="\(age+10)" print(str)
my name is xiaoming,i am 10 years old my name is xiaoming,i am 10 years old 20
字符串拼接用+,字符串拼接数字需用String(num)转换也可以用 \()替换 。\()中可以进行计算,一下代码输出 20
var str:String="\(age+10)" print(str)
数组和map
var names=["xiaoming","xiaoli","xaiohong"] names[0]="xm" print(names) for name in names{ print(name) } var nameAge=[ "xiaoming":10,"xiaoli":11,"xh":12,] print(nameAge) for (name,age)in nameAge{ print(name+" \(age)") } print(nameAge["xh"]) print(nameAge["xxx"]) nameAge["wj"]=20 print(nameAge)
输出
["xm","xaiohong"] xm xiaoli xaiohong ["xiaoming": 10,"xh": 12,"xiaoli": 11] xiaoming 10 xh 12 xiaoli 11 Optional(12) nil ["wj": 20,"xiaoli": 11,"xiaoming": 10,"xh": 12]
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 可变参数,作为数组处理 func sum(nums:Int...)->Int{ var s:Int=0; for n in nums{ s+=n; } return s; } print(sum()) print(sum(nums:1,2,3)) //返回函数,接收int参数,返回一个函数,返回的函数接收参数是int和string,返回值是string func getFunc(num:Int)->( (Int,String) -> String ){ //函数内部可以声明函数 func get(n:Int,s:String)->String{ return "\(s)\(n*2)" } return get } //调用函数,得到另一个函数,并赋值给f var f=getFunc(num: 1) //调用f函数,得到string值 var v=f(5,"abc") print(v) //函数作为参数,需要使用()包裹参数中函数的参数 func getValue(n1:Int,n2:Int,compare:(Int,Int)->Int)->Int{ return compare(n1,n2); } func max(n1:Int,n2:Int)->Int{ if n1>n2 { return n1 } return n2; } var res=getValue(n1: 5,n2: 2,compare: max) print("max is \(res)") // 使用{}创建匿名闭包 res=getValue(n1: 3,n2: 9,compare:{ (v1:Int,v2:Int)->Int in if v1>v2{ return v1 } return v2 } ) print(res) // 使用{}创建匿名闭包 ,同时省略参数类型,返回值类型 res=getValue(n1: 3,n2: 8,compare:{ (v1,v2) in if v1>v2{ return v1 } return v2 } ) print(res)输出如下:
0 6 abc10 max is 5 9 8原文链接:https://www.f2er.com/swift/322869.html