find the current year in swift

You can find the current year in Swift using the Calendar and Date classes like this:

main.swift
let calendar = Calendar.current
let year = calendar.component(.year, from: Date())
print(year)
95 chars
4 lines

This code initializes a Calendar object with the current calendar and then uses the component(_:from:) method to get the year component from the current Date. The print() function is then used to output the year value to the console.

Alternatively, you can use the DateFormatter class to format the current date as a string that only includes the year:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let yearString = dateFormatter.string(from: Date())
print(yearString)
140 chars
5 lines

This code initializes a DateFormatter object and sets its dateFormat property to "yyyy", which specifies that only the year should be included in the output string. The string(from:) method is then used to format the current Date as a string with the specified format, and the print() function is used to output the resulting yearString to the console.

gistlibby LogSnag