首页 > 解决方案 > 价值知识!= null

问题描述

如果我在代码中这样写,编译器知道什么value不是空的

// IT WORKS GOOD
int? value = getIntOrNull();
if (value != null) {
   // now compiler know what value is not null
   int strongInt = value;
} else {
   AssertionError('value should be not null');
}

但我怎么能像guardin那样做呢swift?我尝试通过 来执行此操作assert,但在这种情况下,编译器不知道什么value不为空。

// IT DOESN'T WORK
int? value = getIntOrNull();
assert(
  value != null,
  'value should be not null',
);

// now compiler does not know what value is not null 
// how I can do the same behaviour like in `if`
int strongInt = value; // error: request `value!`

标签: dart

解决方案


断言不会在生产模式下执行,因此之后的代码assert不受断言测试的保护。int strongInt = value;有可能(通过valuenull执行断言)来解决这个问题,因此程序不是sound。仅当所有使用路径都通过确保提升类型的测试时,编译器才会提升。

所以,一个assert(test)不会比

if (assertsEnabled && !(test)) throw AssertionError();

whereassertsEnabled在编译时是未知的。


推荐阅读