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

Swiftの全角文字の活用

Posted at

全角の変数や関数はほとんど使わないけど、どこかで活用できないかと考えてみた

開発環境
Xcode 10.2.1
Swift 5

Date型をString型にするとき

import Foundation

let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "ja-JP")
formatter.dateFormat = "yyyy/MM/dd"

let date = Date()
print (formatter.string(from: date))    // 2019/05/28

dateFormatをenumで定義する

日時を表すアルファベットをよく忘れるのでenumを使用する

DateFormat
enum DateFormat {
    case yyyyMMdd
    case HHmmss
    
    var string: String {
        switch self {
        case .yyyyMMdd:
            return "yyyy/MM/dd"
        case .HHmmss:
            return "HH:mm:ss"
        }
    }
}
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = DateFormat.yyyyMMdd.string

let date = Date()
print (formatter.string(from: date))    // 2019/05/28

問題点

  • 区切り文字が定義できない
  • switch文で返す文字列を分岐させなきゃいけない

全角文字の使用

区切り文字を全角にすることで定義できる
文字列は "\(self)" で受け取り、 applyingTransform(transform: , reverse: )を使用し半角にすればOK

enum DateFormat {
    case yyyyMMdd
    case HHmmss

    var string: String {
        return "\(self)".applyingTransform(.fullwidthToHalfwidth, reverse: false)!
    }
}

Extension

Date + toString
extension Date {
    
    func toString(_ dateFormat: DateFormat,
                  calendar: Calendar = Calendar(identifier: .gregorian),
                  locale: Locale     = Locale(identifier: "en_US_POSIX"),
                  timeZone: TimeZone = TimeZone.current) -> String {
        let formatter = DateFormatter()
        formatter.calendar   = calendar
        formatter.locale     = locale
        formatter.timeZone   = timeZone
        formatter.dateFormat = dateFormat.string
        
        return formatter.string(from: self)
    }
    
}
print (Date().toString(.yyyyMMdd))    // 2019/05/28

まとめ

  • 全角記号は意外と使える場面があると思う
  • 全角スペースは使用できないので注意

他に使用できそうなところがあったら教えてください

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?