1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift のコードをスクリプトから利用する方法

Posted at

Swift の class や struct をスクリプトから利用する方法について紹介します。

はじめに

iPhone アプリを開発中に、 iPhone アプリ向けに実装した Swift の class や struct を、 iPhone アプリの中ではなく、 macOS 上で実行するスクリプトから利用する必要性が生じました。
その際に学んだことを紹介します。

方法

ステップ1: main.swift の作成

まず、 Swift のスクリプトを main.swift という名前で作成します。 Swift では、 main.swift という名称のファイルのみが、 top-level code の記述を許されているようです。
実際、他の名称のファイルにおいて top-level code を記述すると、実行時に以下のようなエラーが発生します。

Expressions are not allowed at the top level

ステップ2: cat を利用したソースコードの連結

次に、 main.swift から他のソースファイルで実装された class や struct を利用するために、例えば以下の方法で main.swift と他のソースファイルを連結し、またそれらをスクリプトとして実行できます。

cat Shared/Model/*.swift Shared/Util/*.swift main.swift | swift -

参考文献

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?