快速声明变量

时间:2020-10-17 11:09:42

标签: swift variables declare

我有这段代码,我的问题是,如何声明变量“连接”到全局变量?我需要在项目中共享连接以用于其他功能

var connection = ???

do {
var configuration = PostgresClientKit.ConnectionConfiguration()
configuration.host = "127.0.0.1"
configuration.database = "example"
configuration.user = "bob"
configuration.credential = .scramSHA256(password: "welcome1")

let connection = try PostgresClientKit.Connection(configuration: configuration)
let text = "SELECT start();"
try connection.prepareStatement(text: text).execute()
} catch {
print(error)
}

我尝试使用struct,但是声明conn仍然有问题-类型'[conn]'的值没有成员'prepareStatement'任何想法?

import UIKit
import PostgresClientKit

struct conn {
    let conn : Connection
}
var myconnection = [conn]()

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            var configuration = PostgresClientKit.ConnectionConfiguration()
            configuration.host = "127.0.0.1"
            configuration.database = "example"
            configuration.user = "bob"
            configuration.credential = .scramSHA256(password: "welcome1")

            let aaa = try PostgresClientKit.Connection(configuration: configuration)
            let bbb = conn ( conn: aaa)
            myconnection.append(bbb)
            
            let text = "SELECT start();"
            try myconnection.prepareStatement(text: text).execute()
            
            
        } catch {
            print(error) // better error handling goes here
        }
        
        
    }

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解您要执行的操作,但我认为我看到了您的问题。您的代码在此行失败:

try myconnection.prepareStatement(text: text).execute()

但是如上所述,myconnection的类型为[conn]

var myconnection = [conn]()

如果要在数组的第一个元素上调用prepareStatement(text:),则可以执行以下操作:

try myconnection[0].conn.prepareStatement(text: text).execute()

您需要在中间使用.conn,因为该数组是conn个结构的数组,这些结构具有conn个实际上为Connection类型的属性。


值得注意的是,至少在此函数中,您可以在创建prepareStatement(text:)并将其存储在数组中之前,只需在aaa上调用bbb