簡體   English   中英

如何創建 function 以從 Swift 的年份返回世紀?

[英]How can I create a function to return the century from the year in Swift?

我在代碼斗爭中遇到了問題。 我收到一個錯誤:

聲明僅在文件 scope 中有效(擴展十進制)

有人可以指導我如何解決這個問題嗎? 順便說一句,我正在創建一個 function 來以年份作為輸入返回世紀。 如果您對我的代碼有任何建議,請告訴我。

func centuryFromYear(year: Int) -> Int {
    let centuryOtherStart = year / 100
    let centuryStart = Double(year / 100)
    let centuryEnd = round(centuryStart)
    var wholeNumber : Bool
    if wholeNumber == true {
        return Int(centuryStart)

    } else {
        return Int(centuryEnd + 1)
    }

    extension Decimal {
        var isWholeNumber: Bool {
            wholeNumber = self.isZero || (self.isNormal && self.exponent >= 0)
        }
    }
}

解決方法很簡單:

func centuryFromYear(year: Int) -> Int {    
    return (year + 99) / 100
}

除了不能在函數內聲明擴展這一事實之外,您還需要擴展FloatingPoint而不是Decimal 只需在您的項目中添加一個新的 Swift 文件並在那里添加擴展名:

extension FloatingPoint {
    var isWholeNumber: Bool {
        return isZero ? true : isNormal ? self == rounded() : false
    }
}

關於您提取年份世紀的方法有一些錯誤。 首先,在將年份轉換為 Double 后,您應該只除以 100。 其次,如果結果是整數,則需要返回四舍五入,否則返回它而不進行四舍五入和遞增一:

func centuryFrom(year: Int) -> Int {
    let centuryStart = Double(year)/100
    return centuryStart.isWholeNumber ? Int(round(centuryStart)) : Int(centuryStart) + 1
}

測試:

centuryFrom(year: 1801)   // XIX
centuryFrom(year: 1900)   // XIX
centuryFrom(year: 1901)   // XX
centuryFrom(year: 2000)   // XX
centuryFrom(year: 2001)   // XXI
centuryFrom(year: 2100)   // XXI
centuryFrom(year: 2101)   // XXII

我可能會遲到。 但也試試這個

    func centuryFromYear(year: Int) -> Int {
        if year % 100 == 0 {
//this will return exact century like 2000 means 20th Century
            return year / 100 
        }else {
//this will return exact century like 2001 means 20th Century

            return year / 100 + 1   
        }
    }

有幾種方法,

你可以這樣做

操作1

func century(_ year: Double) -> String {
    var century = Int((year / 100).rounded(.up))
    if century != 21 {
    return "\(century)th century"
    } else {
    return "21st century"
    }
}

Op2

func century(_ year: Int) -> String {
    switch year {
    case 901...1000: return "10th century"
    case 1001...1100: return "11th century"
    case 1101...1200: return "12th century"
    case 1201...1300: return "13th century"
    case 1301...1400: return "14th century"
    case 1401...1500: return "15th century"
    case 1501...1600: return "16th century"
    case 1601...1700: return "17th century"
    case 1701...1800: return "18th century"
    case 1801...1900: return "19th century"
    case 1901...2000: return "20th century"
    case 2001...2100: return "21st century"
    default: return ""
    }
}
func centuryFromYear(year: Int) -> Int {
    return 1 + Int((year - 1) / 100)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM