# Optionality

## Definition​

``let s1: str? = "Hello"; // type str? (optional), value "Hello"let s2: str? = nil; // type str? (optional), value nil``

## Testing existence​

``let s1: str? = "Hello"; // type str? (optional), value "Hello"let s2: str? = nil; // type str? (optional), value nilif s1? {  log("x1 is not nil");}if !s2? {  log("x2 is nil");}``

## Using if let​

``let s1: str? = "Hello"; // type str? (optional), value "Hello"// unwrap optional s1 and create s from type strif let s = s1 {  log("s is not optional, value \${s}");} else {  log("s1 was nil, s doesn't exists in this scope");}// same as above but shadowing s1 variableif let s1 = s1 {  log("s1 type is str, value \${s1}");} else {  log("s1 was nil");}log("s1 type is optional str");``

## Using ??​

``let s1: str? = nil; // type str? (optional), value nillet s2 = s1 ?? "default value";  // s2 is of type strlog(s2); // prints default value``

## Optional Chaining​

``let j  = Json {  working: {    a: {      b: "value"    }  },  broken: {}};if let value = j.tryGet("working")?.tryGet("a")?.tryGet("b")?.tryAsStr() {  log("value is \${value}");} if let value = j.tryGet("broken")?.tryGet("a")?.tryGet("b")?.tryAsStr() {  // not reachable } else {  log("value was not found");}``

## Optional bool​

``let b3: bool? = false; if b3? {  log("although b3 is false, the if statement here checks for existence of value");}if let b3 = b3  { // unboxing b3 and shadowing original b3   if b3 {    log("b3 is true");  } else {    log("b3 is false");  }} else {  log("b3 is nil");}/** * prints:  although b3 is false, the if statement here checks for existence of value  b3 is false**/``
{"ft_lang_label":"__label__en","ft_lang_prob":0.6037131,"math_prob":0.9244168,"size":1579,"snap":"2023-40-2023-50","text_gpt3_token_len":513,"char_repetition_ratio":0.18222222,"word_repetition_ratio":0.22525597,"special_character_ratio":0.39012033,"punctuation_ratio":0.2404692,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98081094,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-09-22T20:34:08Z\",\"WARC-Record-ID\":\"<urn:uuid:1f118a32-49a2-4867-9eac-6586632f437d>\",\"Content-Length\":\"59813\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:af28f02b-8ac8-4148-aac2-962351d6c94e>\",\"WARC-Concurrent-To\":\"<urn:uuid:72d2f757-3b92-4714-b379-df33feb374f1>\",\"WARC-IP-Address\":\"18.160.46.6\",\"WARC-Target-URI\":\"https://www.winglang.io/docs/examples/optionality\",\"WARC-Payload-Digest\":\"sha1:26JLGPXLGT27TFSNTMIUUSI4BZIMMXLZ\",\"WARC-Block-Digest\":\"sha1:GZXPT24YGDWW65RLT5MOJRV627DQKPR5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233506423.70_warc_CC-MAIN-20230922202444-20230922232444-00205.warc.gz\"}"}