Swift编译错误:类型'Post'无成员'adjustLikes'求助
Hey there, let's get this error sorted out for you! The Value of type 'Post' has no member 'adjustLikes' message means exactly what it says: your Post class or struct doesn't have a method named adjustLikes defined, so the compiler can't find it when you try to call it in your liked IBAction.
Here's how to fix this step by step:
1. Add the adjustLikes method to your Post type
Locate the file where you've defined your Post class/struct, and add the adjustLikes method that matches the logic you're trying to use. Based on your code, this method should toggle the like count up or down depending on the addlike parameter:
// Example Post class with the missing method added class Post { // Your existing Post properties (adjust these to match your actual code) var postKey: String? var likesCount: Int = 0 // Make sure this matches your like count property name // Add this method to handle like adjustments func adjustLikes(addlike: Bool) { if addlike { likesCount += 1 } else { // Use max() to prevent the count from going negative likesCount = max(likesCount - 1, 0) } } }
- Note: If your
Postuses a different name for the like count property (e.g.,likeCountinstead oflikesCount), update the method to reference the correct name.
2. Verify your post instance is properly typed
Double-check that self.post is indeed a non-optional instance of Post. If post is an optional (declared as Post?), you'll need to safely unwrap it before calling the method, like this:
// Safe unwrapping example guard let post = self.post else { return } if let _ = snapshot.value as? NSNull { post.adjustLikes(addlike: true) likeRef.setValue(true) } else { post.adjustLikes(addlike: false) likeRef.removeValue() }
Once you've added the method to your Post type and ensured your instance is correctly accessed, the compilation error should disappear. Your like toggle logic will then update the post's like count as intended when the user taps the like button.
内容的提问来源于stack exchange,提问作者Tarun Sharma

