Swift Learn 5

Source: Internet
Author: User

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

import UIKit

// Use of structs & classes
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)");

// It would be helpful to be able to determine if two constants or variables refer to the same class instance. To achieve this, Swift has two built-in identity operators

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

// Structure instances are always passed by value, and class instances are always passed by reference. This means that the two are suitable for different tasks. When you are considering the data structure and function of an engineering project, you need to decide whether each data structure is defined as a class or a structure.

// The main purpose of the structure is to encapsulate a small number of related simple data values.
// It is reasonable to expect that when a structure instance is assigned or passed, the encapsulated data will be copied instead of referenced.
// Any value type property stored in the structure will also be copied instead of referenced.
// Structures do not need to inherit properties or behaviors of another existing type.

// Suitable structure candidates include:
// The size of the geometry, encapsulates a width property and a height property, both of which are of type Double.
// A path within a certain range, encapsulates a start attribute and a length attribute, both of which are of type Int.
// A point in the three-dimensional coordinate system, which encapsulates the x, y, and z attributes, all of which are Double types.

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

// In addition to storing attributes, classes, structures, and enumerations can define computed attributes. Computed attributes do not store values directly, but instead provide a getter to get the value, and an optional setter to indirectly set the value of other attributes or variables.
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;
        }
    }
}

// Calculate center point coordinates
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))");


// Structures and enums are value types. In general, a property of a value type cannot be modified in its instance method.
// However, if you really need to modify the properties of a structure or enum in a specific method, you can choose to mutate this method, and then the method can change its properties from within the method; Any changes will remain in the original structure at the end of the method. A method can also assign a completely new instance to its implicit self property. This new instance will replace the original instance after the method ends.
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)
    }
}

// Instance method is a method called by an instance of the type. You can also define a method called by the type itself. This method is called a type method. To declare the type method of a class, add the keyword class before the func keyword of the method; to declare the type method of the structure and enumeration, add the keyword static before the func keyword of the method.
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 scripts allow you to access and assign instances by passing one or more index values in square brackets after the instance. The syntax is similar to a mixture of instance methods and computed properties. Similar to defining instance methods, defining subscript scripts uses the subscript keyword, explicitly declaring the input parameter (s) and return type.
// This is used to base a fixed mathematical formula
struct Times {
    let basicNum: Int;
    
    subscript (index: Int)-> String {
        return String.convertFromStringInterpolationSegment (index * basicNum);
    }
}

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

// Subscripts have different meanings according to different usage scenarios. Subscript scripts are usually shortcuts for accessing elements in a collection, list, or sequence. You are free to implement subscript scripts in your own specific classes or structures to provide the appropriate functionality.
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])");



Swift Learn 5


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.