首页 > 代码库 > swift学习记录

swift学习记录

 

0.句末不用打分号

1.变量var 常量let,不用指定类型,自动推断

2.当需要指定类型时:

let explicitDouble:Double=7  //7.0

3.+号不能自动把数字变成string,全部用显式转换:

let label="The width is"

let width=94

let widthLable= label+String(width) 

4.也可以用\()来插入一个变量或常量,比java麻烦嘛。

let apples=3
let summary="I have \(apple) apples" // I have 3 apples
let oranges=5
let fruitSummary="I have  \(apple+oranges) pieces of fruit"//I have 8 pieces of fruit

5.数组和字典用[],感觉跟groovy一样啊

var array=["catfish","water","tulips","blue paint"]
array[1]
array[1]="bottle of water"
var occupations = [
    "malcolm":"Captain",
    "Kaylee":"Mechanic",
]
occupations["Jayne"]="Public Relations" //改了一个值,这语法貌似是跟groovy的map一样的
occupations  //这个直接起到了打印效果,至少在playground里是

6.空的数组和字典,指定类型的

let emptyArrary=String[]()
let emptyDictionary = Dictionary<String,Float>()

7.空的数组和字典,不指定类型的

let shoppinglist=[]
let dictionary=[:]  //如果类型能推断出来才用这里的两种写法

 

 

 

 

// Playground - noun: a place where people can play

import Cocoa

var myVariable=42
myVariable=50
let myConstant=42

let implicitInteger=70
let implicitDouble=70.0
let explicitDouble:Double=70

let explicitFloat:Float=4


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) piece of fruit"

let floatNumber:Float=4
let name="Ting"
let floatsummary="i am adding \(floatNumber+explicitFloat), haha \(name)"

var array=["catfish","water","tulips","blue paint"]
array[1]
array[1]="bottle of water"
var occupations = [
    "malcolm":"Captain",
    "Kaylee":"Mechanic",
]

occupations["Jayne"]="Public Relations"
occupations

let emptyArrary=String[]()
let emptyDictionary = Dictionary<String,Float>()

let shoppinglist=[]


let individualScores=[75,43,103,87,12]
var teamScore = 0
teamScore
for score in individualScores{
   "aaa"
    println(score)
}

"aaa"


for score in individualScores{
    if score > 50 {
        teamScore+=3
    } else {
        teamScore+=1
    }
    
}
teamScore



var optionalString:String? = "Hello"
optionalString == nil

var optionalName:String? = "John Appleseed"

var greeting = "Hello!"
if let name = optionalName{
    greeting = "Hello, \(name)"
} else if optionalName == nil {

    greeting = "Hello, nil"
}



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."
}
View Code