LoginSignup
16

More than 5 years have passed since last update.

SwiftでPlistからTypesafeに値を取得するライブラリを作った

Last updated at Posted at 2016-07-10

WebAPIを利用したアプリ開発をする場合、ApplicationIDやAPIKeyなどソースコードに記述したくない値をPlistに定義して利用することが多いかと思います。そんな時に便利なライブラリ SwiftyConfiguration を書いてみました。

使い方

1. インストール

Carthage, Cocoapodsに対応
(2016/07/10現在 Swift2.2, Xcode7.3.1)

2. Plistを作成・プロジェクトに追加

スクリーンショット 2016-07-10 13.18.35.png

3. PlistのKeyを定義

KeysのExtensionとしてPlistの各Keyを定義

import SwiftyConfiguration

extensino Keys {
    static let string = Key<String>("string")
    static let int    = Key<Int>("int")
    static let float  = Key<Float>("float")
}

対応しているPlistの値

Type Plistでの型
String String
NSURL String
NSNumber NSNumber
Int NSNumber
Float NSNumber
Double NSNumber
Bool Boolean
NSDate Date
Array Array
Dictionary Dictionary

4. Configurationオブジェクトを生成してPlistの値を取得

Plistのパスを指定してConfigrationオブジェクトを作成、getで値を取得
Genericsメソッドとして定義しているので利用側は安全に利用可能

import SwiftyConfiguration

let plistPath = NSBundle.mainBundle().pathForResource("Configuration", ofType: "plist")!
let config = Configuration(plistPath: plistPath)!

let stringValue = config.get(.string)!  // "Hoge"
let intValue    = config.get(.int)!     // 1
let floatValue  = config.get(.float)!   // 3.14

その他

キーを.で区切ることで、Array・Dictionaryのネストした値も取得することができます。Debug, ReleaseでAPIKeyなどを分けたい時に便利です。

スクリーンショット 2016-07-10 13.50.51.png

import SwiftyConfiguration

extension Keys {
    #if DEBUG
        private static let prefix = "Debug"
    #else
        private static let prefix = "Release"
    #endif

    static let apiKey = Key<String>("\(prefix).apiKey")
}

宣伝

他にもいくつかSwift製のUI系ライブラリなどを作成しているので、よければスター・プルリクエストお待ちしてます(ΦωΦ)

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
16