问:
IntelliJ add Java 11
I need to add my installed Java 11 version to the project settings, because of this error (Error:java: invalid source release: 11).

When i go to project structure -> Project settings -> Project there it just shows Java 1.8.
When i try to add "java-11-openjdk-amd64" it fails with the reason "The selected directory points to a JRE, not a JDK.".

```<code>java -version
openjdk version "11.0.4" 2019-07-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.4+11)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.4+11, mixed mode)
</code>```

答:
The java application is available in the Java Runtime Environment (JRE). The fact that java is available in version 11 does not necessarily mean that the Java Development Kit (JDK) is also installed for version 11. However, IntelliJ needs the JDK which includes tools like the compiler javac.

In order to use Java 11 in IntelliJ, you need to install the Java 11 JDK.

For example on Ubuntu you can do that by executing:

```<code>sudo apt install openjdk-11-jdk
</code>```

Title: IntelliJ add Java 11

Body:
I need to add my installed Java 11 version to the project settings, because of this error (Error:java: invalid source release: 11).

When i go to project structure -> Project settings -> Project there it just shows Java 1.8.
When i try to add "java-11-openjdk-amd64" it fails with the reason "The selected directory points to a JRE, not a JDK.".

java -version
openjdk version "11.0.4" 2019-07-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.4+11)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.4+11, mixed mode)

Body:
The java application is available in the Java Runtime Environment (JRE). The fact that java is available in version 11 does not necessarily mean that the Java Development Kit (JDK) is also installed for version 11. However, IntelliJ needs the JDK which includes tools like the compiler javac.

In order to use Java 11 in IntelliJ, you need to install the Java 11 JDK.

For example on Ubuntu you can do that by executing:

sudo apt install openjdk-11-jdk


来源: stackexchange

问:
Jpa query with Predicate

How select one column by predicate in jpa?

For exemple like this

```<code>@Query("SELECT SUM (u.sum) from User u")
Double findSums(Predicate predicate);
</code>```

答:
Spring Data JPA does not have direct support for this kind of query.
Therefore the solution is to fall back to plain  JPA in a custom method for your repository.

In that custom method you'd use the Criteria API to create the SELECT SUM (u.sum) from User u apply the predicate to it and execute it using the EnterpriseManager.

ContentLicense: CC BY-SA 4.0

Title: Jpa query with Predicate

Body:
How select one column by predicate in jpa?

For exemple like this

@Query("SELECT SUM (u.sum) from User u")
Double findSums(Predicate predicate);


问:
Error when use User defined function in mutate
I'm working on a project having 2 dataframe - product & order
Product like:

```<code>product <- data.frame(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                  TM_Product = c("Canvas", "Canvas", "Canvas",
                                 "Mugs", "Mugs"))
</code>```

Order: include SKU_order like

```<code>order <- data.frame(Order_ID = c(1,2,3,4,5,6),
                Lineitem_Sku = c("F-M-White", "MugsW-11-2005",
                                 "TS-BS-F-XL-Black", "  MugsW-15",
                                 "TS-BS-F-XL-White", "TS-BS-F-3XL"))
</code>```

My task is find product from SKU_Order.
My expected dataframe is:
Order_ID, Lineitem_Sku, Product (match Lineitem_Sku with SKU in product data and get TM_Product corresponding)

I write my function:

```<code>product_get <- function(x) {
  if (is.na(x)) {
    z = NA_character_
  } else if (sum(str_detect(x, pattern = paste0("^", product$SKU))) == 0) {
    z = NA_character_
  } else {
    z = product[str_detect(x, pattern = paste0("^", product$SKU)),2] %>%
      pull()
  }
  return(z)
}
</code>```

But when i use it in mutate

```<code>order %>%
  mutate(product = product_get(Lineitem_Sku))
</code>```

```<code>1: In if (is.na(x)) { :
  the condition has length > 1 and only the first element will be used
2: In stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) :
  longer object length is not a multiple of shorter object length
3: In stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) :
  longer object length is not a multiple of shorter object length
</code>```

Anyone can help me. Thank for all

答:
Ok, this will be a long answer, sorry in advance, there are many things which can improve.

First, as I wrote in the comment, your function is not vectorized, as it is a simple if() clause. Not vectorized means that you cannot operate it on an entire vector or column of numbers, it will take just the first one and warn you. And this is what you're trying to do, with mutate() you're trying to iterate on an existing column to create a new one. The vectorized version of if() is ifelse(), but if you insist on using if() (and sometimes you should), you could use map_chr() from purrr to vectorize your function inside of mutate() like so:

```<code>library(tidyverse)

product <- data.frame(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                      TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs"))

order <- data.frame(Order_ID = c(1,2,3,4,5,6),
                    Lineitem_Sku = c("F-M-White", "MugsW-11-2005", "TS-BS-F-XL-Black", "MugsW-15", "TS-BS-F-XL-White", "TS-BS-F-3XL"))

product_get <- function(x){
  if(is.na(x)){
    z = NA_character_
  } else if (sum(str_detect(x, pattern = paste0("^", product$SKU))) == 0){
    z = NA_character_
  } else {
    z = product[str_detect(x, pattern = paste0("^", product$SKU)),2] %>%
      pull()
  }
  return(z)
}

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))
</code>```

And we get an error!

```<code>Error in UseMethod("pull") :
  no applicable method for 'pull' applied to an object of class "factor"
</code>```

That is because when you're using data.frame() (in R < 4.0.0 I think), a character vector of your table is automatically made a factor unless you specify stringsAsFactors = FALSE, like so:

```<code>product <- data.frame(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                  TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs"), stringsAsFactors = FALSE)
</code>```

Another option, if you're already inside the tidyverse is to simply use a tibble:

```<code>product <- tibble(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                  TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs"))

order <- tibble(Order_ID = c(1,2,3,4,5,6),
                Lineitem_Sku = c("F-M-White", "MugsW-11-2005", "TS-BS-F-XL-Black", "MugsW-15", "TS-BS-F-XL-White", "TS-BS-F-3XL"))

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))
</code>```

And we get:

```<code># A tibble: 6 x 3
  Order_ID Lineitem_Sku     product
     <dbl> <chr>            <chr>
1        1 F-M-White        NA
2        2 MugsW-11-2005    Mugs
3        3 TS-BS-F-XL-Black NA
4        4 MugsW-15         NA
5        5 TS-BS-F-XL-White NA
6        6 TS-BS-F-3XL      NA
</code>```

Which is hopefully what you want. But I'm not sure we are done.

First, notice you define with paste0() the vector of patterns each and every time the function is entered! Which is wasteful. And even then, you check it with str_detect() twice.

```<code>product_patterns <- paste0("^", product$SKU)

product_get <- function(x) {
  if (is.na(x)) {
    return(NA_character_)
  }
  check <- str_detect(x, pattern = product_patterns)
  if (sum(check) == 0) {
    z <- NA_character_
  } else {
    z <- product %>%
      filter(check) %>%
      pull(TM_Product)
  }
  return(z)
}

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))
</code>```

Second, this function might still fail if the input is changed just a bit. Suppose I add just one more "Mugs" row to product:

```<code>product <- tibble(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-", "MugsW-11"),
                  TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs", "Mugs"))

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))
</code>```

Another error!

```<code>Error: Result 2 must be a single string, not a character vector of length 2
Run `rlang::last_error()` to see where the error occurred.
</code>```

This is because you explicitly count on finding just one product, and here the function found two products. map_chr() assumes each of the elements it returns is a single string and throws an error. So you might want to look at map() which returns a list, or improve on your function to not fail like this (e.g. returning the first product).

If your data is big I'd also look at somehow doing all this with a inner_join().

Body:
I'm working on a project having 2 dataframe - product & order
Product like:

product <- data.frame(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                  TM_Product = c("Canvas", "Canvas", "Canvas",
                                 "Mugs", "Mugs"))

Order: include SKU_order like

order <- data.frame(Order_ID = c(1,2,3,4,5,6),
                Lineitem_Sku = c("F-M-White", "MugsW-11-2005",
                                 "TS-BS-F-XL-Black", "  MugsW-15",
                                 "TS-BS-F-XL-White", "TS-BS-F-3XL"))

My task is find product from SKU_Order.
My expected dataframe is:
Order_ID, Lineitem_Sku, Product (match Lineitem_Sku with SKU in product data and get TM_Product corresponding)

I write my function:

product_get <- function(x) {
  if (is.na(x)) {
    z = NA_character_
  } else if (sum(str_detect(x, pattern = paste0("^", product$SKU))) == 0) {
    z = NA_character_
  } else {
    z = product[str_detect(x, pattern = paste0("^", product$SKU)),2] %>%
      pull()
  }
  return(z)
}

But when i use it in mutate

order %>%
  mutate(product = product_get(Lineitem_Sku))

1: In if (is.na(x)) { :
  the condition has length > 1 and only the first element will be used
2: In stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) :
  longer object length is not a multiple of shorter object length
3: In stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) :
  longer object length is not a multiple of shorter object length

Anyone can help me. Thank for all

Body:
Ok, this will be a long answer, sorry in advance, there are many things which can improve.

First, as I wrote in the comment, your function is not vectorized, as it is a simple if() clause. Not vectorized means that you cannot operate it on an entire vector or column of numbers, it will take just the first one and warn you. And this is what you're trying to do, with mutate() you're trying to iterate on an existing column to create a new one. The vectorized version of if() is ifelse(), but if you insist on using if() (and sometimes you should), you could use map_chr() from purrr to vectorize your function inside of mutate() like so:

library(tidyverse)

product <- data.frame(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                      TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs"))

order <- data.frame(Order_ID = c(1,2,3,4,5,6),
                    Lineitem_Sku = c("F-M-White", "MugsW-11-2005", "TS-BS-F-XL-Black", "MugsW-15", "TS-BS-F-XL-White", "TS-BS-F-3XL"))

product_get <- function(x){
  if(is.na(x)){
    z = NA_character_
  } else if (sum(str_detect(x, pattern = paste0("^", product$SKU))) == 0){
    z = NA_character_
  } else {
    z = product[str_detect(x, pattern = paste0("^", product$SKU)),2] %>%
      pull()
  }
  return(z)
}

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))

And we get an error!

Error in UseMethod("pull") :
  no applicable method for 'pull' applied to an object of class "factor"

That is because when you're using data.frame() (in R < 4.0.0 I think), a character vector of your table is automatically made a factor unless you specify stringsAsFactors = FALSE, like so:

product <- data.frame(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                  TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs"), stringsAsFactors = FALSE)

Another option, if you're already inside the tidyverse is to simply use a tibble:

product <- tibble(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-"),
                  TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs"))

order <- tibble(Order_ID = c(1,2,3,4,5,6),
                Lineitem_Sku = c("F-M-White", "MugsW-11-2005", "TS-BS-F-XL-Black", "MugsW-15", "TS-BS-F-XL-White", "TS-BS-F-3XL"))

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))

And we get:

