相关疑难解决方法(0)

swift对String有修饰方法吗?

swift对String有修饰方法吗?例如:

let result = " abc ".trim()
// result == "abc"
Run Code Online (Sandbox Code Playgroud)

string trim swift

380
推荐指数
10
解决办法
17万
查看次数

我可以强制 NSExpression 和 expressionValue 以某种方式采用双精度数而不是整数吗?

我正在尝试从字符串中进行数学计算。

当我使用 NSExpression 将字符串转换为数学问题,然后使用 expressionValue 获取结果时,Swift 假设我想要一个整数。考虑这两个 Playground 示例:

let currentCalculation = "10 / 6"
let currentExpression = NSExpression(format: currentCalculation)
print(currentExpression) // 10 / 6
if let result = currentExpression.expressionValue(with: nil, context: nil) as? Double {
    print(result) // 1
}

let anotherCalculation = "10.0 / 6.0"
let anotherExpression = NSExpression(format: anotherCalculation)
print(anotherExpression) // 10 / 6
if let result = anotherExpression.expressionValue(with: nil, context: nil) as? Double {
    print(result) // 1.666666667
}
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能始终获得双倍结果?我不想提前解析字符串。

非常有趣的是,第二个示例将“anotherExpression”转换为整数,但仍然返回 Double 作为结果。

math nsexpression swift

4
推荐指数
1
解决办法
3260
查看次数

标签 统计

swift ×2

math ×1

nsexpression ×1

string ×1

trim ×1