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:
- Call fatalError which will crash the app
- Provide a default value if validation fails
- Don't change numberOfLegs if validation fails and log out an error message
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
How to Detect When Url of Amp Page Changed with Wkwebview
@Objc Keyword Extension Subclass Behaviour
Add a Line as a Selection Indicator to a Uitabbaritem in Swift
Implicitly Import Specific Swift Module
Drag Rotate a Node Around a Fixed Point
Alamofire: Send JSON with Array of Dictionaries
Set the Size and Position of All Windows on the Screen in Swift
Get the Accurate Duration of a Video
Swiftui Call Function on Variable Change
How to Convert a String to a Cstring in the Swift Language
Cannot Invoke 'Join' with an Argument List of Type (String, [String]) in Swift 2.0
Using Non Ns_Enum Objective-C Enum in Swift
Vertically Aligning Text in an Nstextfield Using Swift
How to Find Actual Swiftui API Documentation (And Not Just the Developer Documentation)
How to Use List Type with Codable? (Realmswift)
Why Can't You Assign an Optional to a Variable of Type 'Any' Without a Warning
Reading Currently Playing Track in MACos Using Scriptingbridge Not Working
Swift/Uiview/Drawrect - How to Get Drawrect to Update When Required