# A tibble: 6 x 3
  Order_ID Lineitem_Sku     product
     <dbl> <chr>            <chr>
1        1 F-M-White        NA
2        2 MugsW-11-2005    Mugs
3        3 TS-BS-F-XL-Black NA
4        4 MugsW-15         NA
5        5 TS-BS-F-XL-White NA
6        6 TS-BS-F-3XL      NA

Which is hopefully what you want. But I'm not sure we are done.

First, notice you define with paste0() the vector of patterns each and every time the function is entered! Which is wasteful. And even then, you check it with str_detect() twice.

product_patterns <- paste0("^", product$SKU)

product_get <- function(x) {
  if (is.na(x)) {
    return(NA_character_)
  }
  check <- str_detect(x, pattern = product_patterns)
  if (sum(check) == 0) {
    z <- NA_character_
  } else {
    z <- product %>%
      filter(check) %>%
      pull(TM_Product)
  }
  return(z)
}

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))

Second, this function might still fail if the input is changed just a bit. Suppose I add just one more "Mugs" row to product:

product <- tibble(SKU = c("CVL-","CVP-", "CVS-", "MugsW-11-", "MugsW-15-", "MugsW-11"),
                  TM_Product = c("Canvas", "Canvas", "Canvas", "Mugs", "Mugs", "Mugs"))

order %>%
  mutate(product = map_chr(Lineitem_Sku, product_get))

Another error!

Error: Result 2 must be a single string, not a character vector of length 2
Run `rlang::last_error()` to see where the error occurred.

This is because you explicitly count on finding just one product, and here the function found two products. map_chr() assumes each of the elements it returns is a single string and throws an error. So you might want to look at map() which returns a list, or improve on your function to not fail like this (e.g. returning the first product).

If your data is big I'd also look at somehow doing all this with a inner_join().


问:
Import JS file inside node_modules in Angular
I have an angular app, to this I am trying to add an npm package called svgedit. It gets installed. But when I try to reference a java-script file it says

net::ERR_ABORTED 404 (Not Found)

This is how I am trying to reference it in my index.html in the head section,

```<code><script type="module" src="node_modules/svgedit/svgedit-config-es.js"></script>
</code>```

I can access this file from within vs code by clicking "ctrl + left mouse". It opens the file properly meaning the reference is proper. But when it runs it gives the above mentioned error in the console. I have also tried switching the type attribute to "text/javascript".

Basically I am trying to integrate this package in my angular app. What is the correct method to go about it.

答:
ng serve will only serve compiled files from your src directory and what''s in the assets folder.  It will not serve node_module files directly.

The usual way to add scripts it to add it to the scripts section in angular.json

```<code>scripts:
 [ //other scripts
   "node_modules/svgedit/svgedit-config-es.js"
 ]
</code>```

Body:
I have an angular app, to this I am trying to add an npm package called svgedit. It gets installed. But when I try to reference a java-script file it says

net::ERR_ABORTED 404 (Not Found)

This is how I am trying to reference it in my index.html in the head section,

I can access this file from within vs code by clicking "ctrl + left mouse". It opens the file properly meaning the reference is proper. But when it runs it gives the above mentioned error in the console. I have also tried switching the type attribute to "text/javascript".

Basically I am trying to integrate this package in my angular app. What is the correct method to go about it.

Body:
ng serve will only serve compiled files from your src directory and what''s in the assets folder.  It will not serve node_module files directly.

The usual way to add scripts it to add it to the scripts section in angular.json

scripts:
 [ //other scripts
   "node_modules/svgedit/svgedit-config-es.js"
 ]


问:
Looking for a simpler Objective-C solution
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

```<code>-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;
</code>```

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

答: -[NSNumber numberWithInt: 0] and -[NSNumber numberWithUnsignedInt: 0] are the same number (in fact, they may even be the same object on some implementations of Cocoa).

ContentLicense: CC BY-SA 2.5

Body:
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard


问:
if window.location.href has 'sometext' inside - do this
Currently working on something which uses ajax for some pagination. What I'm looking to do is add something like referal=3 to the end of some links then when they go to that link I'll insert a back button with the window location for example:

User uses the ajax pagination, goes to page 3 I'll add ?ref=3 to the end of the link or something so it would like this this:

http://foo.com/somepage/?ref=3

