【问题标题】:Cannot convert value of type 'Int' to expected argument type 'UInt'无法将“Int”类型的值转换为预期的参数类型“UInt”
【发布时间】:2016-11-02 18:34:00
【问题描述】:

我正在尝试将 insertspaceInExpiryDateTextField() 函数调用到 textField() 函数中并得到上述错误。

// 使到期日期文本字段在 2 位后带“/”。

func insertspaceInExpiryDateTextField(string: String,inout andPreserveCursorPosition cursorPosition: UInt) -> String {

    var stringWithAddedSpaces: String = ""
    for index in 0.stride(to: string.characters.count, by: 1) {
        if index != 0 && index % 2 == 0 {
            stringWithAddedSpaces += " "

            if index < Int(cursorPosition) {
                cursorPosition += 1
            }
        }
        let characterToAdd: Character = Array(string.characters) [index]
        stringWithAddedSpaces.append(characterToAdd)
    }
    return stringWithAddedSpaces
}

// 将上面的函数调用到这个函数中 // 使到期日期字段只占用 4 位数字......同时在 2 位数字后加上“/”来划分月份和年份。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {



if textField == self.txt_expDate {

            self.insertspaceInExpiryDateTextField(textField.text!, andPreserveCursorPosition: (&UInt(range.length)))     // Here I get the error

            txt_expDate.text! = txt_expDate.text!.stringByReplacingOccurrencesOfString(" ", withString: "/", options: NSStringCompareOptions.LiteralSearch, range: nil)

            return ((txt_expDate.text?.characters.count)! >= 4 && range.length == 0) ? false : true
        }
}

// 除了 UInt 错误之外,其他一切正常。

// 我也检查了Error 'cannot convert value of type 'int' to expected argument type 'UInt',但没有用..

我有什么特别的地方出错了吗?谢谢 谢谢

【问题讨论】:

  • self.insertspaceInExpiryDateTextField(textField.text!, andPreserveCursorPosition: (&UInt(range.length))) // 这里我得到错误

标签: swift xcode textfield


【解决方案1】:

NSRange 的长度属性在 Swift 中被桥接为 Int 而不是 UInt(我不知道为什么;its NSUInteger in Objective C)。您可以在 Playground 中进行如下检查:

print(type(of: NSRange(location: 0, length: 0).length))

【讨论】:

  • 回答您对为什么它是Int 而不是UInt 的困惑:Swift 约定是使用Int,除非有充分的理由反对它,即使对于从未预期为负数的数据也是如此。这样,各种类型的整数之间的转换就会减少
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 2017-01-09
  • 2017-02-08
相关资源
最近更新 更多