「Ios/swift/クラス」の版間の差分
提供: 初心者エンジニアの簡易メモ
行53: | 行53: | ||
cat.getName() // cat | cat.getName() // cat | ||
cat.getFoot() // 4 | cat.getFoot() // 4 | ||
+ | |||
+ | ==クラスから生成したインスタンスを配列に入れる== | ||
+ | class User { | ||
+ | var name:String = "" | ||
+ | var age:Int = 0 | ||
+ | init(name: String, age: Int) { | ||
+ | self.name = name | ||
+ | self.age = age | ||
+ | } | ||
+ | } | ||
+ | var users:Array<User> = [] | ||
+ | let user = User(name: "taro", age: 10) as User | ||
+ | let user2 = User(name: "jiro", age: 20) as User | ||
+ | users.append(user) | ||
+ | users.append(user2) | ||
+ | print("name=" + users[0].name) | ||
+ | for user in users { | ||
+ | print("name=" + user.name); | ||
+ | print("age=" + String(user.age)); | ||
+ | } | ||
==NSObjectを継承すべきか== | ==NSObjectを継承すべきか== |
2016年6月25日 (土) 03:01時点における版
クラスのプロパティとメソッド
-User.swift
class User { var name: String let age: Int init(name: String, age: Int) { self.name = name self.age = age } func getName() -> String { return self.name; } func setName(name:String) { self.name = name; } }
-ViewController.swift
var user = User(name: "taro", age: 10) user.getName() // taro user.setName("suzuki"); user.getName() // suzuki
Staticを使う
class Utility { static func bai(a:Int) -> Int { return a * 2; } } Utility.bai(10); // 20
継承
class Animal { var name: String var foot: Int init(name: String, foot: Int) { self.name = name self.foot = foot } func getName() -> String { return self.name; } func getFoot() -> Int { return self.foot; } } class Cat: Animal { init() { super.init(name: "cat", foot: 4) } } var cat = Cat() cat.getName() // cat cat.getFoot() // 4
クラスから生成したインスタンスを配列に入れる
class User { var name:String = "" var age:Int = 0 init(name: String, age: Int) { self.name = name self.age = age } } var users:Array<User> = [] let user = User(name: "taro", age: 10) as User let user2 = User(name: "jiro", age: 20) as User users.append(user) users.append(user2) print("name=" + users[0].name) for user in users { print("name=" + user.name); print("age=" + String(user.age)); }
NSObjectを継承すべきか
遅くなるようなので、なくてよい