从结果类型为 'NSInteger'(也称为 'long')的函数返回 'id _Nullable' 的整数转换指针不兼容

Incompatible pointer to integer conversion returning 'id _Nullable' from a function with result type 'NSInteger' (aka 'long')

我想要一个对象来保存数组的索引,其中 id 是唯一键,它的值是索引 ({[id]:[index]})

我想动态地 return 该索引,即在 javascript 我会做这样的事情

const a = [{
  id: '451', 
  name: 'varun'
}]


const b = {
    '451': 0 
}

const c = '451' 

if (b[c]) return b[c] 
else return -1 

它在 obj c 中的等价物是什么?

目前我正在做这个

@implementation Participants {
    NSMutableDictionary *participantsKey;
}. // Equivalent to const b above


- (NSInteger)doesParticipantExist:(NSString*)id {
    if ([participantsKey valueForKey: id]) {
      return [participantsKey valueForKey: id];
    } else {
      return -1;
    }
  }

但是这是抛出以下警告

Incompatible pointer to integer conversion returning 'id _Nullable' from a function with result type 'NSInteger' (aka 'long')

valueForKey return 一个可为 null 的对象 'id _Nullable' 不是 NSInteger,它是一个 long 值。

[participantsKey valueForKey: id]

您的函数的 return 类型是 NSInteger,这就是为什么它说它不能将可空对象 'id _Nullable' 转换为 NSInteger

以下是解决问题的方法。

- (NSInteger)doesParticipantExist:(NSString*)id {
    if ([participantsKey valueForKey:id]) {
        // Fix here
        return [(NSNumber*)[participantsKey valueForKey:id] integerValue];
    } else {
        return -1;
    }
}