You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中通过TextField计算年龄的代码报错问题求助

Hey there! Let's fix this age calculation code step by step—your error comes from a few syntax mistakes, incorrect API usage, and unsafe force unwraps that we can clean up easily.

First, let's break down the root cause of your error

The Cannot assign to immutable expression of type "NSCalenda..." error is directly from this broken line:

let cal = NSCalendar? = NSCalendar(calendarIdentifier: .gregorian)

This is invalid syntax—you're trying to assign an optional type to a let constant in a messed-up way. Plus, in Swift 4+, we should use the native Calendar type instead of NSCalendar whenever possible.

Here's the fixed, robust version of your code

I've also added safety checks to avoid crashes from bad input or invalid dates:

@IBAction func profilSettings(_ sender: AnyObject) {
    // 1. Safely get the birth date string from the TextField
    guard let dobString = self.dob.text, !dobString.isEmpty else {
        self.myage.text = "Please enter a valid date"
        return
    }
    
    // 2. Set up a DateFormatter to parse the input string (adjust dateFormat to match your TextField's expected format)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy" // Use "yyyy-MM-dd" if input is like "2000-01-01"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // Prevents locale-based parsing issues
    
    // 3. Convert the string to a Date object
    guard let dobDate = dateFormatter.date(from: dobString) else {
        self.myage.text = "Invalid date format"
        return
    }
    
    // 4. Calculate the age using Calendar's built-in date difference method
    let calendar = Calendar(identifier: .gregorian)
    let now = Date()
    let ageComponents = calendar.dateComponents([.year], from: dobDate, to: now)
    
    // 5. Safely display the age
    if let age = ageComponents.year, age >= 0 {
        self.myage.text = String(age)
    } else {
        self.myage.text = "Invalid birth date"
    }
}

Key improvements I made:

  • Removed broken NSCalendar declaration: Replaced it with the correct Swift Calendar initialization.
  • Replaced manual string splitting: Using DateFormatter is way more reliable than splitting strings—it handles invalid formats gracefully instead of crashing.
  • Eliminated force unwraps: Used guard let to safely handle optional values, preventing crashes if the TextField is empty or the date is invalid.
  • Used correct API for age calculation: calendar.dateComponents([.year], from:to:) is the proper way to calculate year differences between two dates in Swift 4+.

内容的提问来源于stack exchange,提问作者benji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:51:01