Swift Error: Cannot Convert of Type '()' to Specified Type 'Bool'

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

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.

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 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' to expected argument type 'Bool'

I have some improvements to suggest:

  1. Numbered variables are almost always a bad idea. Why should people have to constantly glance up and down between the usages/definitions, to see which one is which one is which, when you can just label them directly? It's particularly aggregious here, when the number variables represent 4, 400, 100, unlike what I presume most people would expect, 4, 100, 400. I would recommend you use descriptive names:

    func isLeap(year: Int) {
    let remainderMod4 = year % 4
    let remainderMod100 = year % 100
    let remainderMod400 = year % 400

    var isLeapYear = false

    if remainderMod4 == 0 {
    isLeapYear = true
    } else if remainderMod400 == 0 && remainderMod4 == 0 {
    isLeapYear = true
    } else if remainderMod400 == 0 && remainderMod100 == 0 {
    isLeapYear = false
    } else {
    isLeapYear = false
    }

    if isLeapYear == true {
    print("YES")
    } else {
    print("NO")
    }
    }
  2. Don't set temporary values that will be immediately overwritten. Instead, declare the value without initializing it. There is a neat feature of the Swift compiler called "definite initialization", which guarentees that all variables are set at least once before use. Using it earlier than that would cause an error to alert you of the mistake. Because you're never mutating the value, isLeapYear can be promoted to a let constant.

    let isLeapYear: Bool
  3. Don't compare a boolean to true. Checking for true is already what if does. That just yields the same boolean. There are some exceptions (e.g. checking if a Bool? is true, not false or nil), but anyway:

    if isLeapYear { // ...

  4. Don't use x & y == 0. Use x.isMultiple(of: y) instead, it's much more clear.

    let remainderMod4 = year.isMultiple(of: 4)
    let remainderMod100 = year.isMultiple(of: 400)
    let remainderMod400 = year.isMultiple(of: 400)
  5. At that point, remainderMod4 reads pretty much the same as year.isMultiple(of: 4), so just inline it:

    if year.isMultiple(of: 4) == 0 {
    isLeapYear = true
    } else if year.isMultiple(of: 400) == 0 && year.isMultiple(of: 4) == 0 {
    isLeapYear = true
    } else if year.isMultiple(of: 400) == 0 && year.isMultiple(of: 100) == 0 {
    isLeapYear = false
    } else {
    isLeapYear = false
    }
  6. You can remove your complex if/else branch by using a simpler boolean expression:

    let isLeapYear = (year.isMultiple(of: 4) && !year.isMultiple(of: 100))
    || year.isMultiple(of: 400)
  7. You leap-year calculation should only do one thing: figure out if a given year is a leap year. It would be inappropriate for its job to also print out the result to a user. Do that in a separate function, or for a one-off like this, in the global "script area":

    func isLeap(year: Int) -> Bool {
    return (year.isMultiple(of: 4) && !year.isMultiple(of: 100))
    || year.isMultiple(of: 400)
    }

    let aYear = Int(readLine()!)!

    if isLeap(year: aYear) {
    print("YES")
    } else {
    print("NO")
    }

Swift Compiler Error: Cannot convert value of type '()' to specified type 'String'

Your function sing() is not returning a String object.

Hence you cannot use variable = void function() as it’s not a valid assignment operation.

You can specify String as a return type of sing(), and return the string you are printing in the function. That will solve your problem.

func sing(verb: String, noun: String) -> String {   
return "\(verb), \(verb), \(verb) your \(noun)"
}

let line = sing(verb: "Row", noun: "Boat")

Cannot convert value of type 'PublishedBool.Publisher' to expected argument type 'BindingBool'

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



Leave a reply



Submit