My app have to use int
to do some multiplication, it is easy to meet two fairly big numbers' multiplication.
Of course it will crash. And how can I remark some bool value. Just like every time before we'll quit the app, we saveData
in the AppDelegate.swift
's function:
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
If the result of an integer arithmetic operation (+, -, *, /, ...) overflows, the application terminates immediately. There is no way to catch this situation or to get notified eg to save data. There is no Swift error or NSException
thrown which you could catch. The same would happen for other runtime errors like accessing an array element outside of the valid bounds, or unwrapping an optional which is nil
.
This means that you have to check beforehand if the integer arithmetic operation can be executed. Alternatively – depending on your needs – you can
&+
, &-
and &*
instead, which truncate the result instead of triggering an error, similar as in (Objective-)C.addingReportingOverflow()
and similar methods which “return the sum of this value and the given value, along with a Boolean value indicating whether overflow occurred in the operation.”You should prefer NSInteger
over Int
.
Use NSInteger
when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible int type, which on 32
bit systems is just an int, while on a 64
-bit system it's a long
.
stick with using NSInteger
instead of int/long unless you specifically require them.
NSInteger/NSUInteger
are defined as *dynamic typedef *s
to one of these types, and they are defined like this:
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.