Swiftly语言学习1

单纯值:

1.let常量声明,var声明变量(同时宣布福值,编译器会自己主动判断出类型)

var myVariable = 42

myVariable 50

let myConstant = 42


let implicitInteger = 70

let implicitDouble = 70.0

let explicitDouble:Double = 70

声明类型时在“量”后面加上“:”然后写上类型的名字。

(值永远不会隐式转换,须要转换请显示转换“类型(量)”)

  更简单的办法将值转换成字符串:\(量)

let label = "The width is"
let width = 94
let widthLabel = label + string(width)

let apples = 3

let oranges = 5

let appleSummary = "I have \(apples) apples."

let fruitSummary = "I have \(apples + oranges) pieces of fruit"

2.“[]”创建数组和字典,key或者下标取值

var shoppingList = ["catfish","water","tulips","blue paint"]

shoppingList[1] = "bottle of water"


var occupations = ["Malcolm":"Captain","KayLee":"Mechanic"]

occupations["Jayne"] = "Public Relations"


空数组和空字典声明

let emptyArray  = String[]()

let emptyDictionary = Dictionary<String,Float>()

假设类型信息能够别判断出来。你能够用[]和[:]来创建空数组和空字典,就想你声明变量或者给函数传递參数的时候一样

shoppingList = []


控制流

1.if,switch进行条件操作。for-in,for,while,do-while进行循环(包裹条件和循环变量括号能够省略。可是语句体的大括号是必须的)

let individualScores = [75,43,103,87,12]

var teamScore = 0

for score in individualScores{

        if score>50{

          teamScore += 3

     }

     else

     {

          teamScore += 1

     }

}

if语句的条件必须是布尔值,一个可选的值可能是一个详细的值或者是nil。表示值缺失。在类型后面加上一个问号来标记这个变量的值是可选的。

var optionalString : String? = "Hello"

optionalString == nil


var optionalName:String?="John Appleseed"

var greeting = "Hello!"

if let name = optionalName{

       greeting = "Hello, \(name)"

}


switch支持随意类型的数据以及各种比較操作

let vegetable = "red pepper"

switch vegetable{

case "celery":

        let vegetableComment = "Add some raisins and make ants on a log."

case "cucumber","watercress":

      let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):

     let vegetableComment = "Is it a spicy\(x)?

"

default:

    let vegetableComment = "Everything tastes good in soup."

}


使用for - in 来遍历字典。需呀两个变量来表示每一个键值对

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

for(kind,numbers) in interestingNumbers{

      for number in numbers{

          if number > largest{

               largest = number

          }

     }

}

largest


var n = 2

while n < 100{

     n = n*2

}



var m = 2

do{

     m = m*2

}while m < 100



var firstForLoop = 0

for i in 0...3{

    firstForLoop += i

}



var secondForLoop = 0

for var i= 0;i < 3;++i{

     secondForLoop += 1

}




版权声明:本文博主原创文章,博客,未经同意,不得转载。

posted @ 2015-08-26 12:34  phlsheji  阅读(199)  评论(0编辑  收藏  举报