如何在Swift 3中使用带有FloatingPoint值的sin(

编程入门 行业动态 更新时间:2024-10-26 08:29:52
本文介绍了如何在Swift 3中使用带有FloatingPoint值的sin(_:)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

import Foundation public func sine< T:FloatingPoint> (_ x:T) - > T { return sin(x)} //错误:无法用类型为'(T)'的参数列表调用'sin'

有没有办法解决这个问题? 非常感谢

解决方案

您可以创建一个接受FloatingPoint类型的sin方法,如下所示:

pre $ import UIKit func sin< T:FloatingPoint>(_ x:T) - > T { switch x { case let x as double: return sin(x)as? T? 0 的情况下让x作为CGFloat:返回sin(x)as? T? 0 case让x为浮点数:返回sin(x)as? T? 0 default: return 0 as T } }

另一个选择是向FloatingPoint类型添加一个方法或一个计算的属性扩展如下:

扩展FloatingPoint { var sin:self { switch self { case let x as Double: return UIKit.sin(x)as?自我? 0 case让x为CGFloat:返回UIKit.sin(x)as?自我? 0 大小写为x浮点数:返回UIKit.sin(x)as?自我? 0 default: return 0 as Self } } }

import Foundation public func sine <T: FloatingPoint > (_ x: T ) -> T{ return sin(x) } // Error: Cannot invoke 'sin' with an argument list of type '(T)'

Is there a way around this? Many thanks.

解决方案

You can make a sin method that accepts FloatingPoint type also as follow:

import UIKit func sin<T: FloatingPoint>(_ x: T) -> T { switch x { case let x as Double: return sin(x) as? T ?? 0 case let x as CGFloat: return sin(x) as? T ?? 0 case let x as Float: return sin(x) as? T ?? 0 default: return 0 as T } }

Another option is adding a method or a computed property extension to FloatingPoint type as follow:

extension FloatingPoint { var sin: Self { switch self { case let x as Double: return UIKit.sin(x) as? Self ?? 0 case let x as CGFloat: return UIKit.sin(x) as? Self ?? 0 case let x as Float: return UIKit.sin(x) as? Self ?? 0 default: return 0 as Self } } }

更多推荐

如何在Swift 3中使用带有FloatingPoint值的sin(

本文发布于:2023-11-26 21:57:35,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swift   sin   FloatingPoint

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!