前端之家收集整理的这篇文章主要介绍了
Swift学习笔记-基础语法1,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- 作为开发语言,首先我们要了解他的基本语法特性。按照惯例,就从Hello,World!开始吧!
- print("Hello,World!")
-
- print("helloswift")
- //////////////////////////////////////////////////////////////
- //1.显示指定一个常量,并且把4赋给a,常量(let)意味着你只能给它赋一次值
- leta:Float=4
- letb=5.0
- letc=7
- letstr="helloswift"
- print(a)
- print(b)
- print(c)
- print(str)
-
- //////////////////////////////////////////////////////////////
- //2.使用\()把基本数据类型转化成字符串,字符串的拼接
- letstr1=str+""+String(c)
- letstr2="helloswift\(c).0"
- print(str1)
- print(str2)
-
- //////////////////////////////////////////////////////////////
- //3.数组和字典
- varshoppingList=["book","food","water"]
- print(shoppingList[1])
- shoppingList[1]="pancel"
- print(shoppingList[1])
-
- varoccupations=["Tank":"coder","Wade":"player"]
- print(occupations["Tank"])
-
- //////////////////////////////////////////////////////////////
- //4.控制流
- //4.1{}不能省略;
- //4.2条件必须是一个bool表达式,不是隐式的作比较,可以用iflet来处理缺省值的情况,let后必须要是一个“可选值”
- letindividualscores=[89,20,84,68,73]
- varteamscore=0
- forscoreinindividualscores{
- ifscore>60{
- teamscore+=3
- }
- else{
- teamscore+=1
- }
- }
- print(teamscore)
-
-
- //4.3在类型后面用?来标记一个标示这个变量值是可选的,一个可选的值可能是一个具体的值或者nil
- varoptionalString:String?="Hello"
- print(optionalString==nil)//false
-
- varoptionalName:String?="Kobe"
- vargreeting="Hello!"
- ifletname=optionalName{
- greeting=greeting+"\(name)"//Hello!Kobe
- print(greeting)
- }else{
- print(greeting)
- }
-
- //4.4switch语句,支持任意数据类型的各种比较,switch语句运行到匹配语句后会自动退出,故而不要每一句都加break
- letvegetable="redpepper"
- switchvegetable{
-
-
- case"celery":
- letvegetableComment="Addsomeraisinsandmakeantsonalog"
- print(vegetableComment)
- case"cucumber","watercress":
- letvegetableComment="Thatwouldmakeagoodteasandwich."
- print(vegetableComment)
-
- //申明let可以用于匹配某部分固定值的模式
- caseletxwherex.hasSuffix("pepper"):
- letvegetableComment="Isitaspicy\(x)?"
- print(vegetableComment)
- default:
- letvegetableConnent="Everythingtastesgoodinsoup."
- print(vegetableConnent)
- }
-
-
- //////////////////////////////////////////////////////////////
- //5.forin遍历字典,获取键&&值
- letinterestingNumbers=["Prime":[2,3,5,7,11,13],"Fabomacci":[1,1,2,8],"Square":[1,4,9,16,25]]
- varlargest=0
- vartype=""
- for(kind,numbers)ininterestingNumbers{
- fornumberinnumbers{
- ifnumber>largest{
- largest=number
- type=kind
- }
- }
- }
- print(largest)//25
- print(type)//Square
-
-
- //////////////////////////////////////////////////////////////
- //6.for语法...
- varfirstForLoop=0
- varsecondForLoop=0
- //6.1传统写法
- forvari=0;i<4;++i{
- firstForLoop=firstForLoop+i
- }
- print(firstForLoop)
- //6.2新写法.../..<
- foriin0...4{
- secondForLoop=secondForLoop+i
- }
- print(secondForLoop)
-
-
- //////////////////////////////////////////////////////////////////////////////////////
- //7.函数和闭包(block):①.用func来定义一个函数②.用名字和参数调用函数③.用->来指定函数返回值
-
- //7.1函数返回一个值
- funcgreeting(name:String,day:String)->String{
- return"hello\(name),todayis\(day)"
- }
- print(greeting("tank",day:"september1"))//hellotank,todayisseptember1(day:不能省略)
-
- //7.2函数返回多个值:使用元组让一个函数返回多个值,该元组的元素可以用名称或者数组表示
- funccalculateStatistics(scores:[Int])->(min:Int,max:Int,sum:Int){
- varmin=scores[0]
- varmax=scores[0]
- varsum=0
- forscoreinscores{
- ifscore>max{
- max=score
- }
- ifscore<min{
- min=score
- }
- sum+=score
- }
- return(min,max,sum)
- }
- letstatistics=calculateStatistics([1,6,8,10])
- print(statistics)//(1,10,55)--->不是数组哦
- print(statistics.1)//10
- print(statistics.sum)//55
- print([1,10])//[1,10]
-
- //7.3函数可以带有可变个参数,这些参数在函数内表现为数组形式
- funcsumOf(numbers:Int...)->Int{
- varsum=0
- fornumberinnumbers{
- sum+=number
- }
- returnsum
- }
- letsum=sumOf(1,4)//sumOf([1,4])ERROR
- print(sum)//10
-
- //7.4函数可以被嵌套,被嵌套的函数可以访问外层函数的变量,可以试用嵌套来重构一个“太复杂”或者“太长”的函数
- funcreturnFifteen()->Int{
- vary=10
- funcadd(){
- y=y+5
- }
- add()
- returny
- }
- print(returnFifteen())//15
-
- //7.5函数可以作为另一个函数的返回值(Int->Int)------>表示返回值是一个函数,这个函数传入一个int返回值是int
- funcmakeIncrementer()->(Int->Int){
- funcaddOne(number:Int)->Int{
- returnnumber+1
- }
- returnaddOne//注意这里add不带参数
- }
- varincreament=makeIncrementer()
- print(increament(7))//8
-
- //7.6函数作为参数传入另一个函数
- funchasAnyMatches(list:[Int],condition:Int->Bool)->Bool{
- foriteminlist{
- ifcondition(item){
- returntrue
- }
- }
- returnfalse
- }
- funclessThanTen(number:Int)->Bool{
- ifnumber<10{
- returntrue
- }
- returnfalse
- }
- /************作为参数传入或者返回时,只要写函数名即可,不需要带参数****************/
- print(hasAnyMatches([1,6],condition:lessThanTen))//true
- print(hasAnyMatches([11,12,13,14],condition:lessThanTen))//false
-
- //7.7函数是一种特殊的闭包,可以试用{}来创建一个匿名的闭包。使用in将参数和返回值类型声明与闭包函数体进行分离
- //map函数--->建立一个映射y=f(x)
- varnumbers=[20,19,2]
-
- vartripleNumbers=numbers.map({(number:Int)->Intin
- letresult=3*number
- returnresult
- })
- varoddsToZero=numbers.map({(number:Int)->Intin
- ifnumber%2==0{
- returnnumber
- }else{
- return0
- }
- })
- print(tripleNumbers)//[60,57,21,6]
- print(oddsToZero)//[20,2]
-
-
- //////////////////////////////////////////////////////////////
- //8.对象和类
- //8.1创建一个类,构造器(析构函数)
- classShape{
- varnumberOfSides=0
- varname:String
- varsideLength:Double=0.0
-
- init(sideLength:Double,name:String){
- self.sideLength=sideLength
- self.name=name
- }
-
- varperimetre:Double{
- get{
- return3*sideLength
- }
- set{
- sideLength=newValue/3
- }
- }
-
- funcsimpleDesctiption()->NSString{
- return"\(name)with\(numberOfSides)sides."
- }
- funcsimpleDesctiption(num:Int)->NSString{
- return"ashapewith\(num)sides."
- }
- }
- //8.2创建一个类的实例,在类名后面加入一个括号
- varshape=Shape(sideLength:12,name:"Triangle")
- shape.numberOfSides=3
- print(shape.simpleDesctiption())//ashapewith7sides.
- print(shape.simpleDesctiption(8))//ashapewith8sides.
-
-
- //////////////////////////////////////////////////////////////
- //9.枚举和结构体
- //9.1使用enum来创建枚举,枚举可以包含方法
- enumRank:Int{
- caseAce=1
- caseTwo,Three,Four,Five,Six,Seven,Eight,Nine,Ten
- caseJack,Queen,King
- funcsimpleDescription()->String{
- switchself{
- case.Ace:return"ace"
- case.Jack:return"Jack"
- case.Queen:return"Queen"
- case.King:return"King"
- default:returnString(self.rawValue)
- }
- }
- }
- letace=Rank.Ace
- letaceRawValue=ace.rawValue