Kri*_* PC 5 switch-statement swift3
我正在关注Swift.org的教程
以下switch语句示例引发错误.
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是: error: value of type 'String' has no member 'hasSuffix'
case let x where x.hasSuffix("pepper"):
使用ubuntu 14.04和我的Swift版本swift --version
Swift version 3.0 (swift-3.0-PREVIEW-2)
dfr*_*fri 19
该hasSuffix(_:)成员String来自NSString(并从基金会).在Xcode Playgrounds和项目中使用Swift时,这个方法可以从Swift标准库中获得,而当从例如IBM沙箱/本地Linux机器编译Swift时,Swift std-lib版本是不可访问的,而来自核心的版本-libs基金会是.
要访问后一个实现,您需要显式导入Foundation:
import Foundation // <---
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
Run Code Online (Sandbox Code Playgroud)
大多数Swift教程都会假设通过Xcode执行,并且在Xcode之外编译Swift时,import Foundation对于任何"......没有成员......"错误都可以是首次尝试补救.
正如@Hamish在下面的评论中指出的那样(谢谢!),然而hasSuffix(_:),可以从标准库中获得一个实现_runtime(_ObjC).
来自swift/stdlib/public/core/StringLegacy.swift:
Run Code Online (Sandbox Code Playgroud)#if _runtime(_ObjC) // ... public func hasSuffix(_ suffix: String) -> Bool { // ... } #else // FIXME: Implement hasPrefix and hasSuffix without objc // rdar://problem/18878343 #endif
如果上面的一个不可访问(例如从Linux),则可以使用另一种实现.但是,访问此方法需要隐式import Foundation语句.
来自swift-corelibs-foundation/Foundation/NSString.swift:
Run Code Online (Sandbox Code Playgroud)#if !(os(OSX) || os(iOS)) extension String { // ... public func hasSuffix(_ suffix: String) -> Bool { // ... core foundation implementation } } #endif
| 归档时间: |
|
| 查看次数: |
4055 次 |
| 最近记录: |