等同于Python的Swift URL字符串模板

等同于Python的Swift URL字符串模板,python,ios,swift,string,format,Python,Ios,Swift,String,Format,我正在向web api发出url请求。我想创建一个模板URL,然后使用字符串格式传递参数。在Python中,这非常简单。下面是一个例子: 我一直在尝试在swift中进行等效操作,但由于他们在格式说明符中使用了百分号,所以这很困难。我试图进行研究,但发现了一些令人困惑的概念,比如百分比编码。我可以在Swift中实现这一点吗?您可以在Swift中轻松实现这一点,而无需任何特殊的字符串“魔法”,方法是创建一个函数,该函数接受字符串和Int,然后返回字符串 // Create the template

我正在向web api发出url请求。我想创建一个模板URL,然后使用字符串格式传递参数。在Python中,这非常简单。下面是一个例子:


我一直在尝试在swift中进行等效操作,但由于他们在格式说明符中使用了百分号,所以这很困难。我试图进行研究,但发现了一些令人困惑的概念,比如百分比编码。我可以在Swift中实现这一点吗?

您可以在Swift中轻松实现这一点,而无需任何特殊的字符串“魔法”,方法是创建一个函数,该函数接受
字符串和
Int
,然后返回
字符串

// Create the template function
let urlTemplate: (String, Int) -> String = { (string, number) in
    return "http://www.omdbapi.com/?s=\(string)&page=\(number)"
}

// Then call it with whatever parameter (they will have to be a String and and Int though
urlTemplate("One", 1) // => "http://www.omdbapi.com/?s=One&page=1"
urlTemplate("Banana", 82) // => "http://www.omdbapi.com/?s=Banana&page=82"
您还可以使用速记闭包语法

let urlTemplate: (String, Int) -> String = { return "http://www.omdbapi.com/?s=\($0)&page=\($1)" }

您可以在Swift中轻松实现这一点,而无需任何特殊字符串“魔法”,方法是创建一个函数,该函数接受
字符串
Int
,然后返回
字符串

// Create the template function
let urlTemplate: (String, Int) -> String = { (string, number) in
    return "http://www.omdbapi.com/?s=\(string)&page=\(number)"
}

// Then call it with whatever parameter (they will have to be a String and and Int though
urlTemplate("One", 1) // => "http://www.omdbapi.com/?s=One&page=1"
urlTemplate("Banana", 82) // => "http://www.omdbapi.com/?s=Banana&page=82"
您还可以使用速记闭包语法

let urlTemplate: (String, Int) -> String = { return "http://www.omdbapi.com/?s=\($0)&page=\($1)" }

你试过了吗?这看起来像是
“http://www.omdbapi.com/?s=\(variable1)&page=\(variable2)“
。我这样做了,但在使用字符串之前需要额外设置变量。您尝试过吗?这看起来像是
“http://www.omdbapi.com/?s=\(variable1)&page=\(variable2)“
。我这样做了,但在使用stringOR
let urlTemplate:(String,Int)->String={return”之前需要额外的步骤来设置变量http://www.omdbapi.com/?s=\($0)&page=\($1)“}
,如果您想使用速记参数。;)啊,我从没想过要用闭包。非常感谢你!或者
let urlTemplate:(String,Int)->String={return”http://www.omdbapi.com/?s=\($0)&page=\($1)“}
,如果您想使用速记参数。;)啊,我从没想过要用闭包。非常感谢你!