加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 语法总结

发布时间:2020-12-14 06:49:13 所属栏目:百科 来源:网络整理
导读://输出 println("Hello,world”) //var定义变量 let定义常量 varmyVariable = 42 myVariable = 50 let myConstant = 42 //定义常量或变量的时候指定类型 let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble: Double = 70 //定义字符串
//输出
println("Hello,world”)

//var定义变量 let定义常量
varmyVariable = 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 = “Ihave (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 {
let dataCenterObj:DataCenter = DataCenter()
func getDataCenter() ->DataCenter {
return dataCenterObj
}
}




6.协议(Protocols)

语法:

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

1
2
3
@protocolSampleProtocol
-(void)someMethod;
@end

而在Swift中:

3
4
protocolSampleProtocol
{
funcsomeMethod()
}

在Swift遵循协议:

4 classAnotherClass:SomeSuperClass,SampleProtocol
funcsomeMethod(){}
那么之前Objective-C的protocol中,我们可以标志optional。那在Swift中呢?


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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读