Swift 4中‘Any类型无text成员’错误及对应IBAction代码修正咨询
What's Causing the Error?
Let’s keep this simple: your sender parameter is typed as Any—Swift’s most generic type. Since Swift is strongly typed, it can’t assume this generic "any" value is a text input control (like a UITextField) that has a text property. That’s exactly why you’re seeing this error.
Step-by-Step Fixes
We’ll fix the immediate error and also patch a hidden URL formatting issue that would’ve broken your API call anyway:
Safely cast the sender to a specific text control
We need to tell Swift that the sender is actually aUITextField(the standard control for this kind of edit-ending action). We’ll use optional binding to avoid crashes if the sender ever isn’t a text field.Validate the input properly
Don’t just check iftextexists—make sure it’s not empty (or just whitespace) too. Sending a blank city name to the API will only result in an error response.Fix the API URL structure
Your base URL is missing an equals sign afterq—it should beq=instead of justq. Without this, your final URL will be malformed (e.g.,qLondoninstead ofq=London) and the API will reject your request.
Corrected Code
@IBAction func endEditingText(_ sender: Any) { let baseURL = "http://api.openweathermap.org/data/2.5/forecast?q=" let APIKeysString = "&appid=14b92e1046c4b6e4f4d5adda8259131b" // Safely cast sender to UITextField and validate non-empty input guard let textField = sender as? UITextField, let cityString = textField.text, !cityString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { print("Invalid input or sender isn't a text field") return } // Trim extra whitespace to avoid messy URL encoding issues let cleanedCityName = cityString.trimmingCharacters(in: .whitespacesAndNewlines) if let finalURL = URL(string: baseURL + cleanedCityName + APIKeysString) { requestWeatherDate(url: finalURL) } else { print("Failed to create a valid API URL") } }
Quick Extra Tips
- If you’re using a
UITextViewinstead ofUITextField, just swap outUITextFieldforUITextViewin the cast. - Trimming whitespace ensures you don’t send URLs with unnecessary spaces, which can cause unexpected encoding errors.
- Sticking with
guard letfor type casts and optional properties keeps your code safe from runtime crashes.
内容的提问来源于stack exchange,提问作者chetan dhargalkar

