Swift 3.0 (一)
转载自:酷走天涯(文中部分错误已修改 如发现请告知) 基本数据类型
let myConstant = 42
var myVariable = 42
myVariable = 50
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
var numb:Double
let label = "The width is "
width = 94
let 94
let widthLabel:String = String(width)
let apples = 3
let oranges = 5
let fruitSummary = "I have (apples + oranges) pieces of fruit."
var shoppingList = ["catfish","water",152)">"tulips",152)">"blue paint"]
shoppingList[1] = "bottle of water"
let emptyArray = [String]()
let emptyArray:[String] = []
var occupations = [
"Malcolm": "Captain",152)">"Kaylee": "Mechanic",]
var shopingList1 = ["1",152)">"2"]
shopingList1 = [] // 如果你这个类型,是系统可以推断的类型,你可以这样清空数组或者初始化
let emptyDictionary = [String: Float]()
let emptyDictionary:[String: Float] = [:]
dictionary = [1:"2"]
dictionary = [:]
可选值let nickName: String? = nil
运行下面的代码: let nickName: String? = "酷走天涯"
print(nickName)
结果:
发现有个Optional 就说明这个变量被包着,那么怎么才能不让它包裹着呢? 很简单,给变量加一个"!" print(nickName!)
运行:
我们还有一种解包的方式 String? = nil
let fullName: String = "XUJIE"
let informalGreeting = "Hi (nickName ?? fullName)"
print(informalGreeting)
如果第一个解包值发现为nil,则使用第二值 控制流
// 遍历数组
let individualScores = [75,43,152)">103,152)">87,152)">12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
// 遍历 字典
let interestingNumbers = [
"Prime": [2,152)">3,152)">5,152)">7,152)">11,152)">13],152)">"Fibonacci": [1,152)">8],152)">"Square": [4,152)">9,152)">16,152)">25],]
var largest = for (kind,numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
// 还可以这样使用循环
var total = 0
for i in 0..<4 {
total += i
}
print(total)
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
"cucumber",152)">"watercress":
"That would make a good tea sandwich.")
case let z where z.hasSuffix("pepper"):
"Is it a spicy (z)?")
default:
"Everything tastes good in soup.")
}
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
函数和闭包
func greet(person: String,day: String) -> String {
return "Hello (person),today is (day)."
}
greet(person: "Bob",210)">day: "Tuesday")
func greet(_ person: String,152)">_ day: String) ->
}
greet("John",152)">"Wednesday")
func calculateStatistics(scores: [Int]) -> (min: Int,210)">max: Int,210)">sum: Int) {
min = scores[0]
max = scores[sum = in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min,210)">max,210)">sum)
}
let statistics = calculateStatistics(scores: [100,152)">9])
print(statistics.sum)
print(statistics.2)
func sumOf(numbers: Int...) -> Int {
var sum = in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(numbers: 42,152)">597,152)">12)
returnFifteen() -> Int {
var y = 10
add() {
y += 5
}
// 方法内部定义方法,声明周期为方法
add()
return y
}
returnFifteen()
func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
hasAnyMatches(list: [Int],condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20,152)">19,152)">12]
hasAnyMatches(list: numbers,condition: lessThanTen)
对象和类
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
"A shape with (numberOfSides) sides."
}
}
NamedShape {
var numberOfSides: Int = 0
var name: String
// 初始化方法
init(name: String) {
self.name = name
}
// 成员方法定义
simpleDescription() -> String {
"A shape with (numberOfSides) sides."
}
}
Square: NamedShape {
var sideLength: Double // 如果不是可选类型 必须在初始化方法中初始化
init(sideLength: Double,name: String) {
self.sideLength = sideLength
super.init(name: name) // 调用父类的初始化方法
numberOfSides = 4 // 给父类的属性赋值之前必须先调用父类的初始化方法
}
area() -> Double {
return sideLength * sideLength
}
// 重写父类的方法
override String {
"A square with sides of length (sideLength)."
}
}
EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0 // 定一个属性
init(sideLength: Double,name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
// 这个是setter 和geterr方法的定义
var perimeter: Double {
get {
3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
"An equilateral triangle with sides of length (sideLength)."
}
}
class TriangleAndSquare {
// 定一个三角形对象
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
// 定一个一个正方形对象
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
// 通过检测属性,我们让两个对象的边保持一样长
init(size: Double,name: String) {
square = Square(sideLength: size,name: name)
triangle = EquilateralTriangle(sideLength: size,name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10,name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50,152)">"larger square")
print(triangleAndSquare.triangle.sideLength)
运行结果
枚举类型
enum Rank: Int { // Int 设置枚举值的类型
// 定义枚举值设置值
case ace = 1
// 可以case 后面一次定义多个枚举值
case two,three,four,five,six,seven,eight,nine,ten
case jack,queen,king
// 定义函数 如果多人合作的时候,可以使用这个让别人更加了解你定义的属性的含义
String {
switch self { // self 就是这个枚举本身
case .ace:
"ace"
case .jack:
"jack"
case .queen:
"queen"
case .king:
"king"
default:
return String(self.rawValue)
}
}
}
// 使用
let ace = Rank.ace
let aceRawValue = ace.rawValue
问题1 如何想OC 一样使用 | 或操作呢? 结构体
letthreeOfSpades = Card(rank: .three,suit: .spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() 协议
SimpleClass: ExampleProtocol {
"A very simple class."
var anotherProperty: 69105
adjust() {
simpleDescription += " Now 100% adjusted."
}
}
SimpleStructure: "A simple structure"
" (adjusted)"
}
}
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
扩展例子:给Int 添加一个协议 extension Int: ExampleProtocol {
"The number (self)"
}
adjust() {
self += 42
}
}
print(7.simpleDescription)
错误操作
PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
send(job: Int,toPrinter printerName: String) throws -> if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
"Job sent"
}
do {
let printerResponse = try send(job: 1040,toPrinter: "Bi Sheng")
print(printerResponse)
} catch {
print(error)
}
1440,152)">"Gutenberg")
catch PrinterError.onFire {
print("I'll just put this over here,with the rest of the fire.")
} catch let printerError as PrinterError {
"Printer error: (printerError).")
} catch {
print(error)
}
总结 Swift 的基本语法已经了解完毕,但这只是些简单的东西,如果Swift只是这些东西,那我们就没有学习的必要了,Swift的灵活性,优秀的设计模式,从上面的内容体现不出来,我会在后面几篇文章中,阐述它的高级用法! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |