What's the rationale of Swift's size methods taking `Int`s?
307 просмотра
2 ответа
I've noticed a lot of swift built ins take or return Int
s and not UInt
s:
Here are some examples from Array
:
mutating func reserveCapacity(minimumCapacity: Int)
var capacity: Int { get }
init(count: Int, repeatedValue: T)
mutating func removeAtIndex(index: Int) -> T
Given that the language is completely new, and assuming that this design choice was not arbitrary - I'm wondering: Why do swift built ins take Int
s and not UInt
s?
Some notes: Asking because I'm working on a few collections myself and I'm wondering what types I should use for things like reserveCapacity
etc. What I'd naturally expect is for reserveCapacity
to take a UInt
instead.
Ответы (2)
9 плюса
UInt
is a common cause of bugs. It is very easy to accidentally generate a -1 and wind up with infinite loops or similar problems. (Many C and C++ programmers have learned the hard way that you really should just use int
unless there's a need for unsigned
.) Because of how Swift manages type conversion, this is even more important. If you've ever worked with NSUInteger
with "signed-to-unsigned" warnings turned on (which are an error in Swift, not an optional warning like in C), you know what a pain that is.
The Swift Programming Guide explains their specific rationale in the section on UInt
:
Автор: Rob Napier Размещён: 22.09.2014 11:57NOTE
Use UInt only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this is not the case, Int is preferred, even when the values to be stored are known to be non-negative. A consistent use of Int for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference, as described in Type Safety and Type Inference.
1 плюс
Here is a possible explanation (I am no expert on this subject): Suppose you have this code
let x = 3
test(x)
func test(t: Int) {
}
This will compile without a problem, since the type of 'x' is inferred to be Int.
However, if you change the function to
func test(t: UInt) {
}
The compiler will give you a build error ('Int' is not convertible to 'UInt'
)
So my guess is that it is just for convenience, because Swift's type safety would otherwise require you to convert them manually each time.
Автор: Atomix Размещён: 22.09.2014 11:47Вопросы из категории :
- swift Как я могу программным образом определить, работает ли мое приложение в симуляторе iphone?
- swift iOS: Convert UTC NSDate to local Timezone
- swift Как установить цель и действие для UIBarButtonItem во время выполнения
- swift Жирный и не жирный текст в одном UILabel?
- swift Найти касательную точки на кубической кривой безье
- swift Как я могу рассчитать разницу между двумя датами?
- swift How to get text / String from nth line of UILabel?
- swift Можно ли программно прокрутить до нужной строки в UIPickerView?
- swift Отключение клавиатуры в UIScrollView
- swift Как контролировать межстрочный интервал в UILabel
- swift Формат UILabel с маркерами?
- swift Как я могу создавать локальные уведомления в iOS?
- swift UILabel с текстом двух разных цветов
- swift Многострочная метка iOS в Интерфейсном конструкторе
- swift Неизвестный пароль UITextField
- swift Delete all keys from a NSUserDefaults dictionary iOS
- swift Скопируйте CGContext в другой CGContext
- swift Как ждать в Objective-C и Swift
- swift Событие изменения текста UITextField
- swift Получить системный том iOS