swift基础学习(06)[必要构造器,可空链式调用,错误处理,类型转换]

前端之家收集整理的这篇文章主要介绍了swift基础学习(06)[必要构造器,可空链式调用,错误处理,类型转换]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

@H_404_1@1.在类的构造器前添加required修饰符表明所有该类的子类都必须实现该构造器

必要构造器实现的代码

@H_404_1@

class SomeClass {

required init(){

}

}

子类重写父类的必要构造器方法实现的代码不需要添加override

class SomeSubClass: SomeClass {

}

}

通过设置闭包和函数来设置属性的默认值


struct Checkerboard {

let boardColors: [Bool] = {

var temporaryBoard = [Bool]()

var isBlack = false

for i in 1...10 {

for j in 1...10 {

temporaryBoard.append(isBlack)

isBlack = !isBlack

}

isBlack = !isBlack

}

return temporaryBoard

}()

func squareIsBlackAtRow(row: Int,column: Int) -> Bool {

return boardColors[(row * 10) + column]

}

}

let board = Checkerboard()

print(board.squareIsBlackAtRow(0,column: 1))

2. 可空链式调用

是一种可以请求和调用属性方法及下标的过程,它的可控件体现于请求或调用的目标当前可能为空,如果可空的目标有值,那么调用就会成功,如果选择的目标为空,那么这种调用将返回空,多个连续调用可以背链接在一起形成一个调用,如果其中任何一个节点为空将导致整个链调用失败

class Person {

var residence:Residence?

}


class Residence {

var rooms = [Room]()

var numberOfRooms: Int {

return rooms.count

}

subscript(i: Int) -> Room {

get {

return rooms[i]

}

set {

rooms[i] = newValue

} }

func printNumberOfRooms() {

print("The number of rooms is \(numberOfRooms)")

}

var address: Address?

}


class Room {

let name: String

init(name: String) { self.name = name }

}


class Address {

var buildingName: String?

var buildingNumber: String?

var street: String?

func buildingIdentifier() -> String? {

if buildingName != nil {

return buildingName

} else if buildingNumber != nil {

return buildingNumber

} else {

return nil

} }

}

3.

错误处理:是响应错误以及从错误中恢复的过程。swift提供了在运行对可恢复错误抛出,捕获传送和操作的高级支持

表示并抛出错误:Swift,错误用遵循 ErrorType 协议类型的值来表示

enum VendingMachineError:ErrorType {

case InvalidSelection//选择无效

case InsufficientFunds(coinsNeed:Int)//金额不足

case OutOfStock//缺货

}

错误处理:throwing函数传递错误

do-catch处理错误

4.

类型转换

class MediaItem {

var name: String

init(name:String){

self.name = name

}

}

class Movie:MediaItem {

var director:String

init(name:String,director:String){

self.director = director

super.init(name: name)

}

}

class Song: MediaItem {

var artist:String

init(name:String,artist:String){

self.artist = artist

super.init(name: name)

}

}

给一个数组常量

let library = [ Movie(name: "Casablanca",director: "Michael Curtiz"),

Song(name: "Blue Suede Shoes",artist: "Elvis Presley"),

Movie(name: "Citizen Kane",director: "Orson Welles"),

Song(name: "The One And Only",artist: "Chesney Hawkes"),

Song(name: "Never Gonna Give You Up",artist: "Rick Astley")

]

//检查类型:用类型检查操作符( is )来检查一个实例是否属于特定子类型

var movieCount = 0

var songCount = 0

for item in library {

if item is Movie {

++movieCount

} else if item is Song {

++songCount

}

}

print(movieCount,songCount)

向下转型:某类型的一个常量或变量可能在幕后实际上属于一个子类。当确定是这种情况时,你可以尝试向下转到它的子类型,用类型转换操作符(as? as!)

for item in library {

if let movie = item as? Movie {

print("Movie:'\(movie.name)',dir.\(movie.director)")

} else if let song = item as? Song {

print("Song:'\(song.name)',by \(song.artist)")

}

}

any anyobject的类型转换

swift为不确定类型提供了特殊类型别名

anyobject 可以代表任何class类型的实例

any 可以表示任何类型,包括方法类型

let someObjects: [AnyObject] = [

Movie(name: "2001: A Space Odyssey",director: "Stanley Kubrick"),

Movie(name: "Moon",director: "Duncan Jones"),

Movie(name: "Alien",director: "Ridley Scott")

]

for object in someObjects {

let movie = object as! Movie

print("Movie: '\(movie.name)',dir. \(movie.director)")

}


any类型

var things = [Any]()

things.append(0)

things.append(0.0)

things.append(42)

things.append(3.1415126)

things.append("hello")

things.append(Movie(name:"lihuan",director: "hello"))

猜你在找的Swift相关文章