首页 > 代码库 > swift语法

swift语法

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

 

import UIKit

 

var str = "Hello, playground"

 

var str1="test"

str1

 

println("ddddd")

 

let implmentInteger : Double=12

 

let floattest:Float=4

 

//可变

func sumOf(numbers: Int...) -> Int {

    var sum = 0

    for number in numbers {

        sum += number

    }

    return sum

}

sumOf()

sumOf(42, 597, 12)

 

 

var optionString:String?="Hello"

optionString=nil

var greeting="Hello!"

var optionName:String?="Jack"

optionName=nil

if let name=optionName{

   greeting="Hello,\(name)"

}else{

    greeting

}

 

struct Color {

    let red = 0.0, green = 0.0, blue = 0.0

    init(_ red: Double,_ green: Double,_ blue: Double) {

        self.red   = red

        self.green = green

        self.blue  = blue

    }

}

 

Color(1,1,1)

 

var description : String  {

    return "Hello"

}

description

 

let possibleNumber = "123"

let convertedNumber = possibleNumber.toInt()

// convertedNumber 被推测为类型 "Int?"或者类型 "optional Int"

convertedNumber!

 

数组

Array<SomeType>

SomeType[]

var shoppingList: String[] = ["Eggs", "Milk"]
var shoppingList = ["Eggs", "Milk"]
var someInts = Int[]()

someInts=[]
var threeDoubles = Double[](count: 3, repeatedValue:0.0)


字典
Dictionary<KeyType, ValueType>
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
var airports = ["TYO": "Tokyo", "DUB": "Dublin"]
var namesOfIntegers = Dictionary<Int, String>()
namesOfIntegers = [:]// namesOfIntegers 又成为了一个 Int, String类型的空字典




swift语法