Swift 3.0 语法

//: Playground - noun: a place where people can play

import UIKit

print(“swift 我来了,来啊”)

//let定义 常量
let name = “ak”
// var 定义变量
var password = “11111”
//Swift 并不强制要求你在每条语句的结尾处使用分号( ; ),当然,你也可以按照 你自己的习惯添加分号。有一种情况下必须要用分号,即你打算在同一行内写多条独立的语句
let cat = “?”; print(cat)

//#传变量
var key = “账号名:(name) 密码:(password)”

//定义指定类型变量 只能给 string 类型
//一般来说你很少需要写类型标注。如果你在声明常量或者变量的时候赋了一个初始值,Swift可以推断出这个常 量或者变量的类型,请参考类型安全和类型推断 (页 0)。在上面的例子中,没有给 welcomeMessage 赋初始 值,所以变量 welcomeMessage 的类型是通过一个类型标注指定的,而不是通过初始值推断的。
var welcomeMessage: String
welcomeMessage = “11”

//#类型别名 你可以使用 typealias 关键字来定义类型别名。
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.max

//#定义数组 第一项在数组中的索引值是 0 而不是 1 。 Swift 中的数组索引总是从零开始。
var someInts = Int
someInts.append(3)
print(someInts)

var shoppingList = [“catfish”, “water”, “tulips”, “blue paint”]
shoppingList[1] = “bottle of water”//修改 index=1的值
shoppingList.append(“Eggs”)//在最后加入一项
shoppingList.insert(“Maple Syrup”, at: 1)//指定位置加入一项
shoppingList.remove(at: 0)//移除指定index
//print(shoppingList)

//使用enumerated 遍历数组, 也可以使用 for in
for (index, value) in shoppingList.enumerated() {
print(“Item (String(index + 1)): (value)”)
}

//#定义字典

var occupations = [
“Malcolm”: “Captain”,
“Kaylee”: “Mechanic”,
]
occupations[“Jayne”] = “Public Relations”
occupations.updateValue(“ak”, forKey: “Kaylee”)//更新指定 KEY
occupations.removeValue(forKey: “Jayne”)
//print(occupations)
for (airportCode, airportName) in occupations {
print(“(airportCode): (airportName)”)
}

//#控制流 if
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
} }
print(teamScore)

let nickName: String? = nil
let fullName: String = “John Appleseed”
let informalGreeting = “Hi (nickName ?? fullName)”

//#switch
let vegetable = “red pepper”
switch vegetable {
case “celery”:
print(“Add some raisins and make ants on a log.”)
case “cucumber”, “watercress”://复合匹配
print(“That would make a good tea sandwich.”)
case let x where x.hasSuffix(“pepper”):
print(“Is it a spicy (x)?”)
default:
print(“Everything tastes good in soup.”)
}
//#函数 默认情况下,函数使用它们的参数名称作为它们参数的标签,在参数名称前可以自定义参数标签,或者使用 _ 表示不使用参数标签。
//返回多个值
func say(_ name:String, msg:String)->(persion: String,name:String)
{
return (“(name) 说:(msg)”,”你说的对~”)

}
let res = say(“ak”, msg: “世界你好.”)
print(res.persion,res.name)

//无返回值函数 没有返回箭头(->)和返回类型 没有定义返回类型的函数会返回一 个特殊的 Void 值
func greet(person: String) {
print(“Hello, (person)!”)
}
greet(person: “Dave”)

//#默认参数值,(很有用)你可以在函数体中通过给参数赋值来为任意一个参数定义默认值(Deafult Value)。当默认值被定义后,调用这 个函数时可以忽略这个参数。
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12)->Int {
// 如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
return parameterWithoutDefault+parameterWithDefault
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6)
someFunction(parameterWithoutDefault: 4)
//#可变参数,一个函数最多只能拥有一个可变参数。
func arithmeticMean(_ numbers: Double…) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5,7,10)
arithmeticMean(1, 2)

//#输入输出参数:在参数定义前加 inout 关键字。一个输入输出参数有传入函数的值,这个值被函数 修改,然后被传出函数,替换原来的值。
//交换两个变量值
func swapTwoInts(_ a:inout Int,_ b:inout Int)
{
let temporaryA = a
a=b
b=temporaryA

}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print(“someInt is now (someInt), and anotherInt is now (anotherInt)”)

