深入解析Swift语言编程中的可选链

2020-01-08 22:36:54丽君
易采站长站为您分析深入解析Swift语言编程中的可选链,是Swift入门学习中的基础知识,需要的朋友可以参考下  

查询,调用属性,下标和方法上的一个可选可能 'nil' 的过程被定义为可选的链。可选链返回两个值

如果可选包含一个值,然后调用其相关属性,方法和下标返回值

如果可选包含一个“nil”值,所有的相关属性,方法和下标返回nil

由于多种查询方法,属性和下标故障组合在一起,以一种链将影响到整个链,并导致产生 'nil' 的值。

可选链作为一种替代强制解包裹
可选链与可选值后指定“?”调用一个属性,方法或下标当可选的值返回一些值。

深入解析Swift语言编程中的可选链

程序用于可选链 '!'

复制代码
class ElectionPoll {
   var candidate: Pollbooth?
}
class Pollbooth {   
   var name = "MP"
}
  
let cand = ElectionPoll()
   
let candname = cand.candidate!.name
当我们使用 playground 运行上面的程序,得到以下结果。

 


fatal error: unexpectedly found nil while unwrapping an Optional value
0 swift   0x0000000103410b68 llvm::sys::PrintStackTrace(__sFILE*) + 40
1 swift   0x0000000103411054 SignalHandler(int) + 452
2 libsystem_platform.dylib 0x00007fff9176af1a _sigtramp + 26
3 libsystem_platform.dylib 0x000000000000000b _sigtramp + 1854492939
4 libsystem_platform.dylib 0x00000001074a0214 _sigtramp + 1976783636
5 swift   0x0000000102a85c39 llvm::JIT::runFunction(llvm::Function*, std::__1::vector > const&) + 329
6 swift   0x0000000102d320b3 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > > const&, char const* const*) + 1523
7 swift   0x000000010296e6ba swift::RunImmediately(swift::CompilerInstance&, std::__1::vector, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > > const&, swift::IRGenOptions&, swift::SILOptions const&) + 1066
8 swift   0x000000010275764b frontend_main(llvm::ArrayRef, char const*, void*) + 5275
9 swift   0x0000000102754a6d main + 1677
10 libdyld.dylib  0x00007fff8bb9e5c9 start + 1
11 libdyld.dylib  0x000000000000000c start + 1950751300
Stack dump:
0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -interpret - -target x86_64-apple-darwin14.0.0 -target-cpu core2 -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -module-name main 
/bin/sh: line 47: 15672 Done   cat <<'SWIFT'
import Foundation