Swift Error: cannot convert of type '()' to specified type 'Bool'
The benefit of the new error handling in Swift 2 is the omission of the quasi-redundant return values Bool
/ NSError
. Therefore setResourceValue
does not return a Bool
anymore which is the reason of the error message.
As the function is marked as throws
I recommend this syntax which just passes the result of setResourceValue
class func addSkipBackupAttributeToItemAtPath(filePathString: String) throws
{
let url = NSURL.fileURLWithPath(filePathString)
assert(NSFileManager.defaultManager().fileExistsAtPath(URL.path!))
try url.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey)
}
Handle the error in the method which calls addSkipBackupAttributeToItemAtPath
Cannot convert value of type '() - _' to specified type 'Bool'
Just remove the =
sign
var isSuccessful:Bool {
get {
for (index, element) in results.enumerated()
{
if element.values.contains(false) { return false }
}
return true
}
}
If you use the =
sign, you want to 'assign' a value to your variable.
This is a common mistake to lazy var initialization
lazy var isSuccessful:Bool = {
for (index, element) in results.enumerated()
{
if element.values.contains(false) { return false }
}
return true
}()
This syntax will process the block when you are getting the variable the first time.
Swift properyWrapper cannot convert value of declared type to value of specified type
You’ve declared wrappedValue
as an optional, e.g. Value?
. Change it to not be an optional and the error will go away:
@propertyWrapper struct UserDefaultsBacked<Value> {
let key: String
let storage: UserDefaults = .standard
var defaultValue: Value
var wrappedValue: Value { // not `Value?`
get {
let value = storage.value(forKey: key) as? Value
return value ?? defaultValue
}
set { storage.setValue(newValue, forKey: key) }
}
}
Alternatively, you could keep wrappedValue
as is, but then you’d have to declare snapStatus
as an optional:
var snapStatus: Bool?
I think the elimination of the optionals is the way to go, but I include this for the sake of completeness.
Swift error: Cannot convert value of type '() throws - ()' to specified type 'Bool'
Thanks to @MartinR for linking to a similar question where I found this trick:
Changing the Objective C function declaration to
- (BOOL)hasAnyData:(NSError *__autoreleasing *)errorOut __attribute__((swift_error(nonnull_error)));
And then calling it from Swift like
let hasAnyData: Bool = try self.repo.hasAnyThings()
Does exactly what I wanted!
The swift_error
attribute is documented here: https://github.com/apple/swift-clang/blob/383859a9c4b964af3d127b5cc8abd0a8f11dd164/include/clang/Basic/AttrDocs.td#L1800-L1819
Original answer - doesn't fully solve the problem but may be useful to someone else looking at this question as it is useful in a similar situation.
I finally found this in the Swift docs:
Use the
NS_SWIFT_NOTHROW
macro on an Objective-C method declaration
that produces an NSError to prevent it from being imported by Swift as
a method that throws.
I have now added a NS_SWIFT_NOTHROW
annotation to my Objective C function declaration like
- (BOOL)hasAnyData:(NSError *__autoreleasing *)errorOut NS_SWIFT_NOTHROW;
And am having to pass in the NSError pointer
from Swift
var error: NSError?
let hasAnyData = self.repo.hasAnyData(&error)
This isn't the nicest because I can no longer handle the error in a swifty way (using do, try catch
and instead have to use the NSError
) but it's the best I could find.
Swift Cannot convert value of type '() Error
You are missing a ()
at the end
private lazy var boardManager: BLTNItemManager = {
//other code you have
}()
Cannot convert value of type 'Query' to expected condition type 'Bool'
With the help of my friend, Ive been able to figure this out.
*PostViewModel.swift
@State private var isLiked: Bool = false
@State private var isDisabled: Bool = true
func checkForLikes(id: String, then completion: @escaping (Bool?) -> ()) {
let collection = ref.collection("Posts")
let doc = collection.document(id)
doc.getDocument { docSnapshot, err in
if let err = err {
print(err)
completion(nil)
return
}
guard let docSnapshot = docSnapshot,
let likedBy = docSnapshot.data()?["likedBy"] as? [String] else {
print("No query snapshot")
completion(nil)
return
}
completion(likedBy.contains(self.uid))
}
}
PostView.swift
HStack {
Button {
if isLiked == false {
postData.addLike(id: post.id)
isLiked = true
} else {
postData.unLike(id: post.id)
isLiked = false
}
} label: {
Image(systemName: isLiked ? "heart.fill" : "heart")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 20, height: 20)
.foregroundColor(isLiked ? .red : .gray)
}
.disabled(isDisabled)
.opacity(isDisabled ? 0.3 : 1)
.onAppear {
postData.checkForLikes(id: post.id) { isLiked in
if let isLiked = isLiked {
withAnimation(.easeInOut(duration: 0.2)) {
isDisabled = false
self.isLiked = isLiked
}
}
}
}
Cannot convert value of type '(Int) - Bool' to expected condition type 'Bool' and cannot find x in scope
You have syntax errors, see the fixes below.
import Foundation
func patterns (list: Array<Int>, fn: (Int) -> Bool) -> Array<Int> {
var res = Array<Int>()
for i in list {
if fn(i) { // Fix 1 is here
res.append(i)
}
}
return res
}
let lst1 = [1, 2, 3 , 5 , 6, 7, 8 ,9 , 10]
print(patterns(list: lst1, fn: { x in x % 2 == 0 })) // Fix 2 is here
You should read official docs on Closures in Swift to learn more about this.
Cannot convert value of type 'Published Bool .Publisher' to expected argument type 'Binding Bool '
Here is possible approach - the idea to make possible observation in generated view and avoid tight coupling between factory & presenter.
Tested with Xcode 12 / iOS 14 (for older systems some tuning might be needed)
protocol ResetViewModel {
var showPasswordReset: Bool { get set }
}
struct PasswordResetView<Model: ResetViewModel & ObservableObject>: View {
@ObservedObject var resetModel: Model
var body: some View {
if resetModel.showPasswordReset {
Text("Show password reset")
} else {
Text("Show something else")
}
}
}
class LoginViewModel: ObservableObject, Identifiable, ResetViewModel {
@Published var mailAdress: String = ""
@Published var password: String = ""
@Published var showRegister = false
@Published var showPasswordReset = false
private let applicationStore: ApplicationStore
init(applicationStore: ApplicationStore) {
self.applicationStore = applicationStore
}
var passwordResetView: some View {
PasswordResetView(resetModel: self)
}
}
Related Topics
Split Uint32 into [Uint8] in Swift
How to Cast a Uint64 to an Int64
Modal View Closes When Selecting an Image in Uiwebview iOS
Ui Testing Failure - Neither Element Nor Any Descendant Has Keyboard Focus on Textview
How to Implement iOS 11's Mkusertrackingbutton
Why Does Swift Not Allow Stored Properties in Extensions
Why Does Realitykit Memory Does Not Clear After Deinit Called
Waiting for Alamofire in Unit Tests
Swift Sort Dictionary by Value
Avcapturevideodataoutput Captureoutput Not Being Called
How to Draw a Cosine or Sine Curve in Swift
Firebase Completion Listeners in Swift
Swiftui - in Sheet Have a Fixed Continue Button That Is Not Scrollable