//#函数可以嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()

//#对象和类
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return “A shape with (numberOfSides) sides.”
}
}
//调用类
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

//重写父类方法
class Square: Shape {
override func simpleDescription() -> String {
return “A square with sides of length 7.”
} }
var square = Square()
square.simpleDescription()

//#枚举
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return “ace”
case .Jack:
return “jack”
case .Queen:
return “queen”
case .King:
return “king”
default:
return String(self.rawValue)
}
} }
let ace = Rank.Ace
let aceRawValue = ace.rawValue

//#协议和扩展 类、枚举和结构体都可以实现协议。
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()// mutating 关键字用来标记一个会修改结构体的方法
}

class SimpleClass: ExampleProtocol {
var simpleDescription: String = “A very simple class.”
func adjust() {
simpleDescription += ” Now 100% adjusted.”
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

//#枚举语法 与 C 和 Objective-C 不同,Swift 的枚举成员在被创建时不会被赋予一个默认的整型值。在上面的 nt 例子中, north , south , east 和 west 不会被隐式地赋值为 0 , 1 , 2 和 3 。相反,这些枚举成员本身 就是完备的值,这些值的类型是已经明确定义好的 CompassPoint 类型。
enum CompassPoint
{
case north
case south
case east
case west

}

var somePlanet = CompassPoint.east
switch somePlanet {
case .north:
print(“Lots of planets have a north”)
case .south:
print(“Watch out for penguins”)
case .east:
print(“Where the sun rises”)
case .west:
print(“Where the skies are blue”)
default:
print(“Not a safe place for humans”)

}

//#结构体
//与 Objective-C 语言不同的是,Swift 允许直接设置结构体属性的子属性。上面的最后一个例子,就是直接设 置了 someVideoMode 中 resolution 属性的 width 这个子属性,以上操作并不需要重新为整个 resolution 属性设 置新值
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
let someResolution = Resolution()
let someVideoMode = VideoMode()
someVideoMode.resolution.width = 1280
print(“The width of someVideoMode is now (someVideoMode.resolution.width)”)

//#错误处理
//一种方式是使用 do-catch 。在 do 代码块中,使用 try 来标记可以抛出错误 的代码。在 catch 代码块中,除非你另外命名,否则错误会自动命名为 error 。
enum PrinterError: Error {
case OutOfPaper
case NoToner
case OnFire
}

func send(_ job: Int, _ printerName: String) throws -> String {
// 这个函数有可能抛出错误

if printerName == "Never Has Toner" {
    throw PrinterError.NoToner
}
return "Job sent"

}

do {
let printerResponse = try send(1040, “Never Has Toner”)
// 没有错误消息抛出
print(printerResponse)
} catch {
// 有一个错误消息抛出
print(error)

}

//#断言
let age = 3
assert(age >= 0, “A person’s age cannot be less than zero”) // 因为 age < 0,所以断言会触发

//#闭区间运算符( a…b )定义一个包含从 a 到 b (包括 a 和 b )的所有值的区间。
//1…5 包括1和5
//1..<5 包括1不包括5
for index in 1…5 {
print(“(index) * 5 = (index * 5)”)
}

//#字符串和字符
var emptyString = “” //等价 var emptyString = String()
if emptyString.isEmpty {
print(“string is nil”)
}

//字符长度
var stringlet = “123456”
print(stringlet.characters.count)

//#前缀/后缀相等
var prefixStr = “ABCDEF”
if prefixStr.hasPrefix(“A”)
{
print(“prefix str 以 A 开头”);
}

if prefixStr.hasSuffix(“F”)
{
print(“prefix str 以 F 结束”);
}

//#检测 API 可用性 Swift内置支持检查 API 可用性,这可以确保我们不会在当前部署机器上,不小心地使用了不可用的API。

//#闭包表达式 **
let stnames = [“Chris”, “Alex”, “Ewa”, “Barry”, “Daniella”]

func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var reversedNames = stnames.sorted(by: backward)

//===========================================================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值