0
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 5 years have passed since last update.

今更だけど Swift で Extensions を使って型を拡張してみる

0
Posted at

はじめに

Extensions によって、型を拡張することができます
https://docs.swift.org/swift-book/LanguageGuide/Extensions.html
2つサンプルを書いてみたので備忘録として載せます

String型でIntチェックできるように拡張

//  String+checker.swift

import Foundation

extension String {
    /// "1" // true
    /// "Hello world" // false
    /// "" // false
    var isInt: Bool {
        return Int(self) != nil
    }
}


let hogeNumber: Int = 0
hogeNumber.isInt // true

URL型でパラメータを受け取れるように拡張

//  URL+parameters.swift

import Foundation

/// URL型を拡張します
extension URL {
    /// 指定したURLクエリパラメーターの値を取得する
    /// - Parameter key: URLクエリパラメーターのキー
    /// - Returns: 指定したURLクエリパラメーターの値(存在しない場合はnil)
    func queryValue(for key: String) -> String? {
        let queryItems = URLComponents(string: absoluteString)?.queryItems
        return queryItems?.filter { $0.name == key }.compactMap { $0.value }.first
    }
}


http://nananana/hahahaha?param_id=5
let id = URL(string: url.absoluteString)?.queryValue(for: "param_id")
NGLog(id) // 5
0
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
0
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?