【问题标题】:checking if value is nil and replacing it with empty string in NSdictionary检查值是否为 nil 并将其替换为 NSdictionary 中的空字符串
【发布时间】:2022-01-12 06:17:03
【问题描述】:

我不是 iOS 开发者,而是选择目标 c 的 rn 开发者。

我有一个 NSdictionry,看起来像这样

NSDictionary *selfInfo = @{
    @"id": selfPartcipant.id,
    @"name": selfPartcipant.name,
    @"picture": selfPartcipant.picture,
    @"audioEnabled": @(selfPartcipant.audioEnabled),
    @"videoEnabled": @(selfPartcipant.videoEnabled),
    @"isPinned": @(selfPartcipant.isPinned)
};

在这里,selfPartcipant.nameselfPartcipant.picture 可以为 nil(这会导致代码中断)。当值为 nil 时,我想放空字符串。

javascript中的等价物应该是这样的

const a = {
  name: selfPartcipant.name || '', 
  picture: selfPartcipant.picture || '', 
  ...other properties
}

我怎样才能做到这一点?

【问题讨论】:

    标签: ios objective-c react-native


    【解决方案1】:

    虽然 Swift 有一个 nil-coalescing 运算符 ??,但 Objective C 没有,所以最好的办法是像这样使用三元运算符:

    NSDictionary *selfInfo = @{
        @"id": selfPartcipant.id,
        @"name": selfPartcipant.name ? selfPartcipant.name : @"",
        @"picture": selfPartcipant.picture ? selfPartcipant.picture : @"",
        @"audioEnabled": @(selfPartcipant.audioEnabled),
        @"videoEnabled": @(selfPartcipant.videoEnabled),
        @"isPinned": @(selfPartcipant.isPinned)
    };
    

    公平的警告,这是我写过的最客观的 C,所以不能保证如果你复制和粘贴它会起作用,但这个想法应该是可靠的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-21
      • 2013-11-08
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      相关资源
      最近更新 更多