FloatingPoint扩展-与其他FloatingPoint类型的初始化

时间:2018-09-07 19:59:14

标签: swift generics type-conversion

我需要为任何FloatingPoint值编写一个初始化器,该值可以采用其他类型的FloatingPoint,并将其转换为Selfswift中有可能吗?我尝试过这样的事情:

init<FloatingPointType: FloatingPoint>(_ value: FloatingPointType) {
    guard let sameValue = value as? Self else {
        // Pass throu double to get best precision
        self.init(Double(value))
        return
    }
    self = sameValue // The same type
}

但这只会造成无限循环。问题在于创建新的self,没有初始化器接受其他FloatingPoint。我认为这可能是不可能的,但也许有一些方法可以实现。

1 个答案:

答案 0 :(得分:1)

标准库中已经存在此类初始化程序:

public DataTable GetMyList()
{
    string Count;
    string cmdStr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
    string cmdStr = @"SELECT column1,
                             column2,
                             column3
                       FROM Table_Name
                      ORDER BY mydate DESC;";

    using (SqlConnection conn = new SqlConnection(connStr))
    using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
    {
        try
        {
            dataGridView1.Rows.Clear();

            conn.Open();
            cmd.CommandText = cmdStr;
            cmd.CommandType = CommandType.Text;

            DataTable dt = new DataTable();

            SqlDataReader reader = cmd.ExecuteReader();

            dt.Load(reader);

            dataGridView1.DataSource = dt;

            // Add a button column. 
            DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
            buttonColumn.HeaderText = "Edit";
            buttonColumn.Name = "Status Request Name";
            buttonColumn.Text = "Edit";
            buttonColumn.UseColumnTextForButtonValue = true;

            DGV_UserList.Columns.Add(buttonColumn);
            return dt;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
           return null;
        }
    }
}

您可以正确找到here

let a: Double = Double(3.625)

//From Double to Float and Float80
let b: Float = Float(a)
let c: Float80 = Float80(a)

//From Float to Double and Float80
let d: Double = Double(b)
let e: Float80 = Float80(b)

//From Float80 to Double and Float
let f: Double = Double(c)
let g: Float = Float(c)