Swift基本文法

來源:互聯網
上載者:User

標籤:

1.常量 變數  自動類型推斷

  let age = 20 常量不可變

  var num = 24 變數可變

  num = 30

  let count:Int = 2  

  Double(count)  類型轉換

2.字串

  Swift的String操作比較複雜,經常轉為oc 的NSString

  let name:String = "hrrrrrrrrr"

  var addr:String = String() 

  print(name)

  print("my name is \(name)") 

  name.endIndex

  (name as NSString).substringToIndex(5)

  (name as NSString).substringWithRange(NSMakeRange(5, 2))

  (name as NSString).length

3.數組裡面只能存放一種類型,和oc不相同

  var heightArray:Array<Int> = Array()

  heightArray.append(3)

  heightArray.insert(2, atIndex: 1)

  heightArray[0]

4.字典

  let numberofLegs:[String:Int] = ["cat":4,"duck":2]

5.bool類型   true false

6.可選值optional

  var temp:String?    nil

  temp = "test"    "test"

  print(temp)     "Optional("test")\n"

  自動會加問號 表示temp存在嗎,存在才會做,不存在就不會做

  print(temp?.endIndex)  "Optional(4)\n"

  var temp:String! 一定有

7.for in 迴圈

  for index in 1...5{

      print(index)

  }

  for name in namesArray{

      print(name)

  }

  let numberofLegs:[String:Int] = ["cat":4,"duck":2]

  for (name,legs) in numberofLegs{

  一對一對取出來    

  }

Swift基本文法

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.