??
Original articles, welcome reprint. Reprint Please specify: Dongsheng's Blog
In other languages such as C, Objective-c, and Java, there are two ways to convert integers:
From the small range number to the large range number conversion is automatic;
Forcing type conversions from a large number to a small range can result in the loss of data precision.
In Swift, these two methods do not work, and need to be explicitly converted through some functions, the code is as follows:
Let Historyscore:uint8 = 90
Let englishscore:uint16 = 130
Let Totalscore = Historyscore + englishscore//Error
The program will have a compilation error because Historyscore is a UInt8 type, and Englishscore is a UInt16 type and cannot be converted between them.
Two methods of conversion:
One is to convert the UInt8 historyscore to the UInt16 type. This conversion is safe because it is converted from a small range to a large range number.
Code:
Let Totalscore = UInt16 (historyscore) + Englishscore//is the correct conversion method.
The other is to convert the UInt16 englishscore to the UInt8 type. Because it is converted from a large range to a small range number, this conversion is unsafe, and if the number of conversions is larger it can result in loss of precision.
Code:
Let Totalscore = Historyscore + UInt8 (englishscore)//is the correct conversion method.
In this case, the value of Englishscore is 130, the conversion is successful, if the number is changed to 1300, although the program compiles no problem, but the exception information is output in the console.
Conversion between integral type and floating point type
Conversions between integral and floating-point types are similar to conversions between integral types:
Let historyscore:float = 90.6
Let englishscore:uint16 = 130
Let Totalscore = Historyscore + englishscore//Error
Let Totalscore = Historyscore + Float (englishscore)//correct, secure
Let Totalscore = UInt16 (historyscore) + englishscore//correct, decimals truncated
Welcome to follow Dongsheng Sina Weibo @tony_ Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
More Products iOS, Cocos, mobile design courses please pay attention to the official website of Chi Jie Classroom: http://www.zhijieketang.com
Luxgen Classroom Forum Website: http://51work6.com/forum.php
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift 2.0 Study Notes (Day 15)--note the conversion between numeric types