如何在 Swift 中将 Int 转换为字符

How to convert an Int to a Character in Swift(如何在 Swift 中将 Int 转换为字符)
本文介绍了如何在 Swift 中将 Int 转换为字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里挣扎和失败了十多分钟,我屈服了.我需要在 Swift 中将 Int 转换为 Character,但无法解决.

I've struggled and failed for over ten minutes here and I give in. I need to convert an Int to a Character in Swift and cannot solve it.

问题

你如何将一个 Int (integer) 转换 (cast) 为一个 Character (char) 在 Swift 中?

How do you convert (cast) an Int (integer) to a Character (char) in Swift?

说明性问题/任务挑战

生成一个 for 循环,打印字母 'A' 到 'Z',例如像这样:

Generate a for loop which prints the letters 'A' through 'Z', e.g. something like this:

    for(var i:Int=0;i<26;i++) {      //Important to note - I know 
        print(Character('A' + i));   //this is horrendous syntax...
    }                                //just trying to illustrate! :)

推荐答案

不能将整数直接转换为 Character 实例,但可以从整数转换为 UnicodeScalarCharacter 并再次返回:

You can't convert an integer directly to a Character instance, but you can go from integer to UnicodeScalar to Character and back again:

let startingValue = Int(("A" as UnicodeScalar).value) // 65
for i in 0 ..< 26 {
    print(Character(UnicodeScalar(i + startingValue)))
}

这篇关于如何在 Swift 中将 Int 转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)