How to Declare That a Computed Property 'Throws' in Swift

How do I declare that a computed property 'throws' in Swift?

This functionality is added for read-only computed properties in Swift 5.5 as part of SE-0310 (included in Xcode 13).

Based on SE-0310, the syntax would be:

class SomeClass {
var someProperty: Int {
get throws {
throw Err("SNAFU")
}
}
}

Here is the previous answer for versions of Swift prior to 5.5:

You cannot throw from a computed property. You must use a function if you want to throw. The Declarations section of the Language Reference part at the end of The Swift Programming Language only lists throws (and rethrows) as a keyword for function and initializer declarations.

How do I report error when setting a swift property?

Options:

  1. Call fatalError which will crash the app
  2. Provide a default value if validation fails
  3. Don't change numberOfLegs if validation fails and log out an error message
  4. Make numberOfShoes read only and instead provide a function to set the number of shoes that returns an optional error:

    func setNumberOfShoes(number: Int) -> NSError? {
    // ...
    }

Option 4 is the closest to an exception in that it allows the calling code to decide how it want to handle the invalid input. Of course, it does not however, force the caller to handle the error.

Swift Reference Cycle When Capturing A Computed String Property Declared From Inside An Instance Method

storeItem.updateInventory now keeps strong reference to itemText.

I think the issue is that itemText holds a strong reference to self implicitly in order to access storeDelegate, instead of keeping a reference to storeDelegate. Anothe option is that even though self is keeping the delegate as unowned, once you pass ot to itemText for keeping, it is managed (ie, strong reference again).

Either way, you can guarantee not keeping strong reference changing itemText to a function and pass the delegate directly:

func setupItems() {
func itemText(with delegate: StoreDelegate) -> String
return "item info goes here \(storeDelegate.player.health)"
}
let storeItem...
storeItem.updateInventory = {
// ...
storeItem.label.text = itemText(with self.storeDelegate)
}
}

How does throw declare throughs 'startAccessingSecurityScopedResource()' in Swift?

Error is not handled because the enclosing function is not declared 'throws'

this refers to your presentDocument function. Declare it like so:

func presentDocument(at documentURL: URL) throws {
...
}

Computed read-only property vs function in Swift

It seems to me that it's mostly a matter of style: I strongly prefer using properties for just that: properties; meaning simple values that you can get and/or set. I use functions (or methods) when actual work is being done. Maybe something has to be computed or read from disk or from a database: In this case I use a function, even when only a simple value is returned. That way I can easily see whether a call is cheap (properties) or possibly expensive (functions).

We will probably get more clarity when Apple publishes some Swift coding conventions.

How can I create a static computed property that computes only once?

Your solution should work. Maybe there is something wrong with some other part of your code. Take a look at the following example:

var myStrings = ["a", "b"]

class SomeClass {
static let strings: [String] = {
return myStrings
}()
}

print("myStrings: \(myStrings)")
print("static strings: \(SomeClass.strings)")

myStrings.append("c")

print("myStrings: \(myStrings)")
print("static strings: \(SomeClass.strings)")

Prints:

myStrings: ["a", "b"]
static strings: ["a", "b"]
myStrings: ["a", "b", "c"]
static strings: ["a", "b"]

So for you the following piece of code should work:

class ConferenceNumberDirectory {
static let att: [ConferenceNumber] = {
return buildDirectory(for: .att, from: jsonArray)
}()
}

Modify getter for Swift optional variable

First notice that myString cannot be nil as it is not an optional. If you want to allow storing nil declare it as an optional:

var myString: String?

checking for self == nil is redundant since if self is nil this property can never be accessed AND you cannot throw an exception from a computed property so throwing won't work either.

You can declare it as private and provide a getter method that can check if its nil or empty and throw accordingly
}

If you do not want myString to ever be nil then do not declare it as optional. If you do not want the string to be empty than avoid that when setting the string.

private(set) myString: String // You cannot set the string directly outside of the class but you can access it freely

func setMyString(withValue value: String)
{
if (value.isEmpty)
{
throw ... //
}

myString = value
}

regarding throwing errors check this link



Related Topics



Leave a reply



Submit