类型转换
本页展示了在原始类型之间进行转换以及从复合类型中获取这些类型的示例。
Int
↔ String
如何将 String
转换为 Int
// Defining a new extension function for type String that returns value of type Int// Caution: produces unexpected results when String contains non-numeric characters!extends fun toInt(self: String): Int { // Cast the String as a Slice for parsing let string: Slice = self.asSlice();
// A variable to store the accumulated number let acc: Int = 0;
// Loop until the String is empty while (!string.empty()) { let char: Int = string.loadUint(8); // load 8 bits (1 byte) from the Slice acc = (acc * 10) + (char - 48); // using ASCII table to get numeric value // Note, that this approach would produce unexpected results // when the starting String contains non-numeric characters! }
// Produce the resulting number return acc;}
fun runMe() { let string: String = "26052021"; dump(string.toInt());}
如何将 Int
转换为 String
字符
let number: Int = 261119911;
// Converting the [number] to a Stringlet numberString: String = number.toString();
// Converting the [number] to a float String,// where passed argument 3 is the exponent of 10^(-3) of resulting float String,// and it can be any integer between 0 and 76 including both endslet floatString: String = number.toFloatString(3);
// Converting the [number] as coins to a human-readable Stringlet coinsString: String = number.toCoinsString();
dump(numberString); // "261119911"dump(floatString); // "261119.911"dump(coinsString); // "0.261119911"
Struct
或 Message
↔ Cell
或 Slice
如何将任意的 Struct
或 Message
转换成一个 Cell
或 Slice
struct Profit { big: String?; dict: map<Int, Int as uint64>; energy: Int;}
message(0x45) Nice { maybeStr: String?;}
fun convert() { let st = Profit{ big: null, dict: null, energy: 42, }; let msg = Nice{ maybeStr: "Message of the day!" };
st.toCell(); msg.toCell();
st.toCell().asSlice(); msg.toCell().asSlice();}
如何将 Cell
或 Slice
转换为任意的 Struct
或 Message
struct Profit { big: String?; dict: map<Int, Int as uint64>; energy: Int;}
message(0x45) Nice { maybeStr: String?;}
fun convert() { let stCell = Profit{ big: null, dict: null, energy: 42, }.toCell(); let msgCell = Nice{ maybeStr: "Message of the day!" }.toCell();
Profit.fromCell(stCell); Nice.fromCell(msgCell);
Profit.fromSlice(stCell.asSlice()); Nice.fromSlice(msgCell.asSlice());}