Working with NSNumber & Integer values in Swift 3

前端 未结 5 1556
星月不相逢
星月不相逢 2021-01-03 17:54

I am trying to convert my project to Swift 3.0 however I am having two error messages when working with NSNumber and Integers.

相关标签:
5条回答
  • 2021-01-03 18:08

    Swift 4:

    var currentIndex:Int = 0
    for item in self.selectedFolder.arrayOfTasks {
       item.index = NSNumber(value: currentIndex) // <--
       currentIndex += 1
    }
    
    0 讨论(0)
  • 2021-01-03 18:17

    In Swift 4 (and it might be the same in Swift 3) NSNumber(integer: Int) was replaced with NSNumber(value: ) where value can be any almost any type of number:

    public init(value: Int8)
    
    public init(value: UInt8)
    
    public init(value: Int16)
    
    public init(value: UInt16)
    
    public init(value: Int32)
    
    public init(value: UInt32)
    
    
    public init(value: Int64)
    
    public init(value: UInt64)
    
    public init(value: Float)
    
    public init(value: Double)
    
    public init(value: Bool)
    
    @available(iOS 2.0, *)
    public init(value: Int)
    
    @available(iOS 2.0, *)
    public init(value: UInt)
    
    0 讨论(0)
  • 2021-01-03 18:19

    Swift 4.2

    item.index = Int(truncating: currentIndex)
    
    0 讨论(0)
  • 2021-01-03 18:21

    Before Swift 3, many types were automatically "bridged" to an instance of some NSObject subclass where necessary, such as String to NSString, or Int, Float, ... to NSNumber.

    As of Swift 3 you have to make that conversion explicit:

    var currentIndex = 0
    for item in self.selectedFolder.arrayOfTasks {
       item.index = currentIndex as NSNumber // <--
       currentIndex += 1
    }
    

    Alternatively, use the option "Use scalar properties for primitive data types" when creating the NSManagedObject subclass, then the property has some integer type instead of NSNumber, so that you can get and set it without conversion.

    0 讨论(0)
  • 2021-01-03 18:27

    You should stay with or original code and just change the assignment, so that it works:

    var currentIndex = 0
    for item in self.selectedFolder.arrayOfTasks {
        item.index = NSNumber(integer: currentIndex)
        currentIndex += 1
    }
    

    As your code works fine in Swift 2, I'd expect that this is behaviour that might change in the next update.

    0 讨论(0)
提交回复
热议问题