Equivalent of C++ STL container “pair” in Objective-C?

后端 未结 5 783
无人及你
无人及你 2021-02-13 03:34

I\'m new to Objective-C, so please don\'t judge me too much. I was wondering: Is there an equivalent of the C++ STL pair container I can use in Objective-C?

I want to bu

5条回答
  •  时光说笑
    2021-02-13 04:20

    Yet another option, is to (ab)use a single-entry NSDictionary for storing the pair - since NSDictionary can now be defined to force typed "key" and "value" and also supports literals as syntactic sugar. The drawback - the pair can only hold NSObjects (instance references) and not primitive values.

    A sample would look like this:

    typedef NSDictionary *Pair;
    

    And then in your code:

    Pair myPair = @{@"my name": [NSDate date]};
    Pair myOtherPair =  @{@"his name": [NSDate date]};
    NSArray *myArrayOfPairs = @[myPair, myOtherPair];
    

    Go on and print the results:

    NSLog(@"%@", myArrayOfPairs);
    

    and it looks very much like what you'd expect.

    2019-03-18 16:08:21.740667+0200 TesterApp[23135:23269890] (
      {
        "my name" = "2019-03-18 14:08:21 +0000";
      },
      {
        "his name" = "2019-03-18 14:08:21 +0000";
      }
    )
    

    Payback time comes as you try to extract values from the so-called "Pair". You have to actually dig that single entry from the NSDictionary, not by its "Key" as usual, but assuming there's only one entry, like this:

    Pair somePair = myArrayOfPairs.lastObject;
    NSString *name = somePair.allKeys.firstObject;
    NSDate *date = somePair.allValues.firstObject;
    NSLog(@"name: %@ date: %@", name, date);
    

    which finally yields:

    name: his name date: Mon Mar 18 16:16:43 2019
    

    I don't especially recommend this alternative, but it has its niceties and benefits.

提交回复
热议问题