码迷,mamicode.com
首页 > 其他好文 > 详细

Swiftly语言学习1

时间:2014-08-05 15:53:29      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:style   color   使用   io   数据   for   ar   cti   

简单值:

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

}

n


var m = 2

do{

     m = m*2

}while m < 100

m


var firstForLoop = 0

for i in 0..3{

    firstForLoop += i

}

firstForLoop

var secondForLoop = 0

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

     secondForLoop += 1

}

secondForLoop(..不包含上界,...包含上界)




Swiftly语言学习1,布布扣,bubuko.com

Swiftly语言学习1

标签:style   color   使用   io   数据   for   ar   cti   

原文地址:http://blog.csdn.net/u010877867/article/details/38384951

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!