表題の通り、objective-cで書かれたコードをswift化する練習をしようと思い、まずは簡単な
犬の年齢を人間換算するアプリをswift化してみましたので手順を書いていきたいと思います。
拡張子を.swiftにする
まずは、AppDelegate.swiftを作成します
File -> New -> Fileから
Swift Fileを選択
File名を AppDelegate.swift として作成します。
初めてSwiftファイルを作る際には
上記のようにbridge headerを作るか聞かれるのでYesを選択します。
このファイルはSwiftからobjective-cを呼ぶためのもののようです。
AppDelegate.hと.mをAppDelegate.swiftに書き換える。
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
上記のようにobj-cでは二つのファイルで構成されてますが、swiftでは1つのファイルにまとめます。
import UIKit
@UIApplicationMain
class AppDelegate : UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
AppDelegateはこれでOKです。
次行きましょう。
ViewController.hと.mをViewController.swiftに書き換える。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
{
IBOutlet UITextField *textField1;
IBOutlet UILabel *ageLabel;
IBOutlet UILabel *resultLabel;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)tap:(id)sender {
dogAge = [textField1.text intValue]*7;
ageLabel.text = [NSString stringWithFormat:@"%d",dogAge];
if(dogAge >= 20){
resultLabel.text = @"大人です";
}else if(dogAge < 20){
resultLabel.text = @"子供です";
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
このファイルも二枚で一つです。
内容としては、テキストフィールドに犬の年齢を入力し、tapボタンを押したらその年齢を7倍してageLabelに返し、20歳以上なら『大人です』、以下なら『子供です』とstring型で返す簡単なアプリです。
ちょっと簡単すぎたかもしれませんが最初はこんなもんでいいでしょう。
ではswiftに書き換えます。
import UIKit
class ViewController: UIViewController {
@IBOutlet var textField1: UITextField!
@IBOutlet var ageLabel: UILabel!
@IBOutlet var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func tap(_ sender: AnyObject) {
let dogAge = Int(textField1.text!)! * 7
self.ageLabel.text = "\(dogAge)"
if dogAge >= 20 {
resultLabel.text = "大人です"
}else if dogAge < 20 {
resultLabel.text = "子供です"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
今回書き換えるのは以上のファイルで全てです。
obj-cのファイルを削除する
書き換え終わったobj-cのファイルを削除します。
最後にストーリーボードとViewController.swiftを紐付け、ビルドしてみます。
、
、
、
、
、
あれ?できない。。。
調べたらどうやらSupporting Filesにあるmain.m
このファイルが不要のようなので削除します。
再びビルドします
今度はうまく行きました!
以上obj-cからのswift化の手順でした。記述が少なく簡単なアプリでしたが、違いがよくわかり良い勉強になりました。
次回はもう少しobj-cでゴリゴリ書かれたものをswift化してみたいと思います。