Swift学习笔记-基础语法1

前端之家收集整理的这篇文章主要介绍了Swift学习笔记-基础语法1前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 作为开发语言,首先我们要了解他的基本语法特性。按照惯例,就从Hello,World!开始吧!
  2. print("Hello,World!")
  3.  
  4. print("helloswift")
  5. //////////////////////////////////////////////////////////////
  6. //1.显示指定一个常量,并且把4赋给a,常量(let)意味着你只能给它赋一次值
  7. leta:Float=4
  8. letb=5.0
  9. letc=7
  10. letstr="helloswift"
  11. print(a)
  12. print(b)
  13. print(c)
  14. print(str)
  15.  
  16. //////////////////////////////////////////////////////////////
  17. //2.使用\()把基本数据类型转化成字符串,字符串的拼接
  18. letstr1=str+""+String(c)
  19. letstr2="helloswift\(c).0"
  20. print(str1)
  21. print(str2)
  22.  
  23. //////////////////////////////////////////////////////////////
  24. //3.数组和字典
  25. varshoppingList=["book","food","water"]
  26. print(shoppingList[1])
  27. shoppingList[1]="pancel"
  28. print(shoppingList[1])
  29.  
  30. varoccupations=["Tank":"coder","Wade":"player"]
  31. print(occupations["Tank"])
  32.  
  33. //////////////////////////////////////////////////////////////
  34. //4.控制流
  35. //4.1{}不能省略;
  36. //4.2条件必须是一个bool表达式,不是隐式的作比较,可以用iflet来处理缺省值的情况,let后必须要是一个“可选值”
  37. letindividualscores=[89,20,84,68,73]
  38. varteamscore=0
  39. forscoreinindividualscores{
  40. ifscore>60{
  41. teamscore+=3
  42. }
  43. else{
  44. teamscore+=1
  45. }
  46. }
  47. print(teamscore)
  48.  
  49.  
  50. //4.3在类型后面用?来标记一个标示这个变量值是可选的,一个可选的值可能是一个具体的值或者nil
  51. varoptionalString:String?="Hello"
  52. print(optionalString==nil)//false
  53.  
  54. varoptionalName:String?="Kobe"
  55. vargreeting="Hello!"
  56. ifletname=optionalName{
  57. greeting=greeting+"\(name)"//Hello!Kobe
  58. print(greeting)
  59. }else{
  60. print(greeting)
  61. }
  62.  
  63. //4.4switch语句,支持任意数据类型的各种比较,switch语句运行到匹配语句后会自动退出,故而不要每一句都加break
  64. letvegetable="redpepper"
  65. switchvegetable{
  66.  
  67.  
  68. case"celery":
  69. letvegetableComment="Addsomeraisinsandmakeantsonalog"
  70. print(vegetableComment)
  71. case"cucumber","watercress":
  72. letvegetableComment="Thatwouldmakeagoodteasandwich."
  73. print(vegetableComment)
  74.  
  75. //申明let可以用于匹配某部分固定值的模式
  76. caseletxwherex.hasSuffix("pepper"):
  77. letvegetableComment="Isitaspicy\(x)?"
  78. print(vegetableComment)
  79. default:
  80. letvegetableConnent="Everythingtastesgoodinsoup."
  81. print(vegetableConnent)
  82. }
  83.  
  84.  
  85. //////////////////////////////////////////////////////////////
  86. //5.forin遍历字典,获取键&&值
  87. letinterestingNumbers=["Prime":[2,3,5,7,11,13],"Fabomacci":[1,1,2,8],"Square":[1,4,9,16,25]]
  88. varlargest=0
  89. vartype=""
  90. for(kind,numbers)ininterestingNumbers{
  91. fornumberinnumbers{
  92. ifnumber>largest{
  93. largest=number
  94. type=kind
  95. }
  96. }
  97. }
  98. print(largest)//25
  99. print(type)//Square
  100.  
  101.  
  102. //////////////////////////////////////////////////////////////
  103. //6.for语法...
  104. varfirstForLoop=0
  105. varsecondForLoop=0
  106. //6.1传统写法
  107. forvari=0;i<4;++i{
  108. firstForLoop=firstForLoop+i
  109. }
  110. print(firstForLoop)
  111. //6.2新写法.../..<
  112. foriin0...4{
  113. secondForLoop=secondForLoop+i
  114. }
  115. print(secondForLoop)
  116.  
  117.  
  118. //////////////////////////////////////////////////////////////////////////////////////
  119. //7.函数和闭包(block):①.用func来定义一个函数②.用名字和参数调用函数③.用->来指定函数返回值
  120.  
  121. //7.1函数返回一个值
  122. funcgreeting(name:String,day:String)->String{
  123. return"hello\(name),todayis\(day)"
  124. }
  125. print(greeting("tank",day:"september1"))//hellotank,todayisseptember1(day:不能省略)
  126.  
  127. //7.2函数返回多个值:使用元组让一个函数返回多个值,该元组的元素可以用名称或者数组表示
  128. funccalculateStatistics(scores:[Int])->(min:Int,max:Int,sum:Int){
  129. varmin=scores[0]
  130. varmax=scores[0]
  131. varsum=0
  132. forscoreinscores{
  133. ifscore>max{
  134. max=score
  135. }
  136. ifscore<min{
  137. min=score
  138. }
  139. sum+=score
  140. }
  141. return(min,max,sum)
  142. }
  143. letstatistics=calculateStatistics([1,6,8,10])
  144. print(statistics)//(1,10,55)--->不是数组哦
  145. print(statistics.1)//10
  146. print(statistics.sum)//55
  147. print([1,10])//[1,10]
  148.  
  149. //7.3函数可以带有可变个参数,这些参数在函数内表现为数组形式
  150. funcsumOf(numbers:Int...)->Int{
  151. varsum=0
  152. fornumberinnumbers{
  153. sum+=number
  154. }
  155. returnsum
  156. }
  157. letsum=sumOf(1,4)//sumOf([1,4])ERROR
  158. print(sum)//10
  159.  
  160. //7.4函数可以被嵌套,被嵌套的函数可以访问外层函数的变量,可以试用嵌套来重构一个“太复杂”或者“太长”的函数
  161. funcreturnFifteen()->Int{
  162. vary=10
  163. funcadd(){
  164. y=y+5
  165. }
  166. add()
  167. returny
  168. }
  169. print(returnFifteen())//15
  170.  
  171. //7.5函数可以作为另一个函数的返回值(Int->Int)------>表示返回值是一个函数,这个函数传入一个int返回值是int
  172. funcmakeIncrementer()->(Int->Int){
  173. funcaddOne(number:Int)->Int{
  174. returnnumber+1
  175. }
  176. returnaddOne//注意这里add不带参数
  177. }
  178. varincreament=makeIncrementer()
  179. print(increament(7))//8
  180.  
  181. //7.6函数作为参数传入另一个函数
  182. funchasAnyMatches(list:[Int],condition:Int->Bool)->Bool{
  183. foriteminlist{
  184. ifcondition(item){
  185. returntrue
  186. }
  187. }
  188. returnfalse
  189. }
  190. funclessThanTen(number:Int)->Bool{
  191. ifnumber<10{
  192. returntrue
  193. }
  194. returnfalse
  195. }
  196. /************作为参数传入或者返回时,只要写函数名即可,不需要带参数****************/
  197. print(hasAnyMatches([1,6],condition:lessThanTen))//true
  198. print(hasAnyMatches([11,12,13,14],condition:lessThanTen))//false
  199.  
  200. //7.7函数是一种特殊的闭包,可以试用{}来创建一个匿名的闭包。使用in将参数和返回值类型声明与闭包函数体进行分离
  201. //map函数--->建立一个映射y=f(x)
  202. varnumbers=[20,19,2]
  203.  
  204. vartripleNumbers=numbers.map({(number:Int)->Intin
  205. letresult=3*number
  206. returnresult
  207. })
  208. varoddsToZero=numbers.map({(number:Int)->Intin
  209. ifnumber%2==0{
  210. returnnumber
  211. }else{
  212. return0
  213. }
  214. })
  215. print(tripleNumbers)//[60,57,21,6]
  216. print(oddsToZero)//[20,2]
  217.  
  218.  
  219. //////////////////////////////////////////////////////////////
  220. //8.对象和类
  221. //8.1创建一个类,构造器(析构函数)
  222. classShape{
  223. varnumberOfSides=0
  224. varname:String
  225. varsideLength:Double=0.0
  226.  
  227. init(sideLength:Double,name:String){
  228. self.sideLength=sideLength
  229. self.name=name
  230. }
  231.  
  232. varperimetre:Double{
  233. get{
  234. return3*sideLength
  235. }
  236. set{
  237. sideLength=newValue/3
  238. }
  239. }
  240.  
  241. funcsimpleDesctiption()->NSString{
  242. return"\(name)with\(numberOfSides)sides."
  243. }
  244. funcsimpleDesctiption(num:Int)->NSString{
  245. return"ashapewith\(num)sides."
  246. }
  247. }
  248. //8.2创建一个类的实例,在类名后面加入一个括号
  249. varshape=Shape(sideLength:12,name:"Triangle")
  250. shape.numberOfSides=3
  251. print(shape.simpleDesctiption())//ashapewith7sides.
  252. print(shape.simpleDesctiption(8))//ashapewith8sides.
  253.  
  254.  
  255. //////////////////////////////////////////////////////////////
  256. //9.枚举和结构体
  257. //9.1使用enum来创建枚举,枚举可以包含方法
  258. enumRank:Int{
  259. caseAce=1
  260. caseTwo,Three,Four,Five,Six,Seven,Eight,Nine,Ten
  261. caseJack,Queen,King
  262. funcsimpleDescription()->String{
  263. switchself{
  264. case.Ace:return"ace"
  265. case.Jack:return"Jack"
  266. case.Queen:return"Queen"
  267. case.King:return"King"
  268. default:returnString(self.rawValue)
  269. }
  270. }
  271. }
  272. letace=Rank.Ace
  273. letaceRawValue=ace.rawValue

猜你在找的Swift相关文章