Swift learn 6

Swift Class继承处理

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

import UIKit

//结构体&类的使用
struct NewStruct {
    var name:String = "";
    var age:Int = 18;
}

class Person{
    var person:NewStruct = NewStruct(name: "MichaelZero", age: 20);
    
    var className:String?;
    
    var friendIds:[Int]?;
    
    init(className:String){
        self.className = className;
    }
}

var person0 = Person(className:"C1");
println("PName:\(person0.person.name)");

//如果能够判定两个常量或者变量是否引用同一个类实例将会很有帮助。为了达到这个目的,Swift 内建了两个恒等运算符

var person1 = person0;
if person0 === person1{
    println("this is a same class.");
}else{
    println("this is a not same class.");
}

//结构体实例总是通过值传递,类实例总是通过引用传递。这意味两者适用不同的任务。当你在考虑一个工程项目的数据构造和功能的时候,你需要决定每个数据构造是定义成类还是结构体。

//结构体的主要目的是用来封装少量相关简单数据值。
//有理由预计一个结构体实例在赋值或传递时,封装的数据将会被拷贝而不是被引用。
//任何在结构体中储存的值类型属性,也将会被拷贝,而不是被引用。
//结构体不需要去继承另一个已存在类型的属性或者行为。

//合适的结构体候选者包括:
//几何形状的大小,封装一个width属性和height属性,两者均为Double类型。
//一定范围内的路径,封装一个start属性和length属性,两者均为Int类型。
//三维坐标系内一点,封装x,y和z属性,三者均为Double类型。

struct StaticStr {
    var name:Int;
    let systemName:String;
}

//除存储属性外,类、结构体和枚举可以定义计算属性,计算属性不直接存储值,而是提供一个 getter 来获取值,一个可选的 setter 来间接设置其他属性或变量的值。
class ParamsCount{
    var x:Int = 10;
    var y:Int = 10;
    var (x0, y0):(Int, Int);
    
    init(){
        (x0, y0) = (0 , 0);
    }
    
    var pointLink:(Int , Int){
        get {
            let x_link = self.x - self.x0;
            let y_link = self.y - self.y0;
            
            return (x_link , y_link);
        }
        
        set(newPoint){
            self.x = newPoint.0;
            self.y = newPoint.1;
        }
    }
}

//计算中心点坐标
struct Point {
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter) {
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
    size: Size(width: 10.0, height: 10.0));
let initialSquareCenter = square.center;
square.center = Point(x: 15.0, y: 15.0)
println("square.origin is now at (\(square.origin.x), \(square.origin.y))");


//结构体和枚举是值类型。一般情况下,值类型的属性不能在它的实例方法中被修改。
//但是,如果你确实需要在某个具体的方法中修改结构体或者枚举的属性,你可以选择变异(mutating)这个方法,然后方法就可以从方法内部改变它的属性;并且它做的任何改变在方法结束时还会保留在原始结构中。方法还可以给它隐含的self属性赋值一个全新的实例,这个新实例在方法结束后将替换原来的实例。
struct PointS {
    var x = 0.0, y = 0.0
    mutating func moveByX(deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}
var somePoint = PointS(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
println("The point is now at (\(somePoint.x), \(somePoint.y))");

struct PointN {
    var x = 0.0, y = 0.0
    mutating func moveByX(deltaX: Double, y deltaY: Double) {
        self = PointN(x: x + deltaX, y: y + deltaY)
    }
}

//实例方法是被类型的某个实例调用的方法。你也可以定义类型本身调用的方法,这种方法就叫做类型方法。声明类的类型方法,在方法的func关键字之前加上关键字class;声明结构体和枚举的类型方法,在方法的func关键字之前加上关键字static。
struct LevelTracker {
    static var highestUnlockedLevel = 1
    static func unlockLevel(level: Int) {
        if level > highestUnlockedLevel { highestUnlockedLevel = level }
    }
    static func levelIsUnlocked(level: Int) -> Bool {
        return level <= highestUnlockedLevel
    }
    var currentLevel = 1
    mutating func advanceToLevel(level: Int) -> Bool {
        if LevelTracker.levelIsUnlocked(level) {
            currentLevel = level
            return true
        } else {
            return false
        }
    }
}

class Player{
    var tracker = LevelTracker();
    let playerName : String;
    func completedLevel(level:Int){
        LevelTracker.unlockLevel(level+1);
        tracker.advanceToLevel(level+1);
    }
    
    init(name:String){
        playerName = name;
    }
}

var player = Player(name: "Zero");
player.completedLevel(1);
println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)");

player = Player(name: "Michael")
if player.tracker.advanceToLevel(6) {
    println("player is now on level 6");
} else {
    println("level 6 has not yet been unlocked");
}

//下标脚本允许你通过在实例后面的方括号中传入一个或者多个的索引值来对实例进行访问和赋值。语法类似于实例方法和计算型属性的混合。与定义实例方法类似,定义下标脚本使用subscript关键字,显式声明入参(一个或多个)和返回类型。
//这种是用于基于一个固定的数学公式
struct Times{
    let basicNum:Int;
    
