1

I am getting an error that says "Cannot convert value of type 'String' to argument type 'Test'" when trying to return a value from a function in lazy stored property. I am not able to spot any issue in the lazy var's closure.

import UIKit

public struct Value {}

public class Test {

    var id: String = ""

    public func getValueById(id: String) -> Value {
        return Value()
    }

    public lazy var value: Value = {
        // Compiler error: Cannot convert value of 'String' to expected argument type 'Test'
        return getValueById(self.id)
    }() 
}

1 Answer 1

2

The compiler is confused about getValueById and the error message is meaningless - if not misleading.

What you need is to add self in front of getValueById(self.id) inside the closure:

public struct Value {}

public class Test {

    var id: String = ""

    public func getValueById(id: String) -> Value {
        return Value()
    }

    public lazy var value: Value = {
        return self.getValueById(self.id)
    }() 
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's correct.Here's the quote from the ARC chapter, section Resolving Strong Reference Cycles for Closures (The Swift Programming Language) - Swift requires you to write self.someProperty or self.someMethod() (rather than just someProperty or someMethod()) whenever you refer to a member of self within a closure. This helps you remember that it’s possible to capture self by accident.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.