swift basic 2

protocol

// protocol

protocol Printable {
    var type: String { get }
    var count : Int { get set}
    func printout()
}

class User : Printable{
    let name: String // property
    let type = "Laser"
    var count = 0
    init(_ name: String){
        self.name = name
    }
    func printout(){
        count += 1
        print("\(type): \(count)")
    }
}

let tom = User("tom")
tom.printout()
tom.printout()
tom.printout()

extension

// extension

extension String {
    var length: Int {
        return self.characters.count
    }
}

let msg = "hello"
print(msg.characters.count)
print(msg.length)

protocol Printable {
    func printout()
}

class User{
    let name: String // property
    init(_ name: String){
        self.name = name
    }
}
// extension

extension String {
    var length: Int {
        return self.characters.count
    }
}

let msg = "hello"
print(msg.characters.count)
print(msg.length)

protocol Printable {
    func printout()
}

extension Printable {
    func printout(){
        print("now printing...")
    }
}

class User: Printable{
    let name: String // property
    init(_ name: String){
        self.name = name
    }
}
let tom = User("tom")
tom.printout

値の参照

// Int, Double, Array .. ->値型
// Class -> 参照型

// var original = 10
// var copy = original // original

// original = 20
// print(original)
// print(copy)

class User{
    var name: String // property
    init(_ name: String){
        self.name = name
    }
}

var original = User("tom")
var copy = original // originalのデータが格納されている場所
original.name = "bob"
print(original.name)
print(copy.name)

構造体

// 構造体
// クラスと同機能

struct User{
    var name: String // property
    init(_ name: String){
        self.name = name
    }
    mutating func changeName(){
        self.name = name.Uppercased()
    }
}

var original = User("tom")
var copy = original // originalの値
original.name = "bob"
print(original.name)
print(copy.name)
// 列挙型

enum Direction {
    case right
    case left
}

// var dir: Direction
// // dir = Direction.right
// dir = .right

// switch(dir){
//     case .right:
//         print("right")
//     case .left:
//         print("left")
// }
enum Direction: Int {
    case right = 1
    case left = -1
}
print(Direction.right.rawValue)