8
3

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.

Swift4行で誕生日から年齢を算出する ~今何歳だっけ?となったあなたに~

Posted at

今何歳ですか?
パッとは答えられないあなたのために、生年月日から誕生日を算出するプログラムを組みました。

var birthdate = DateComponents(year: 1994, month: 10, day: 1)
var age: Int
// 年齢を算出します
let calendar = Calendar.current
let now = calendar.dateComponents([.year, .month, .day], from: Date())
let ageComponents = calendar.dateComponents([.year], from: birthdate, to: now)
age = ageComponents.year!

Date型からDateComponents型に変換することもできるので、誕生日をDateで管理したい場合は応用してください。
【Swift】DateとDateComponentsの相互変換 - しめ鯖日記


おまけ

誕生日を入れると自動で年齢を入れてくれるようにしたかったんですけど、initの時はdidsetが呼ばれないので諦めました。

class Person {
    var age: Int?
    var birthdate: DateComponents {
        didSet(date){
            // 呼ばれないよ!!!
            let calendar = Calendar.current
            let now = calendar.dateComponents([.year, .month, .day], from: Date())
            let ageComponents = calendar.dateComponents([.year], from: date, to: now)
            age = ageComponents.year!
        }
    }
    init(date: DateComponents) {
        birthdate = date
    }
}

let hoge = Person(date: DateComponents(year: 1994, month: 10, day: 1))

Swiftでdeinit時にメンバ変数(property)のdidSetが呼ばれない気がした – su- tech blog

8
3
1

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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?