Swift compiler segmentation fault when building

后端 未结 30 2672
南旧
南旧 2020-11-29 03:59

Adding a (convenient) computed height property to UIView in my UIViewExtension.swift file is causing the Swift compiler to segfault...

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 04:56

    This typically happens when the compiler does not have enough information (despite what you think) to guarantee/determine the state of a statement or a variable within a statement.

    For example, imagine you have a dictionary of type [String: String] which you populate with city names as keys and a comma separated list of corresponding zip codes/post codes.

    Imagine that somewhere in your code you want to update the list of corresponding codes:

    myDict[town] += newZipCode + ","
    

    In this case, the compiler will respond with segmentation fault as town might not be in the dictionary and therefore it cannot guarantee that the above statement will have a valid value.

    To resolve this, you should store the current state of myDict[town] in a separate variable allowing you to handle the case of key not in dict and then update the value for the given key:

    myDict[town] = guaranteedValue + "," newZipCode + ","
    

    Unfortunately, it is not always straightforward to determine the root cause so I hope this simple example helps.

提交回复
热议问题