LoginSignup
5
1

More than 5 years have passed since last update.

Xcode PlaygroundでPlatformによる分岐をする

Last updated at Posted at 2017-12-10

これは Swift愛好会 Advent Calendar 2017 10日目の投稿です。
昨日9日目は@kamui_projectさんのLottieアニメーションをTableViewCell内で動かしてみたでした。

TL;DR

Playground上でも、Compiler Control Statementsが使えるよという話。
特に使いたいことないけども...


#if os(iOS)
    print("iOS")
#elseif os(macOS)
    print("macOS")
#elseif os(OSX) // macOSの時と一緒
    print("OSX")
#elseif os(tvOS)
    print("tvOS")
#endif

PlaygroundのPlatform

新規Playgroundを作成時

これ
Screen Shot 2017-12-08 at 21.09.03.png

既存のファイルの場合は

File Inspector から変更可能
Screen Shot 2017-12-09 at 13.25.01.png

Compiler Control Statements

Compiler Control Statementsはコンパイル時に評価され、条件外の行は無視されるので、以下のようには使えます。


#if os(iOS)
    import UIKit
    let color: UIColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
#elseif os(macOS)
    import AppKit
    let color: NSColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
#elseif os(tvOS)
#endif

print(color)
//
//  Platform: iOS
//  UIExtendedSRGBColorSpace 1 0.149131 0 1
//
//  Platform: macOS
//  NSCustomColorSpace sRGB IEC61966-2.1 colorspace 1 0.149131 0 1
//
//  Platform: tvOS
//  Playground execution failed:
//
//  error: Qiita.playground:15:7: error: use of unresolved identifier 'color'
//  print(color)
//

まとめ

勉強会の懇親会で@takasek@nonchalant0303と話してた時に見つけました。
いろいろ考えてみたけど、やはりPlaygroundで使いたいタイミングは思いつかない...

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