本文介绍了从Swift中的Ascii Int转换为Char / String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试将ascii字符的整数表示形式转换回字符串。

I'm trying to convert the integer representation of an ascii character back into a string.

string += (char) int;

在Java等其他语言(此处的示例)中,我可以将整数转换为char。 Swift显然不知道这些,我猜测使用所有强大的NSString以某种方式将能够做到这一点。

In other languages like Java (the example here) I can just cast the integer into a char. Swift obviously does not know these and I'm guessing using the all powerful NSString somehow will be able to do the trick.

推荐答案

它可能不像Java一样干净,但你可以这样做:

It may not be as clean as Java, but you can do it like this:

var string = ""
string.append(Character(UnicodeScalar(50)))

如果您愿意,您还可以修改语法以使其更相似:

You can also modify the syntax to look more similar if you like:

//extend Character so it can created from an int literal
extension Character: IntegerLiteralConvertible {
    public static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character {
        return Character(UnicodeScalar(value))
    }
}

//append a character to string with += operator
func += (inout left: String, right: Character) {
    left.append(right)
}

var string = ""
string += (50 as Character)

或者使用dasblinkenlight的方法:

Or using dasblinkenlight's method:

func += (inout left: String, right: Int) {
    left += "\(UnicodeScalar(right))"
}
var string = ""
string += 50

这篇关于从Swift中的Ascii Int转换为Char / String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:24