LoginSignup
19
15

More than 5 years have passed since last update.

Objective-CとSwiftの書き方違い

Last updated at Posted at 2016-07-07

はじめに

既存のObjective-cのコードをSwiftに置き換える際に迷ったのでまとめておきます。

変数・定数

Objective-C

// 変数
NSInteger i = 0;

// 定数
const NSInteger n = 0;

Swift

  • 変数はvar, 定数はletで定義。
  • 型推論してくれるので型は省略可能。
// 変数
var i :Int = 0

// 定数
let i :Int = 0

文字列

Objective-C

NSString *hello      = @"Hello";
NSString *world      = @"World";
NSString *helloWorld = [NSString stringWithFormat:@"%@, %@!", hello, world];

Swift

let hello      = "Hello"
let world      = "World"
let helloWorld = "\(hello), \(world)!"  // Hello, World!

配列

Objective-C

NSArray        *array        = @[@"abc", @"123"];
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"xyz", @"789", nil];
[mutableArray addObjectsFromArray:array];  // [@"xyz", @"789", @"abc", @"123"]

Swift

let array        = ["abc", "123"]
var mutableArray = ["xyz", "789"]
mutableArray += array    // ["xyz", "789", "abc", "123"]

クラス定義

Objective-C

以下のようにヘッダーファイル(.h)と実装ファイル(.m)に分かれて2つのファイルで1セットになる。

Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@end
Person.m
#import "Person.h"
@implementation Person
  hogehoge;
@end

Swift

Person.swift
class Person {
  hogehoge
}

メソッド定義

引数1つの場合

Objective-C

- (void)setName:(NSString *)name
{
    hogehoge;
}

Swift

func setName(name: String) -> Void {
    hogehoge
}

引数が複数ある場合

Objective-C

  • - (戻り値の型)メソッド名:(引数の型)引数1 ラベル:(引数の型)引数2 ラベル:(引数の型)引数3のように書く。
    • ラベルは省略可。
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile 
  encoding:(NSStringEncoding)enc 
{
  hogehoge;
}

Swift

func writeToFile(path: String, useAuxiliaryFile: Bool, enc: String) -> Bool{
  hogehoge;
}

インスタンス生成、メソッド呼び出し

Objective-C

// Personクラスのインスタンスを生成する
Person *yuki = [[Person alloc] init];

// 名前を設定する
[yuki setName:@"hogehoge"];

Swift

// Personクラスのインスタンスを生成する
let yuki = Person()

// 名前を設定する
yuki.setName = "hogehoge"
19
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
15