Would someone please explain the <> in let requestedComponents: Set<Calendar.Component> = [ ...]?

Yes, still learning Swift, and no, am not lazy, but I do have some sort of reading problem.

In code block below, what do the < and > represent?

let requestedComponents: Set<Calendar.Component> = [
    .year,
    .month,
    .day,
    .hour,
    .minute,
    .second

]

Accepted Reply

You should read Set<X> as "Set of X".

I.e. Set<X> is a Set where every element must be of type X.

(This syntax is shared with C++, Java and probably other languages where it goes by various different names.)

Replies

For an array, you define the type of components with

let myArray: [Int] = [1, 2, 3]

for sets, syntax is a bit different, it uses <> instead of [] for type declaration (don't know why).

So that means:

requestedComponents is a set which elements are of type Calendar.Component.

What is confusing is that the set is later built using []…

For an array, it would have been:

let request :  [Calendar.Component] = [
    .year,
    .month,
    .day,
    .hour,
    .minute,
    .second
]

But the API you use requests a Set.

Reference: https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html

  • So take make sure I read it correctly,

    Sets and Array are the same except a Set has no ordering, and each value must be unique?

    And in the example I gave, Calendar.Component was already defined as a set?

Add a Comment

You should read Set<X> as "Set of X".

I.e. Set<X> is a Set where every element must be of type X.

(This syntax is shared with C++, Java and probably other languages where it goes by various different names.)