swift 语法总结

来源:互联网 发布:网络推手阿建讲诚信 编辑:程序博客网 时间:2024/05/16 19:19
//输出
println("Hello, world”)

//var定义变量  let定义常量
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.”

//创建字典和数组
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>()

//for in 语句
let individualScores = [75, 43, 103, 87, 12]
for index in individualScores {
    println("\(index) times 5 is \(index * 5)")
}

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    println("\(animalName)s have \(legCount) legs")
}

for character in "Hello" {
    println(character)
}


//for循环
for var index = 0; index < 3; ++index {
    println("index is \(index)")
}

//while
var square = 0
var diceRoll = 0
while square < finalSquare {
    // roll the dice
    if ++diceRoll == 7 { diceRoll = 1 }
    // move by the rolled amount
    square += diceRoll
    if square < board.count {
        // if we're still on the board, move up or down for a snake or a ladder
        square += board[square]
    }
}
println("Game over!")

//if else
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    println("It's really warm. Don't forget to wear sunscreen.")
} else {
    println("It's not that cold. Wear a t-shirt.")
}

//switch case
64


//问号 感叹号
!告诉编译器这个变量绝对不为nil,当为nil的时候会报错
?告诉编译器这个变量可能为nil,当为nil的时候不会报错

//创建单例
import UIKit
 
classDataCenter: NSObject {
 
    classlet dataCenterObj:DataCenter = DataCenter()
 
    classfunc getDataCenter() ->DataCenter {
        returndataCenterObj
    }
}




6.协议(Protocols)

语法:

在Objective-C中我们这么声明Protocol:

1
2
3
@protocol SampleProtocol
- (void)someMethod;
@end

而在Swift中:

1
2
3
4
protocol SampleProtocol 
{
    func someMethod()
}

在Swift遵循协议:

1
2
3
4
class AnotherClass: SomeSuperClass, SampleProtocol
{
    func someMethod() {}
}

那么之前Objective-C的protocol中,我们可以标志optional。那在Swift中呢?


遗憾的是,目前纯Swift的protocol还不支持optional。但根据苹果官方论坛的一位员工的回答,未来Swift是会支持的。










0 0
原创粉丝点击