ios 如何在 Swift 中从文件扩展名中拆分文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26707352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:28:20  来源:igfitidea点击:

How to split filename from file extension in Swift?

iosstringswift

提问by JohnK

Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

给定包中文件的名称,我想将该文件加载到我的 Swift 应用程序中。所以我需要使用这个方法:

let soundURL = NSBundle.mainBundle().URLForResource(fname, withExtension: ext)

For whatever reason, the method needs the filename separated from the file extension. Fine, it's easy enough to separate the two in most languages. But so far I'm not finding it to be so in Swift.

无论出于何种原因,该方法都需要将文件名与文件扩展名分开。很好,在大多数语言中很容易将两者分开。但到目前为止,我在 Swift 中并没有发现它是如此。

So here is what I have:

所以这就是我所拥有的:

var rt: String.Index = fileName.rangeOfString(".", options:NSStringCompareOptions.BackwardsSearch)
var fname: String = fileName .substringToIndex(rt)
var ext = fileName.substringFromIndex(rt)

If I don't include the typing on the first line, I get errors on the two subsequent lines. With it, I'm getting an error on the first line:

如果我在第一行中不包括打字内容,则会在随后的两行中出现错误。有了它,我在第一行收到一个错误:

Cannot convert the expression's type '(UnicodeScalarLiteralConvertible, options: NSStringCompareOptions)' to type 'UnicodeScalarLiteralConvertible'

How can I split the filename from the extension? Is there some elegant way to do this?

如何从扩展名中拆分文件名?有没有一些优雅的方法来做到这一点?

I was all excited about Swift because it seemed like a much more elegant language than Objective C. But now I'm finding that it has its own cumbersomeness.

我对 Swift 感到非常兴奋,因为它似乎是一种比 Objective C 优雅得多的语言。但现在我发现它有它自己的笨拙之处。



Second attempt: I decided to make my own string-search method:

第二次尝试:我决定制作自己的字符串搜索方法:

func rfind(haystack: String, needle: Character) -> Int {
    var a = Array(haystack)

    for var i = a.count - 1; i >= 0; i-- {
        println(a[i])
        if a[i] == needle {
            println(i)
            return i;
        }
    }
    return -1
}

But now I get an error on the line var rt: String.Index = rfind(fileName, needle: "."):

但是现在我在线上收到一个错误var rt: String.Index = rfind(fileName, needle: ".")

'Int' is not convertible to 'String.Index'

Without the cast, I get an error on the two subsequent lines.

如果没有演员表,我会在随后的两行中收到错误消息。

Can anyone help me to split this filename and extension?

谁能帮我拆分这个文件名和扩展名?

回答by gabbler

Swift 5.0 update:

斯威夫特 5.0 更新:

As pointed out in the comment, you can use this.

正如评论中指出的那样,您可以使用它。

let filename: NSString = "bottom_bar.png"
let pathExtention = filename.pathExtension
let pathPrefix = filename.deletingLastPathComponent

回答by Julian

This is with Swift 2, Xcode 7: If you have the filename with the extension already on it, then you can pass the full filename in as the first parameter and a blank string as the second parameter:

这是在 Swift 2、Xcode 7 中:如果您已经有了带有扩展名的文件名,那么您可以将完整的文件名作为第一个参数传入,并将一个空字符串作为第二个参数传入:

let soundURL = NSBundle.mainBundle()
    .URLForResource("soundfile.ext", withExtension: "")

Alternatively nil as the extension parameter also works.

或者 nil 作为扩展参数也有效。

If you have a URL, and you want to get the name of the file itself for some reason, then you can do this:

如果您有一个 URL,并且出于某种原因想要获取文件本身的名称,那么您可以这样做:

soundURL.URLByDeletingPathExtension?.lastPathComponent

Swift 4

斯威夫特 4

let soundURL = NSBundle.mainBundle().URLForResource("soundfile.ext", withExtension: "")
soundURL.deletingPathExtension().lastPathComponent

回答by tesla

Works in Swift 5. Adding these behaviors to Stringclass:

适用于 Swift 5。将这些行为添加到String类中:

extension String {

    func fileName() -> String {
        return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent 
    }

    func fileExtension() -> String {
        return URL(fileURLWithPath: self).pathExtension
    }
}

Example:

例子:

let file = "image.png"
let fileNameWithoutExtension = file.fileName()
let fileExtension = file.fileExtension()

回答by Lore

Solution Swift 4

解决方案 Swift 4

This solution will work for all instances and does not depend on manually parsing the string.

此解决方案适用于所有实例,并且不依赖于手动解析字符串。

let path = "/Some/Random/Path/To/This.Strange.File.txt"

let fileName = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent

Swift.print(fileName)

The resulting output will be

结果输出将是

This.Strange.File

回答by Santanu Karar

In Swift 2.1 String.pathExtension is not available anymore. Instead you need to determine it through NSURL conversion:

在 Swift 2.1 String.pathExtension 不再可用。相反,您需要通过 NSURL 转换来确定它:

NSURL(fileURLWithPath: filePath).pathExtension

回答by Defide Tester Defide

In Swift you can change to NSStringto get extension faster:

在 Swift 中,您可以更改为NSString以更快地获得扩展:

extension String {
    func getPathExtension() -> String {
        return (self as NSString).pathExtension
    }
}

回答by Aneel

In Swift 2.1, it seems that the current way to do this is:

在 Swift 2.1 中,目前的做法似乎是:

let filename = fileURL.URLByDeletingPathExtension?.lastPathComponent
let extension = fileURL.pathExtension

回答by Giannis Giannopoulos

Latest Swift 4.2 works like this:

最新的 Swift 4.2 是这样工作的:

extension String {
    func fileName() -> String {
        return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
    }

    func fileExtension() -> String {
        return URL(fileURLWithPath: self).pathExtension
    }
}

回答by Den

Swift 5

斯威夫特 5

 URL(string: filePath)?.pathExtension

回答by Trevor

SWIFT 3.x Shortest Native Solution

SWIFT 3.x 最短本机解决方案

let fileName:NSString = "the_file_name.mp3"
let onlyName = fileName.deletingPathExtension
let onlyExt = fileName.pathExtension

No extension or any extra stuff (I've tested. based on @gabbler solution for Swift 2)

没有扩展或任何额外的东西 (我已经测试过。基于 Swift 2 的 @gabbler 解决方案)