技术文章分类(180)

技术随笔(11)

swift的语法小demo1

1,新建OS X /Application/Command Line Tool  下一步   选择swift语言(这里只是练习语法,所以不用启动ios模拟器了,那个太慢了)

//
//  main.swift
//  SwiftGrammarStudy
//
//  Created by dongway on 14-6-6.
//  Copyright (c) 2014年 dongway. All rights reserved.
//

import Foundation

/*
    定义变量
*/
var myVariable = 42
myVariable = 50
let myConstant = 42
let explictiDouble:Double = 70
println("\(myVariable) 和 \(myConstant)  \(explictiDouble)")

/*
    拼接字符串
*/
let label = "the width is "
let width = 90
let widthLabel = label + String(width)
println("\(widthLabel)")

/*
    数组和字典
*/
var shoppingList = ["catfisth","water","tulips","blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
    "1":"captain",
    "2":"mechanic",
]
occupations["1"] = "public relations"

//创建一个空的数组或字典
let emptyArray = String[]()
let emptyDictionary = Dictionary<String,Float>()
//如果类型信息无法判断,可以写空
var list = []


/*
    遍历数组和字典
*/
for li in shoppingList{
    print("\(li)  ")
}
println("")
for (key,value) in occupations{
    println("\(key) + \(value)")
}


/*
    这个很有用。
    比如:我从服务器拿到数据,可能为nil,也可能有数据,那么就可以这么赋值,如果拿到nil可以给出相应的提示
*/
var optionalName: String? = "John Appleseed"
optionalName = nil
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
    println("11 \(greeting)")
}else{
    println("optionalName为nil")
}

/*
    switch判断
*/
var vegetable = "red pepper"
vegetable = "watercress"
var vegetableComment = ""
switch vegetable {
case "celery":
    vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
    vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
    vegetableComment = "Is it a spicy \(x)?"
default:    //by gashero
    vegetableComment = "Everything tastes good in soup."
}
println("\(vegetableComment)")

 

posted @ 2014-06-06 16:04  坤哥MartinLi  阅读(103)  评论(0编辑  收藏  举报