The Swift Programming Language阅读笔记

前端之家收集整理的这篇文章主要介绍了The Swift Programming Language阅读笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

传统上,每种语言都用Hello World作为首程序,那么,我们也以此开始Swift学习之旅吧!

打开Xcode—>create a new project—>OS X Application—>Command Line Tool—>Language(Swift)

main.swift

println("Hello,World")

1.生成文件名:以.swift作为扩展名
2.从上面的程序可知:
①Swift不需要导入头文件
②Swift不需要main函数
③Swift不需要每一语句都以;结束

此外,在编写Swift程序的时候,可以通过Xcode 的playground来进行查看程序运行的结果,工欲善其事必先利其器,如何使用playground,http://www.jb51.cc/article/p-thguepmy-bbr.html,这是个人的一个小总结,下面所讲的程序都将在playground中进行

01-变量和常量
用 var定义变量,let定义常量

var myVariable = 42 
myVariable = 50
let myConstant = 42

但是,无论是变量还是常量,好像都不知道所定义的数据类型。其实不是这样的,编译器会根据所赋值默认变量的数据类型,可以如下:

let implicitInteger = 70
let implicitDouble = 70.0 // ①

对于①,如果是Float类型(注:在Swift中,数据类型名首字母大写),是否跟C语言一样写成70.0f?不是的:

let explicitFloat : Float = 70.0
// ②

如何证明呢?
可以在②处输入explicitFloat,Xcode会有提示提示可以看到:Float explicitFloat

练习:
定义一个数据类型为Float的常量

let num: Float = 4

一种数据类型的数可以通过强制转换成另一种数据类型

02-字符串

let label = "The width is "
let width = 94
let labelWidth = label + String(94) // + :具有拼接两个字符串的作用

输出结果:

“The width is 94”

如果要在字符串中显示变量,可以:(变量名)

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

练习:

let name = "chengfeng_Yang"
let a: Float = 12.2
let b: Float = 12.2
let greeting = "Hello,\(name). \(a) + \(b) = \(a+b)"

03-数组和字典
空数组用[],空字典用:[:]

let emptyArray = [String]() // ①
let emptyDictionary = DIctionary<String,Float>()


对于①,原来是:let emptyArray = String[]():不过运行过程出现:Array types are now written with the brackets around the element type,并且此时编译器会提示:Fix-it String[->[String 或 Fix-it Insert [

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

04-控制流

let individualscore = [75,43,103,87,12]
var teamscore = 0
for score in individualscore{
    if score > 50{ // if后面应该是Bool类型
        teamscore  += 3
    } else {
        teamscore += 1
    }
}
teamscore

如无特殊说明,下面的程序的输出结果作为注释,注在 // 后

用?标记optional type,用nil表示此类型数据丢失

var optionalSrting: String? = "Hello" // Hello
optionalSrting == nil // false

if语句:

var optionalName: String? = "John"
var greeting1 = "Hello"
if let name = optionalName{
    greeting1 = "Hello,\(name)"
}

switch语句:
1.一定要讨论到所有情况(即:default在大部分情况下是不能省略的)
2.where的作用:用来增加判断条件
3.case用法
4.不需要break也可以执行完对应的内容自动对出程序

let vegetable = "red pepper"
switch vegetable {
    case "celery":
        let vegetableComment = "Add1"
    case "cucuber","watercress":
        let vegetableComment = "Add2"
    case let x where x.hasSuffix("pepper"):
        let vegetableComment = "\(x)"
    default:
        let vegetableComment = "nothing"
}
原文链接:https://www.f2er.com/swift/324764.html

猜你在找的Swift相关文章