我想知道关于布尔快速,如果Bool是基本数据类型(原始),那么为什么布尔默认值是nil
var test: Bool! print(test) // nil在java布尔默认值是false
java中布尔的默认值
I want to know about Bool in Swift.
If Bool is basic primitive datatype, why is a bool's default value nil?
var test: Bool! print(test) // nilIn Java the Bool default value is false:
Default value of boolean and Boolean in Java
最满意答案
Bool , Bool! 和Bool? 在Swift中都是不同的。
1. Bool是一个非可选的数据类型,可以有值 - true/false 。 您需要在初始化程序中初始化它,或者在使用它之前声明它。
var x : Bool = false var x: Bool init() { x = false }Bool? 是一个可选的数据类型,可以有值 - nil/true/false 。 为了使用这种类型,你需要使用解包来解开它。
var x: Bool? if let value = x { //TODO: use value instead of x }Bool! 是一个隐式解包的可选数据类型,可以具有值 - nil/true/false 。 这里的区别是它在使用它之前必须包含一个值,否则会导致runtime exception 。 由于它是隐式解开的, if let or force unwrapping压缩,不需要使用它来解开它。
var x: Bool! //Must contain value before usingBool, Bool! and Bool? all are different in Swift.
1. Bool is a non-optional data type that can have values - true/false. You need to initialize it in the initializer or while declaring it before using it.
var x : Bool = false var x: Bool init() { x = false }2. Bool? is an optional data type that can have values - nil/true/false. In order to use this type, you need to unwrap it using if let or force unwrapping.
var x: Bool? if let value = x { //TODO: use value instead of x }3. Bool! is an implicitly unwrapped optional data type that can have values - nil/true/false. The difference here is it must contain a value before using it else it will result in runtime exception. Since it is implicitly unwrapped, no need to unwrap it using if let or force unwrapping.
var x: Bool! //Must contain value before using更多推荐
发布评论