//var s: String? //s = nil let name: String? = "yamada" let msg = "hello " + name! if name != nil { let msg = "hello " + name! } if let s = name { let msg = "hello " + s } var label: String! label = "score" println(label)
function
//func sayHi(){ // println("hi") //} //sayHi() func sayHi(name: String){ println("hi " + name) } sayHi("satoshi") func sayHi(myname name: String){ println("hi " + name) } sayHi(myname: "satoshi") func sayHi(#name: String = "jiro"){ println("hi " + name) } sayHi(name: "satoshi")
列挙型
enum Result { case Success case Error func getMessage() -> String { switch self { case .Success: return "OK" case .Error: return "OK" } } } var r: Result r = Result.Success r = .Success Result.Error.rawValue
class
class User { var name: String var score: Int = 0 init(name: String){ self.name = name } func updrade() { score++ } } var tom = User(name: "Tom") tom.name tom.score tom.updrade() tom.score
継承
class User { var name: String var score: Int = 0 init(name: String){ self.name = name } final func upgrade() { score++ } } class AdminUser: User { func reset(){ score = 0 } override func upgrade(){ score += 3 } }
protocol
protocol Student { var studentId: String { get set } func study() } class User: Student { var name: String var score: Int = 0 var studentId: String = "hoge" func study(){ println("studying.....") } init(name: String){ self.name = name } func upgrade() { score++ } } var tom = User(name: "Tom") tom.name tom.score tom.upgrade() tom.score
willSet, didSet
class User { var name: String var score: Int = 0 { willSet{ println("\(score) -> \(newValue)") } didSet { println("\(oldValue) -> \(score)") } } var level: Int { get{ return Int(score / 10) } set { score = Int(newValue * 10) } } init(name: String){ self.name = name } func upgrade() { score++ } }
optional chaining
class User { var blog: Blog? } class Blog { var title = "My Blog" } var tom = User() tom.blog = Blog() tom.blog?.title if let t = tom.blog?.title { println(t) }
type casting
class User { var name: String init(name: String){ self.name = name } } class AdminUser: User {} let tom = User(name: "Tom") let bob = AdminUser(name: "Bob") let steve = someUser() let users: [AnyObject] = [tom, bob, steve] for user in users { if let u = user as? AdminUser { println(u.name)
構造体
struct UserStruct { var name: String var score: Int = 0 init(name: String){ self.name = name } mutating func upgrade(){ score++ } }
拡張
extension String { var size: Int { return countElements(self) } func dummy() -> String { return "dummy" } } var s: String = "hoge" s.size s.dummy()
generics
func getArray(item: T, count: Int) -> [T] { var result = [T]() for _ in 0..