LoginSignup
56
59

More than 5 years have passed since last update.

Swiftで #define (マクロ)を使う

Posted at

Objective-Cでは使えていた #define がSwiftになって使えなくなったように見えるのですが、Swiftベースのプロジェクトでも使うことは可能なようです。

Xcodeでプロジェクトを作成する際にLanguage:Swiftを選択すると .pchファイル 自体が作られないないですし、Swiftのみでは #define を使うことはできません。

ですが、Objective-Cと共存可能という特性を利用すれば、Swiftから #define 定義されたマクロを使えるようになりました。

以下試した手順です。


1: Swiftベースのプロジェクトに.pchファイルを追加

.pchファイルの作成

2: Bridging-Header.hファイルをプロジェクトに追加

Bridging-Header.hファイルの追加

※今回はとりあえずObjective-Cのファイルを作成しています。

3: Bridging-Header.hファイルで.pchファイルをimport

SwiftMacroSample-Bridging-Header.h
#import "PrefixHeader.pch"

Bridging-Header.hファイルでimport

4: .pchファイルにて #define を定義

PrefixHeader.pch
#define MESSAGE  @"HELLO!"

#defineを定義

5: Swiftから呼び出し(実行結果)

ViewController.swift
println(MESSAGE)

実行結果

HELLO!

以上で.swiftファイル内でマクロ名が使えるようになりました。

56
59
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
56
59