gpt4 book ai didi

swift - 在swift中连接两个int

转载 作者:行者123 更新时间:2023-11-28 06:30:55 28 4
gpt4 key购买 nike

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

int1: 18
int2: 2

然后我希望它们是一个整数: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: Optional(18)Optional(2)

是的,我知道我必须解决分钟问题,如果当前分钟小于十,我必须首先插入一个零,但我不明白为什么我不能将字符串转换回 int 所以这是一个大字符串。

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

最佳答案

下面的代码打印:

作为 Int 的当前时间:2249

当前时间为字符串: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)

关于swift - 在swift中连接两个int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40365228/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com