    subscript(index:Int) -> String{
        return String.convertFromStringInterpolationSegment(index * basicNum);
    }
}

var times = Times(basicNum: 10);
println("testing Value\(times[5])");

//根据使用场景不同下标脚本也具有不同的含义。通常下标脚本是用来访问集合(collection),列表(list)或序列(sequence)中元素的快捷方式。你可以在你自己特定的类或结构体中自由的实现下标脚本来提供合适的功能。
struct Matrix {
    let rows: Int, columns: Int
    var grid: [Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: 0.0)
    }
    func indexIsValidForRow(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

var matrix = Matrix(rows: 10, columns: 10);

matrix[0 , 0] = 10;

println("value\(matrix[0 , 0])");

//object的继承操作
class User{
    var name:String?;
    var age:Int?;
    
    init(name:String, age:Int){
        self.name = name;
        self.age = age;
    }
    
    var desctiption: String{
        return "My Name is:\(self.name), age is:\(self.age)";
    }
    
    func jobs(){}
}

class Student: User{
    var className:String?;
    
    override func jobs() {
        println("my work is a student!");
    }
}

class Teacher: User{
    var officeName:String?;
    
    init(name:String, age:Int, officeName:String){
        self.officeName = officeName;
        super.init(name: name, age: age);
    }
    
    override var desctiption:String{
        get{
            return "new desctiption for teacher.";
        }
        set{
            super.desctiption+"& new for teacher.";
        }
    }
}

var stu1 = Student(name:"Michael", age:10);

println(stu1.desctiption);
stu1.jobs();

var tea = Teacher(name:"Zero" , age:20, officeName:"office");
println(tea.desctiption);

//你可以在定义构造器时提供构造参数,为其提供定制化构造所需值的类型和名字。构造器参数的功能和语法跟函数和方法参数相同。
class Temperature{
    var temperatureV: Double = 0.0;
    
    init(formF f:Double){
        temperatureV = (f-32)/1.8;
    }
    
    init(formK k:Double){
        temperatureV = k - 273.15;
    }
}

//
struct Rects {
    var origin = Point()
    var size = Size()
    init() {}
    init(origin: Point, size: Size) {
        self.origin = origin
        self.size = size
    }
    init(center: Point, size: Size) {
        let originX = center.x - (size.width / 2)
        let originY = center.y - (size.height / 2)
        self.init(origin: Point(x: originX, y: originY), size: size)
    }
}

class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    convenience init() {
        self.init(name: "[Unnamed]")
    }
}
var food = Food();

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]
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Learn Swift by Building Applications: Explore Swift programming through iOS app development by Emil Atanasov Packt Publishing English 2018-05-25 366 pages 5.0/5.0 1 reviews Details Title: Learn Swift by Building Applications: Explore Swift programming through iOS app development Author: Emil Atanasov Length: 366 pages Edition: 1 Language: English Publisher: Packt Publishing Publication Date: 2018-05-25 ISBN-10: 178646392X ISBN-13: 9781786463920 Sales Rank: #1123253 (See Top 100 Books) Categories Computers & Technology Mobile Phones, Tablets & E-Readers Operating Systems Programming Programming Languages Description Start building your very own mobile apps with this comprehensive introduction to Swift and object-oriented programming Key Features A complete beginner's guide to Swift programming language Understand core Swift programming concepts and techniques for creating popular iOS apps Start your journey toward building mobile app development with this practical guide Book Description Swift Language is now more powerful than ever; it has introduced new ways to solve old problems and has gone on to become one of the fastest growing popular languages. It is now a de-facto choice for iOS developers and it powers most of the newly released and popular apps. This practical guide will help you to begin your journey with Swift programming through learning how to build iOS apps. You will learn all about basic variables, if clauses, functions, loops, and other core concepts; then structures, classes, and inheritance will be discussed. Next, you'll dive into developing a weather app that consumes data from the internet and presents information to the user. The final project is more complex, involving creating an Instagram like app that integrates different external libraries. The app also uses CocoaPods as its package dependency manager, to give you a cutting-edge tool to add to your skillset. By the end of the book, you will have learned how to model real-world apps

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值