IT门户网,专注电脑知识与技术及手机硬件信息服务网站!

当前位置:IT门户网 > 系统教程 >

苹果公司推出的新编程语言Swift简介和入门教程

时间:2021-09-14    来源:IT门户网    人气:

一、Swift是什么?

Swift是苹果于WWDC 2014宣布的编程语言,这里引用The Swift Programming Language的原话:

复制代码 代码如下:


Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility.
Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible and more fun.
Swift's clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to imagine how software development works.
Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.

简朴的说:
Swift用来写iOS和OS X措施。(预计也不会支持其它丝系统)
Swift吸取了C和Objective-C的利益,且越发强大易用。
Swift可以利用现有的Cocoa和Cocoa Touch框架。
Swift兼具编译语言的高机能(Performance)和剧本语言的交互性(Interactive)。

二、Swift语言概览

1.根基观念

注:这一节的代码源自The Swift Programming Language中的A Swift Tour。

1.1.Hello, world

雷同于剧本语言,下面的代码等于一个完整的Swift措施。

复制代码 代码如下:


println("Hello, world")

1.2.变量与常量

Swift利用var声明变量,let声明常量。

复制代码 代码如下:


ar myVariable = 42
myVariable = 50
let myConstant = 42

1.3.范例推导

Swift支持范例推导(Type Inference),所以上面的代码不需指定范例,假如需要指定范例:

复制代码 代码如下:

let explicitDouble : Double = 70

Swift不支持隐式范例转换(Implicitly casting),所以下面的代码需要显式范例转换(Explicitly casting):

复制代码 代码如下:


let label = "The width is "
let width = 94
let width = label + String(width)


1.4.字符串名目化

Swift利用(item)的形式举办字符串名目化:

复制代码 代码如下:


let apples = 3
let oranges = 5
let appleSummary = "I have (apples) apples."
let appleSummary = "I have (apples + oranges) pieces of fruit."


1.5.数组和字典

Swift利用[]操纵符声明数组(array)和字典(dictionary):

复制代码 代码如下:


var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

一般利用初始化器(initializer)语法建设空数组和空字典:

复制代码 代码如下:


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

假如范例信息已知,则可以利用[]声明空数组,利用[:]声明空字典。

2.节制流

2.1概览

Swift的条件语句包括if和switch,轮回语句包括for-in、for、while和do-while,轮回/判定条件不需要括号,但轮回/判定体(body)必须括号:

复制代码 代码如下:


let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

2.2可空范例

团结if和let,可以利便的处理惩罚可空变量(nullable variable)。对付空值,需要在范例声明后添加?显式标明该范例可空。

复制代码 代码如下:


var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String? = "John Appleseed"
var gretting = "Hello!"
if let name = optionalName {
    gretting = "Hello, (name)"
}

2.3机动的switch

Swift中的switch支持各类百般的较量操纵:

复制代码 代码如下:


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

2.4其它轮回

for-in除了遍历数组也可以用来遍历字典:

复制代码 代码如下:


let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

while轮回和do-while轮回:

复制代码 代码如下:


var n = 2
while n < 100 {
    n = n * 2
}

var m = 2
do {
    m = m * 2
} while m < 100
m

Swift支持传统的for轮回,另外也可以通过团结..(生成一个区间)和for-in实现同样的逻辑。

复制代码 代码如下:

相关文章

系统教程排行榜

更多>>

网络知识排行榜

更多>>

系统教程排行榜

更多>>

服务号