swift 语法总结

31 篇文章 0 订阅
1 篇文章 0 订阅
//输出
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
 
class DataCenter: NSObject {
 
     class let dataCenterObj:DataCenter = DataCenter()
 
     class func getDataCenter() ->DataCenter {
         return dataCenterObj
     }
}




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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值