无法将类型“Range<Int32>”的值转换为预期的参数类型“Range<_>”
Posted
技术标签:
【中文标题】无法将类型“Range<Int32>”的值转换为预期的参数类型“Range<_>”【英文标题】:cannot convert value of type 'Range<Int32>' to expected argument type 'Range<_>' 【发布时间】:2021-02-05 18:05:18 【问题描述】:@IBAction func Guess(_ sender: UIButton)
var R1 = (Range1.text!as NSString).intValue
var R2 = (Range2.text! as NSString).intValue
//print(R1, " ", R2)
var answer = Int.random(in: R1..<R2)
我想从用户通过TextField给定的范围内生成随机数。
【问题讨论】:
您没有提供足够的信息。变量Range1
和Range2
是如何声明的?
【参考方案1】:
您的代码有很多问题(Leo 在他的回答中涵盖了其中一些问题,但为了完整性列出了所有问题。)
-
不要使用以大写字母开头的变量名
使用 Swift 类型而不是 Objective-C “NS”类型
NSString
intValue
属性返回一个Int32,你需要Int类型
试试这段代码,它使用原生 Swift 类型和正确的变量命名:
let text1 = "7"
let text2 = "13"
if let r1 = Int(text1),
let r2 = Int(text2),
r1 < r2
let answer = Int.random(in: r1..<r2)
print("random answer = \(answer)")
else
print("Could not convert '\(text1)' or '\(text2)' to an Int")
编辑:
将以上内容重写为函数,进行大约 500 磅的错误检查:
@discardableResult func randomValue(lowerString: String?, upperString: String?) -> Int?
guard let lowerNonNilString = lowerString,
let upperNonNilString = upperString else
print("One or more inputs is nil")
return nil
guard let lower = Int(lowerNonNilString) else
print("'\(lowerNonNilString)' cannot be converted to an Int")
return nil
guard let upper = Int(upperNonNilString) else
print("'\(upperNonNilString)' cannot be converted to an Int")
return nil
guard lower < upper else
print("\(lower) must be less than \(upper)")
return nil
let result = Int.random(in: lower..<upper)
print("random value between '\(lowerNonNilString)' and '\(upperNonNilString)' is \(result)")
return result
randomValue(lowerString: nil, upperString: "13")
randomValue(lowerString: "07", upperString: "13")
randomValue(lowerString: "13", upperString: "7")
randomValue(lowerString: "7", upperString: "7")
randomValue(lowerString: "7", upperString: "8")
randomValue(lowerString: "foo", upperString: "7")
randomValue(lowerString: "7", upperString: "bar")
输出:
One or more inputs is nil
random value between '07' and '13' is 10
13 must be less than 7
7 must be less than 7
random value between '7' and '8' is 7
'foo' cannot be converted to an Int
'bar' cannot be converted to an Int
【讨论】:
请注意,如果上限小于或等于下限,这可能会崩溃 是的。我修好了。以上是关于无法将类型“Range<Int32>”的值转换为预期的参数类型“Range<_>”的主要内容,如果未能解决你的问题,请参考以下文章
无法将类型为“System.Collections.Generic.List`1[EPMS.Domain.SingleItem]”的对象强制转换为类型“EPMS
C# 无法将类型为“System.Byte[]”的对象强制转换为类型“System.Data.DataTable
无法将类型“[PHAsset]”的值分配给类型“UIImageView!”