在swift中连接两个int

时间:2016-11-01 17:19:34

标签: swift

我尝试连接两个整数值(当前小时和当前时间分钟)。 例如:

int1: 18
int2: 2

然后我希望它们是一个int:182。 我使用以下代码获取当前小时和当前时间:

// get the current date and time
    let currentDateTime = Date()

    // get the user's calendar
    let userCalendar = Calendar.current

    // choose which date and time components are needed
    let requestedComponents: Set<Calendar.Component> = [
        .year,
        .month,
        .day,
        .hour,
        .minute,
        .second
    ]

    // get the components
    let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)

    // now the components are available
    let dtHour = dateTimeComponents.hour   
    let dtMinute = dateTimeComponents.minute 

然后我认为当我将它们转换为字符串而不是返回int时,我可以将这两个整数连接起来,这样我就有了大的int值。我用以下几行完成了这个:

let strHour = String(describing: dtHour)
    let strMinute = String(describing: dtMinute)

    var currenttime : String = strHour
    currenttime += strMinute

    //reconvert to int
    let ct: Int? = Int(currenttime)

    print("currentTime as Int   : ", ct)
    print("currenttime as String: ", currenttime)

第一张照片的输出是:

  

currentTime as Int:nil

第二次印刷的输出是:

  

currenttime as String:可选(18)可选(2)

是的我知道如果当前分钟低于10我必须解决问题,我必须先插入零但是我不知道为什么我不能将字符串转换回int,这样它就是一个大字符串。

那么有没有一种正确的方法来连接两个整数然后将它们重新转换回一个大的int值?

1 个答案:

答案 0 :(得分:0)

以下代码打印:

currentTime as Int:2249

currenttime as String:2249

    // get the current date and time
    let currentDateTime = Date()

    // get the user's calendar
    let userCalendar = Calendar.current

    // choose which date and time components are needed
    let requestedComponents: Set<Calendar.Component> = [
        .year,
        .month,
        .day,
        .hour,
        .minute,
        .second
    ]

    // get the components
    let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)

    // now the components are available
    let dtHour = dateTimeComponents.hour   
    let dtMinute = dateTimeComponents.minute

    let strHour = String(dtHour!.description)
    let strMinute = String(dtMinute!.description)

    var currenttime : String = strHour!
    currenttime += strMinute!

    //reconvert to int
    let ct = Int(currenttime)

    print("currentTime as Int   : ", ct!)
    print("currenttime as String: ", currenttime)