(not sure if that's a corrent way of doing it)

Then the user clicks that link and I'll append a back button on that page with that link.

So when they go back to the homepage using the generated button the window.location.href will be:

http://foo.com?ref=3

The idea is that when they click that back button, the ajax pagination will load to page 3.

I'm not sure how else to explain this, but does anyone know how I would go about doing a conditional statement dependant on the window.location.href?

答:
To find a if the url contains some string:</p>

```<code>if (document.location.href.search("ref=3")!=-1){
 alert('got ref=3');
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To find a if the url contains some string:

if (document.location.href.search("ref=3")!=-1){
 alert('got ref=3');
}


问:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
I am getting this kind of error, how to fix it.</p>

```<code>Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'.
Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
</code>```

答:
If you using Ubuntu, So firstly you have unhide all files from your home directory or where located your android studio folder :

Go to your home directory and unhide all files by using ctrl+h

You found .gradle folder

Inside .gradle -> wrapper

You can found dists folder, So delete this dists folder

Create a New Project than your Gradle file re-downloaded

Congo you successfully build project

Body:
I am getting this kind of error, how to fix it.

Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'.
Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.


问:
Node.js returning an error on a colon in JSON array
I am trying to use node.js to read a JSON file server-side and reading it using fs. When I try to parse a JSON file, it works with a single object, but when reading an array, it gives an error on a colon. The server script is in the same directory as the JSON file, and I wrote my JSON file to comply with the directions shown at https://www.json.org/json-en.html.

Javascript code I am trying to run:

```<code>console.log('recived login request');
var obj = fs.readFileSync('userInfo.json');
console.log(JSON.parse(obj));
</code>```

Json file code:

```<code>{ "test": [ "testUno" :"yes" ] }
</code>```

(Note: the json file code shown is just a test)

答: Also suggest considering code compatibility, please always use dictionary { } as root of json object.</p>

Body:
I am trying to use node.js to read a JSON file server-side and reading it using fs. When I try to parse a JSON file, it works with a single object, but when reading an array, it gives an error on a colon. The server script is in the same directory as the JSON file, and I wrote my JSON file to comply with the directions shown at https://www.json.org/json-en.html.

Javascript code I am trying to run:

console.log('recived login request');
var obj = fs.readFileSync('userInfo.json');
console.log(JSON.parse(obj));

Json file code:

{ "test": [ "testUno" :"yes" ] }

(Note: the json file code shown is just a test)


问:
string.split is not working for some reason
I am trying to print the last name of the person "Michael" by splitting the string into an array and calling out the next word available.

When I run this code, I get undefined. I tried using Pythontutor to see what am I doing wrong and it turns out that string.split() is not working.

Can you please take a look and help figure me out what am I doing wrong?

Here is my code:

function getMichaelLastName(inputText) {
  var names = inputText;
  var newN = [names.split(" ")];
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] == "Michael") {
      var Michael = newN[i++];
    }
    return Michael;
  }
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)```

答:
This code uses regex and capture the word (ie, potential lastname) after Michael<space>

const regex = /Michael (\w+)/gm;
const str = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?";
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
```


问:
AWS Aurora MySQL serverless: how to connect from MySQL Workbench
I was trying to use AWS Aurora Serverless for MySQL in my project, but I am impossible to connect to it, though I have the endpoint, username, password.

What I have done:

From AWS console managment, I select RDS > Instances > Aurora > Serverless

Leave the default settings

Create database

AWS will only create an AWS Cluster

I open MySQL Workbench, and use endpoint, username, password to connect the database

Ressult:

Your connection attempt failed for user 'admin' from your host to
  server at xxxxx.cluster-abcdefg1234.eu-west-1.rds.amazonaws.com:3306:
  Can't connect to MySQL server on
  'xxxxx.cluster-abcdefg1234.eu-west-1.rds.amazonaws.com' (60)

Did I make any wrong steps ? Please advice me.

****EDIT****

I tried to create another Aurora database with capacity type: Provisioned. I can connect to the endpoint seamlessly with username and password by MySql workbench. It means that the port 3306 is opened for workbench.

About the security group:

答:
Data API and Query Editor for connecting to Aurora Serverless are now available in some more regions.

https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-rds-data-api-and-query-editor-available-additional-regions/


问:
Access denied for user 'root'@'192.168.128.3' in Laravel project in Docker
I try to set up Laravel project in Docker.
My docker-compose.yml:

```<code>version: "2"
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - MYSQL_DATABASE=identy
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_HOST=db
    ports:
      - "8080:80"
    volumes:
      - .:/var/www
    depends_on:
      - db
    networks:
      - identy-network

  db:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=654321
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_DATABASE=identy
    volumes:
      - "mysql_data:/var/lib/mysql"
      - ./data/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    networks:
      - identy-network

volumes:
  mysql_data:
    driver: local

networks:
  identy-network:
</code>```

My Dockerfile:

```<code>FROM php:7.4-apache

RUN apt-get update \
    && apt-get install -y vim git zlib1g-dev mariadb-client libzip-dev \
    && docker-php-ext-install zip mysqli pdo_mysql \
    && pecl install xdebug \
    && docker-php-ext-enable xdebug \
    && echo 'xdebug.remote_enable=on' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_host=host.docker.internal' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_port=9000' >>  /usr/local/etc/php/conf.d/xdebug.ini \
    && a2enmod rewrite \
    && sed -i 's!/var/www/html!/var/www/public!g' /etc/apache2/sites-available/000-default.conf \
    && mv /var/www/html /var/www/public \
    && curl -sS https://getcomposer.org/installer \
    | php -- --install-dir=/usr/local/bin --filename=composer \
    && echo "AllowEncodedSlashes On" >> /etc/apache2/apache2.conf

WORKDIR /var/www
</code>```

.env:

```<code>...
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=identy
DB_USERNAME=root
DB_PASSWORD=654321
...
</code>```

When I run
docker exec identy-api_web_1 php artisan migrate
I get error:
**  Illuminate\Database\QueryException

SQLSTATE[HY000] [1045] Access denied for user 'root'@'192.168.144.3' (using password: YES) (SQL: select * from information_schema.tables where table_schema = identy and table_name = migrations and table_type = 'BASE TABLE')
**

I have no idea why it doesn't work.

答:
I think, You don't have permission to access the database from remote host on the mysql server. You need to allow access remotely to root from any host on the mysql server.  </p>

```<code>GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.144.3' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;
</code>```

Body:
I try to set up Laravel project in Docker.
My docker-compose.yml:

version: "2"
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - MYSQL_DATABASE=identy
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_HOST=db
    ports:
      - "8080:80"
    volumes:
      - .:/var/www
    depends_on:
      - db
    networks:
      - identy-network

  db:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=654321
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_DATABASE=identy
    volumes:
      - "mysql_data:/var/lib/mysql"
      - ./data/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    networks:
      - identy-network

volumes:
  mysql_data:
    driver: local

networks:
  identy-network:

My Dockerfile:

FROM php:7.4-apache

RUN apt-get update \
    && apt-get install -y vim git zlib1g-dev mariadb-client libzip-dev \
    && docker-php-ext-install zip mysqli pdo_mysql \
    && pecl install xdebug \
    && docker-php-ext-enable xdebug \
    && echo 'xdebug.remote_enable=on' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_host=host.docker.internal' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_port=9000' >>  /usr/local/etc/php/conf.d/xdebug.ini \
    && a2enmod rewrite \
    && sed -i 's!/var/www/html!/var/www/public!g' /etc/apache2/sites-available/000-default.conf \
    && mv /var/www/html /var/www/public \
    && curl -sS https://getcomposer.org/installer \
    | php -- --install-dir=/usr/local/bin --filename=composer \
    && echo "AllowEncodedSlashes On" >> /etc/apache2/apache2.conf

WORKDIR /var/www

.env:

...
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=identy
DB_USERNAME=root
DB_PASSWORD=654321
...

When I run
docker exec identy-api_web_1 php artisan migrate
I get error:
**  Illuminate\Database\QueryException

SQLSTATE[HY000] [1045] Access denied for user 'root'@'192.168.144.3' (using password: YES) (SQL: select * from information_schema.tables where table_schema = identy and table_name = migrations and table_type = 'BASE TABLE')
**

I have no idea why it doesn't work.

Body:
I think, You don't have permission to access the database from remote host on the mysql server. You need to allow access remotely to root from any host on the mysql server.

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.144.3' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;


问:
How do you get UID:GID in the [1002120000, 1002129999] range to make it run in OpenShift?
This is with OpenShift Container Platform 4.3.

Consider this Dockerfile.

```<code>FROM eclipse-mosquitto

# Create folders
USER root

RUN mkdir -p /mosquitto/data /mosquitto/log

# mosquitto configuration
USER mosquitto

# This is crucial to me
COPY --chown=mosquitto:mosquitto ri45.conf /mosquitto/config/mosquitto.conf

EXPOSE 1883
</code>```

And, this is my Deployment YAML.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mosquitto-broker
spec:
  selector:
    matchLabels:
      app: mosquitto-broker
  template:
    metadata:
      labels:
        app: mosquitto-broker
    spec:
      containers:
        - name: mosquitto-broker
          image: org/repo/eclipse-mosquitto:1.0.1
          imagePullPolicy: Always
          resources:
            limits:
              memory: "128Mi"
              cpu: "500m"
          volumeMounts:
            - name: mosquitto-data
              mountPath: /mosquitto/data
            - name: mosquitto-log
              mountPath: /mosquitto/log
          ports:
            - name: mqtt
              containerPort: 1883
      volumes:
        - name: mosquitto-log
          persistentVolumeClaim:
            claimName: mosquitto-log
        - name: mosquitto-data
          persistentVolumeClaim:
            claimName: mosquitto-data
```

<p>When I do a <code>oc create -f</code> with the above YAML, I get this error, <code>2020-06-02T07:59:59: Error: Unable to open log file /mosquitto/log/mosquitto.log for writing.</code> <em>Maybe</em> this is a permissions error; can't tell. Anyway, going by the <code>eclipse/mosquitto</code> <code>Dockerfile</code>, I see that <code>mosquitto</code> is a user with UID and GID of <code>1883</code>. So, I added the <code>securityContext</code> as described here.</p>

<pre class="lang-yaml prettyprint-override"><code>securityContext:
  fsGroup: 1883
</code>```

When I do a oc create -f with this modification, I get this error - securityContext.securityContext.runAsUser: Invalid value: 1883: must be in the ranges: [1002120000, 1002129999].

This approach of adding an initContainer to set permissions on volume does not work for me because, I have to be root to do that.

So, how do I enable the Eclipse mosquitto container to write to /mosquitto/log successfully?

答:
There are multiple things to address here.

First off, you should make sure that you really want to bake a configuration file into your container image. Typically, configuration files are added via ConfigMaps or Secrets, as the configuration in cloud-native applications should typically come from the environment (OpenShift in your case).

Secondly, it seems that you are logging into a PersistentVolume, which is also a terrible practice, as the best practice would be to log to stdout. Of course, having application data (transaction logs) on a persistent volume makes sense.

As for your original question (that should no longer be relevant given the two points above), the issue can be approached using SecurityContextContraints (SCCs): Managing Security Context Constraints

So to resolve your issue you should use / create a SCC with runAsUser set correctly.

Body:
This is with OpenShift Container Platform 4.3.

Consider this Dockerfile.

FROM eclipse-mosquitto

# Create folders
USER root

RUN mkdir -p /mosquitto/data /mosquitto/log

# mosquitto configuration
USER mosquitto

# This is crucial to me
COPY --chown=mosquitto:mosquitto ri45.conf /mosquitto/config/mosquitto.conf

EXPOSE 1883

And, this is my Deployment YAML.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mosquitto-broker
spec:
  selector:
    matchLabels:
      app: mosquitto-broker
  template:
    metadata:
      labels:
        app: mosquitto-broker
    spec:
      containers:
        - name: mosquitto-broker
          image: org/repo/eclipse-mosquitto:1.0.1
          imagePullPolicy: Always
          resources:
            limits:
              memory: "128Mi"
              cpu: "500m"
          volumeMounts:
            - name: mosquitto-data
              mountPath: /mosquitto/data
            - name: mosquitto-log
              mountPath: /mosquitto/log
          ports:
            - name: mqtt
              containerPort: 1883
      volumes:
        - name: mosquitto-log
          persistentVolumeClaim:
            claimName: mosquitto-log
        - name: mosquitto-data
          persistentVolumeClaim:
            claimName: mosquitto-data

When I do a oc create -f with the above YAML, I get this error, 2020-06-02T07:59:59: Error: Unable to open log file /mosquitto/log/mosquitto.log for writing. Maybe this is a permissions error; can't tell. Anyway, going by the eclipse/mosquitto Dockerfile, I see that mosquitto is a user with UID and GID of 1883. So, I added the securityContext as described here.

securityContext:
  fsGroup: 1883

When I do a oc create -f with this modification, I get this error - securityContext.securityContext.runAsUser: Invalid value: 1883: must be in the ranges: [1002120000, 1002129999].

This approach of adding an initContainer to set permissions on volume does not work for me because, I have to be root to do that.

So, how do I enable the Eclipse mosquitto container to write to /mosquitto/log successfully?


问:
Storing every iteration of dictionary comprehension in new nested dictionary
Apologies for redundancy, been trying to make this work for 3 days.

I can't figure out how to store a new dictionary inside my nested dictionary.

```<code>for team, roster in team_roster.items():
 stats['rp'][team] = {}
 for player in roster:
    if player in rp_year_STD[1]:
        stats['rp'][team] = {stat_type: stat for stat_type in p_stat_type for stat_list in rp_year_STD\
for stat in stat_list if stat_list[0] == stat_type}
</code>```

Tried this, does exact same (1 duplicate dictionary for each team):

```<code>for team, roster in team_roster.items():
 stats['rp'][team] = {}
 for player in roster:
     if player in rp_year_STD[1]:
         for stat_type in p_stat_type:
             for stat_list in rp_year_STD:
                  if stat_list[0] == stat_type:
                     for stat in stat_list:
                       stats['rp'][team][stat_type] = stat
</code>```

Team is a string key in separate dictionary (team_roster, shown below)
roster is a list of strings/player names for each team.
Player is string in list of strings (roster).
rp_year_STD is a list of lists. rp_year_STD1 is a list of strings/player names.
p_stat_type is a list of strings that validates the keys in the resultant dictionary (rp_year_STD is a list of lists compiled from a spreadsheet, the title of each column is potentially a key in the resultant dictionary).

I understand I'm creating 1 dictionary with this dictionary comprehension.

What I want is to create a new dictionary for each player that's included in roster and rp_year_STD and store it in the corresponding team dictionary, but I'm just creating 1 identical player dictionary (which is of course consists of the key/value pairs from the last entry in rp_year_STD or row in the spreadsheet the data comes from) for each team dictionary.

Sorry if this doesn't make sense, truly appreciate all of the information posted here. Thank you.

Here's what rp_year_STD is, each column being a list within a list and rp_year_STD1 being a list of strings/player names.

Here's the list of keys that I'm comparing against the column header/[0] index of each list. I don't want each column/list item/value to be in the resulting dictionary, which is why I validate with the list p_stat_type (shown below):

```<code>p_stat_type = ['Name', 'TBF', 'H', '2B', '3B', 'R', 'ER', 'HR', 'BB', 'IBB', 'HBP', 'SO', 'AVG', 'OBP', 'SLG', 'wOBA', 'playerId',  'K/BB', 'HR/9',\
           'K%', 'BB%', 'K-BB%', 'AVG', 'WHIP', 'BABIP', 'LOB%', 'FIP', 'xFIP', 'playerId' 'GB/FB', 'LD%', 'GB%', 'FB%', 'IFFB%', 'HR/FB', 'IFH%', 'BUH%', \
               'Pull%', 'Cent%', 'Oppo%', 'Soft%', 'Med%', 'Hard%', 'playerId']
</code>```

Here's the duplicate dictionary that being put in each [team] key:

```<code>'CHC': {'Name': 'Emmanuel Clase', 'TBF': '89', 'H': '19', '2B': '5', '3B': '1', 'R': '8', 'ER': '6', 'HR': '2', 'BB': '4', 'IBB': '0', 'HBP': '1', 'SO': '21', 'AVG': '0.226190476', 'OBP': '0.269662921', 'SLG': '0.38095238', 'wOBA': '0.2757020506', 'playerId': '21032'}
</code>```

Very close to working, but this is just the last value for each list in rp_year_STD.

Here's the team_roster dictionary, the function team_roster returns a list of strings\current players for each team :

```<code>team_roster = {'ARI' : team_roster(ARI, 'Diamondbacks'),
'BAL' : team_roster(BAL, 'Orioles'),
'BOS' : team_roster(BOS, 'Red Sox'),
'CHC' : team_roster(CHC, 'Cubs'),
'CIN' : team_roster(CIN, 'Reds'),
'CLE' : team_roster(CLE, 'Indians'),
'COL' : team_roster(COL, 'Rockies'),
'DET' : team_roster(DET, 'Tigers'),
'HOU' : team_roster(HOU, 'Astros'),
'KC' : team_roster(KC, 'Royals'),
'LAD' : team_roster(LAD, 'Dodgers'),
'WSH' : team_roster(WSH, 'Nationals'),
'NYM' : team_roster(NYM, 'Mets'),
'OAK' : team_roster(OAK, 'Athletics'),
'PIT' : team_roster(PIT, 'Pirates'),
'SD' : team_roster(SD, 'Padres'),
'SEA' : team_roster(SEA, 'Mariners'),
'SF' : team_roster(SF, 'Giants'),
'STL' : team_roster(STL, 'Cardinals'),
'TB' : team_roster(TB, 'Rays'),
'TEX' : team_roster(TEX, 'Rangers'),
'TOR' : team_roster(TOR, 'Blue Jays'),
'MIN' : team_roster(MIN, 'Twins'),
'PHI' : team_roster(PHI, 'Phillies'),
'ATL' : team_roster(ATL, 'Braves'),
'CWS' : team_roster(CWS, 'White Sox'),
'MIA' : team_roster(MIA, 'Marlins'),
'NYY' : team_roster(NYY, 'Yankees'),
'MIL' : team_roster(MIL, 'Brewers')}
</code>```

team_roster(teamA, 'TeamA') would be ['A. Man', 'A-Jax']

Again, thanks all for any suggestions.

答:
I eventually solved the problem by 1. using the player as a key, as @furas suggested - thanks for your time! 2. referencing the index of the the player in the dictionary comprehension and removing the nested loop from the comprehension and adding as normal loop as, again, @furas suggested. So, hopefully this has some use and/or I receive some informed suggestions for improvement. Thanks, below is code I ended up with:</p>

```<code>  for team in team_roster.keys():
  stats['hitter'][team] = {}
  for player in sort_roster(team)[0]:
      if player in h_zips[0]:
          h_zips_index = h_zips[0].index(player)
          index = h_year_STD[1].index(player)
          if h_zips[1][h_zips_index] == team and h_zips[25][h_zips_index] == h_year_STD[23][index]:
              stats['hitter'][team][player] = {}
              for stat_list in h_year_STD:
                  player_dict = {stat_type: stat_list[index] for stat_type in h_stat_type if stat_list[0] == stat_type}
                  stats['hitter'][team][player].update(player_dict)
</code>```

Body:
Apologies for redundancy, been trying to make this work for 3 days.

I can't figure out how to store a new dictionary inside my nested dictionary.

for team, roster in team_roster.items():
 stats['rp'][team] = {}
 for player in roster:
    if player in rp_year_STD[1]:
        stats['rp'][team] = {stat_type: stat for stat_type in p_stat_type for stat_list in rp_year_STD\
for stat in stat_list if stat_list[0] == stat_type}

Tried this, does exact same (1 duplicate dictionary for each team):

for team, roster in team_roster.items():
 stats['rp'][team] = {}
 for player in roster:
     if player in rp_year_STD[1]:
         for stat_type in p_stat_type:
             for stat_list in rp_year_STD:
                  if stat_list[0] == stat_type:
                     for stat in stat_list:
                       stats['rp'][team][stat_type] = stat

Team is a string key in separate dictionary (team_roster, shown below)
roster is a list of strings/player names for each team.
Player is string in list of strings (roster).
rp_year_STD is a list of lists. rp_year_STD1 is a list of strings/player names.
p_stat_type is a list of strings that validates the keys in the resultant dictionary (rp_year_STD is a list of lists compiled from a spreadsheet, the title of each column is potentially a key in the resultant dictionary).

I understand I'm creating 1 dictionary with this dictionary comprehension.

What I want is to create a new dictionary for each player that's included in roster and rp_year_STD and store it in the corresponding team dictionary, but I'm just creating 1 identical player dictionary (which is of course consists of the key/value pairs from the last entry in rp_year_STD or row in the spreadsheet the data comes from) for each team dictionary.

Sorry if this doesn't make sense, truly appreciate all of the information posted here. Thank you.

Here's what rp_year_STD is, each column being a list within a list and rp_year_STD1 being a list of strings/player names.

Here's the list of keys that I'm comparing against the column header/[0] index of each list. I don't want each column/list item/value to be in the resulting dictionary, which is why I validate with the list p_stat_type (shown below):

p_stat_type = ['Name', 'TBF', 'H', '2B', '3B', 'R', 'ER', 'HR', 'BB', 'IBB', 'HBP', 'SO', 'AVG', 'OBP', 'SLG', 'wOBA', 'playerId',  'K/BB', 'HR/9',\
           'K%', 'BB%', 'K-BB%', 'AVG', 'WHIP', 'BABIP', 'LOB%', 'FIP', 'xFIP', 'playerId' 'GB/FB', 'LD%', 'GB%', 'FB%', 'IFFB%', 'HR/FB', 'IFH%', 'BUH%', \
               'Pull%', 'Cent%', 'Oppo%', 'Soft%', 'Med%', 'Hard%', 'playerId']

Here's the duplicate dictionary that being put in each [team] key:

'CHC': {'Name': 'Emmanuel Clase', 'TBF': '89', 'H': '19', '2B': '5', '3B': '1', 'R': '8', 'ER': '6', 'HR': '2', 'BB': '4', 'IBB': '0', 'HBP': '1', 'SO': '21', 'AVG': '0.226190476', 'OBP': '0.269662921', 'SLG': '0.38095238', 'wOBA': '0.2757020506', 'playerId': '21032'}

Very close to working, but this is just the last value for each list in rp_year_STD.

Here's the team_roster dictionary, the function team_roster returns a list of strings\current players for each team :

team_roster = {'ARI' : team_roster(ARI, 'Diamondbacks'),
'BAL' : team_roster(BAL, 'Orioles'),
'BOS' : team_roster(BOS, 'Red Sox'),
'CHC' : team_roster(CHC, 'Cubs'),
'CIN' : team_roster(CIN, 'Reds'),
'CLE' : team_roster(CLE, 'Indians'),
'COL' : team_roster(COL, 'Rockies'),
'DET' : team_roster(DET, 'Tigers'),
'HOU' : team_roster(HOU, 'Astros'),
'KC' : team_roster(KC, 'Royals'),
'LAD' : team_roster(LAD, 'Dodgers'),
'WSH' : team_roster(WSH, 'Nationals'),
'NYM' : team_roster(NYM, 'Mets'),
'OAK' : team_roster(OAK, 'Athletics'),
'PIT' : team_roster(PIT, 'Pirates'),
'SD' : team_roster(SD, 'Padres'),
'SEA' : team_roster(SEA, 'Mariners'),
'SF' : team_roster(SF, 'Giants'),
'STL' : team_roster(STL, 'Cardinals'),
'TB' : team_roster(TB, 'Rays'),
'TEX' : team_roster(TEX, 'Rangers'),
'TOR' : team_roster(TOR, 'Blue Jays'),
'MIN' : team_roster(MIN, 'Twins'),
'PHI' : team_roster(PHI, 'Phillies'),
'ATL' : team_roster(ATL, 'Braves'),
'CWS' : team_roster(CWS, 'White Sox'),
'MIA' : team_roster(MIA, 'Marlins'),
'NYY' : team_roster(NYY, 'Yankees'),
'MIL' : team_roster(MIL, 'Brewers')}

team_roster(teamA, 'TeamA') would be ['A. Man', 'A-Jax']

Again, thanks all for any suggestions.

Body:
I eventually solved the problem by 1. using the player as a key, as @furas suggested - thanks for your time! 2. referencing the index of the the player in the dictionary comprehension and removing the nested loop from the comprehension and adding as normal loop as, again, @furas suggested. So, hopefully this has some use and/or I receive some informed suggestions for improvement. Thanks, below is code I ended up with:

  for team in team_roster.keys():
  stats['hitter'][team] = {}
  for player in sort_roster(team)[0]:
      if player in h_zips[0]:
          h_zips_index = h_zips[0].index(player)
          index = h_year_STD[1].index(player)
          if h_zips[1][h_zips_index] == team and h_zips[25][h_zips_index] == h_year_STD[23][index]:
              stats['hitter'][team][player] = {}
              for stat_list in h_year_STD:
                  player_dict = {stat_type: stat_list[index] for stat_type in h_stat_type if stat_list[0] == stat_type}
                  stats['hitter'][team][player].update(player_dict)


问:
How can I solve unconditionallyBridgeFromObjectiveC crash when storing a String value? (WKInterfaceDevice.current().name)
I'm getting a unconditionallyBridgeFromObjectiveC crash in an Apple Watch app out in the wild. I'm not able to replicate it locally, and haven't ever encountered it on a test device through regular use. Here's the info about the exception:

```<code>Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000000224c58b0
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [653]
</code>```

The crash reports show it's happening on the second line of this code:

```<code>let name: String
name = WKInterfaceDevice.current().name
</code>```

(I have these on separate lines for better readability in my code)

I'm not very family with Objective-C or how things can fail related to Objective-C values, but from what I've found around the Internet, here's my guess:

Even though the API says that WKInterfaceDevice.current().name is a String instead of String?, name is somehow actually a nil value in some cases.

As a possible solution, I'm thinking that instead of name: String I should use name: String? and then make sure it's non-nil later. Does this make sense? Would that help with the issue, or would it be possible that it still crashes from trying to store WKInterfaceDevice.current().name in a constant of type String?? Is there some other kind of safety check I should be doing on WKInterfaceDevice.current().name first?

This crash is not happening much (on at least 7 devices out of ~5000 in about 5 days) but it's the most frequent crash in the newest version of my app, so I'm trying to use it as a learning opportunity to make my app more robust. I guess maybe it could be an issue in WatchKit rather than a problem with my code? Or something that could only be checked and solved with Objective-C?

Stack Trace:

```<code>Hardware Model:      Watch5,2
Version:             1 (2020.29)
AppVariant:          1:Watch5,2:6
Code Type:           ARM (Native)
Role:                Foreground
Parent Process:      launchd [1]

Date/Time:           2020-05-28 14:32:42.6998 +0900
Launch Time:         2020-05-28 14:32:07.0000 +0900
OS Version:          Watch OS 6.2.5 (17T608)
Release Type:        User
Baseband Version:    n/a
Report Version:      104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000000224c58b0
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [653]
Triggered by Thread:  5

Thread 0 name:
Thread 0:
0   libsystem_kernel.dylib          0x21fdb134 mach_msg_trap + 8
1   libsystem_kernel.dylib          0x21fda604 mach_msg + 72 (mach_msg.c:103)
2   libdispatch.dylib               0x21e5a49c _dispatch_mach_send_and_wait_for_reply + 580 (mach.c:830)
3   libdispatch.dylib               0x21e5a858 dispatch_mach_send_with_result_and_wait_for_reply + 52 (mach.c:2006)
4   libxpc.dylib                    0x220bd150 xpc_connection_send_message_with_reply_sync + 228 (connection.c:829)
5   CoreFoundation                  0x2239cfec __99-[CFPrefsPlistSource sendFullyPreparedMessage:toConnection:settingValues:forKeys:count:retryCount:]_block_invoke + 56 (CFPrefsPlistSource.m:933)
6   CoreFoundation                  0x22353cb4 -[_CFXPreferences withConnectionForRole:performBlock:] + 48 (CFXPreferences.m:1330)
7   CoreFoundation                  0x2239cf88 -[CFPrefsPlistSource sendFullyPreparedMessage:toConnection:settingValues:forKeys:count:retryCount:] + 188 (CFPrefsPlistSource.m:962)
8   CoreFoundation                  0x2239d2c4 -[CFPrefsPlistSource sendMessageSettingValues:forKeys:count:] + 304 (CFPrefsPlistSource.m:994)
9   CoreFoundation                  0x2239c0f4 -[CFPrefsPlistSource alreadylocked_setPrecopiedValues:forKeys:count:from:] + 948 (CFPrefsPlistSource.m:397)
10  CoreFoundation                  0x2249ac9c -[CFPrefsSource setValues:forKeys:count:copyValues:removeValuesForKeys:count:from:] + 392 (CFPrefsSource.m:771)
11  CoreFoundation                  0x2249affc -[CFPrefsSource setValues:forKeys:count:copyValues:from:] + 36 (CFPrefsSource.m:793)
12  CoreFoundation                  0x223d74e4 -[CFPrefsSearchListSource alreadylocked_setPrecopiedValues:forKeys:count:from:] + 968 (CFPrefsSearchListSource.m:738)
13  CoreFoundation                  0x2249ac9c -[CFPrefsSource setValues:forKeys:count:copyValues:removeValuesForKeys:count:from:] + 392 (CFPrefsSource.m:771)
14  CoreFoundation                  0x2249affc -[CFPrefsSource setValues:forKeys:count:copyValues:from:] + 36 (CFPrefsSource.m:793)
15  CoreFoundation                  0x2234fc04 -[CFPrefsSource setValue:forKey:from:] + 64 (CFPrefsSource.m:799)
16  CoreFoundation                  0x224a3008 __76-[_CFXPreferences setValue:forKey:appIdentifier:container:configurationURL:]_block_invoke + 64 (CFXPreferences.m:795)
17  CoreFoundation                  0x223d9540 __108-[_CFXPreferences(SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:]_block_invoke + 372 (CFPrefsSearchListSource.m:1719)
18  CoreFoundation                  0x2234c6bc -[_CFXPreferences(SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:] + 340 (CFPrefsSearchListSource.m:68)
19  CoreFoundation                  0x2234f674 -[_CFXPreferences setValue:forKey:appIdentifier:container:configurationURL:] + 108 (CFXPreferences.m:791)
20  CoreFoundation                  0x224a619c _CFPreferencesSetAppValueWithContainerAndConfiguration + 132 (CFXPreferences.m:1853)
21  Foundation                      0x22e55a4c -[NSUserDefaults(NSUserDefaults) setObject:forKey:] + 64 (NSUserDefaults.m:226)
22  My App Name                     0x04a55320 specialized static NSUserDefaults.lastSentToPhone.setter + 272 (UserDefaults.swift:423)
23  My App Name                     0x04a500ac WatchConnectivityManager.sendBatteryLevel() + 2692 (<compiler-generated>:0)
24  My App Name                     0x04a55714 @objc ExtensionDelegate.applicationWillEnterForeground() + 188 (ExtensionDelegate.swift:32)
25  WatchKit                        0x34d21654 __80-[SPRemoteInterface applicationWillEnterForeground:withVisibleViewControllerID:]_block_invoke_2 + 128 (SPRemoteInterface.m:3668)
26  WatchKit                        0x34d40910 -[SPRemoteInterface performAfterApplicationDidFinishLaunching:] + 56 (SPRemoteInterface.m:3713)
27  WatchKit                        0x34d215c8 __80-[SPRemoteInterface applicationWillEnterForeground:withVisibleViewControllerID:]_block_invoke + 80 (SPRemoteInterface.m:3666)
28  WatchKit                        0x34d3ef08 spUtils_dispatchAsyncToMainThread + 40 (SPUtils.m:347)
29  WatchKit                        0x34d21444 -[SPRemoteInterface applicationWillEnterForeground:withVisibleViewControllerID:] + 212 (SPRemoteInterface.m:3665)
30  WatchKit                        0x34d2135c -[SPRemoteInterface appWillEnterForeground:withVisibleViewControllerID:] + 60 (SPRemoteInterface.m:4535)
31  WatchKit                        0x34d21280 __75-[SPExtensionConnection appWillEnterForegroundWithVisibleViewControllerID:]_block_invoke + 320 (SPExtensionConnection.m:1669)
32  WatchKit                        0x34d3d64c -[SPExtensionConnection performOnSendQueue:syncIfUnsuspended:] + 564 (SPExtensionConnection.m:0)
33  WatchKit                        0x34d2111c -[SPExtensionConnection appWillEnterForegroundWithVisibleViewControllerID:] + 112 (SPExtensionConnection.m:1667)
34  WatchKit                        0x34d21010 -[SPApplicationDelegate applicationWillEnterForeground:] + 264 (SPApplicationDelegate.m:670)
35  UIKitCore                       0x3f3a7ca4 -[UIApplication _sendWillEnterForegroundCallbacks] + 164 (UIApplication.m:10680)
36  UIKitCore                       0x3ec6c630 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke_2 + 1748 (_UISceneLifecycleMultiplexer.m:572)
37  UIKitCore                       0x3f069a5c _UIScenePerformActionsWithLifecycleActionMask + 104 (_UISceneLifecycleState.m:109)
38  UIKitCore                       0x3ec6beb8 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke + 208 (_UISceneLifecycleMultiplexer.m:501)
39  UIKitCore                       0x3ec6b8d0 -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:] + 292 (_UISceneLifecycleMultiplexer.m:450)
40  UIKitCore                       0x3ec6bcc4 -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:] + 768 (_UISceneLifecycleMultiplexer.m:500)
41  UIKitCore                       0x3ec6b564 -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:] + 336 (_UISceneLifecycleMultiplexer.m:406)
42  UIKitCore                       0x3ec6fb50 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block... + 188 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:102)
43  UIKitCore                       0x3efa7548 +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:actions:completion:] + 804 (BSAnimationSettings+UIKit.m:50)
44  UIKitCore                       0x3f0827dc _UISceneSettingsDiffActionPerformChangesWithTransitionContext + 244 (_UISceneSettingsDiffAction.m:43)
45  UIKitCore                       0x3ec6f920 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block... + 136 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:87)
46  UIKitCore                       0x3f0826d8 _UISceneSettingsDiffActionPerformActionsWithDelayForTransitionContext + 100 (_UISceneSettingsDiffAction.m:35)
47  UIKitCore                       0x3ec6f78c -[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 376 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:85)
48  UIKitCore                       0x3eaf2b78 __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke + 640 (UIScene.m:1340)
49  UIKitCore                       0x3eaf1720 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 236 (UIScene.m:1073)
50  UIKitCore                       0x3eaf28ac -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 220 (UIScene.m:1317)
51  UIKitCore                       0x3efc7c8c -[UIApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 464 (UIApplicationSceneClientAgent.m:80)
52  PepperUICore                    0x2ebc2d94 -[PUICApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 804 (PUICApplicationSceneClientAgent.m:156)
53  CarouselUIServices              0x32abcbec -[CUISWatchKitApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 276 (CUISWatchKitApplicationSceneClientAgent.m:80)
54  FrontBoardServices              0x25ea1660 -[FBSSceneImpl updater:didUpdateSettings:withDiff:transitionContext:completion:] + 528 (FBSSceneImpl.m:551)
55  FrontBoardServices              0x25ec5914 __88-[FBSWorkspaceScenesClient sceneID:updateWithSettingsDiff:transitionContext:completion:]_block_invoke_2 + 120 (FBSWorkspaceScenesClient.m:356)
56  FrontBoardServices              0x25eab12c -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 232 (FBSWorkspace.m:357)
57  FrontBoardServices              0x25ec5848 __88-[FBSWorkspaceScenesClient sceneID:updateWithSettingsDiff:transitionContext:completion:]_block_invoke + 184 (FBSWorkspaceScenesClient.m:355)
58  libdispatch.dylib               0x21e44fc0 _dispatch_client_callout + 16 (object.m:495)
59  libdispatch.dylib               0x21e47cac _dispatch_block_invoke_direct + 248 (queue.c:466)
60  FrontBoardServices              0x25ee9b44 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40 (FBSSerialQueue.m:173)
61  FrontBoardServices              0x25ee9810 -[FBSSerialQueue _queue_performNextIfPossible] + 412 (FBSSerialQueue.m:216)
62  FrontBoardServices              0x25ee9d94 -[FBSSerialQueue _performNextFromRunLoopSource] + 28 (FBSSerialQueue.m:247)
63  CoreFoundation                  0x223ee2f8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 (CFRunLoop.c:1922)
64  CoreFoundation                  0x223ee250 __CFRunLoopDoSource0 + 80 (CFRunLoop.c:1956)
65  CoreFoundation                  0x223ed9f0 __CFRunLoopDoSources0 + 184 (CFRunLoop.c:1992)
66  CoreFoundation                  0x223e8adc __CFRunLoopRun + 772 (CFRunLoop.c:2882)
67  CoreFoundation                  0x223e84d0 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
68  GraphicsServices                0x25984358 GSEventRunModal + 160 (GSEvent.c:2246)
69  UIKitCore                       0x3f392fac UIApplicationMain + 1756 (UIApplication.m:4820)
70  libxpc.dylib                    0x220d9bdc _xpc_objc_main.cold.3 + 208
71  libxpc.dylib                    0x220c5ccc _xpc_objc_main + 212 (main.m:0)
72  libxpc.dylib                    0x220c82b0 xpc_main + 152 (init.c:1384)
73  Foundation                      0x22e51738 -[NSXPCListener resume] + 160 (NSXPCListener.m:276)
74  PlugInKit                       0x2bdb40a8 -[PKService run] + 396 (PKService.m:165)
75  WatchKit                        0x34d39e94 WKExtensionMain + 60 (main.m:19)
76  libdyld.dylib                   0x21e80f48 start + 4

Thread 1:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 2:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 3 name:
Thread 3:
0   libsystem_kernel.dylib          0x21fdb134 mach_msg_trap + 8
1   libsystem_kernel.dylib          0x21fda604 mach_msg + 72 (mach_msg.c:103)
2   CoreFoundation                  0x223edb5c __CFRunLoopServiceMachPort + 148 (CFRunLoop.c:2575)
3   CoreFoundation                  0x223e8c40 __CFRunLoopRun + 1128 (CFRunLoop.c:2931)
4   CoreFoundation                  0x223e84d0 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
5   Foundation                      0x22e1638c -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 228 (NSRunLoop.m:374)
6   Foundation                      0x22e1626c -[NSRunLoop(NSRunLoop) runUntilDate:] + 88 (NSRunLoop.m:421)
7   UIKitCore                       0x3f4235f8 -[UIEventFetcher threadMain] + 152 (UIEventFetcher.m:733)
8   Foundation                      0x22f42404 __NSThread__start__ + 844 (NSThread.m:724)
9   libsystem_pthread.dylib         0x22079984 _pthread_start + 156 (pthread.c:896)
10  libsystem_pthread.dylib         0x22081814 thread_start + 8

Thread 4 name:
Thread 4:
0   libobjc.A.dylib                 0x21d8407c getMethodNoSuper_nolock(objc_class*, objc_selector*) + 168 (objc-runtime-new.mm:5813)
1   libobjc.A.dylib                 0x21d8e164 lookUpImpOrForward + 348 (objc-runtime-new.mm:6221)
2   libobjc.A.dylib                 0x21d7ad5c _objc_msgSend_uncached + 60
3   libobjc.A.dylib                 0x21d7a588 CALLING_SOME_+initialize_METHOD + 20 (objc-initialize.mm:384)
4   libobjc.A.dylib                 0x21d80140 initializeNonMetaClass + 548 (objc-initialize.mm:554)
5   libobjc.A.dylib                 0x21d814d8 initializeAndMaybeRelock(objc_class*, objc_object*, mutex_tt<false>&, bool) + 272 (objc-runtime-new.mm:2183)
6   libobjc.A.dylib                 0x21d8e2c8 lookUpImpOrForward + 704 (objc-runtime-new.mm:2199)
7   libobjc.A.dylib                 0x21d7ad5c _objc_msgSend_uncached + 60
8   WatchConnectivity               0x3616795c -[WCQueueManager onqueue_sendMessage:completionHandler:] + 64 (WCQueueManager.m:100)
9   libdispatch.dylib               0x21e43c1c _dispatch_call_block_and_release + 24 (init.c:1408)
10  libdispatch.dylib               0x21e44fc0 _dispatch_client_callout + 16 (object.m:495)
11  libdispatch.dylib               0x21e4b128 _dispatch_lane_serial_drain + 676 (inline_internal.h:2484)
12  libdispatch.dylib               0x21e4bb08 _dispatch_lane_invoke + 404 (queue.c:3863)
13  libdispatch.dylib               0x21e5501c _dispatch_workloop_worker_thread + 584 (queue.c:6445)
14  libsystem_pthread.dylib         0x2207b704 _pthread_wqthread + 276 (pthread.c:2351)
15  libsystem_pthread.dylib         0x22081808 start_wqthread + 8

Thread 5 name:
Thread 5 Crashed:
0   CoreFoundation                  0x224c58b0 _CFRelease.cold.2 + 16
1   CoreFoundation                  0x223efda4 _CFRelease + 1440 (CFRuntime.c:2041)
2   libswiftCore.dylib              0x48565aa8 String.init(_cocoaString:) + 44 (<compiler-generated>:0)
3   libswiftFoundation.dylib        0x48820d94 static String._unconditionallyBridgeFromObjectiveC(_:) + 36 (String.swift:25)
4   My App Name                     0x04a503f0 WatchConnectivityManager.getCurrentWatchInfo() + 424 (WatchConnectivityManager.swift:219)
5   My App Name                     0x04a4f798 WatchConnectivityManager.sendWatchInfo() + 368 (WatchConnectivityManager.swift:149)
6   My App Name                     0x04a508cc @objc WatchConnectivityManager.session(_:activationDidCompleteWith:error:) + 72 (WatchConnectivityManager.swift:252)
7   WatchConnectivity               0x36156f28 __57-[WCSession onqueue_completeSwitchTask:withSessionState:]_block_invoke_2 + 380 (WCSession.m:1509)
8   Foundation                      0x22f1eb4c __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 16 (NSOperation.m:1541)
9   Foundation                      0x22e2ca00 -[NSBlockOperation main] + 84 (NSOperation.m:1560)
10  Foundation                      0x22f20d80 __NSOPERATION_IS_INVOKING_MAIN__ + 20 (NSOperation.m:2184)
11  Foundation                      0x22e2c6ec -[NSOperation start] + 752 (NSOperation.m:2201)
12  Foundation                      0x22f21750 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 20 (NSOperation.m:2215)
13  Foundation                      0x22f21230 __NSOQSchedule_f + 180 (NSOperation.m:2226)
14  libdispatch.dylib               0x21e43c1c _dispatch_call_block_and_release + 24 (init.c:1408)
15  libdispatch.dylib               0x21e44fc0 _dispatch_client_callout + 16 (object.m:495)
16  libdispatch.dylib               0x21e47700 _dispatch_continuation_pop + 496 (inline_internal.h:2484)
17  libdispatch.dylib               0x21e46e18 _dispatch_async_redirect_invoke + 588 (queue.c:803)
18  libdispatch.dylib               0x21e53cfc _dispatch_root_queue_drain + 356 (inline_internal.h:2525)
19  libdispatch.dylib               0x21e54494 _dispatch_worker_thread2 + 116 (queue.c:6628)
20  libsystem_pthread.dylib         0x2207b6c8 _pthread_wqthread + 216 (pthread.c:2364)
21  libsystem_pthread.dylib         0x22081808 start_wqthread + 8

Thread 6:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 7:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 5 crashed with ARM Thread State (64-bit):
    x0: 0x0000000014ee1b10   x1: 0x0000000048c0cc97   x2: 0x0000000000005002   x3: 0x0000000000000000
    x4: 0x0000000014ee1af0   x5: 0x0000000000000002   x6: 0x0000000000000000   x7: 0x0000000000000000
    x8: 0x000000004fb0e000   x9: 0x0000000022533950  x10: 0x00000000153c2e00  x11: 0x000000000000003f
   x12: 0x00000000153c2eb8  x13: 0x00000000001c0369  x14: 0x0000000000000000  x15: 0x000000005cd5d1ff
   x16: 0x0000000050b251d8  x17: 0x000000002235c024  x18: 0x0000000000000000  x19: 0x0000000014ee1b10
   x20: 0x0000000004600790  x21: 0x0000000014ee1b10  x22: 0x0000000000005002  x23: 0x0000000014d8e900
   x24: 0x0000000000000001  x25: 0x0000000004a65000  x26: 0x000000000000c000  x27: 0x0000000004a65d60
   x28: 0x00000000c0004002   fp: 0x00000000192ee8b0   lr: 0x00000000223efda4
    sp: 0x00000000192ee840   pc: 0x00000000224c58b0 cpsr: 0x60000000
   esr: 0xf2000001  Address size fault
</code>```

WatchConnectivityManager class:

```<code>class WatchConnectivityManager {

    static let shared = WatchConnectivityManager()

    let session = WCSession.default

    func sendWatchInfo() {

            if session.activationState == .activated {

                let name = getCurrentWatchInfo()

                let message: [String : Any] = ["appleWatchName" : name]

                if session.isReachable {
                    session.sendMessage(message,
                                        replyHandler: nil,
                                        errorHandler: nil)
                }

                do {
                    try session.updateApplicationContext(message)
                } catch(let error) {
                    fatalError(error.localizedDescription)
                }
            }
        }

        private func getCurrentWatchInfo() -> String {

            let name: String

            name = WKInterfaceDevice.current().name

            return name
    }
}
</code>```

答:
Even though the API says that WKInterfaceDevice.current().name is a String instead of String?, name is somehow actually a nil value in some cases.

It can't be nil. name is a property declared as:

var name: String { get }
```

<p>It can be an empty string, but not <code>nil</code> (Swift context). And the Objective-C:</p>

<pre class="lang-c prettyprint-override"><code>@property(nonatomic, readonly, copy) NSString *name;
</code>```

It's encapsulated with the NS_ASSUME_NONNULL_BEGIN & NS_ASSUME_NONNULL_END which effectively means:

@property(nonatomic, readonly, copy) NSString * _Nonnull safeName;
```

<p>Read Nullability and Objective-C to see how it affects Objective-C -> Swift.</p>

<p>Actually it can be <code>nil</code> in the Objective-C context, but it violates the <code>_Nonnull</code> contract then.</p>

<p><strong>As a possible solution, I'm thinking that instead of <code>name: String</code> I should use <code>name: String?</code>.</strong></p>

<p>I don't think it's going to help even if you can do this. Imagine you have the following method<sup>1</sup>:</p>

<pre class="lang-c prettyprint-override"><code>- (NSString * _Nonnull)canNotBeNilNothing {
    return nil;
}
</code>```

Used in Swift:

let name: String? = WKInterfaceDevice.current().canNotBeNilNothing();
print("\(String(describing: name))")
```

<p>You still get the <code>Optional("")</code>, not <code>nil</code>. And it's expected, because there's this <code>_Nonnull</code> (it violates the contract, but it's another story).</p>

<p>You can create something like this if you are really sure it can return <code>nil</code> in Objective-C:</p>

<pre class="lang-c prettyprint-override"><code>- (NSString * _Nullable)maybeName {
    return [self name];
}
</code>```

And then you can use String? in Swift and it can become nil if [self name] will return nil.

Possible causes of your problem

Bug somewhere in the WatchKit (Incorrect nullability annotation, ...)

Something else

I'm not sure what's happening, because I didn't see the stacktrace.

Possible solution

WatchKit & Objective-C problem (throws an exception)? It might be fixable with the following wrapper in Objective-C:

- (NSString * _Nullable)maybeName {
    @try {
        return [self name];
    }
    @catch (NSException *exception) {
        // Return nil or handle it your way
        return nil;
    }
}
```

<p>Bridging issue (incorrect nullability)? It might be fixable with the following code in Swift:</p>

<pre class="lang-swift prettyprint-override"><code>extension WKInterfaceDevice {
    var maybeName: String? {
        self.perform(#selector(getter: WKInterfaceDevice.name))?.takeRetainedValue() as! String?
    }
}
</code>```

1 In general, you should look at nullable and nonnull roughly the way you currently use assertions or exceptions: violating the contract is a programmer error. In particular, return values are something you control, so you should never return nil for a non-nullable return type unless it is for backwards-compatibility. (Nullability and Objective-C)

Body:
I'm getting a unconditionallyBridgeFromObjectiveC crash in an Apple Watch app out in the wild. I'm not able to replicate it locally, and haven't ever encountered it on a test device through regular use. Here's the info about the exception:

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000000224c58b0
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [653]

The crash reports show it's happening on the second line of this code:

let name: String
name = WKInterfaceDevice.current().name

(I have these on separate lines for better readability in my code)

I'm not very family with Objective-C or how things can fail related to Objective-C values, but from what I've found around the Internet, here's my guess:

Even though the API says that WKInterfaceDevice.current().name is a String instead of String?, name is somehow actually a nil value in some cases.

As a possible solution, I'm thinking that instead of name: String I should use name: String? and then make sure it's non-nil later. Does this make sense? Would that help with the issue, or would it be possible that it still crashes from trying to store WKInterfaceDevice.current().name in a constant of type String?? Is there some other kind of safety check I should be doing on WKInterfaceDevice.current().name first?

This crash is not happening much (on at least 7 devices out of ~5000 in about 5 days) but it's the most frequent crash in the newest version of my app, so I'm trying to use it as a learning opportunity to make my app more robust. I guess maybe it could be an issue in WatchKit rather than a problem with my code? Or something that could only be checked and solved with Objective-C?

Stack Trace:

Hardware Model:      Watch5,2
Version:             1 (2020.29)
AppVariant:          1:Watch5,2:6
Code Type:           ARM (Native)
Role:                Foreground
Parent Process:      launchd [1]

Date/Time:           2020-05-28 14:32:42.6998 +0900
Launch Time:         2020-05-28 14:32:07.0000 +0900
OS Version:          Watch OS 6.2.5 (17T608)
Release Type:        User
Baseband Version:    n/a
Report Version:      104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000000224c58b0
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [653]
Triggered by Thread:  5

Thread 0 name:
Thread 0:
0   libsystem_kernel.dylib          0x21fdb134 mach_msg_trap + 8
1   libsystem_kernel.dylib          0x21fda604 mach_msg + 72 (mach_msg.c:103)
2   libdispatch.dylib               0x21e5a49c _dispatch_mach_send_and_wait_for_reply + 580 (mach.c:830)
3   libdispatch.dylib               0x21e5a858 dispatch_mach_send_with_result_and_wait_for_reply + 52 (mach.c:2006)
4   libxpc.dylib                    0x220bd150 xpc_connection_send_message_with_reply_sync + 228 (connection.c:829)
5   CoreFoundation                  0x2239cfec __99-[CFPrefsPlistSource sendFullyPreparedMessage:toConnection:settingValues:forKeys:count:retryCount:]_block_invoke + 56 (CFPrefsPlistSource.m:933)
6   CoreFoundation                  0x22353cb4 -[_CFXPreferences withConnectionForRole:performBlock:] + 48 (CFXPreferences.m:1330)
7   CoreFoundation                  0x2239cf88 -[CFPrefsPlistSource sendFullyPreparedMessage:toConnection:settingValues:forKeys:count:retryCount:] + 188 (CFPrefsPlistSource.m:962)
8   CoreFoundation                  0x2239d2c4 -[CFPrefsPlistSource sendMessageSettingValues:forKeys:count:] + 304 (CFPrefsPlistSource.m:994)
9   CoreFoundation                  0x2239c0f4 -[CFPrefsPlistSource alreadylocked_setPrecopiedValues:forKeys:count:from:] + 948 (CFPrefsPlistSource.m:397)
10  CoreFoundation                  0x2249ac9c -[CFPrefsSource setValues:forKeys:count:copyValues:removeValuesForKeys:count:from:] + 392 (CFPrefsSource.m:771)
11  CoreFoundation                  0x2249affc -[CFPrefsSource setValues:forKeys:count:copyValues:from:] + 36 (CFPrefsSource.m:793)
12  CoreFoundation                  0x223d74e4 -[CFPrefsSearchListSource alreadylocked_setPrecopiedValues:forKeys:count:from:] + 968 (CFPrefsSearchListSource.m:738)
13  CoreFoundation                  0x2249ac9c -[CFPrefsSource setValues:forKeys:count:copyValues:removeValuesForKeys:count:from:] + 392 (CFPrefsSource.m:771)
14  CoreFoundation                  0x2249affc -[CFPrefsSource setValues:forKeys:count:copyValues:from:] + 36 (CFPrefsSource.m:793)
15  CoreFoundation                  0x2234fc04 -[CFPrefsSource setValue:forKey:from:] + 64 (CFPrefsSource.m:799)
16  CoreFoundation                  0x224a3008 __76-[_CFXPreferences setValue:forKey:appIdentifier:container:configurationURL:]_block_invoke + 64 (CFXPreferences.m:795)
17  CoreFoundation                  0x223d9540 __108-[_CFXPreferences(SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:]_block_invoke + 372 (CFPrefsSearchListSource.m:1719)
18  CoreFoundation                  0x2234c6bc -[_CFXPreferences(SearchListAdditions) withSearchListForIdentifier:container:cloudConfigurationURL:perform:] + 340 (CFPrefsSearchListSource.m:68)
19  CoreFoundation                  0x2234f674 -[_CFXPreferences setValue:forKey:appIdentifier:container:configurationURL:] + 108 (CFXPreferences.m:791)
20  CoreFoundation                  0x224a619c _CFPreferencesSetAppValueWithContainerAndConfiguration + 132 (CFXPreferences.m:1853)
21  Foundation                      0x22e55a4c -[NSUserDefaults(NSUserDefaults) setObject:forKey:] + 64 (NSUserDefaults.m:226)
22  My App Name                     0x04a55320 specialized static NSUserDefaults.lastSentToPhone.setter + 272 (UserDefaults.swift:423)
23  My App Name                     0x04a500ac WatchConnectivityManager.sendBatteryLevel() + 2692 (<compiler-generated>:0)
24  My App Name                     0x04a55714 @objc ExtensionDelegate.applicationWillEnterForeground() + 188 (ExtensionDelegate.swift:32)
25  WatchKit                        0x34d21654 __80-[SPRemoteInterface applicationWillEnterForeground:withVisibleViewControllerID:]_block_invoke_2 + 128 (SPRemoteInterface.m:3668)
26  WatchKit                        0x34d40910 -[SPRemoteInterface performAfterApplicationDidFinishLaunching:] + 56 (SPRemoteInterface.m:3713)
27  WatchKit                        0x34d215c8 __80-[SPRemoteInterface applicationWillEnterForeground:withVisibleViewControllerID:]_block_invoke + 80 (SPRemoteInterface.m:3666)
28  WatchKit                        0x34d3ef08 spUtils_dispatchAsyncToMainThread + 40 (SPUtils.m:347)
29  WatchKit                        0x34d21444 -[SPRemoteInterface applicationWillEnterForeground:withVisibleViewControllerID:] + 212 (SPRemoteInterface.m:3665)
30  WatchKit                        0x34d2135c -[SPRemoteInterface appWillEnterForeground:withVisibleViewControllerID:] + 60 (SPRemoteInterface.m:4535)
31  WatchKit                        0x34d21280 __75-[SPExtensionConnection appWillEnterForegroundWithVisibleViewControllerID:]_block_invoke + 320 (SPExtensionConnection.m:1669)
32  WatchKit                        0x34d3d64c -[SPExtensionConnection performOnSendQueue:syncIfUnsuspended:] + 564 (SPExtensionConnection.m:0)
33  WatchKit                        0x34d2111c -[SPExtensionConnection appWillEnterForegroundWithVisibleViewControllerID:] + 112 (SPExtensionConnection.m:1667)
34  WatchKit                        0x34d21010 -[SPApplicationDelegate applicationWillEnterForeground:] + 264 (SPApplicationDelegate.m:670)
35  UIKitCore                       0x3f3a7ca4 -[UIApplication _sendWillEnterForegroundCallbacks] + 164 (UIApplication.m:10680)
36  UIKitCore                       0x3ec6c630 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke_2 + 1748 (_UISceneLifecycleMultiplexer.m:572)
37  UIKitCore                       0x3f069a5c _UIScenePerformActionsWithLifecycleActionMask + 104 (_UISceneLifecycleState.m:109)
38  UIKitCore                       0x3ec6beb8 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke + 208 (_UISceneLifecycleMultiplexer.m:501)
39  UIKitCore                       0x3ec6b8d0 -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:] + 292 (_UISceneLifecycleMultiplexer.m:450)
40  UIKitCore                       0x3ec6bcc4 -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:] + 768 (_UISceneLifecycleMultiplexer.m:500)
41  UIKitCore                       0x3ec6b564 -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:] + 336 (_UISceneLifecycleMultiplexer.m:406)
42  UIKitCore                       0x3ec6fb50 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block... + 188 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:102)
43  UIKitCore                       0x3efa7548 +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:actions:completion:] + 804 (BSAnimationSettings+UIKit.m:50)
44  UIKitCore                       0x3f0827dc _UISceneSettingsDiffActionPerformChangesWithTransitionContext + 244 (_UISceneSettingsDiffAction.m:43)
45  UIKitCore                       0x3ec6f920 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block... + 136 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:87)
46  UIKitCore                       0x3f0826d8 _UISceneSettingsDiffActionPerformActionsWithDelayForTransitionContext + 100 (_UISceneSettingsDiffAction.m:35)
47  UIKitCore                       0x3ec6f78c -[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 376 (_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction.m:85)
48  UIKitCore                       0x3eaf2b78 __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke + 640 (UIScene.m:1340)
49  UIKitCore                       0x3eaf1720 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 236 (UIScene.m:1073)
50  UIKitCore                       0x3eaf28ac -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 220 (UIScene.m:1317)
51  UIKitCore                       0x3efc7c8c -[UIApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 464 (UIApplicationSceneClientAgent.m:80)
52  PepperUICore                    0x2ebc2d94 -[PUICApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 804 (PUICApplicationSceneClientAgent.m:156)
53  CarouselUIServices              0x32abcbec -[CUISWatchKitApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 276 (CUISWatchKitApplicationSceneClientAgent.m:80)
54  FrontBoardServices              0x25ea1660 -[FBSSceneImpl updater:didUpdateSettings:withDiff:transitionContext:completion:] + 528 (FBSSceneImpl.m:551)
55  FrontBoardServices              0x25ec5914 __88-[FBSWorkspaceScenesClient sceneID:updateWithSettingsDiff:transitionContext:completion:]_block_invoke_2 + 120 (FBSWorkspaceScenesClient.m:356)
56  FrontBoardServices              0x25eab12c -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 232 (FBSWorkspace.m:357)
57  FrontBoardServices              0x25ec5848 __88-[FBSWorkspaceScenesClient sceneID:updateWithSettingsDiff:transitionContext:completion:]_block_invoke + 184 (FBSWorkspaceScenesClient.m:355)
58  libdispatch.dylib               0x21e44fc0 _dispatch_client_callout + 16 (object.m:495)
59  libdispatch.dylib               0x21e47cac _dispatch_block_invoke_direct + 248 (queue.c:466)
60  FrontBoardServices              0x25ee9b44 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40 (FBSSerialQueue.m:173)
61  FrontBoardServices              0x25ee9810 -[FBSSerialQueue _queue_performNextIfPossible] + 412 (FBSSerialQueue.m:216)
62  FrontBoardServices              0x25ee9d94 -[FBSSerialQueue _performNextFromRunLoopSource] + 28 (FBSSerialQueue.m:247)
63  CoreFoundation                  0x223ee2f8 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 (CFRunLoop.c:1922)
64  CoreFoundation                  0x223ee250 __CFRunLoopDoSource0 + 80 (CFRunLoop.c:1956)
65  CoreFoundation                  0x223ed9f0 __CFRunLoopDoSources0 + 184 (CFRunLoop.c:1992)
66  CoreFoundation                  0x223e8adc __CFRunLoopRun + 772 (CFRunLoop.c:2882)
67  CoreFoundation                  0x223e84d0 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
68  GraphicsServices                0x25984358 GSEventRunModal + 160 (GSEvent.c:2246)
69  UIKitCore                       0x3f392fac UIApplicationMain + 1756 (UIApplication.m:4820)
70  libxpc.dylib                    0x220d9bdc _xpc_objc_main.cold.3 + 208
71  libxpc.dylib                    0x220c5ccc _xpc_objc_main + 212 (main.m:0)
72  libxpc.dylib                    0x220c82b0 xpc_main + 152 (init.c:1384)
73  Foundation                      0x22e51738 -[NSXPCListener resume] + 160 (NSXPCListener.m:276)
74  PlugInKit                       0x2bdb40a8 -[PKService run] + 396 (PKService.m:165)
75  WatchKit                        0x34d39e94 WKExtensionMain + 60 (main.m:19)
76  libdyld.dylib                   0x21e80f48 start + 4

Thread 1:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 2:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 3 name:
Thread 3:
0   libsystem_kernel.dylib          0x21fdb134 mach_msg_trap + 8
1   libsystem_kernel.dylib          0x21fda604 mach_msg + 72 (mach_msg.c:103)
2   CoreFoundation                  0x223edb5c __CFRunLoopServiceMachPort + 148 (CFRunLoop.c:2575)
3   CoreFoundation                  0x223e8c40 __CFRunLoopRun + 1128 (CFRunLoop.c:2931)
4   CoreFoundation                  0x223e84d0 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
5   Foundation                      0x22e1638c -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 228 (NSRunLoop.m:374)
6   Foundation                      0x22e1626c -[NSRunLoop(NSRunLoop) runUntilDate:] + 88 (NSRunLoop.m:421)
7   UIKitCore                       0x3f4235f8 -[UIEventFetcher threadMain] + 152 (UIEventFetcher.m:733)
8   Foundation                      0x22f42404 __NSThread__start__ + 844 (NSThread.m:724)
9   libsystem_pthread.dylib         0x22079984 _pthread_start + 156 (pthread.c:896)
10  libsystem_pthread.dylib         0x22081814 thread_start + 8

Thread 4 name:
Thread 4:
0   libobjc.A.dylib                 0x21d8407c getMethodNoSuper_nolock(objc_class*, objc_selector*) + 168 (objc-runtime-new.mm:5813)
1   libobjc.A.dylib                 0x21d8e164 lookUpImpOrForward + 348 (objc-runtime-new.mm:6221)
2   libobjc.A.dylib                 0x21d7ad5c _objc_msgSend_uncached + 60
3   libobjc.A.dylib                 0x21d7a588 CALLING_SOME_+initialize_METHOD + 20 (objc-initialize.mm:384)
4   libobjc.A.dylib                 0x21d80140 initializeNonMetaClass + 548 (objc-initialize.mm:554)
5   libobjc.A.dylib                 0x21d814d8 initializeAndMaybeRelock(objc_class*, objc_object*, mutex_tt<false>&, bool) + 272 (objc-runtime-new.mm:2183)
6   libobjc.A.dylib                 0x21d8e2c8 lookUpImpOrForward + 704 (objc-runtime-new.mm:2199)
7   libobjc.A.dylib                 0x21d7ad5c _objc_msgSend_uncached + 60
8   WatchConnectivity               0x3616795c -[WCQueueManager onqueue_sendMessage:completionHandler:] + 64 (WCQueueManager.m:100)
9   libdispatch.dylib               0x21e43c1c _dispatch_call_block_and_release + 24 (init.c:1408)
10  libdispatch.dylib               0x21e44fc0 _dispatch_client_callout + 16 (object.m:495)
11  libdispatch.dylib               0x21e4b128 _dispatch_lane_serial_drain + 676 (inline_internal.h:2484)
12  libdispatch.dylib               0x21e4bb08 _dispatch_lane_invoke + 404 (queue.c:3863)
13  libdispatch.dylib               0x21e5501c _dispatch_workloop_worker_thread + 584 (queue.c:6445)
14  libsystem_pthread.dylib         0x2207b704 _pthread_wqthread + 276 (pthread.c:2351)
15  libsystem_pthread.dylib         0x22081808 start_wqthread + 8

Thread 5 name:
Thread 5 Crashed:
0   CoreFoundation                  0x224c58b0 _CFRelease.cold.2 + 16
1   CoreFoundation                  0x223efda4 _CFRelease + 1440 (CFRuntime.c:2041)
2   libswiftCore.dylib              0x48565aa8 String.init(_cocoaString:) + 44 (<compiler-generated>:0)
3   libswiftFoundation.dylib        0x48820d94 static String._unconditionallyBridgeFromObjectiveC(_:) + 36 (String.swift:25)
4   My App Name                     0x04a503f0 WatchConnectivityManager.getCurrentWatchInfo() + 424 (WatchConnectivityManager.swift:219)
5   My App Name                     0x04a4f798 WatchConnectivityManager.sendWatchInfo() + 368 (WatchConnectivityManager.swift:149)
6   My App Name                     0x04a508cc @objc WatchConnectivityManager.session(_:activationDidCompleteWith:error:) + 72 (WatchConnectivityManager.swift:252)
7   WatchConnectivity               0x36156f28 __57-[WCSession onqueue_completeSwitchTask:withSessionState:]_block_invoke_2 + 380 (WCSession.m:1509)
8   Foundation                      0x22f1eb4c __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 16 (NSOperation.m:1541)
9   Foundation                      0x22e2ca00 -[NSBlockOperation main] + 84 (NSOperation.m:1560)
10  Foundation                      0x22f20d80 __NSOPERATION_IS_INVOKING_MAIN__ + 20 (NSOperation.m:2184)
11  Foundation                      0x22e2c6ec -[NSOperation start] + 752 (NSOperation.m:2201)
12  Foundation                      0x22f21750 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 20 (NSOperation.m:2215)
13  Foundation                      0x22f21230 __NSOQSchedule_f + 180 (NSOperation.m:2226)
14  libdispatch.dylib               0x21e43c1c _dispatch_call_block_and_release + 24 (init.c:1408)
15  libdispatch.dylib               0x21e44fc0 _dispatch_client_callout + 16 (object.m:495)
16  libdispatch.dylib               0x21e47700 _dispatch_continuation_pop + 496 (inline_internal.h:2484)
17  libdispatch.dylib               0x21e46e18 _dispatch_async_redirect_invoke + 588 (queue.c:803)
18  libdispatch.dylib               0x21e53cfc _dispatch_root_queue_drain + 356 (inline_internal.h:2525)
19  libdispatch.dylib               0x21e54494 _dispatch_worker_thread2 + 116 (queue.c:6628)
20  libsystem_pthread.dylib         0x2207b6c8 _pthread_wqthread + 216 (pthread.c:2364)
21  libsystem_pthread.dylib         0x22081808 start_wqthread + 8

Thread 6:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 7:
0   libsystem_pthread.dylib         0x22081800 start_wqthread + 0

Thread 5 crashed with ARM Thread State (64-bit):
    x0: 0x0000000014ee1b10   x1: 0x0000000048c0cc97   x2: 0x0000000000005002   x3: 0x0000000000000000
    x4: 0x0000000014ee1af0   x5: 0x0000000000000002   x6: 0x0000000000000000   x7: 0x0000000000000000
    x8: 0x000000004fb0e000   x9: 0x0000000022533950  x10: 0x00000000153c2e00  x11: 0x000000000000003f
   x12: 0x00000000153c2eb8  x13: 0x00000000001c0369  x14: 0x0000000000000000  x15: 0x000000005cd5d1ff
   x16: 0x0000000050b251d8  x17: 0x000000002235c024  x18: 0x0000000000000000  x19: 0x0000000014ee1b10
   x20: 0x0000000004600790  x21: 0x0000000014ee1b10  x22: 0x0000000000005002  x23: 0x0000000014d8e900
   x24: 0x0000000000000001  x25: 0x0000000004a65000  x26: 0x000000000000c000  x27: 0x0000000004a65d60
   x28: 0x00000000c0004002   fp: 0x00000000192ee8b0   lr: 0x00000000223efda4
    sp: 0x00000000192ee840   pc: 0x00000000224c58b0 cpsr: 0x60000000
   esr: 0xf2000001  Address size fault

WatchConnectivityManager class:

class WatchConnectivityManager {

    static let shared = WatchConnectivityManager()

    let session = WCSession.default

    func sendWatchInfo() {

            if session.activationState == .activated {

                let name = getCurrentWatchInfo()

                let message: [String : Any] = ["appleWatchName" : name]

                if session.isReachable {
                    session.sendMessage(message,
                                        replyHandler: nil,
                                        errorHandler: nil)
                }

                do {
                    try session.updateApplicationContext(message)
                } catch(let error) {
                    fatalError(error.localizedDescription)
                }
            }
        }

        private func getCurrentWatchInfo() -> String {

            let name: String

            name = WKInterfaceDevice.current().name

            return name
    }
}

Body:
Even though the API says that WKInterfaceDevice.current().name is a String instead of String?, name is somehow actually a nil value in some cases.

It can't be nil. name is a property declared as:

var name: String { get }

It can be an empty string, but not nil (Swift context). And the Objective-C:

@property(nonatomic, readonly, copy) NSString *name;

It's encapsulated with the NS_ASSUME_NONNULL_BEGIN & NS_ASSUME_NONNULL_END which effectively means:

@property(nonatomic, readonly, copy) NSString * _Nonnull safeName;

Read Nullability and Objective-C to see how it affects Objective-C -> Swift.

Actually it can be nil in the Objective-C context, but it violates the _Nonnull contract then.

As a possible solution, I'm thinking that instead of name: String I should use name: String?.

I don't think it's going to help even if you can do this. Imagine you have the following method1:

- (NSString * _Nonnull)canNotBeNilNothing {
    return nil;
}

Used in Swift:

let name: String? = WKInterfaceDevice.current().canNotBeNilNothing();
print("\(String(describing: name))")

You still get the Optional(""), not nil. And it's expected, because there's this _Nonnull (it violates the contract, but it's another story).

You can create something like this if you are really sure it can return nil in Objective-C:

- (NSString * _Nullable)maybeName {
    return [self name];
}

And then you can use String? in Swift and it can become nil if [self name] will return nil.

Possible causes of your problem

Bug somewhere in the WatchKit (Incorrect nullability annotation, ...)

Something else

I'm not sure what's happening, because I didn't see the stacktrace.

Possible solution

WatchKit & Objective-C problem (throws an exception)? It might be fixable with the following wrapper in Objective-C:

- (NSString * _Nullable)maybeName {
    @try {
        return [self name];
    }
    @catch (NSException *exception) {
        // Return nil or handle it your way
        return nil;
    }
}

Bridging issue (incorrect nullability)? It might be fixable with the following code in Swift:

extension WKInterfaceDevice {
    var maybeName: String? {
        self.perform(#selector(getter: WKInterfaceDevice.name))?.takeRetainedValue() as! String?
    }
}

1 In general, you should look at nullable and nonnull roughly the way you currently use assertions or exceptions: violating the contract is a programmer error. In particular, return values are something you control, so you should never return nil for a non-nullable return type unless it is for backwards-compatibility. (Nullability and Objective-C)