我正在尝试将类型为'long long'的变量分配给类型NSUInteger,这样做的正确方法是什么?

我的代码行:

expectedSize = response.expectedContentLength > 0 ? response.expectedContentLength : 0;

其中expectedSize的类型为NSUInteger,而response.expectedContentLength的返回类型的类型为'long long。变量response的类型为NSURLResponse

显示的编译错误是:

最佳答案

它实际上只是一个强制转换,并进行了一些范围检查:

const long long expectedContentLength = response.expectedContentLength;
NSUInteger expectedSize = 0;

if (NSURLResponseUnknownLength == expectedContentLength) {
    assert(0 && "length not known - do something");
    return errval;
}
else if (expectedContentLength < 0) {
    assert(0 && "too little");
    return errval;
}
else if (expectedContentLength > NSUIntegerMax) {
    assert(0 && "too much");
    return errval;
}

// expectedContentLength can be represented as NSUInteger, so cast it:
expectedSize = (NSUInteger)expectedContentLength;

10-07 23:31