swift basic3

generic

// Generics

func getThree<T>(x: T){
    print(x)
    print(x)
    print(x)
}

getThree(x: 5)
getThree(x: "Hello")
getThree(x: 2.3)

guard

// func sayHi(_ msg: String?){
//     if let s = msg{
//         print(s)
//     } else {
//         print("value is not set!")
//     }
// }
// sayHi(nil)
// sayHi("hello")

func sayHi(_ msg: String?){
    guard let s = msg else{
        print("value not set!")
        return
    } 
    print(s)
}

sayHi(nil)
sayHi("hello")

例外処理

// 例外処理

enum LoginError: Error{
    case emptyName
    case shortName
}

class User {
    let name: String
    init(_ name: String){
        self.name = name
    }
    func login() throws{
        guard name != "" else {
            throw LoginError.emptyName
        }
        guard name.characters.count > 5 else {
            throw LoginError.shortName
        }
        print("login success")
    }
}
let tom = User("tom")

do {
    try tom.login()
} catch LoginError.emptyName {
    print("please enter your name")
} catch LoginError.shortName{
    print("too short")
}

optional

// class User {
//     var name: String = ""
// }

// let user: User
// user = User()
// user.name = "him"
// let s = user.name.uppercased()
// print(s)

class User {
    var name: String = ""
}

let user: User?
user = User()
user?.name = "him"
if let s = user?.name?.uppercased(){
    print(s)
}
// Implicity Unwrapped Optional

// var msg: String?
var msg: String!
msg = "hello"

// if msg != nil {
//     print(msg!)
// }

print(msg)