a swift tourを駆け足で終わらせたので、いよいよSwiftでアプリを作成していきます。
詳しく説明していければいいのですが、swiftで本格的に開発するまで1ヶ月くらいしか勉強期間がないのでそこそこ飛ばしていきます。(他もやること色々あるのです...)
環境
- xcode6.0.1
最初に作成するアプリはチャットアプリ。Listにコメントをならべる「アレ」です。
プロジェクト作成
object-c時代と変わらないです。
xcode → File → New → Projectでプロジェクト作成。言語だけswiftにします。また今回はmaster detail applicationを利用します。
コードの中を見てみると、objective-cの時とあまり変わってない...。本当に開発効率あがるのでしょうか。
Userオブジェクトの作成
User情報を格納するクラスを作成します。以下の通りです。
import Foundation
class User {
let id: Int
var name: String?
var description: String?
init(id: Int) {
self.id = id
}
convenience init(id: Int, name: String, description: String) {
self.init(id: id)
self.name = name
self.description = description
}
func displayName() -> String {
if let name = self.name {
return name
}
return "no name"
}
func displayDescription() -> String {
if let description = self.description {
return description
}
return "no description"
}
}
convenience initは委譲イニシャライザ。要はself.initを中で呼ないといけないってことです。呼ばないとエラーになります。
displayName(),displayDescription()はoptinalのString?をString型で返しています。Optional Bindingで非Optional型に変換(String型ってこと)しています。
Userオブジェクトのテストコードの作成
XCTestCaseを継承して作成します。Quickなるものが熱いらしいが、時間ないしXCTestCaseで十分。
import UIKit
import XCTest
class UserTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDisplayName() {
var user = User(id: 1)
XCTAssertEqual(user.displayName(), "no name")
}
func testDisplayDescription() {
var user = User(id: 1)
XCTAssertEqual(user.displayDescription(), "no description")
}
func testDisplayName_name() {
var user = User(id: 1, name: "taro", description: "hello")
XCTAssertEqual(user.displayName(), "taro")
}
func testDisplayName_description() {
var user = User(id: 1, name: "taro", description: "hello")
XCTAssertEqual(user.displayDescription(), "hello")
}
}
produce → test で実行。全部うまくいってグリーンになると思います。
しかし相変わらずTestコードの説明をしているサイトが少なくてうんざりしたのは内緒w(テストコードを書くって、ちょっとした習慣なんですけどね。なのにほとんどみんなやらない)
さて、この調子で作成していきます。次はchatクラスを作成します。
参考サイト
0 件のコメント:
コメントを投稿