是否可以在字符串的插值中包括一个方法? (SWIFT)

问题描述 投票:0回答:1

[我试图将我的commercial()类的Cars方法包括在我的finalNegotiation()类的PriceNegotiation方法执行的字符串插值中。那可能吗?我已经尝试过使用.commercial(),也尝试过,正如您在这段代码中所看到的,我尝试使用super.commerical()

class Cars  {
    var make = ""
    var model = ""
    var year = 0

    init(carMake make:String, carModel model:String, carYear year:Int) {
        self.make = make
        self.model = model
        self.year = year
    }
    func commercial() {
        print("This car is a \(year) \(make) \(model)")
    }

}




class PriceNegotation: Cars {
    var price:Double = 0


    init(desiredBuyerPrice price:Double,carMake make:String, carModel model:String, carYear year:Int ) {
        self.price = price

    super.init(carMake: make, carModel: make, carYear: year)


    }

    func finalNegotiation() {
        let dealerPrice = price * 1.5
        print("Since \(super.commercial()) the asking price is \(dealerPrice)")
    }

}
swift string-interpolation
1个回答
0
投票

当您调用commercial()时,它会打印文本并退出功能。为了实现您的目标,请使commercial()函数包含一个返回值。这是一个例子。

class Cars  {
    var make = ""
    var model = ""
    var year = 0

    init(carMake make:String, carModel model:String, carYear year:Int) {
        self.make = make
        self.model = model
        self.year = year
    }

    func commercial()->String {
       return "This car is a \(year) \(make) \(model)"
    }
}
class PriceNegotation: Cars {
    var price:Double = 0

    init(desiredBuyerPrice price:Double,carMake make:String, carModel model:String, carYear year:Int ) {
        self.price = price

        super.init(carMake: make, carModel: make, carYear: year)
    }

    func finalNegotiation() {
        let dealerPrice = price * 1.5
        let commercialOutput = commercial()
        print("Since \(commercialOutput) the asking price is \(dealerPrice)")
    }
}

这是通过内插将commercial()函数的输出String放置在另一个字符串中。以前该函数未返回任何内容,因此看起来好像该函数不起作用。另一方面,这应该起作用。让我知道是否可以。

© www.soinside.com 2019 - 2024. All rights reserved.