blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
5d465fe7d49b163f5f302b045923bad68d8b9005
|
Swift
|
heptal/kathy
|
/Kathy/ChatInputView.swift
|
UTF-8
| 3,044
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ChatInputView.swift
// Kathy
//
// Created by Michael Bujol on 6/13/16.
// Copyright © 2016 heptal. All rights reserved.
//
import Cocoa
extension ChatView: NSTextFieldDelegate {
func resetHistoryIndex() {
if let history = userDefaults.array(forKey: "history") as? [String] {
historyIndex = history.count - 1
}
}
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if let history = userDefaults.array(forKey: "history") as? [String] {
if commandSelector == #selector(moveUp) {
control.stringValue = history[historyIndex]
historyIndex = max(historyIndex - 1, 0)
control.currentEditor()?.moveToEndOfLine(nil)
return true
}
if commandSelector == #selector(moveDown) {
historyIndex = min(historyIndex + 1, history.count - 1)
control.stringValue = history[historyIndex]
control.currentEditor()?.moveToEndOfLine(nil)
return true
}
if commandSelector == #selector(insertTab) {
control.currentEditor()?.complete(nil)
return true
}
}
return false
}
func control(_ control: NSControl, textView: NSTextView, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>) -> [String] {
return (session.channels.selectedObjects.first as? Channel)?.users
.map { return $0.name + ": " }
.filter { $0.hasPrefix(control.stringValue) } ?? []
}
override func controlTextDidEndEditing(_ obj: Notification) {
guard let inputField = obj.object as? NSTextField else { return }
guard inputField.stringValue.trimmingCharacters(in: .whitespaces) != "" else { return }
defer { inputField.stringValue = "" }
let text = inputField.stringValue
if text.hasPrefix("/") {
session?.command(text)
} else {
if let channel = session.channels.selectedObjects.first as? Channel {
if channel.name != session.consoleChannelName {
session?.command("/PRIVMSG \(channel.name) :\(text)")
let message = "\(session.currentNick): \(text)\n"
channel.log.append(message)
appendMessageToActiveChannel(message)
} else {
let message = text + "\n"
channel.log.append(message)
appendMessageToActiveChannel(message)
}
}
}
if var history = userDefaults.array(forKey: "history") as? [String] {
if let index = history.index(of: text) {
history.remove(at: index)
}
history.append(text)
userDefaults.set(history, forKey: "history")
}
resetHistoryIndex()
}
}
| true
|
53d4c16481625ab4746bd77a25382f8cdad91e8f
|
Swift
|
islamshazly/Foundation-IS
|
/Foundation-IS/Classes/Array+IS.swift
|
UTF-8
| 3,208
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public extension Array {
mutating func safeSwap(from index: Index, to otherIndex: Index) {
guard index != otherIndex else { return }
guard startIndex..<endIndex ~= index else { return }
guard startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: All elements up until condition evaluates to false.
func take(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() where try !condition(element) {
return Array(self[startIndex..<index])
}
return self
}
/// [0, 2, 4, 7].keep( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: self after applying provided condition.
/// - Throws: provided condition exception.
mutating func keep(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() where try !condition(element) {
self = Array(self[startIndex..<index])
break
}
return self
}
/// [0, 1, 2, 3, 4, 5].divided { $0 % 2 == 0 } -> ( [0, 2, 4], [1, 3, 5] )
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: Two arrays, the first containing the elements for which the specified condition evaluates to true, the second containing the rest.
func divided(by condition: (Element) throws -> Bool) rethrows -> (matching: [Element], nonMatching: [Element]) {
//Inspired by: http://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-partition
var matching = [Element]()
var nonMatching = [Element]()
for element in self {
try condition(element) ? matching.append(element) : nonMatching.append(element)
}
return (matching, nonMatching)
}
mutating func shuffle() -> [Element] {
// http://stackoverflow.com/questions/37843647/shuffle-array-swift-3
guard count > 1 else { return self }
for index in startIndex..<endIndex - 1 {
let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
if index != randomIndex { swapAt(index, randomIndex) }
}
return self
}
}
public extension Array where Element: Equatable {
mutating func removeDuplicates() {
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
/// - Returns: self after removing all instances of item.
mutating func removeAll(_ item: Element) -> [Element] {
self = filter { $0 != item }
return self
}
}
| true
|
12bf412753e97dd2c885d6de17c99d5cf1629b58
|
Swift
|
hugo082/unicbooking-iOS
|
/Unic Booking/Models/Book.swift
|
UTF-8
| 572
| 3.03125
| 3
|
[] |
no_license
|
//
// Product.swift
// Unic Booking
//
// Created by Hugo Fouquet on 20/07/2017.
// Copyright © 2017 Hugo Fouquet. All rights reserved.
//
import UIKit
class Book: Model {
enum CodingKeys: String, CodingKey {
case id, products
}
let id: Int
let products: [Product]
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.products = try container.decode([Product].self, forKey: .products)
}
}
| true
|
6dad6f605e9a1a29b5ec11fd8f98a20e52188f49
|
Swift
|
confusionhill/CleanRawgMockApp
|
/CleanRawgMockApp/Favourites/ViewModel/FavVM.swift
|
UTF-8
| 1,160
| 2.84375
| 3
|
[] |
no_license
|
//
// FavVM.swift
// CleanRawgMockApp
//
// Created by Farhandika Zahrir Mufti guenia on 01/09/21.
//
import Foundation
class favVM:ObservableObject {
@Published var items = [ItemPreviewModel]()
@Published var showAlert = false
private lazy var persistanceProvider:PersistanceProvider = {
return PersistanceProvider()
}()
init() {
print("Initialize.............\n")
fetchData()
}
func fetchData(){
self.persistanceProvider.getAllFav {[weak self] items in
DispatchQueue.main.async {
self?.items = items
print("items : \(items) \n")
print("Initialize.............\n")
}
}
}
func addNew(_ item:ItemPreviewModel){
self.persistanceProvider.createNewFav(id: item.id!, slug: item.slug!, name: item.name!, image: item.image!, released: item.released!, desc: item.desc!, rating: item.rating!) {
print("New item added into the database")
self.fetchData()
}
}
func deleteAllItems() {
self.persistanceProvider.deleteAll {
print("all deleted...")
}
}
}
| true
|
e48ea2bdc26225ce30bebd91d10c0994c09a0444
|
Swift
|
meilulu/DevelopAccumulate
|
/DevelopControls/DevelopControls/加载页/LoadingView.swift
|
UTF-8
| 2,299
| 2.8125
| 3
|
[] |
no_license
|
//
// LoadingView.swift
// DevelopControls
//
// Created by ShareAnimation on 2018/3/5.
// Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//
import UIKit
import SnapKit
class LoadingView: UIView {
var indicatorView: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
return indicatorView
}()
var indicatorLabel: UILabel = {
let label = UILabel()
label.text = "正在加载,请稍候..."
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red: 249/255.0, green: 249/255.0, blue: 249/255.0, alpha: 1)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
self.addSubview(indicatorView)
indicatorView.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
indicatorView.startAnimating()
self.addSubview(indicatorLabel)
indicatorLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(indicatorView)
make.top.equalTo(indicatorView.snp.bottom).offset(5)
}
}
}
extension UIView {
struct LoadingViewConstants {
static let Tag = 10086
}
public func showLoadingView() {
if self.viewWithTag(LoadingViewConstants.Tag) != nil {
//loadingView已经存在,不要重复添加
print("loadingView已经存在,不要重复添加")
return
}
let loadingView = LoadingView(frame: self.frame)
loadingView.tag = LoadingViewConstants.Tag
self.addSubview(loadingView)
loadingView.alpha = 0
UIView.animate(withDuration: 0.5) {
loadingView.alpha = 1
}
}
public func hideLoadingView() {
if let loadingView = self.viewWithTag(LoadingViewConstants.Tag) {
UIView.animate(withDuration: 0.5, animations: {
loadingView.alpha = 0
}, completion: { (result) in
loadingView.removeFromSuperview()
})
}
}
}
| true
|
1f220318dc36e36f3b4bc92bc931a2fc05311f2b
|
Swift
|
slimlime/SourceView-Swift
|
/SourceView/FileViewController.swift
|
UTF-8
| 3,550
| 2.53125
| 3
|
[] |
no_license
|
//
// FileViewController.swift
// SourceView
//
// Translated by OOPer in cooperation with shlab.jp, on 2015/4/6.
//
//
/*
Copyright (C) 2017 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
View controller object to host the UI for file information
*/
import Cocoa
@objc(FileViewController)
class FileViewController: NSViewController {
var url: URL?
@IBOutlet private var fileIcon: NSImageView!
@IBOutlet private var fileName: NSTextField!
@IBOutlet private var fileSize: NSTextField!
@IBOutlet private var modDate: NSTextField!
@IBOutlet private var creationDate: NSTextField!
@IBOutlet private var fileKindString: NSTextField!
//MARK: -
// -------------------------------------------------------------------------------
// awakeFromNib
// -------------------------------------------------------------------------------
override func awakeFromNib() {
// listen for changes in the url for this view
self.addObserver(self,
forKeyPath: "url",
options: [.new, .old],
context: nil)
}
// -------------------------------------------------------------------------------
// dealloc
// -------------------------------------------------------------------------------
deinit {
self.removeObserver(self, forKeyPath: "url")
}
// -------------------------------------------------------------------------------
// observeValueForKeyPath:ofObject:change:context
//
// Listen for changes in the file url.
// -------------------------------------------------------------------------------
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?)
{
if let url = self.url {
let path = url.path
// name
self.fileName.stringValue = FileManager.default.displayName(atPath: path)
// icon
let iconImage = NSWorkspace.shared().icon(forFile: path)
iconImage.size = NSMakeSize(64, 64)
self.fileIcon.image = iconImage
if let attr = try? FileManager.default.attributesOfItem(atPath: path) {
// file size
let theFileSize = attr[FileAttributeKey.size] as! NSNumber
self.fileSize.stringValue = "\(theFileSize.stringValue) KB on disk"
// creation date
let fileCreationDate = attr[FileAttributeKey.creationDate] as! Date
self.creationDate.stringValue = fileCreationDate.description
// mod date
let fileModDate = attr[FileAttributeKey.modificationDate] as! Date
self.modDate.stringValue = fileModDate.description
}
// kind string
let resource = try? url.resourceValues(forKeys: [.localizedTypeDescriptionKey])
let kindStr = resource?.localizedTypeDescription
if let str = kindStr {
self.fileKindString.stringValue = str
}
} else {
self.fileName.stringValue = ""
self.fileIcon.image = nil
self.fileSize.stringValue = ""
self.creationDate.stringValue = ""
self.modDate.stringValue = ""
self.fileKindString.stringValue = ""
}
}
}
| true
|
9e0e6f3824c5562ffea5a46741f61940ae420262
|
Swift
|
voynovia/YTS
|
/YTS/Torrentino.swift
|
UTF-8
| 9,833
| 2.546875
| 3
|
[] |
no_license
|
//
// Torrentino.swift
// YTS
//
// Created by Igor Voynov on 26.12.16.
// Copyright © 2016 Igor Voynov. All rights reserved.
//
import Foundation
import Kanna
protocol TrackerDelegate {
func requestFast(url: String, operation: ParseOperation)
func parsedPage()
}
class Torrentino {
var delegate: TrackerDelegate!
var encoding: String.Encoding = .utf8
let domain: String = "http://www.torrentino.me"
let moviesPage: String = "http://www.torrentino.me/movies?quality=hq&page="
let searchMoviesPage: String = "http://www.torrentino.me/search?type=movies&page="
let movieLink: String = "section div.plate div.tiles div.tile a" // ссылка на страницу с фильмом
var genres: [GenreAPI: [String]] = [
.All: ["Все"],
.Action: ["боевик"],
.Adventure: ["приключения"],
.Animation: ["мультфильм", "аниме", "детский"],
.Biography: ["биография"],
.Comedy: ["комедия"],
.Crime: ["криминал", "детектив"],
.Documentary: ["документальный", "новости"],
.Drama: ["драма"],
.Family: ["семейный", "детский"],
.Fantasy: ["фэнтези"],
.FilmNoir: ["фильм-нуар"],
.History: ["история"],
.Horror: ["ужасы"],
.Music: ["музыка", "концерт"],
.Musical: ["мюзикл"],
.Mystery: ["ужасы"],
.Romance: ["мелодрама"],
.SciFi: ["фантастика"],
.Short: ["короткометражка"],
.Sport: ["спорт"],
.Thriller: ["триллер", "детектив"],
.War: ["военный"],
.Western: ["вестерн"]
]
let audio = ["iTunes", "Лицензия", "Дублированный"]
var sort = ["date", "rating", "popularity"]
func parsePage(html: String) -> [String] {
var links = [String]()
if let doc = Kanna.HTML(html: html, encoding: encoding) {
for item in doc.css(movieLink) {
links.append(item["href"]!)
}
}
return links
}
func parsePageFast(html: String) {
if let doc = Kanna.HTML(html: html, encoding: encoding) {
for item in doc.css(movieLink) {
delegate.requestFast(url: item["href"]!, operation: ParseOperation.One)
}
}
self.delegate.parsedPage()
}
func parseMovie(html: String, url: String, fast: Bool = false) {
if let doc = Kanna.HTML(html: html, encoding: encoding) {
var genres = [Genre]()
let movie = Movie()
movie.id = Int(url.between(from: "/", to: "-")!)!
movie.imdb_code = String(movie.id)
movie.slug = url.toEnd(from: "-")
// Add Files Information
// ------------------------
var torrent720: Torrent?
var torrent1080: Torrent?
if let list = doc.at_css("div.main div.entity div.list-start table.quality") {
var group: String?
for item in list.css("tr.item") {
if let quality = item.at_css("td.quality a.group-label") {
if (quality["title"]?.contains("Blu-ray"))! || (quality["title"]?.contains("BDRip"))! || (quality["title"]?.contains("HDRip"))! {
group = quality["data-group"]
} else {
continue
}
} else {
if item["data-group"] != group {
continue
}
}
if let videoText = item.at_css("td.video")?.text, let audioText = item.at_css("td.audio")?.text?.trim(),
let seedsText = item.at_css("td.seed-leech span.seed")?.text?.toInteger {
let curTorrent = Torrent()
if videoText.hasPrefix("1280") && audio.contains(audioText) {
if let maxSeeds = torrent1080?.seeds {
if seedsText < maxSeeds {
continue
}
}
curTorrent.qualityEnum = QualityAPI.p1080
torrent1080 = curTorrent
} else if videoText.hasPrefix("720") && audio.contains(audioText) {
if let maxSeeds = torrent720?.seeds {
if seedsText < maxSeeds {
continue
}
}
curTorrent.qualityEnum = QualityAPI.p720
torrent720 = curTorrent
} else {
continue
}
curTorrent.idMovie = movie.id
if let sizeString = item.at_css("td.size")?.text, let size = sizeString.toDouble {
curTorrent.size = sizeString.contains("ГБ") ? String(describing: size) + " GB" : String(describing: size) + " MB"
curTorrent.size_bytes = String(Int(size) * 1000000000)
}
curTorrent.date_uploaded = item.at_css("td.updated")?.text?.changeDateFormat(fromFormat: "dd.MM.yyyy", toFormat: "yyyy-MM-dd HH:mm:ss")
curTorrent.date_uploaded_unix = curTorrent.date_uploaded?.toUnixTime(format: "yyyy-MM-dd HH:mm:ss") ?? 0.0
curTorrent.seeds = seedsText
curTorrent.peers = item.at_css("td.seed-leech span.leech")?.text?.toInteger ?? 0
curTorrent.url = item.at_css("td.download a[data-type=download]")?["data-torrent"]
curTorrent._hash = item.at_css("td.download a[data-type=download]")?["data-default"]?.between(from: "btih:", to: "&")
}
}
}
// Add Movie Information
// ------------------------
if torrent720 != nil || torrent1080 != nil {
if let head = doc.at_css("div.main div.entity div.head-plate") {
movie.title = head.at_css("h1[itemprop='name']")?.text
movie.year = head.at_css("td[itemprop='copyrightYear']")?.text?.toInteger ?? 2000
movie.rating = head.at_css("meta[itemprop='ratingValue']")?["content"]?.toDouble ?? 0.0
if let runtime = head.at_css("td[itemprop='duration']")?["datetime"] {
if let hours = runtime.between(from: "PT", to: "H")?.toInteger,
let minutes = runtime.between(from: "H", to: "M")?.toInteger {
movie.runtime = hours * 60 + minutes
}
}
movie.small_cover_image = "https://st.kp.yandex.net/images/film_iphone/iphone360_"+String(movie.id)+".jpg"
movie.medium_cover_image = "https://st.kp.yandex.net/images/film_big/"+String(movie.id)+".jpg"
if let synopsis = head.xpath("//div[@class='specialty']/text()")[1].text?.trim(), !synopsis.isEmpty {
movie.synopsis = synopsis
} else {
movie.synopsis = head.at_css("div.specialty p")?.text
}
movie.yt_trailer_code = nil
for item in head.css("a[href*=genres]") {
let name = (item["href"]?.toEnd(from: "="))!
if let genreYts = self.genres.first(where: { $0.value.contains(name)}) {
let genre = Genre()
genre.name = (genreYts.key.rawValue)
genres.append(genre)
} else {
print("Для", name, "нет соответствия")
}
}
}
// save in database
let database = DataBase()
database.executeInTransaction(execute: {
database.updateInTransaction(object: movie)
if let tor = torrent720 {
database.updateInTransaction(object: tor)
movie.torrents.append(tor)
}
if let tor = torrent1080 {
database.updateInTransaction(object: tor)
movie.torrents.append(tor)
}
if genres.count > 0 {
for genre in genres {
database.updateInTransaction(object: genre)
movie.genres.append(genre)
}
} else {
let genre = Genre()
genre.name = GenreAPI.All.rawValue
movie.genres.append(genre)
}
})
}
}
if fast {
self.delegate.parsedPage()
}
}
}
| true
|
48453e36fe0d24a79d357743b69bbdd4faa99338
|
Swift
|
stripe/stripe-ios
|
/Example/CardImageVerification Example/CardImageVerification Example/URLHelper.swift
|
UTF-8
| 446
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// URLHelper.swift
// CardImageVerification Example
//
// Created by Jaime Park on 11/18/21.
//
import Foundation
enum URLHelper: String {
case cardSet = "card-set/checkout"
case cardAdd = "card-add/checkout"
case verify = "verify"
private static let baseURL: URL = URL(string: "https://stripe-card-scan-civ-example-app.glitch.me")!
var verifyURL: URL { return URLHelper.baseURL.appendingPathComponent(self.rawValue) }
}
| true
|
2c165716fc76eac4edf14dc07e13b243ce39e0b3
|
Swift
|
knetikmedia/knetikcloud-swift3-client
|
/JSAPI/Classes/Swaggers/Models/AvailableSettingResource.swift
|
UTF-8
| 1,702
| 2.875
| 3
|
[] |
no_license
|
//
// AvailableSettingResource.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** The definition of an activity parameters: ex: difficulty level */
open class AvailableSettingResource: JSONEncodable {
/** Whether the setting is advanced. Default: false */
public var advancedOption: Bool?
/** The default value of the setting (must be in options array). Ex: easy */
public var defaultValue: String?
/** The description of the setting: Ex: Choose the difficulty level to show more or less complicated questions (for a trivia activity) */
public var description: String?
/** The unique ID for the setting: Ex: difficulty */
public var key: String?
/** The textual name of the setting: Ex: Difficulty Level */
public var name: String?
/** The set of options available for this setting, Ex: easy, medium, hard */
public var options: [SettingOption]?
/** The type of the setting value: Ex: TEXT */
public var type: String?
public init() {}
// MARK: JSONEncodable
open func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["advanced_option"] = self.advancedOption
nillableDictionary["default_value"] = self.defaultValue
nillableDictionary["description"] = self.description
nillableDictionary["key"] = self.key
nillableDictionary["name"] = self.name
nillableDictionary["options"] = self.options?.encodeToJSON()
nillableDictionary["type"] = self.type
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
| true
|
e5adaa1b6ae70d1d487e7f009525c8c22392fee9
|
Swift
|
enjoylifeenjoycoding/weather
|
/GetWeather/GetWeather/Class/Main/M/WeatherM.swift
|
UTF-8
| 1,698
| 2.78125
| 3
|
[] |
no_license
|
//
// WeatherM.swift
// GetWeather
//
// Created by 赵宇鹏 on 2019/1/21.
// Copyright © 2019年 赵宇鹏. All rights reserved.
//
import UIKit
open class WeatherM: NSObject {
@objc var area: String = ""
@objc var forecast: String = ""
@objc var latitude: Double = 0
@objc var longitude: Double = 0
convenience init(jsonData:Any) {
self.init()
area = JSON(jsonData)["area"].string ?? ""
latitude = JSON(jsonData)["latitude"].double ?? 0
longitude = JSON(jsonData)["longitude"].double ?? 0
forecast = JSON(jsonData)["forecast"].string ?? ""
}
class func updateLocation(json:Any?) {
guard let json = json else { return }
let model: WeatherM? = J_Select(WeatherM.self).Where("area = '\(JSON(json)["name"].string ?? "")'").list().first
guard let dbModel = model else { return }
if dbModel.latitude == 0 || dbModel.longitude == 0 {
dbModel.latitude = JSON(json)["label_location"]["latitude"].double ?? 0
dbModel.longitude = JSON(json)["label_location"]["longitude"].double ?? 0
dbModel.jr_saveOrUpdateOnly()
}
}
class func updateForecast(json:Any?) {
guard let json = json else { return }
let model = WeatherM(jsonData: json)
let dbModel: WeatherM? = J_Select(WeatherM.self).Where("area = '\(model.area)'").list().first
if dbModel == nil {
model.jr_save()
}else {
dbModel?.forecast = model.forecast
dbModel?.jr_saveOrUpdateOnly()
}
}
}
| true
|
35d04d8a5f118e473d0c57c0191210a034203d94
|
Swift
|
TaylorRayHoward/Why-Not-Today
|
/Why Not Today/StatsViewController.swift
|
UTF-8
| 1,716
| 2.578125
| 3
|
[] |
no_license
|
//
// Created by Taylor Howard on 5/28/17.
// Copyright (c) 2017 TaylorRayHoward. All rights reserved.
//
import UIKit
import UICountingLabel
class StatsViewController: UIViewController {
@IBOutlet weak var monLabel: UICountingLabel!
@IBOutlet weak var tuesLabel: UICountingLabel!
@IBOutlet weak var wedLabel: UICountingLabel!
@IBOutlet weak var thursLabel: UICountingLabel!
@IBOutlet weak var friLabel: UICountingLabel!
@IBOutlet weak var satLabel: UICountingLabel!
@IBOutlet weak var sunLabel: UICountingLabel!
var labelList = [UICountingLabel]()
var habit: Habit? = nil
override func viewDidLoad() {
labelList = [sunLabel, monLabel, tuesLabel, wedLabel, thursLabel, friLabel, satLabel]
super.viewDidLoad()
setDayPercentText()
}
func setDayPercentText() {
for day in iterateEnum(dayOfWeek.self){
let label = labelList[day.rawValue - 1]
label.format = "%d%%"
label.method = UILabelCountingMethod.linear
label.count(from: 0, to: CGFloat(calcDay(forDay: day)), withDuration: 1.0)
}
}
func calcDay(forDay weekday: dayOfWeek) -> Int {
var startDate = habit!.createDate
var weekDaysSince = 1
while(!startDate.isSameDay(date: Date().endOfDay)) {
if(startDate.weekday == weekday.rawValue) {
weekDaysSince += 1
}
startDate = startDate.add(1.days)
}
let daysCompleted = habit!.datesCompleted.filter {
$0.dateCompleted.weekday == weekday.rawValue && $0.successfullyCompleted == 1
}
return Int(round(Double(daysCompleted.count)/Double(weekDaysSince) * 100))
}
}
| true
|
c4eb6a3f3879c5262c4937bac81fa8917ff50e5c
|
Swift
|
brend/Nonograms
|
/Nonograms/Rules/CompleteUnambiguousRule.swift
|
UTF-8
| 693
| 3.046875
| 3
|
[] |
no_license
|
//
// CompleteUnambiguousRule.swift
// Picross
//
// Created by Philipp Brendel on 30.05.19.
// Copyright © 2019 Philipp Brendel. All rights reserved.
//
import Foundation
public class CompleteUnambiguousRule: Rule {
public override var name: String { return "Complete Unambiguous" }
override func apply(to row: [Mark], hints: [Int]) -> [Mark] {
guard hints.reduce(0, +) + hints.count - 1 == row.count else {
return row
}
var start = 0
var alteredRow = row
for h in hints {
alteredRow = chisel(alteredRow, from: start, count: h)
start += h + 1
}
return alteredRow
}
}
| true
|
9c8dac693012f9cf2272ca5400cc0ddb2cffb84e
|
Swift
|
rama11/tableViewDynamic
|
/tableViewDynamic/ViewController.swift
|
UTF-8
| 1,967
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// tableViewDynamic
//
// Created by Sinergy on 7/14/20.
// Copyright © 2020 Sinergy. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var tableView: UITableView!
var model = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
getData{
print("Successfull")
self.tableView.reloadData()
}
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style:.default, reuseIdentifier: nil)
cell.textLabel?.text = model[indexPath.row].name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? DetailViewController {
destination.model = model[(tableView.indexPathForSelectedRow?.row)!]
}
}
func getData(completed: @escaping () -> ()){
let url = URL(string: "https://sinergy-dev.xyz:2096/arrayTableDynamic")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.model = try JSONDecoder().decode([Model].self, from: data!)
DispatchQueue.main.async {
completed()
}
} catch {
print("JSON Error")
}
}
}.resume()
}
}
| true
|
b06f9edfc3eba7b7767fd18265caa87f89f3009e
|
Swift
|
brianjohnson21/XWAppKit_Swift
|
/Sources/XWAppKit-Swift/UI/PhotoAccess/XWAKImageBrower.swift
|
UTF-8
| 4,526
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// XWAKImageBrower.swift
// XWAppKit_Swift
//
// Created by ZHXW on 2020/11/11.
// Copyright © 2020 ZhuanagXiaowei. All rights reserved.
//
import UIKit
public class XWAKImageBrower: UIView {
public var image: UIImage? {
didSet {
imageView.image = image
if let image = image {
imageView.frame = image.size.fixFrameTo(bounds)
}
}
}
public let scrollView: UIScrollView = {
let view = UIScrollView()
view.translatesAutoresizingMaskIntoConstraints = false
view.minimumZoomScale = 1.0
view.maximumZoomScale = 3.0
return view
}()
public let imageView: UIImageView = {
let view = UIImageView()
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
addSubview(scrollView)
scrollView.delegate = self
scrollView.addSubview(imageView)
scrollView.xwak.edge(equalTo: xwak, inset: 0, edges: [.all])
.width(equalTo: xwak.width)
.height(equalTo: xwak.height)
}
private var isInit = false
public override func layoutSubviews() {
super.layoutSubviews()
if !isInit {
if let image = image {
let frame = image.size.fixFrameTo(bounds.insetBy(dx: 10, dy: 10))
imageView.frame = frame
}
}
}
}
extension XWAKImageBrower: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
centerScrollViewContents()
}
private var scrollViewVisibleSize: CGSize {
let contentInset = scrollView.contentInset
let scrollViewSize = scrollView.bounds.standardized.size
let width = scrollViewSize.width - contentInset.left - contentInset.right
let height = scrollViewSize.height - contentInset.top - contentInset.bottom
return CGSize(width:width, height:height)
}
private var scrollViewCenter: CGPoint {
let scrollViewSize = self.scrollViewVisibleSize
return CGPoint(x: scrollViewSize.width / 2.0,
y: scrollViewSize.height / 2.0)
}
private func centerScrollViewContents() {
guard let image = imageView.image else {
return
}
let imgViewSize = imageView.frame.size
let imageSize = image.size
var realImgSize: CGSize
if imageSize.width / imageSize.height > imgViewSize.width / imgViewSize.height {
realImgSize = CGSize(width: imgViewSize.width,height: imgViewSize.width / imageSize.width * imageSize.height)
} else {
realImgSize = CGSize(width: imgViewSize.height / imageSize.height * imageSize.width, height: imgViewSize.height)
}
var frame = CGRect.zero
frame.size = realImgSize
imageView.frame = frame
let screenSize = scrollView.frame.size
let offx = screenSize.width > realImgSize.width ? (screenSize.width - realImgSize.width) / 2 : 0
let offy = screenSize.height > realImgSize.height ? (screenSize.height - realImgSize.height) / 2 : 0
scrollView.contentInset = UIEdgeInsets(top: offy,
left: offx,
bottom: offy,
right: offx)
// The scroll view has zoomed, so you need to re-center the contents
let scrollViewSize = scrollViewVisibleSize
// First assume that image center coincides with the contents box center.
// This is correct when the image is bigger than scrollView due to zoom
var imageCenter = CGPoint(x: scrollView.contentSize.width / 2.0,
y: scrollView.contentSize.height / 2.0)
let center = scrollViewCenter
//if image is smaller than the scrollView visible size - fix the image center accordingly
if scrollView.contentSize.width < scrollViewSize.width {
imageCenter.x = center.x
}
if scrollView.contentSize.height < scrollViewSize.height {
imageCenter.y = center.y
}
imageView.center = imageCenter
}
}
| true
|
e98804ce9e9acb73d5cd4d8cf4d91f5dac7074fe
|
Swift
|
arnaud2G/CSpot
|
/Capitaine spot/CDHelper.swift
|
UTF-8
| 3,091
| 2.625
| 3
|
[] |
no_license
|
//
// CDHelper.swift
// Capitaine spot
//
// Created by 2Gather Arnaud Verrier on 03/05/2017.
// Copyright © 2017 Arnaud Verrier. All rights reserved.
//
import Foundation
import CoreData
class CDHelper {
static let sharedInstance = CDHelper()
let UserDefaultShareKey: String = "group.avpro.CSpot"
let modelName = "CDCSpot"
// Définition de l'URL de l'emplacement de sauvegarde
lazy var storeDirectory: URL = {
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: self.UserDefaultShareKey)!
}()
// Retourne l'url de la base locale
lazy var localStoreURL: URL = {
let url = self.storeDirectory.appendingPathComponent("\(self.modelName).sqlite")
return url
}()
// Définition de l'url du model
lazy var modelURL: URL = {
// Test la présence du fichier momd
let bundle = Bundle.main
if let url = bundle.url(forResource: self.modelName, withExtension: "momd") {
return url
}
print("CRITICAL - Managed Object Model fil not found")
abort()
}()
// Retourne le model associé au fichier momd
lazy var model: NSManagedObjectModel = {
return NSManagedObjectModel(contentsOf: self.modelURL)!
}()
// Retourne le coordinateur (model -> local)
lazy var coordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.model)
let mOption = [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true]
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.localStoreURL, options: mOption)
} catch {
print("Could not add the persistent store")
abort()
}
return coordinator
}()
}
class CDContext:NSManagedObjectContext {
// Share instance permet l'utilisation des fonctions en local
static let sharedInstance = CDContext()
var nCount = 0
init() {
super.init(concurrencyType: .mainQueueConcurrencyType)
self.persistentStoreCoordinator = CDHelper.sharedInstance.coordinator
self.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
self.shouldDeleteInaccessibleFaults = true
nCount = nCount + 1
if nCount > 1 { fatalError("Ne doit être appellé qu'une fois") }
else {print("DisplayContext initialisé")}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func deleteAllData(entity: String) throws {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let results = try self.fetch(fetchRequest) as! [NSManagedObject]
_ = results.map({
(result:NSManagedObject) in
self.delete(result)
})
try self.save()
}
}
| true
|
4d17116f506714677132a8790a6a07aed8447363
|
Swift
|
yusuftrn/SwiftLearn
|
/SwiftLearner/advanced/advanced7.playground/Contents.swift
|
UTF-8
| 2,018
| 4
| 4
|
[] |
no_license
|
//Error Handling
import Foundation
//First level error handling with optionals
//failable initializers:
let val = Int("3")
let failedVal = Int("data") //nil
enum PetFood: String {
case kibble, canned
}
let morning = PetFood(rawValue: "kibble") //kibble
let snack = PetFood(rawValue: "just another food") //nil
struct PetHouse {
let squareFeet: Int
//basic ctor must have optional
init?(squareFeet: Int){
if squareFeet < 1 {
return nil
}
self.squareFeet = squareFeet
}
}
let tooSmall = PetHouse(squareFeet: 0) //nil
let house = PetHouse(squareFeet: 5)
class Pet {
var breed: String?
init (breed: String? = nil) {
self.breed = breed
}
}
class Person {
let pet: Pet
init(pet: Pet) {
self.pet = pet
}
}
let delta = Pet(breed: "Pug")
let olive = Pet()
let janie = Person(pet: olive)
let xdog = Person(pet: delta)
let dogBreed = janie.pet.breed
print(xdog.pet.breed!)
//Error protocol:
class Pasty {
let flavor: String
var numberOnHand: Int
init(flavor: String, numberOnHand: Int) {
self.flavor = flavor
self.numberOnHand = numberOnHand
}
}
enum BakeryError: Error {
case tooFew(numberOnHand: Int)
case doNotSell
case wrongFlavor
}
//Throw errors:
class Bakery {
var itemsForSale = [
"Cookie": Pasty(flavor: "Chocolate", numberOnHand: 20),
"PopTart": Pasty(flavor: "WildBerry", numberOnHand: 13),
"Donut": Pasty(flavor: "Cherry", numberOnHand: 6)
]
func orderPastry(item: String, amountRequested: Int, flavor: String) throws -> Int {
guard let pastry = itemsForSale[item] else {
throw BakeryError.doNotSell
}
guard flavor == pastry.flavor else {
throw BakeryError.wrongFlavor
}
guard amountRequested <= pastry.numberOnHand else {
throw BakeryError.tooFew(numberOnHand: pastry.numberOnHand)
}
pastry.numberOnHand -= amountRequested
return pastry.numberOnHand
}
}
let bakery = Bakery()
do {
try
bakery.orderPastry(item: "Doner", amountRequested: 2, flavor: "Cherry")
} catch BakeryError.doNotSell {
print("we dont have")
}
| true
|
6ec23195e496e67c983eb7bca6a449f3d95cb4c2
|
Swift
|
AckeeCZ/TezosSwift
|
/TezosSwift/Core/Models/ContractStatus.swift
|
UTF-8
| 1,777
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// ContractStatus.swift
// TezosSwift
//
// Created by Marek Fořt on 11/1/18.
// Copyright © 2018 Keefer Taylor. All rights reserved.
//
import Foundation
/// Contract's status keys
public enum ContractStatusKeys: String, CodingKey {
case balance = "balance"
case spendable = "spendable"
case manager = "manager"
case delegate = "delegate"
case counter = "counter"
case script = "script"
case storage = "storage"
}
/// Contract's storage keys
public enum StorageKeys: String, CodingKey {
case int
case string
case prim
case args
case bytes
}
/// Tezos primary key types
public enum TezosPrimaryType: String, Codable {
case some = "Some"
case none = "None"
case pair = "Pair"
case map = "Elt"
case right = "Right"
case left = "Left"
}
/// Status data of account with no or unit storage
public struct ContractStatus: Decodable {
/// Balance of account in Tezos
public let balance: Tez
/// Is contract spendable
public let spendable: Bool
/// Account's manager address
public let manager: String
/// Account's delegate
public let delegate: StatusDelegate
/// Account's current operation counter
public let counter: Int
/// Account's storage
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ContractStatusKeys.self)
self.balance = try container.decode(Tez.self, forKey: .balance)
self.spendable = try container.decode(Bool.self, forKey: .spendable)
self.manager = try container.decode(String.self, forKey: .manager)
self.delegate = try container.decode(StatusDelegate.self, forKey: .delegate)
self.counter = try container.decodeRPC(Int.self, forKey: .counter)
}
}
| true
|
dd64dbcd8bcef348f250c43c65c221bb58fe7eeb
|
Swift
|
Bruce-pac/RxIGListKit
|
/Example/RxIGListKit/Feed.swift
|
UTF-8
| 687
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// Feed.swift
// RxIGListKit_Example
//
// Created by Bruce-pac on 2019/3/24.
// Copyright © 2019 RxSwiftCommunity. All rights reserved.
//
import Foundation
import IGListKit.IGListDiffable
import RxIGListKit
class Feed: SectionModelDiffable {
typealias ObjectType = Feed
func diffIdentifier() -> NSObjectProtocol {
return id as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard let object = object as? Feed else { return false }
return id == object.id
}
var id: Int = 1
var name: String = ""
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
| true
|
f3a4673a0033eb8f4dcd3d8f204dccfebef2711f
|
Swift
|
bayupaoh/learn-ios-2018
|
/tableviewmultipleview/tableviewmultipleview/model/ModelTimeline.swift
|
UTF-8
| 361
| 2.5625
| 3
|
[] |
no_license
|
//
// ModelTimeline.swift
// tableviewmultipleview
//
// Created by Bayu Paoh on 25/09/18.
// Copyright © 2018 Bayu Paoh. All rights reserved.
//
import Foundation
import UIKit
class ModelTimeline {
var status: String?
var image: UIImage?
init(status: String?,image: UIImage?) {
self.status = status
self.image = image
}
}
| true
|
4f712e2f77021efab1e995a62db095a63dee8645
|
Swift
|
bobgodwinx/GoEuro
|
/GoEuroSwift/GoEuroSwift/Builder.swift
|
UTF-8
| 3,528
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
//
// Builder.swift
// GoEuroSwift
//
// Created by Bob Godwin Obi on 10/16/15.
// Copyright © 2015 Bob Godwin Obi. All rights reserved.
//
import Foundation
import CoreLocation
class Builder {
/**
Returns a dictionary of Strings for search
*/
func buildParamentersFromQuery(query:Query) -> [String:String]{
var parameters = [String:String]()
parameters[kConst.Locale] = query.locale
parameters[kConst.Term] = query.term
return parameters
}
/**
Returns an array of locations based on the server response
*/
func buildServerResponse(response:[AnyObject]) -> [Location] {
var locations = [Location]()
for item in response {
var latitude:Double = 0.0000000
var longitude:Double = 0.0000000
guard let dictionary = item as? [String:AnyObject] else {
//Go to the next dictionary
continue
}
let identifier = (dictionary[kResponseKey.Id] as? NSNumber)?.longLongValue ?? 0
let coreCountry = (dictionary[kResponseKey.CoreCountry] as? NSNumber)?.boolValue ?? false
let country = dictionary[kResponseKey.Country] as? String ?? nil
let countryCode = dictionary[kResponseKey.CountryCode] as? String ?? nil
let distance = (dictionary[kResponseKey.Distance] as? NSNumber)?.longLongValue ?? 0
let fullname = dictionary[kResponseKey.FullName] as? String ?? nil
if let coordinateItem = dictionary[kResponseKey.Coordinate] as? [String :AnyObject] {
//If possibile we store the right position. Else location 0.0
latitude = (coordinateItem[kResponseKey.Latitude] as? NSNumber)?.doubleValue ?? 0.0000000
longitude = (coordinateItem[kResponseKey.Longitude] as? NSNumber)?.doubleValue ?? 0.0000000
}
let coordinate = CLLocationCoordinate2DMake(latitude, longitude)
let airportCode = dictionary[kResponseKey.AirportCode] as? String ?? nil
let inEurope = (dictionary[kResponseKey.InEurope] as? NSNumber)?.boolValue ?? false
let key = dictionary[kResponseKey.Key] as? String ?? nil
let locationId = (dictionary[kResponseKey.LocationId] as? NSNumber)?.longLongValue ?? 0
let name = dictionary[kResponseKey.Name] as? String ?? nil
let locationString = dictionary[kResponseKey.TypeString] as? String ?? nil
let typeString = locationTypeWithString(locationString)
let location = Location(identifier:identifier, coreCountry:coreCountry, country:country, countryCode:countryCode, distance:distance, fullname:fullname, coordinate:coordinate, airportCode:airportCode, inEurope:inEurope, key:key, locationId:locationId, name:name, type:typeString)
locations.append(location)
}
return locations
}
func locationTypeWithString(string:String?) -> LocationType {
guard let typeString = string else {
return .LocationTypeUnknown
}
switch typeString
{
case kResponseKey.TypeAirportString:
return .LocationTypeAirPort
case kResponseKey.TypeLocationString:
return .LocationTypeLocation
case kResponseKey.TypeStationString:
return .LocationTypeStation
default:break
}
return .LocationTypeUnknown
}
}
| true
|
f2e6991219e3ca6367b6c6dedd7e34f8b4a6095d
|
Swift
|
oozimok/rool-dice-app
|
/Rool Dice/ViewController.swift
|
UTF-8
| 836
| 3.046875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Rool Dice
//
// Created by Oleg Ozimok on 12/02/2019.
// Copyright © 2019 Oleg Ozimok. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var leftImageView: UIImageView!
@IBOutlet weak var rightImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
rollDice()
}
@IBAction func rollACTION(_ sender: Any) {
rollDice()
}
func rollDice(){
let numberOne = arc4random_uniform(6) + 1
let numberTwo = arc4random_uniform(6) + 1
label.text = "The sum is: \(numberOne + numberTwo)"
leftImageView.image = UIImage(named: "Dice\(numberOne)")
rightImageView.image = UIImage(named: "Dice\(numberTwo)")
}
}
| true
|
70f818ef14a2b45916030f9b58d6e5cb19160367
|
Swift
|
adnaanaeem/AssetsDemo
|
/Anim_iOS/iOS-Anim/Anim_Delegate.swift
|
UTF-8
| 2,921
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//****************************************************************************************
// Anima_Delegate.swift
//
// Copyright (C) 2019 Reflect Code Technologies (OPC) Pvt. Ltd.
// For detailed please check - http://ReflectCode.com
//
// Description - Simple class to store reference to method to be called by deligate
// The instance of this class can be assigned to "deligate" property
// This class can also be we created inlined
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//****************************************************************************************
import UIKit
class Anim_Delegate: NSObject, CAAnimationDelegate {
var onAnimationStart : ((_ animation : CAAnimation) -> ())?
var onAnimationEnd : ((_ animation : CAAnimation, _ finished : Bool) -> ())?
init(onAnimationStart : ((_ animation : CAAnimation) -> ())? , onAnimationEnd : ((_ animation : CAAnimation, _ finished : Bool) -> ())? ) {
self.onAnimationStart = onAnimationStart
self.onAnimationEnd = onAnimationEnd
super.init()
}
init(onAnimationStart : ((_ animation : CAAnimation) -> ())? ) {
self.onAnimationStart = onAnimationStart
self.onAnimationEnd = nil
super.init()
}
init(onAnimationEnd : ((_ animation : CAAnimation, _ finished : Bool) -> ())? ) {
self.onAnimationStart = nil
self.onAnimationEnd = onAnimationEnd
super.init()
}
// CAAnimationDelegate method
func animationDidStart( _ anim: CAAnimation ) {
if let onAnimationStart = onAnimationStart {
onAnimationStart(anim)
}
}
// CAAnimationDelegate method
func animationDidStop( _ anim: CAAnimation, finished flag: Bool ) {
if let onAnimationEnd = onAnimationEnd {
onAnimationEnd(anim, flag)
}
}
}
| true
|
1621dad596820584f01401c20019e6474272581a
|
Swift
|
Pra9ptl/Zombie-Conga
|
/ZombieConga/GameScene.swift
|
UTF-8
| 10,508
| 3.171875
| 3
|
[] |
no_license
|
//
// GameScene.swift
// ZombieConga
//
// Created by Parrot on 2019-01-29.
// Copyright © 2019 Parrot. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
// SPRITES
let zombie = SKSpriteNode(imageNamed: "zombie1")
let enemy = SKSpriteNode(imageNamed: "enemy")
// GAME STAT SPRITES
let livesLabel = SKLabelNode(text: "Lives: ")
let scoreLabel = SKLabelNode(text: "Score: ")
// MATH VARIABLES
var xd:CGFloat = 0
var yd:CGFloat = 0
// GAME STATISTIC VARIABLES
var lives = 2 // for testing, use a small number
var score = 0
override func didMove(to view: SKView) {
// Set the background color of the app
self.backgroundColor = SKColor.black;
// MARK: Create a background image:
// --------------------------
// 1. create an image node
let bgNode = SKSpriteNode(imageNamed: "background2")
// 2. by default, image is shown in bottom left corner
// I want to move image to middle
// middle x: self.size.width/2
// middle y: self.size.height/2
bgNode.position = CGPoint(x:self.size.width/2,
y:self.size.height/2)
// Force the background to always appear at the back
bgNode.zPosition = -1
// MARK: Create a zombie sprite
// --------------------------
// 1. create an image node
// ---> zombie is created as a global variable
// 2. by default, image is shown at (400, 400)
zombie.position = CGPoint(x:150,
y:400)
// MARK: Create a enemy sprite
// --------------------------
// 1. create an image node
// --> check global variables for code
// 2. position the enemy
enemy.position = CGPoint(x:self.size.width - 200,
y:self.size.height/2)
// MARK: Add a lives label
// ------------------------
self.livesLabel.text = "Lives: \(self.lives)"
self.livesLabel.fontName = "Avenir-Bold"
self.livesLabel.fontColor = UIColor.yellow
self.livesLabel.fontSize = 100;
self.livesLabel.position = CGPoint(x:300,
y:self.size.height-400)
// MARK: Add a score label
// ------------------------
self.scoreLabel.text = "Score: \(self.score)"
self.scoreLabel.fontName = "Avenir-Bold"
self.scoreLabel.fontColor = UIColor.yellow
self.scoreLabel.fontSize = 100;
self.scoreLabel.position = CGPoint(x:800,
y:self.size.height-400)
// MARK: Add your sprites to the screen
addChild(zombie)
addChild(enemy)
addChild(self.livesLabel)
addChild(self.scoreLabel)
// MARK: setup enemy movement
// move to (w/2, 0)
let m1 = SKAction.move(
to: CGPoint(
x:self.size.width/2,
y:400),
duration: 2)
// move to (0,h/2)
let m2 = SKAction.move(
to: CGPoint(
x:200,
y:self.size.height/2),
duration: 2)
// move to (w, h/2)
let m3 = SKAction.move(
to: CGPoint(
x:self.size.width - 200,
y:self.size.height/2),
duration: 2)
let sequence:SKAction = SKAction.sequence([m1, m2, m1, m3])
enemy.run(SKAction.repeatForever(sequence))
// write the code to generate a cat every 3 seconds
// let generateCatsSequence = SKAction.sequence(
// [
// SKAction.run {
// [weak self] in self?.makeCats()
// },
// SKAction.wait(forDuration: 1.5)
// ]
// )
// self.run(SKAction.repeatForever(generateCatsSequence))
} //did move function
// keep track of all the cat objects on the screen
var cats:[SKSpriteNode] = []
func makeCats() {
// lets add some cats
let cat = SKSpriteNode(imageNamed: "cat")
// generate a random (x,y) for the cat
let randX = Int(CGFloat(arc4random_uniform(UInt32(self.size.width-400))))
let randY = Int(CGFloat(arc4random_uniform(UInt32(self.size.height-400))))
cat.position = CGPoint(x:randX, y:randY)
// add the cat to the scene
addChild(cat)
// add the cat to the cats array
self.cats.append(cat)
print("Where is cat? \(randX), \(randY)")
}
// variable to keep track of how much time has passed
var timeOfLastUpdate:TimeInterval?
override func update(_ currentTime: TimeInterval) {
self.zombie.position.x = self.zombie.position.x + self.xd * 10
self.zombie.position.y = self.zombie.position.y + self.yd * 10
if (timeOfLastUpdate == nil) {
timeOfLastUpdate = currentTime
}
// print a message every 3 seconds
var timePassed = (currentTime - timeOfLastUpdate!)
if (timePassed >= 1.5) {
print("HERE IS A MESSAGE!")
timeOfLastUpdate = currentTime
// make a cat
self.makeCats()
}
// MARK: Check for collisions
// ---------------------------
// MARK: R1: detect collisions between zombie and old lady
var collisionDetected = self.zombie.intersects(self.enemy)
if (collisionDetected == true) {
// player dies
// --------
// 1. remove a life
self.lives = self.lives - 1
// 2. update the lives label
self.livesLabel.text = "Lives: \(self.lives)"
if (self.lives == 0) {
// DISPLAY THE YOU LOSE SCENE
let loseScene = GameOverScene(size: self.size)
// CONFIGURE THE LOSE SCENE
loseScene.scaleMode = self.scaleMode
// MAKE AN ANIMATION SWAPPING TO THE LOSE SCENE
let transitionEffect = SKTransition.flipHorizontal(withDuration: 2)
self.view?.presentScene(loseScene, transition: transitionEffect)
}
// player restarts in original position
// ---------------
self.zombie.position = CGPoint(x:150,
y:400)
// restart his xd & yd
// If you don't reset (xd,yd), the player
// will move in his original direction after this collision
self.xd = 0
self.yd = 0
}
// MARK: R2: detect collisions between zombie and cat
for (arrayIndex, cat) in cats.enumerated() {
if (self.zombie.intersects(cat) == true) {
print("CAT COLLISION DETECTED!")
// 1. increase the score
self.score = self.score + 1
self.scoreLabel.text = "Score: \(self.score)"
// 2. remove the cat from the scene
print("Removing cat at position: \(arrayIndex)")
// ---- 2a. remove from the array
self.cats.remove(at: arrayIndex)
// ---- 2b. remove from scene (undraw the cat)
if (self.score == 5) {
// DISPLAY THE YOU WIN SCENE
let winScene = GameOverScene(size: self.size)
// CONFIGURE THE WIN SCENE
winScene.scaleMode = self.scaleMode
// MAKE AN ANIMATION SWAPPING TO THE WIN SCENE
let transitionEffect = SKTransition.flipHorizontal(withDuration: 2)
self.view?.presentScene(winScene, transition: transitionEffect)
}
cat.removeFromParent()
}
}
// MARK: R3: Check for collisions between zombie & wall
if (self.zombie.position.x <= 50) {
// left of screen
self.xd = self.xd * -1
}
else if (self.zombie.position.x >= self.size.width-100) {
// right of screen
self.xd = self.xd * -1
}
else if (self.zombie.position.y <= 50) {
// botttom of screen
self.yd = self.yd * -1
}
else if (self.zombie.position.y >= self.size.height-100) {
// top of screen
self.yd = self.yd * -1
}
// if (self.zombie.intersects(self.cat) == true) {
// print("CAT COLLISION DETECTED!")
//
// }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let locationTouched = touches.first
if (locationTouched == nil) {
// This is error handling
// Sometimes the mouse detection doesn't work properly
// and IOS can't get the position.
return
}
let mousePosition = locationTouched!.location(in:self)
print("MOUSE X? \(mousePosition.x)")
print("MOUSE Y? \(mousePosition.y)")
print("------")
// calculate those math variables (d, xd, yd)
// (x2-x1)
let a = mousePosition.x - self.zombie.position.x
// (y2-y1)
let b = mousePosition.y - self.zombie.position.y
// d
let d = sqrt( (a*a) + (b*b))
self.xd = a/d
self.yd = b/d
}
// MARK: end of file
}
| true
|
2be332640f366ef33b7e03946e5bfcd34e3479f2
|
Swift
|
todanfifi46/hello-world
|
/8.15/week_1_part_1_v_1.playground/Contents.swift
|
UTF-8
| 696
| 4.09375
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
class Animal{
var species: String
init(species:String){
self.species = species
}
func makeSounds(){
}
}
class Lion : Animal {
//more safety
convenience init(){self.init(species:"Lion")}
override func makeSounds() {
print("roar")
}
}
class Dog : Animal{
convenience init(){self.init(species:"Dog")}
override func makeSounds(){
print("bark")
}
}
class Duck : Animal{
convenience init(){self.init(species:"Duck")}
override func makeSounds(){
print("quack")
}
}
let lion = Lion()
let dog = Dog()
let duck = Duck()
| true
|
f3cb879972d67c7ee4ee767cc7047388aa8cc5ea
|
Swift
|
ThePowerOfSwift/CoreKit
|
/Sources/CoreKit/Swift/String/String+UrlEscaped.swift
|
UTF-8
| 409
| 2.9375
| 3
|
[
"WTFPL"
] |
permissive
|
//
// String+UrlEscaped.swift
// CoreKit
//
// Created by Tibor Bödecs on 2017. 09. 27..
// Copyright © 2017. Tibor Bödecs. All rights reserved.
//
public extension String {
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
*/
public var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
}
}
| true
|
2f9ee92fc6a2a398a055ba6a60fd666a8f49286c
|
Swift
|
dagronf/DSFSparkline
|
/Sources/DSFSparkline/overlay/surfaces/DSFSparklineSurface+AttributedString.swift
|
UTF-8
| 3,711
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// DSFSparklineSurface+AttributedString.swift
// DSFSparklines
//
// Created by Darren Ford on 26/2/21.
// Copyright © 2021 Darren Ford. All rights reserved.
//
// MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// NSAttributedString extensions for DSFSparklineSurface.Bitmap
import CoreGraphics
import Foundation
public extension DSFSparklineSurface.Bitmap {
/// Returns an NSAttributedString containing an image of the sparkline
/// - Parameters:
/// - size: The dimensions of the image
/// - scale: The scale for the returned image. For example, for a retina scale (144dpi) image, scale == 2
/// - Returns: An NSAttributedString containing the sparkline bitmap, or nil if the bitmap couldn't be generated
@objc(attributedString::) func attributedString(size: CGSize, scale: CGFloat = 1) -> NSAttributedString? {
guard let attachment = self.textAttachment(size: size, scale: scale) else {
return nil
}
return NSAttributedString(attachment: attachment)
}
}
// MARK: - AppKit Additions
#if os(macOS)
import AppKit
public extension DSFSparklineSurface.Bitmap {
/// Returns a TextAttachment containing an image of the sparkline
/// - Parameters:
/// - size: The dimensions of the image
/// - scale: The scale for the returned image. For example, for a retina scale (144dpi) image, scale == 2
/// - Returns: An NSTextAttachment containing the sparkline bitmap, or nil if the bitmap couldn't be generated
@objc(textAttachment::) func textAttachment(size: CGSize, scale: CGFloat = 1) -> NSTextAttachment? {
guard let image = self.image(size: size, scale: scale) else {
return nil
}
let attachment = NSTextAttachment()
let flipped = NSImage(size: size, flipped: false, drawingHandler: { (rect: NSRect) -> Bool in
image.draw(in: rect)
return true
})
attachment.image = flipped
return attachment
}
}
#else
// MARK: - UIKit Additions
import UIKit
public extension DSFSparklineSurface.Bitmap {
/// Returns an NSTextAttachment containing an image of the sparkline
/// - Parameters:
/// - size: The dimensions of the image
/// - scale: The scale for the returned image. For example, for a retina scale (144dpi) image, scale == 2
/// - Returns: An NSTextAttachment containing the sparkline bitmap, or nil if the bitmap couldn't be generated
@objc(textAttachment::) func textAttachment(size: CGSize, scale: CGFloat = 1) -> NSTextAttachment? {
guard let image = self.image(size: size, scale: scale) else {
return nil
}
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
return attachment
}
}
#endif
| true
|
9eeadc0dda4366c34139f5d42249e2150ab34a39
|
Swift
|
Donrichard/Speech-Notes
|
/Speech Notes/ZeroNotesView.swift
|
UTF-8
| 1,526
| 2.84375
| 3
|
[] |
no_license
|
//
// ZeroNotesView.swift
// Speech Notes
//
// Created by Richard Richard on 02/04/18.
// Copyright © 2018 Richard Richard. All rights reserved.
//
import UIKit
class ZeroNotesView: UIView {
let noNotesLabel: UILabel = {
var label = UILabel()
label.isHidden = false
label.translatesAutoresizingMaskIntoConstraints = false
label.text = " No note created yet! "
label.font = .systemFont(ofSize: 24)
return label
}()
let noNotesEmoji: UILabel = {
var label = UILabel()
label.isHidden = false
label.translatesAutoresizingMaskIntoConstraints = false
label.text = " :( "
label.font = .systemFont(ofSize: 24)
label.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(noNotesLabel)
addSubview(noNotesEmoji)
setupConstraint()
}
private func setupConstraint() {
noNotesLabel.bottomAnchor.constraint(equalTo: centerYAnchor, constant: -2).isActive = true
noNotesLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
noNotesEmoji.topAnchor.constraint(equalTo: noNotesLabel.bottomAnchor).isActive = true
noNotesEmoji.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
4b9d5cae0d213b9409c05f1f7082e0124243754f
|
Swift
|
Jaboxa/Pagina
|
/Pagina/Pagina/Story tables/StoryEditViewController.swift
|
UTF-8
| 9,729
| 2.59375
| 3
|
[] |
no_license
|
//
// wController.swift
// Pagina
//
// Created by user on 2/8/18.
// Copyright © 2018 dogbird. All rights reserved.
//
import UIKit
import Firebase
class StoryEditViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
@IBOutlet weak var navbarTitle: UINavigationItem!
@IBOutlet weak var storyEditTextView: UITextView!
@IBOutlet weak var inspirationCollectionView: UICollectionView!
struct Inspiration {
var type:String = ""; //"image", "map", "text"
var id:String = "";
//Image
var imageUrl:String = "";
var image: UIImage? = nil;
//Map
var long:Double = 0.0;
var lat:Double = 0.0;
//Text
var text:String = "";
}
var storageRef: StorageReference!; // Firebase Storage
var ref:DatabaseReference!; //Firebase dbs
var inspirations:[Inspiration] = [];
var currentChapter:ChapterTableViewController.Chapter = ChapterTableViewController.Chapter();
// To save every so and so
var saveTextTimer: Timer!
var currentText = "";
var userid = ""
//Class
override func viewDidLoad() {
super.viewDidLoad()
if let user = Auth.auth().currentUser {
userid = user.uid;
} else {
// No user is signed in.
self.dismiss(animated: true, completion: nil); // What are you doing here? Get out!
}
ref = Database.database().reference();
storageRef = Storage.storage().reference();
fetchInspirations();
navbarTitle.title = currentChapter.title;
storyEditTextView.text = currentChapter.content;
currentText = storyEditTextView.text;
saveTextTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(saveText), userInfo: nil, repeats: true)
//Recognize taps and hides keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
tap.cancelsTouchesInView = false
storyEditTextView.addGestureRecognizer(tap)
}
override func viewWillDisappear(_ animated:Bool){
super.viewWillDisappear(true)
saveTextTimer.invalidate();
saveText();
currentChapter.content = currentText;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Keyboard
@objc func dismissKeyboard() {
storyEditTextView.endEditing(true); // Hides Keyboard
}
//Save to dbs
@objc func saveText(){
if storyEditTextView.text != currentText{
self.ref.child("users").child(userid).child("stories").child(currentChapter.storyid).child("chapters").child(currentChapter.id).updateChildValues(["text": self.storyEditTextView.text]);
currentText = storyEditTextView.text;
}
}
//Fetch from dbs
func fetchInspirations(){
ref.child("users").child(userid).child("stories").child(currentChapter.storyid).child("chapters").child(currentChapter.id).child("inspirations").observe(DataEventType.value, with: { (snapshot) in
self.inspirations.removeAll(keepingCapacity: false);
for child in snapshot.children.allObjects as! [DataSnapshot]{
let value = child.value as? NSDictionary;
var inspiration = Inspiration();
inspiration.type = value?["type"] as? String ?? "";
inspiration.id = child.key;
if inspiration.type == "text"{
inspiration.text = value?["text"] as? String ?? "";
}else if inspiration.type == "map"{
inspiration.long = value?["long"] as? Double ?? 0.0;
inspiration.lat = value?["lat"] as? Double ?? 0.0;
}else if inspiration.type == "image"{
inspiration.imageUrl = value?["url"] as? String ?? "";
}
self.inspirations.append(inspiration);
}
//fetch all images from storage
for i in 0..<self.inspirations.count{
if self.inspirations[i].type == "image"{
let storagePath = self.inspirations[i].imageUrl;
let imgRef = Storage.storage().reference(forURL: storagePath);
var image:UIImage?
imgRef.getData(maxSize: 15 * 1024 * 1024) { data, error in
if let error = error {
print(error)
} else {
image = UIImage(data: data!) ?? nil;
self.inspirations[i].image = image;
self.inspirationCollectionView.reloadData();
}
}
}
}
self.inspirationCollectionView.reloadData();
}) { (error) in
print(error.localizedDescription)
}
}
// Collection/Inspirations (Yes, we should have used a container view /similar for this)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return inspirations.count + 1 // +1 for add
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item >= inspirations.count{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addInspirationCell", for: indexPath) as! AddInspirationCollectionViewCell
return cell
}
if inspirations[indexPath.item].type == "image"{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageInspirationCell", for: indexPath) as! ImageInspirationCollectionViewCell
if let image = inspirations[indexPath.item].image {
cell.image.image = image;
}
return cell
}
if inspirations[indexPath.item].type == "text"{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "textInspirationCell", for: indexPath) as! TextInspirationCollectionViewCell
cell.inspirationTextView.text = inspirations[indexPath.item].text;
return cell
}
if inspirations[indexPath.item].type == "map"{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mapInspirationCell", for: indexPath) as! MapInspirationCollectionViewCell;
cell.setMap(long: inspirations[indexPath.item].long, lat: inspirations[indexPath.item].lat);
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ErrorInspirationCollectionViewCell
cell.myLabel.text = "error"
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: ((collectionView.bounds.size.width/3) - 5), height: collectionView.bounds.size.height);
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return CGFloat(5);
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item >= inspirations.count {
//???
}
else if inspirations[indexPath.item].type == "image"{
performSegue(withIdentifier: "zoomImageSegue", sender: indexPath.item)
}
else if inspirations[indexPath.item].type == "text"{
performSegue(withIdentifier: "zoomTextSegue", sender: indexPath.item)
}
else if inspirations[indexPath.item].type == "map"{
performSegue(withIdentifier: "zoomMapSegue", sender: indexPath.item)
}
}
//Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addInspirationSegue" {
if let inspiration = segue.destination as? AddInspirationViewController {
inspiration.currentChapter = currentChapter;
}
}else if segue.identifier == "zoomTextSegue"{
if let zoom = segue.destination as? TextZoomViewController {
if let i = sender as? Int {
zoom.currentChapter = currentChapter;
zoom.currentInspiration = inspirations[i];
}
}
}else if segue.identifier == "zoomMapSegue"{
if let zoom = segue.destination as? MapZoomViewController {
if let i = sender as? Int {
zoom.currentChapter = currentChapter;
zoom.currentInspiration = inspirations[i];
}
}
}else if segue.identifier == "zoomImageSegue"{
if let zoom = segue.destination as? ImageZoomViewController {
if let i = sender as? Int {
zoom.currentChapter = currentChapter;
zoom.currentInspiration = inspirations[i];
}
}
}
}
}
| true
|
ede8ae85a20893736e376e1119dd577eadeb3d72
|
Swift
|
PrinceWang-Cal/Eventure-iOS
|
/Eventure/Organization Account/Event Editor/TicketTypes.swift
|
UTF-8
| 4,435
| 2.53125
| 3
|
[] |
no_license
|
//
// TicketTypes.swift
// Eventure
//
// Created by Jia Rui Shan on 2019/9/17.
// Copyright © 2019 UC Berkeley. All rights reserved.
//
import UIKit
class TicketTypes: UITableViewController {
private var draftPage: EventDraft!
private var sortedAdmissionTypes = [AdmissionType]()
private var emptyLabel: UILabel!
required init(draftPage: EventDraft) {
super.init(nibName: nil, bundle: nil)
self.draftPage = draftPage
title = "Ticket Types"
view.backgroundColor = EventDraft.backgroundColor
sortedAdmissionTypes = draftPage.draft.admissionTypes.sorted { t1, t2 in
(t1.price ?? 0.0) >= (t2.price ?? 0.0)
}
}
func resortAndReload() {
sortedAdmissionTypes.sort { ($0.price ?? 0.0) >= ($1.price ?? 0.0) }
draftPage.draft.admissionTypes = sortedAdmissionTypes
emptyLabel.isHidden = !sortedAdmissionTypes.isEmpty
draftPage.edited = true
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
tableView.separatorStyle = .none
tableView.contentInset.top = 6
tableView.contentInset.bottom = 6
tableView.register(TicketTypeCell.classForCoder(), forCellReuseIdentifier: "ticket type")
navigationItem.rightBarButtonItem = .init(barButtonSystemItem: .add, target: self, action: #selector(addTicket))
emptyLabel = {
let label = UILabel()
label.isHidden = !draftPage.draft.admissionTypes.isEmpty
label.textAlignment = .center
label.textColor = .gray
label.text = "No tickets configured"
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
return label
}()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedAdmissionTypes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ticket type", for: indexPath) as! TicketTypeCell
let admission = sortedAdmissionTypes[indexPath.row]
cell.titleLabel.text = admission.typeName
cell.valueLabel.text = "$" + admission.priceDescription
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = TicketInfoEditor(parentVC: self, admissionInfo: sortedAdmissionTypes[indexPath.row])
navigationController?.pushViewController(vc, animated: true)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let action = UITableViewRowAction(style: .destructive, title: "Delete", handler: { (action, indexPath) in
let alert = UIAlertController(title: "Delete ticket type?", message: "There is no going back. User who have already purchased this type of ticket will be unaffected.", preferredStyle: .alert)
alert.addAction(.init(title: "Cancel", style: .cancel))
alert.addAction(.init(title: "Delete", style: .destructive, handler: {_ in
self.sortedAdmissionTypes.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
self.draftPage.draft.admissionTypes = self.sortedAdmissionTypes
self.draftPage.edited = true
}))
self.present(alert, animated: true)
})
action.backgroundColor = FATAL_COLOR
return [action]
}
@objc private func addTicket() {
let newType = AdmissionType.new
sortedAdmissionTypes.append(newType)
let vc = TicketInfoEditor(parentVC: self, admissionInfo: newType)
navigationController?.pushViewController(vc, animated: true)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| true
|
596c701e4484b1b301f452cbfe842a21a70f766a
|
Swift
|
cuba/PiuPiu
|
/Example/PewPewTests/URLTransformTests.swift
|
UTF-8
| 990
| 2.671875
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// URLTransformTests.swift
// PewPewTests
//
// Created by Jacob Sikorski on 2019-11-27.
// Copyright © 2019 Jacob Sikorski. All rights reserved.
//
import XCTest
import PiuPiu
class URLTransformTests: XCTestCase {
func testFromJSONTransform() {
let transform = URLTransform()
let json = "https://example.com"
do {
// When
let value = try transform.from(json: json, codingPath: [])
XCTAssertEqual(value, URL(string: "https://example.com")!)
} catch {
XCTFail(error.localizedDescription)
}
}
func testToJSONTransform() {
// Given
let transform = URLTransform()
let value = URL(string: "https://example.com")!
do {
// When
let json = try transform.toJSON(value, codingPath: [])
XCTAssertEqual(json, "https://example.com")
} catch {
XCTFail(error.localizedDescription)
}
}
}
| true
|
c6f782fc3d41ce7802584b8831db577534b7df94
|
Swift
|
GilbertNicholas/U-Cide
|
/U-Cide/Model/OptionsModel.swift
|
UTF-8
| 5,645
| 3.1875
| 3
|
[] |
no_license
|
//
// OptionsModel.swift
// U-Cide
//
// Created by Gilbert Nicholas on 04/05/21.
//
import Foundation
struct option {
var id: Int
var nextQuestion: Int
var optionLabel: String
static func getOptionsBasedOnQuestions(id: Int) -> [option] {
var chosenOption: [option] = []
var flag = 0
for option in optionList {
if(option.id == id) {
chosenOption.append(option)
flag += 1
}
if flag == 2 {
break
}
}
return chosenOption
}
}
var optionList: [option] = [
option(id: 0, nextQuestion: 1, optionLabel: "Unfortunately No.."),
option(id: 0, nextQuestion: 2, optionLabel: "Yes! I think so!!"),
option(id: 1, nextQuestion: 3, optionLabel: "Yeah.."),
option(id: 1, nextQuestion: 3, optionLabel: "Okay"),
option(id: 2, nextQuestion: 3, optionLabel: "Of Course!"),
option(id: 2, nextQuestion: 3, optionLabel: "Let's go!!"),
option(id: 3, nextQuestion: 4, optionLabel: "Ermm.."),
option(id: 3, nextQuestion: 4, optionLabel: "Understood!"),
option(id: 4, nextQuestion: 5, optionLabel: "Argh.."),
option(id: 4, nextQuestion: 5, optionLabel: "I love it!"),
option(id: 5, nextQuestion: 31, optionLabel: "I don't care.."),
option(id: 5, nextQuestion: 6, optionLabel: "Go to the crime scene!"),
option(id: 6, nextQuestion: 7, optionLabel: "Victim's body"),
option(id: 6, nextQuestion: 7, optionLabel: "Blood on the crime scene"),
option(id: 7, nextQuestion: 8, optionLabel: "Investigate the house keeper"),
option(id: 7, nextQuestion: 28, optionLabel: "Investigate Daniel, victim's ex-boyfriend"),
option(id: 8, nextQuestion: 9, optionLabel: "Investigate his alibi"),
option(id: 8, nextQuestion: 26, optionLabel: "Investigate Daniel, victim's ex-boyfriend"),
option(id: 9, nextQuestion: 10, optionLabel: "I need Daniel's information!"),
option(id: 9, nextQuestion: 10, optionLabel: "Investigate Daniel, victim's ex-boyfriend"),
option(id: 10, nextQuestion: 13, optionLabel: "Investigate Daniel’s alibi"),
option(id: 10, nextQuestion: 11, optionLabel: "Judge the murderer!"),
option(id: 11, nextQuestion: 12, optionLabel: "Housekeeper is the murderer"),
option(id: 11, nextQuestion: 12, optionLabel: "Of course Daniel the murderer!"),
option(id: 12, nextQuestion: -2, optionLabel: "Opps.."),
option(id: 12, nextQuestion: -2, optionLabel: "Oh no!"),
option(id: 13, nextQuestion: 14, optionLabel: "Check the crime scene"),
option(id: 13, nextQuestion: 19, optionLabel: "Hm? The housekeeper tell you something.."),
option(id: 14, nextQuestion: 15, optionLabel: "Check the suspects"),
option(id: 14, nextQuestion: 11, optionLabel: "Judge the murderer!"),
option(id: 15, nextQuestion: 16, optionLabel: "Judge the murderer!"),
option(id: 15, nextQuestion: 16, optionLabel: "I know who the murderer is.."),
option(id: 16, nextQuestion: 17, optionLabel: "Daniel!"),
option(id: 16, nextQuestion: 18, optionLabel: "The Housekeeper!"),
option(id: 17, nextQuestion: -2, optionLabel: "Oh no.."),
option(id: 17, nextQuestion: -2, optionLabel: "What??"),
option(id: 18, nextQuestion: -1, optionLabel: "Yeah!"),
option(id: 18, nextQuestion: -1, optionLabel: "I knew it!!"),
option(id: 19, nextQuestion: 21, optionLabel: "Suspicious.. no!"),
option(id: 19, nextQuestion: 20, optionLabel: "What is it? Let’s go!"),
option(id: 20, nextQuestion: -2, optionLabel: "..."),
option(id: 20, nextQuestion: -2, optionLabel: "R.I.P"),
option(id: 21, nextQuestion: 22, optionLabel: "Shoot him!"),
option(id: 21, nextQuestion: 23, optionLabel: "Chase him!"),
option(id: 22, nextQuestion: -2, optionLabel: "What??"),
option(id: 22, nextQuestion: -2, optionLabel: "Oh no.."),
option(id: 23, nextQuestion: 24, optionLabel: "Left!"),
option(id: 23, nextQuestion: 25, optionLabel: "Right!"),
option(id: 24, nextQuestion: -2, optionLabel: "Damn!"),
option(id: 24, nextQuestion: -2, optionLabel: "Oh no.."),
option(id: 25, nextQuestion: -1, optionLabel: "Yeah!"),
option(id: 25, nextQuestion: -1, optionLabel: "Hehe..!"),
option(id: 26, nextQuestion: 13, optionLabel: "Check his alibi"),
option(id: 26, nextQuestion: 27, optionLabel: "What’s the housekeeper alibi?"),
option(id: 27, nextQuestion: 14, optionLabel: "Check the crime scene"),
option(id: 27, nextQuestion: 19, optionLabel: "Hm? The housekeeper tell you something.."),
option(id: 28, nextQuestion: 11, optionLabel: "I am sure who is the murderer!"),
option(id: 28, nextQuestion: 29, optionLabel: "Investigate the house keeper"),
option(id: 29, nextQuestion: 30, optionLabel: "What’s your alibi?"),
option(id: 29, nextQuestion: 30, optionLabel: "I need your alibi!"),
option(id: 30, nextQuestion: 11, optionLabel: "I know the murderer!"),
option(id: 30, nextQuestion: 13, optionLabel: "Investigate Daniel’s alibi"),
option(id: 31, nextQuestion: 32, optionLabel: "No! I don’t want to do it!"),
option(id: 31, nextQuestion: 6, optionLabel: "Okay.. I’m going.."),
option(id: 32, nextQuestion: 6, optionLabel: "Actually no, I am going now.."),
option(id: 32, nextQuestion: 33, optionLabel: "Yeah!!"),
option(id: 33, nextQuestion: -2, optionLabel: "What??"),
option(id: 33, nextQuestion: -2, optionLabel: "Noo..."),
]
| true
|
afbef052f8efb2b416fab7c1b520dec31a414099
|
Swift
|
gongddong/GDONG-front
|
/GDONG/Cell/DetailCell/ContentTableViewCell.swift
|
UTF-8
| 1,439
| 2.703125
| 3
|
[] |
no_license
|
//
// ContentTableViewCell.swift
// GDONG
//
// Created by JoSoJeong on 2021/07/07.
//
import UIKit
class ContentTableViewCell: UITableViewCell {
static var identifier = "ContentTableViewCell"
@IBOutlet weak var frameView: UIView!
@IBOutlet weak var contentTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
UISetting()
calculate()
}
static func nib() -> UINib {
return UINib(nibName: "ContentTableViewCell", bundle: nil)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func UISetting(){
contentTextView.isUserInteractionEnabled = true
contentTextView.isSelectable = true
contentTextView.isEditable = false
print("원래 height")
print(contentView.height)
print(contentTextView.height)
//contentTextView.isScrollEnabled = false
}
func calculate(){
frameView.translatesAutoresizingMaskIntoConstraints = false
//2배 해줌
frameView.heightAnchor.constraint(equalToConstant: contentTextView.height / 2 + 50).isActive = true
print("height")
print(contentView.height)
print(contentTextView.height)
}
}
| true
|
1d5d5332b0e80ba9bdfa40e22515062f6ccfa30d
|
Swift
|
jsrc/uts-ios-2019-project3-group-188
|
/MyWardrobe/MyWardrobe/ComponentViewController/ComponentTabView.swift
|
UTF-8
| 2,276
| 2.875
| 3
|
[] |
no_license
|
//
// ComponentView.swift
// MyWardrobe
//
// Created by Bunlong on 25/5/19.
// Copyright © 2019 UTS. All rights reserved.
//
import UIKit
//method to create the tab color
extension UIImage {
class func itemTabColor(color: UIColor, size: CGSize) -> UIImage {
let frameColor = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(frameColor)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
class ComponentTabView: UITabBarController {
var tabItem = UITabBarItem()
override func viewDidLoad() {
super.viewDidLoad()
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.white], for: .selected)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.black], for: .normal)
setTabBarImage()
setTabColor()
}
// function to set image on tab bars
func setTabBarImage (){
let imageShirt = UIImage(named: "shirt")?.withRenderingMode(.alwaysOriginal)
tabItem = (self.tabBar.items?[0])!
tabItem.image = imageShirt
let imagePant = UIImage(named: "pant")?.withRenderingMode(.alwaysOriginal)
tabItem = (self.tabBar.items?[1])!
tabItem.image = imagePant
let imageHat = UIImage(named: "hat")?.withRenderingMode(.alwaysOriginal)
tabItem = (self.tabBar.items?[2])!
tabItem.image = imageHat
let imageShoes = UIImage(named: "shoes")?.withRenderingMode(.alwaysOriginal)
tabItem = (self.tabBar.items?[3])!
tabItem.image = imageShoes
self.selectedIndex = 0
}
//function to create tab color
func setTabColor() {
let tabNumber = CGFloat((tabBar.items?.count)!)
let tabSize = CGSize(width: tabBar.frame.width / tabNumber, height: 80)
tabBar.selectionIndicatorImage = UIImage.itemTabColor(color: #colorLiteral(red: 0.7515752951, green: 0.8359550695, blue: 1, alpha: 1), size: tabSize)
}
}
| true
|
616968b0671a8bf2dea4233ae9ad13101eff2b3b
|
Swift
|
natepill/Make-School-Projects
|
/MakeSchoolNotes-Swift-V2-Starter-swift4-coredata/MakeSchoolNotes/Controllers/DisplayNoteViewController.swift
|
UTF-8
| 2,296
| 3.046875
| 3
|
[] |
no_license
|
//
// DisplayNoteViewController.swift
// MakeSchoolNotes
//
// Created by Chris Orcutt on 1/10/16.
// Copyright © 2016 MakeSchool. All rights reserved.
//
import UIKit
class DisplayNoteViewController: UIViewController {
var note: Note?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 1
if let note = note {
// 2
titleTextField.text = note.title
contentTextView.text = note.content
} else {
// 3
titleTextField.text = ""
contentTextView.text = ""
}
}
// In our viewWillAppear() method, we check for an existing note in the note property to determine whether the user is displaying an existing note or creating a new one.
//
// Check the note property for an existing note using if-let optional binding.
// If the note property is non-nil, then our DisplayNoteViewController populates the text field and text view with the content of the existing note.
// If the note property is nil, then our DisplayNoteViewController clear the storyboard's lorem ipsum filler text so the user can quickly begin taking notes.
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var contentTextView: UITextView!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier
else{return}
switch identifier {
case "save" where note != nil:
note?.title = titleTextField.text ?? ""
note?.content = contentTextView.text ?? ""
note?.modificationTime = Date()
CoreDataHelper.saveNote()
case "save" where note == nil:
let note = CoreDataHelper.newNote()
note.title = titleTextField.text ?? ""
note.content = contentTextView.text ?? ""
note.modificationTime = Date()
CoreDataHelper.saveNote()
case "cancel":
print("cancel bar tapped")
default:
print("unindentified segue")
}
}
}
| true
|
ca7e9036d76608078c7f3ee60665d3ba9210e110
|
Swift
|
vzheng56/simpleWeather
|
/simpleWeather/ForecastService.swift
|
UTF-8
| 2,089
| 3.21875
| 3
|
[] |
no_license
|
//
// ForecastService.swift
// simpleWeather
//
// Created by 刘卫斌 on 15/11/28.
// Copyright © 2015年 yufu. All rights reserved.
//
import Foundation
protocol ForecastDelegate{
func GetCurrentWeather(weather:CurrentWeather?)
}
struct ForecastService {
let forecastAPIKey:String
let forcastBaseURL:NSURL?
var delegate:ForecastDelegate?
init(APIKey:String){
forecastAPIKey = APIKey
forcastBaseURL = NSURL(string: "https://api.forecast.io/forecast/\(forecastAPIKey)/")
}
func getForecast(lat:Double,lon:Double,completion:(CurrentWeather?->Void)){
if let forecastURL = NSURL(string: "\(lat),\(lon)", relativeToURL: forcastBaseURL) {
let networkOperation = NetworkOperation(url: forecastURL)
networkOperation.downloadJsonFromURL(){
(let JSONDictionary) in
if let currentWeather:CurrentWeather = self.currentWeatherFromJSONDictionary(JSONDictionary){
completion(currentWeather)
}
}
}
}
func getForecast(lat:Double,lon:Double){
if let forecastURL = NSURL(string: "\(lat),\(lon)", relativeToURL: forcastBaseURL) {
let networkOperation = NetworkOperation(url: forecastURL)
networkOperation.downloadJsonFromURL(){
(let JSONDictionary) in
if let currentWeather:CurrentWeather = self.currentWeatherFromJSONDictionary(JSONDictionary){
self.delegate?.GetCurrentWeather(currentWeather)
}
}
}
}
func currentWeatherFromJSONDictionary(jsonDictionary:[String:AnyObject])->CurrentWeather?{
if let currentWeatherDictionary = jsonDictionary["currently"] as? [String:AnyObject]{
return CurrentWeather(weatherDictionary: currentWeatherDictionary)
}else{
print("JSON dictionary return nil!!!")
return nil
}
}
}
| true
|
481d446d724bde37579ecc11b8ffc49193dc46a1
|
Swift
|
apple/swift-corelibs-foundation
|
/Darwin/Foundation-swiftoverlay/URL.swift
|
UTF-8
| 67,790
| 2.9375
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : __owned Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(macOS 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(macOS)
/// True if the resource is scriptable. Only applies to applications.
@available(macOS 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(macOS)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(macOS)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(macOS 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
let value = _values[.quarantinePropertiesKey]
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if value is NSNull {
return nil
} else {
return value as? [String : Any]
}
}
set {
// Use NSNull for nil, a special case for deleting quarantine
// properties
_set(.quarantinePropertiesKey, newValue: newValue ?? NSNull())
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
#if os(macOS) || os(iOS)
/// Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
/// Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
/// This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForImportantUsage: Int64? { return _get(.volumeAvailableCapacityForImportantUsageKey) }
/// Total available capacity in bytes for "Opportunistic" resources, including space expected to be cleared by purging non-essential and cached resources. "Opportunistic" means something that the user is likely to want but does not expect to be present on the local system, but is ultimately non-essential and replaceable. This would include items that will be created or downloaded without an explicit request from the user on the current device.
/// Examples: A background download of a newly available episode of a TV series that a user has been recently watching, a piece of content explicitly requested on another device, and a new document saved to a network server by the current user from another device.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForOpportunisticUsage: Int64? { return _get(.volumeAvailableCapacityForOpportunisticUsageKey) }
#endif
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if the volume supports clonefile(2).
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsFileCloning : Bool? { return _get(.volumeSupportsFileCloningKey) }
/// true if the volume supports renamex_np(2)'s RENAME_SWAP option.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsSwapRenaming : Bool? { return _get(.volumeSupportsSwapRenamingKey) }
/// true if the volume supports renamex_np(2)'s RENAME_EXCL option.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsExclusiveRenaming : Bool? { return _get(.volumeSupportsExclusiveRenamingKey) }
/// true if the volume supports making files immutable with isUserImmutable or isSystemImmutable.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var volumeSupportsImmutableFiles : Bool? { return _get(.volumeSupportsImmutableFilesKey) }
/// true if the volume supports setting POSIX access permissions with fileSecurity.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var volumeSupportsAccessPermissions : Bool? { return _get(.volumeSupportsAccessPermissionsKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(macOS 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(macOS 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if os(macOS) || os(iOS)
// true if ubiquitous item is shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousItemIsShared: Bool? { return _get(.ubiquitousItemIsSharedKey) }
// The current user's role for this shared item, or nil if not shared
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserRole: URLUbiquitousSharedItemRole? { return _get(.ubiquitousSharedItemCurrentUserRoleKey) }
// The permissions for the current user, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserPermissions: URLUbiquitousSharedItemPermissions? { return _get(.ubiquitousSharedItemCurrentUserPermissionsKey) }
// The name components for the owner, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemOwnerNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemOwnerNameComponentsKey) }
// The name components for the most recent editor, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemMostRecentEditorNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemMostRecentEditorNameComponentsKey) }
#endif
#if !os(macOS)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
private var _url: NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: __shared String) {
guard !string.isEmpty, let inner = NSURL(string: string) else { return nil }
_url = URL._converted(from: inner)
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: __shared String, relativeTo url: __shared URL?) {
guard !string.isEmpty, let inner = NSURL(string: string, relativeTo: url) else { return nil }
_url = URL._converted(from: inner)
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(macOS 10.11, iOS 9.0, *)
public init(fileURLWithPath path: __shared String, isDirectory: Bool, relativeTo base: __shared URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(macOS 10.11, iOS 9.0, *)
public init(fileURLWithPath path: __shared String, relativeTo base: __shared URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: __shared String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: __shared String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(macOS 10.11, iOS 9.0, *)
public init?(dataRepresentation: __shared Data, relativeTo url: __shared URL?, isAbsolute: Bool = false) {
guard !dataRepresentation.isEmpty else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, obsoleted: 4.2)
public init?(resolvingBookmarkData data: __shared Data, options: BookmarkResolutionOptions = [], relativeTo url: __shared URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, introduced: 4.2)
public init(resolvingBookmarkData data: __shared Data, options: BookmarkResolutionOptions = [], relativeTo url: __shared URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(macOS 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: __shared URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: __shared URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_url)
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(macOS 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(macOS 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(macOS 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
let path = (c.path as NSString).appendingPathComponent(pathComponent)
c.path = isDirectory ? path + "/" : path
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
guard !path.isEmpty, let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) else { return self }
return result
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
guard !path.isEmpty, let result = _url.appendingPathExtension(pathExtension) else { return self }
return result
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
guard !path.isEmpty, let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) else { return self }
return result
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
guard let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) else { return self }
return result
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
guard let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) else { return self }
return result
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
guard let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) else { return self }
return result
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(macOS 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(macOS 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(macOS 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(macOS 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
private init(reference: __shared NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference: NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : _CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "URL.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
extension URL : Codable {
private enum CodingKeys : Int, CodingKey {
case base
case relative
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let relative = try container.decode(String.self, forKey: .relative)
let base = try container.decodeIfPresent(URL.self, forKey: .base)
guard let url = URL(string: relative, relativeTo: base) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid URL string."))
}
self = url
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.relativeString, forKey: .relative)
if let base = self.baseURL {
try container.encode(base, forKey: .base)
}
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
| true
|
6409bc0b400a98b91008b92cd4bea84a2d0addab
|
Swift
|
AndrewFakher/Promises-Sample-App
|
/Promises-Demo/ParallelPromises.swift
|
UTF-8
| 2,466
| 3.0625
| 3
|
[] |
no_license
|
//
// ParallelPromises.swift
// Promises-Demo
//
// Created by Andrew on 8/29/20.
// Copyright © 2020 Andrew. All rights reserved.
//
import UIKit
import PromiseKit
class ParallelPromises: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var todosTableView: UITableView!
@IBOutlet weak var countriesTableView: UITableView!
let networker = Networker()
var countryList: [Country] = []
var todoList: [Todo] = []
override func viewDidLoad() {
super.viewDidLoad()
countriesTableView.dataSource = self
todosTableView.dataSource = self
getAllTodosAndCountries()
}
// Parallel Promises /////////////////////////////
func getAllTodosAndCountries(){
firstly {
when(fulfilled: networker.promiseFetchAllTodos(), networker.promiseFetchAllCountries())
}
.done { todoArray, countryArray in
self.todoList = todoArray
self.countryList = countryArray
self.countriesTableView.reloadData()
self.todosTableView.reloadData()
}.ensure {
self.activityIndicator.stopAnimating()
}.catch { error in
print("some kind of error listing all countries and todos -> \(error)")
}
}
}
extension ParallelPromises: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == todosTableView {
return todoList.count
}
else {
return countryList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = countriesTableView.dequeueReusableCell(withIdentifier: "ParallelPromisesCell")!
let cell2 = todosTableView.dequeueReusableCell(withIdentifier: "ParallelPromisesCell2")!
if tableView == todosTableView{
cell2.textLabel?.text = todoList[indexPath.row].title
return cell2
}
else {
cell.textLabel?.text = countryList[indexPath.row].name
return cell
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == todosTableView {
return "Todos List"
}else {
return "Countries List"
}
}
}
| true
|
861225da75855ef6069844259f7098ee097229e3
|
Swift
|
j11042004/LiveFilter
|
/FilterLive/ViewController.swift
|
UTF-8
| 2,108
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// FilterLive
//
// Created by Uran on 2019/6/25.
// Copyright © 2019 Uran. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var filterLiveView: FilterLiveView!
@IBOutlet weak var msgTextView: UITextView!
let streamURL = URL(string: "https://camerabaymbr-walkgame.cdn.hinet.net/walkgame-camerabaymbr/smil:cbch000066live4.smil/playlist.m3u8")!
let streamOtherURL = URL(string:"http://camerabaymbr-walkgame.cdn.hinet.net/walkgame-camerabaymbr/smil:cbsi000051auto.smil/playlist.m3u8")!
var currentPlayingUrl : URL!
override func viewDidLoad() {
super.viewDidLoad()
self.filterLiveView.liveDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
currentPlayingUrl = streamURL
self.filterLiveView.play(stream: currentPlayingUrl)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
segue.destination.preferredContentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2)
segue.destination.popoverPresentationController?.delegate = self
}
@IBAction func changeVideo(_ sender: Any) {
switch currentPlayingUrl {
case streamURL:
currentPlayingUrl = streamOtherURL
break
default:
currentPlayingUrl = streamURL
break
}
self.filterLiveView.play(stream: currentPlayingUrl)
}
}
extension ViewController : UIPopoverPresentationControllerDelegate{
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .formSheet
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
self.filterLiveView.play(stream: streamURL)
}
}
extension ViewController : FilterLiveDelegate{
func filterLiveGetQRCode(info: String?) {
self.msgTextView.text = info
}
}
| true
|
9ef1320a375c04202e139cf0f9ca534383466688
|
Swift
|
kevingduck/Pitch-Perfect
|
/Pitch Perfect/playSoundsViewController.swift
|
UTF-8
| 4,484
| 2.875
| 3
|
[] |
no_license
|
//
// playSoundsViewController.swift
// Pitch Perfect
//
// Created by Kevin Duck on 3/4/15.
// Copyright (c) 2015 Kevin Duck. All rights reserved.
//
import UIKit
import AVFoundation
class playSoundsViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
var receivedAudio:RecordedAudio!
var audioEngine:AVAudioEngine!
var audioFile:AVAudioFile!
override func viewDidLoad() {
super.viewDidLoad()
//Create AVAudioPlayer object with the audio file received from the previous view
audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filePathUrl, error: nil)
//Enable adjustment of audio playback rate
audioPlayer.enableRate = true
//Create AVAudioEngine object and prepare to set it up with the audio file to be read
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: receivedAudio.filePathUrl, error: nil)
}
override func viewWillDisappear(animated: Bool) {
audioFile = nil
}
//Play audio with adjusted pitch
func playAudioWithVariablePitch(pitch: Float) {
//Reset audioPlayer, engine to ensure it's not playing
audioPlayer.stop()
audioEngine.stop()
audioEngine.reset()
//Create player node object, attach to AVAudioEngine
var audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
//Create AVAudioUnitTimePitch and attach is to the engine
var changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
audioEngine.attachNode(changePitchEffect)
//Connect the node to the engine
audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil)
//Connect the AVAudioUnitTimePitch object to the engine
audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil)
//Prepare player node file's playback schedule
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
//Start audio engine
audioEngine.startAndReturnError(nil)
//Play back whatever the audioPlayerNode has
audioPlayerNode.play()
}
//Same as playAudioWithVariablePitch, but uses reverb effect instead of pitch adjustment
//TODO: reuse code, combine this function and playAudioWithVariablePitch if possible
func playAudioWithReverb() {
audioPlayer.stop()
audioEngine.stop()
audioEngine.reset()
var audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
var reverbEffect = AVAudioUnitReverb()
reverbEffect.wetDryMix = 90
audioEngine.attachNode(reverbEffect)
audioEngine.connect(audioPlayerNode, to: reverbEffect, format: nil)
audioEngine.connect(reverbEffect, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)
audioPlayerNode.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Audio plays back at 1.5x rate
@IBAction func playFastSound(sender: AnyObject) {
audioPlayer.stop()
audioPlayer.currentTime = 0.0
audioPlayer.enableRate = true
audioPlayer.rate = 1.5
audioPlayer.play()
}
//Audio plays back at 0.5x rate
@IBAction func playSlowSound(sender: AnyObject) {
audioPlayer.stop()
audioPlayer.currentTime = 0.0
audioPlayer.enableRate = true
audioPlayer.rate = 0.5
audioPlayer.play()
}
//Stop audio playback
@IBAction func stopPlayback(sender: AnyObject) {
audioPlayer.stop()
audioEngine.stop()
audioEngine.reset()
}
//Audio plays back with decreased pitch
@IBAction func playDarthAudio(sender: AnyObject) {
playAudioWithVariablePitch(-800)
}
//Audio plays back with increased pitch
@IBAction func playChipmunkAudio(sender: UIButton) {
playAudioWithVariablePitch(1000)
}
@IBAction func playReverbAudio(sender: UIButton) {
playAudioWithReverb()
}
}
| true
|
91279bfcc4ec6e74d7bd092959682a1de33ea328
|
Swift
|
MisakiChatani/syoryuken
|
/syoryuken/ViewController.swift
|
UTF-8
| 2,671
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// syoryuken
//
// Created by 茶谷美咲 on 2020/09/06.
// Copyright © 2020 Misaki Chatani. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var fristimage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var testView: UIView!
var imageArrayJump : Array<UIImage> = []
@IBOutlet var Imageattak: UIImageView!
// ボタンをタップしてanimation開始
@IBAction func StartBotton(_ sender: Any) {
// アニメーション用の画像
let image1 = UIImage(named:"attak1")!
let image2 = UIImage(named:"attak2")!
let image3 = UIImage(named:"attak3")!
let image4 = UIImage(named:"attak4")!
let image5 = UIImage(named:"attak5")!
let image6 = UIImage(named:"attak6")!
let image7 = UIImage(named:"attak7")!
let image8 = UIImage(named:"attak8")!
let image9 = UIImage(named:"attak9")!
let image10 = UIImage(named:"attak10")!
let image11 = UIImage(named:"attak11")!
let image12 = UIImage(named:"attak12")!
let image13 = UIImage(named:"attak13")!
let image14 = UIImage(named:"attak14")!
let image15 = UIImage(named:"attak15")!
let image16 = UIImage(named:"attak16")!
let image17 = UIImage(named:"attak17")!
let image18 = UIImage(named:"attak18")!
let image19 = UIImage(named:"attak19")!
let image20 = UIImage(named:"attak20")!
// 各要素を追加
imageArrayJump.append(image1)
imageArrayJump.append(image2)
imageArrayJump.append(image3)
imageArrayJump.append(image4)
imageArrayJump.append(image5)
imageArrayJump.append(image6)
imageArrayJump.append(image7)
imageArrayJump.append(image8)
imageArrayJump.append(image9)
imageArrayJump.append(image10)
imageArrayJump.append(image11)
imageArrayJump.append(image12)
imageArrayJump.append(image13)
imageArrayJump.append(image14)
imageArrayJump.append(image15)
imageArrayJump.append(image16)
imageArrayJump.append(image17)
imageArrayJump.append(image18)
imageArrayJump.append(image19)
imageArrayJump.append(image20)
//画像Arrayをアニメーションにセット
Imageattak.animationImages = imageArrayJump
//間隔(秒単位)
Imageattak.animationDuration = 3
// 繰り返し
Imageattak.animationRepeatCount = 1
// アニメーションを開始
Imageattak.startAnimating()
}
}
| true
|
d504b92734689ea2a4aa773c87f201be80078a4c
|
Swift
|
ashubaweja1/McKinley
|
/Test/UserDefaultHelper.swift
|
UTF-8
| 794
| 2.703125
| 3
|
[] |
no_license
|
//
// UserDefaultHelper.swift
// Test
//
// Created by Ashu Baweja on 20/05/20.
// Copyright © 2020 Ashu Baweja. All rights reserved.
//
import Foundation
class UserDefaultHelper {
class func set(_ value : Any?, forkey key : String) {
if let value = value {
UserDefaults.standard.set(value, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
UserDefaults.standard.synchronize()
}
class func get(_ key : String) -> Any? {
return UserDefaults.standard.object(forKey: key)
}
class func setToken(token: String) {
UserDefaultHelper.set(token, forkey: kToken)
}
class func getToken() -> String? {
return (UserDefaultHelper.get(kToken) as? String)
}
}
| true
|
03433a705999749fb6a2b7f4bc0abc3d10dc5c07
|
Swift
|
distributed-contact-tracing/contact-tracing-peer
|
/src/Models/ActivePeripheral.swift
|
UTF-8
| 3,139
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// ActivePeripheral.swift
// DistContactTracing
//
// Created by Axel Backlund on 2020-04-04.
//
import Foundation
import CoreBluetooth
import Combine
class ActivePeripheral: Identifiable, ObservableObject {
let objectWillChange = ObservableObjectPublisher()
let peripheral: CBPeripheral
let id: String
var interaction: Interaction?
var sentHandshakeToken: String? {
didSet {
objectWillChange.send()
addToCoreData()
}
}
var receivedHandshakeToken: String? {
didSet {
objectWillChange.send()
addToCoreData()
}
}
var signalStrengths: [NSNumber] {
didSet {
objectWillChange.send()
updateCoreData()
}
}
var timestamps: [Date] {
didSet {
objectWillChange.send()
updateCoreData()
}
}
init(signalStrength: NSNumber, peripheral: CBPeripheral, initialTimestamp: Date) {
self.peripheral = peripheral
self.timestamps = [initialTimestamp]
self.signalStrengths = [signalStrength]
self.id = peripheral.identifier.uuidString
}
func shouldUseSentToken() -> Bool? {
if sentHandshakeToken != nil || receivedHandshakeToken != nil {
// TODO: Are we sure the sent token is received?
guard let sentToken = sentHandshakeToken else { return false }
guard let receivedToken = receivedHandshakeToken else { return true }
guard let sentTokenObject = TokenManager().tokenFrom(string: sentToken) else { return nil }
guard let receivedTokenObject = TokenManager().tokenFrom(string: receivedToken) else { return nil }
return sentTokenObject.timestamp >= receivedTokenObject.timestamp
} else {
return nil
}
}
func severity() -> Float {
return 0
}
private func addToCoreData() {
if (sentHandshakeToken != nil || receivedHandshakeToken != nil) && interaction == nil {
do {
if let useSentToken = shouldUseSentToken() {
let tokenToUse = useSentToken ? sentHandshakeToken : receivedHandshakeToken
guard let hash = tokenToUse?.sha256() else { return }
print("HASH:", hash)
let storedInteraction = try StorageManager.shared.insertInteraction(id: hash, severity: severity())
interaction = storedInteraction
}
} catch (let e) {
print(e.localizedDescription)
}
}
}
private func updateCoreData() {
if let storedInteraction = interaction {
do {
try StorageManager.shared.update(storedInteraction, with: severity())
} catch let e {
print(e.localizedDescription)
}
}
}
}
extension ActivePeripheral: Equatable {
static func ==(lhs: ActivePeripheral, rhs: ActivePeripheral) -> Bool {
return lhs.peripheral == rhs.peripheral
}
}
| true
|
3f6236378383a9cf976fcb26a32c4ec73c29456e
|
Swift
|
gowdham-k/CatchUp_Chat_Productivity
|
/Catch Up/Supporting files/BorderedLabel.swift
|
UTF-8
| 1,297
| 2.796875
| 3
|
[] |
no_license
|
//
// BorderedLabel.swift
// Catch Up
//
// Created by Paramesh V on 11/07/19.
// Copyright © 2019 CZ Ltd. All rights reserved.
//
import Foundation
import UIKit
//class BorderedLabel: UILabel {
// var sidePadding = CGFloat(1) // Needed padding, add property observers
//
// override func sizeToFit() {
// super.sizeToFit()
//// bounds.size.width += 2 * sidePadding
// }
//
// override func drawText(in rect: CGRect) {
// print(rect)
// super.drawText(in: rect.insetBy(dx: sidePadding, dy: 0))
// invalidateIntrinsicContentSize()
// }
//}
@IBDesignable class BorderedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
}
| true
|
ac00f04017c3c51871d5c9d61b889b2558d29010
|
Swift
|
K-Y-31/YoutubePlayer-1
|
/YoutubePlayer/FetchUserInfo/FetchUserModelinFireStore.swift
|
UTF-8
| 1,823
| 2.734375
| 3
|
[] |
no_license
|
//
// FetchUserModelinFireStore.swift
// YoutubePlayer
//
// Created by 木本瑛介 on 2021/06/17.
//
import Foundation
import SwiftUI
import Firebase
import FirebaseFirestore
import FirebaseAuth
class FetchUserModelinFireStore: ObservableObject {
@Published var usermodellist: [UserModel] = [UserModel]()
init() {
fetchuserModelinFireStore()
}
private func fetchuserModelinFireStore() {
Firestore.firestore().collection("users").getDocuments { (snapshots, error) in
if let error = error {
print("Failed getting user info to FireStore: \(error)")
return
}
snapshots?.documents.forEach({ (snapshot) in
let data = snapshot.data()
var user = UserModel(dic: data)
user.uid = snapshot.documentID
guard let uid = Auth.auth().currentUser?.uid else { return }
if (uid == snapshot.documentID) {
return
}
Firestore.firestore().collection("users").document(uid).getDocument { (snapshot, error) in
if let error = error {
print("Failed getting snapshot: \(error)")
return
}
let frienddata = snapshot?.data()
let frienduser = UserModel(dic: frienddata!)
print(frienduser.uid, snapshot?.documentID)
if (frienduser.uid == snapshot?.documentID) {
print(frienduser.uid, snapshot?.documentID)
return
}
else {
self.usermodellist.append(user)
}
}
})
}
}
}
| true
|
c6ed58a638703457ec9d7f515ce23b4212ac4ac8
|
Swift
|
arjunpa/ToDo
|
/Todo/ImagePickHandler.swift
|
UTF-8
| 1,963
| 3.03125
| 3
|
[] |
no_license
|
//
// ImagePickHandler.swift
// Todo
//
// Created by Arjun P A on 25/06/20.
// Copyright © 2020 Arjun P A. All rights reserved.
//
import UIKit
final class ImagePickHandler {
let quality: CGFloat
private enum Errors: Error {
case noDirectoryFound
}
private let imageDirectoryName = "images"
private var imagePath: String {
return "/" + self.imageDirectoryName + "/" + UUID().uuidString
}
private let pathGenerator: DirectoryPathGenerator
init(pathGenerator: DirectoryPathGenerator, quality: CGFloat) {
self.quality = quality
self.pathGenerator = pathGenerator
}
func handleImage(from info: Any, completion: (Result<String, Error>) -> ()) {
guard let info = info as? [UIImagePickerController.InfoKey : Any],
let originalImage = info[.originalImage] as? UIImage
else { return }
do {
try self.checkAndCreateDirectoryIfRequired()
let imagePath = self.imagePath
let url = self.pathGenerator.buildURL(for: imagePath)
try originalImage.jpegData(compressionQuality: self.quality)?.write(to: url)
completion(.success(imagePath))
} catch let error {
completion(.failure(error))
}
}
private func checkAndCreateDirectoryIfRequired() throws {
let directoryURL = self.pathGenerator.buildURL(for: self.imageDirectoryName)
var isDirectory: ObjCBool = false
if FileManager.default.fileExists(atPath: directoryURL.path, isDirectory: &isDirectory) {
guard !isDirectory.boolValue else { return }
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} else {
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
}
}
}
| true
|
289684648c189fd44972932933c9383814fd60bf
|
Swift
|
danielgarciasantos/curso-ios
|
/TodoDocker/TodoDocker/Model/Tasks.swift
|
UTF-8
| 1,029
| 2.65625
| 3
|
[] |
no_license
|
//
// Tasks.swift
// TodoDocker
//
// Created by Daniel Garcia on 07/12/2017.
// Copyright © 2017 Daniel Garcia. All rights reserved.
//
import Foundation
import EasyRest
import Genome
class Task: BaseModel {
var count: Int?
var next: String?
var previous: String?
var results : [Result]?
override func sequence(_ map: Map) throws {
try count <~> map["count"]
try next <~ map["next"]
try previous <~ map["previous"]
try results <~ map["results"]
}
}
class Result: BaseModel {
var id: String?
var expiration_date: String?
var title: String?
var descriptionn: String?
var is_complete: Bool?
var id_owner : String?
override func sequence(_ map: Map) throws {
try id <~> map["id"]
try expiration_date <~> map["expiration_date"]
try title <~> map["title"]
try descriptionn <~> map["description"]
try is_complete <~> map["is_complete"]
try id_owner <~> map["id_owner"]
}
}
| true
|
b41d4f91a417f69b2f4548b090c299c8520d715a
|
Swift
|
JVGraupera/Shoot-Out
|
/SHOOT OUT/People & Things/Short.swift
|
UTF-8
| 1,013
| 3.140625
| 3
|
[] |
no_license
|
//
// Short.swift
// SHOOT OUT
//
// Created by james graupera on 12/17/19.
// Copyright © 2019 James' Games. All rights reserved.
//
import Foundation
import SpriteKit
class Short: SKSpriteNode {
init(X: Double, Y: Double) {
let texture = SKTexture(imageNamed: "short")
super.init(texture: texture, color: .clear, size: texture.size())
self.size = CGSize(width: 100, height: 100)
self.position = CGPoint(x: X, y: Y)
self.scaleTo(screenWidthPercentage: 0.035)
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
self.physicsBody?.affectedByGravity = false
self.physicsBody?.categoryBitMask = PhysicsCategory.short
self.physicsBody?.contactTestBitMask = PhysicsCategory.bullet
self.physicsBody?.collisionBitMask = PhysicsCategory.cac
self.physicsBody?.isDynamic = false
self.name = "short"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
afbf1b8ac5f4e9461a3a3c9f9afd5696eed64644
|
Swift
|
onmyway133/Github.swift
|
/Carthage/Checkouts/Tailor/TailorTests/Shared/TestInspectable.swift
|
UTF-8
| 1,525
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
import Tailor
class TestInspectable: XCTestCase {
func testInspectableOnClass() {
let firstName = "Taylor"
let lastName = "Swift"
let sex = Sex.Female
let person = TestPersonClass()
person.firstName = firstName
person.lastName = lastName
person.sex = sex
XCTAssertEqual(firstName, person.firstName)
XCTAssertEqual(firstName, person.property("firstName"))
XCTAssertEqual(lastName, person.lastName)
XCTAssertEqual(lastName, person.property("lastName"))
XCTAssertEqual(sex, person.sex)
XCTAssertEqual(sex, person.property("sex"))
}
func testInspectableOnStruct() {
let firstName = "Taylor"
let lastName = "Swift"
let sex = Sex.Female
var person = TestPersonStruct([:])
person.firstName = firstName
person.lastName = lastName
person.sex = sex
XCTAssertEqual(firstName, person.firstName)
XCTAssertEqual(firstName, person.property("firstName"))
XCTAssertEqual(lastName, person.lastName)
XCTAssertEqual(lastName, person.property("lastName"))
XCTAssertEqual(sex, person.sex)
XCTAssertEqual(sex, person.property("sex"))
}
func testNestedAttributes() {
let data: [String : AnyObject] = ["firstName" : "Taylor",
"lastName" : "Swift",
"sex": "female",
"birth_date": "2014-07-15"]
var parent = TestPersonStruct(data)
var clone = parent
clone.firstName += " + Clone"
parent.relatives.append(clone)
XCTAssertEqual(parent.property("relatives.0"), clone)
}
}
| true
|
6e9f01f95ef3df793ed8d4d8f5741380759c1610
|
Swift
|
jdebecka/SwiftLivecoding
|
/mvcSample/mvcSample/Controller/Networking/WeatherImage.swift
|
UTF-8
| 1,561
| 2.890625
| 3
|
[] |
no_license
|
//
// WeatherImage.swift
// mvcSample
//
// Created by Julia Debecka on 17/04/2020.
// Copyright © 2020 lpb. All rights reserved.
//
import Foundation
import Alamofire
import UIKit
import AlamofireImage
enum WeatherImageAPI {
case imageFor(String)
private var basePath: String {
return "https://openweathermap.org"
}
var path: String {
return basePath + endpoint + imageCode + "@2x.png"
}
var imageCode: String {
switch self {
case .imageFor(let code):
return code
}
}
var url: URL? {
return URL(string: path)
}
var endpoint: String {
return "/img/wn/"
}
}
struct ImageRepository {
static func getImage(for code: String, completion: @escaping ((UIImage?) -> Void)) {
execureRequest(.imageFor(code), completion: completion)
}
private static func execureRequest(_ request: WeatherImageAPI,
completion: @escaping ((UIImage?) -> Void)) {
guard let requestUrl = request.url else { return }
AF.request(requestUrl).responseImage(completionHandler: { (response) in
if let data = response.data {
let image = UIImage(data: data)
DispatchQueue.main.async {
completion(image)
}
}else {
DispatchQueue.main.async {
completion(UIImage(systemName: "Cloud.sun"))
}
}
})
}
}
| true
|
08553839ecea6e31915c3c668c9814851a33caa2
|
Swift
|
wanruu/FYP
|
/CUMap Collect/CUMap Collect/Pages/BusPage/NewBusView.swift
|
UTF-8
| 5,152
| 2.671875
| 3
|
[] |
no_license
|
import SwiftUI
struct NewBusView: View {
@Binding var locations: [Location]
@Binding var buses: [Bus]
@State var id = ""
@State var nameEn = ""
@State var nameZh = ""
@State var serviceDay = ServiceDay.ordinaryDay
@State var startTime = Date()
@State var endTime = Date()
@State var departTime: [Int] = []
@State var curDepartTime = ""
@State var chosenStops: [Location] = []
@State var showStopList: Bool = false
@Binding var showing: Bool
var body: some View {
List {
Section(header: Text(NSLocalizedString("basic", comment: ""))) {
TextField("ID", text: $id)
TextField(NSLocalizedString("English name", comment: ""), text: $nameEn)
TextField(NSLocalizedString("Chinese name", comment: ""), text: $nameZh)
}
Section(header: Text(NSLocalizedString("service", comment: ""))) {
Picker(selection: $serviceDay, label: Text("Service Day")) {
Text(NSLocalizedString("Mon - Sat", comment: "")).tag(ServiceDay.ordinaryDay)
Text(NSLocalizedString("Sun & public holidays", comment: "")).tag(ServiceDay.holiday)
Text(NSLocalizedString("Mon - Sat", comment: "") + " " + NSLocalizedString("non-teaching days", comment: "")).tag(ServiceDay.ordinaryNotTeachingDay)
Text(NSLocalizedString("teaching days only", comment: "")).tag(ServiceDay.teachingDay)
}
DatePicker(NSLocalizedString("start at", comment: ""), selection: $startTime, displayedComponents: .hourAndMinute)
DatePicker(NSLocalizedString("end at", comment: ""), selection: $endTime, displayedComponents: .hourAndMinute)
}
Section(header: Text(NSLocalizedString("departs hourly at (mins)", comment: ""))) {
ForEach(departTime) { depart in
Text(String(depart))
}.onDelete(perform: { index in
departTime.remove(at: index.first!)
})
HStack {
TextField("", text: $curDepartTime).keyboardType(.numberPad)
Button(action: {
departTime.append(Int(curDepartTime)!)
curDepartTime = ""
// TODO: hide keyboard
}) {
Text(NSLocalizedString("button.add", comment: ""))
}.disabled(curDepartTime.isEmpty || Int(curDepartTime) == nil || Int(curDepartTime)! < 0 || Int(curDepartTime)! > 60)
}
}
Section(header: Text(NSLocalizedString("bus stops", comment: ""))) {
ForEach(chosenStops) { stop in
Text(stop.nameEn)
}.onDelete(perform: { index in
chosenStops.remove(at: index.first!)
})
NavigationLink(destination: StopListArrayView(locations: $locations, chosenStops: $chosenStops, showing: $showStopList), isActive: $showStopList) {
HStack {
Image(systemName: "plus.circle.fill").imageScale(.large).foregroundColor(.green)
Text(NSLocalizedString("new", comment: ""))
}
}
}
Button(action: {
createBus()
id = ""
nameEn = ""
nameZh = ""
serviceDay = .ordinaryDay
departTime = []
chosenStops = []
}) {
HStack {
Spacer()
Text(NSLocalizedString("button.confirm", comment: ""))
Spacer()
}
}
.disabled(id.isEmpty || nameEn.isEmpty || departTime.isEmpty)
}
.listStyle(GroupedListStyle())
.navigationTitle(Text(NSLocalizedString("new.route", comment: "")))
}
private func createBus() {
let bus = Bus(id: id, line: id, nameEn: nameEn, nameZh: nameZh, serviceHour: ServiceHour(startTime: startTime, endTime: endTime), serviceDay: serviceDay, departTime: departTime, stops: chosenStops)
let busResponse = bus.toBusResponse()
let jsonData = try? JSONEncoder().encode(busResponse)
let url = URL(string: server + "/bus")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = jsonData
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else { return }
do {
let bus = try JSONDecoder().decode(BusResponse.self, from: data)
buses.append(bus.toBus(locations: locations))
showing.toggle()
} catch let error {
print(error)
}
}.resume()
}
}
| true
|
3ff7c78bb56b0f180bd09ee1994a23be9dac1896
|
Swift
|
rcarlsen/Pocket-Earth-GPS-Merge
|
/Pocket Earth GPS Merge/GPXDocument.swift
|
UTF-8
| 3,314
| 2.546875
| 3
|
[] |
no_license
|
//
// GPXDocument.swift
// Pocket Earth GPS Merge
//
// Created by Robert Carlsen on 8/31/15.
// Copyright © 2015 Robert Carlsen. All rights reserved.
//
import Foundation
public class GPXDocumentMerge {
private(set) var trackDocument: NSXMLDocument?
private(set) var routeDocument: NSXMLDocument?
var loggingLevel = LogLevel.None
init?(trackURL track: NSURL, routeURL route: NSURL) {
do {
trackDocument = try NSXMLDocument(contentsOfURL: track, options: 0)
routeDocument = try NSXMLDocument(contentsOfURL: route, options: 0)
}
catch let error as NSError {
print("unable to parse xml file: \(error.localizedDescription)")
return nil
}
}
}
extension GPXDocumentMerge {
// returns a copy of the passed in elements
internal class func convertRoutePointsToWaypoints(routePoints: [NSXMLElement], logLevel: LogLevel = .None) -> [NSXMLElement] {
if logLevel >= .Info {
print("processing route points...")
}
var convertedPoints = [NSXMLElement]()
for routePoint in routePoints {
let waypoint: NSXMLElement = routePoint.copy() as! NSXMLElement
waypoint.name = "wpt"
convertedPoints.append(waypoint)
if logLevel >= .Debug {
print("converted route point to waypoint: \(waypoint.description)")
}
}
return convertedPoints
}
// returns a modified copy of the passed in element
internal class func convertCommentToDescription(waypointElement: NSXMLElement, logLevel: LogLevel = .None) -> NSXMLElement {
if logLevel >= .Debug {
print("converting waypoint comment to description...")
}
let waypoint: NSXMLElement = waypointElement.copy() as! NSXMLElement
if let commentElement = waypoint.elementsForName("cmt").first {
commentElement.name = "desc"
}
return waypoint
}
// returns a spliced copy of the track document
internal class func spliceWaypoints(waypoints: [NSXMLNode], trackDoc: NSXMLDocument, logLevel: LogLevel = .None) -> NSXMLDocument {
if logLevel >= .Info {
print("splicing waypoints into track file...")
}
let trackDocCopy = trackDoc.copy() as! NSXMLDocument
if let root = trackDocCopy.rootElement() {
root.insertChildren(waypoints, atIndex: (root.childCount > 0) ? root.childCount - 1 : 0)
}
if logLevel >= .Info {
print("...finished!")
}
return trackDocCopy
}
var mergedDocument: NSXMLDocument? {
if let routePoints = routeDocument?.rootElement()?.elementsForName("rte").first?.elementsForName("rtept") {
let waypoints = GPXDocumentMerge.convertRoutePointsToWaypoints(routePoints, logLevel:loggingLevel)
if loggingLevel >= .Info {
print("modifying waypoint comments...")
}
let modifiedWaypoints = waypoints.map({ waypoint in
return GPXDocumentMerge.convertCommentToDescription(waypoint, logLevel: loggingLevel)
})
return GPXDocumentMerge.spliceWaypoints(modifiedWaypoints, trackDoc: trackDocument!, logLevel: loggingLevel)
}
return nil
}
}
| true
|
4017c4519a23617cb882834b0f4ac230dc684e33
|
Swift
|
virgilius-santos/PirataSwift
|
/Pirata/Model/enum/Orientation.swift
|
UTF-8
| 536
| 3.40625
| 3
|
[] |
no_license
|
import Foundation
struct Orientation: Equatable {
static let horizontal = Orientation(
value: 0,
internWall: { row, col, indice in Index(col: col+indice, row: row) }
)
static let vertical = Orientation(
value: 1,
internWall: { row, col, indice in Index(col: col, row: row+indice) }
)
static func == (lhs: Orientation, rhs: Orientation) -> Bool {
lhs.value == rhs.value
}
let value: Int
let internWall: (_ row: Int, _ col: Int, _ indice: Int) -> Index
}
| true
|
cc0dbda7fb8a84dcef5d8c9ee323d996c80ebf4a
|
Swift
|
gufo/slack-sourcing
|
/Sources/SlackSourcingCore/SourcingAPI/SourcingCase.swift
|
UTF-8
| 607
| 2.65625
| 3
|
[] |
no_license
|
import Foundation
class SourcingCase: Decodable {
var id: String
var isArchived: Bool
var customer: String
var suggestedConsultants: [String]?
var proposedConsultants: [String]?
enum CodingKeys: String, CodingKey {
case id = "_id"
case isArchived
case customer
case suggestedConsultants
case proposedConsultants
}
func containsConsultant(_ consultant: SourcingConsultant) -> Bool {
let allConsultants = (suggestedConsultants ?? []) + (proposedConsultants ?? [])
return allConsultants.contains(consultant.id)
}
}
| true
|
35c2f4d3d4f4b3a23a0093234e685a399aa09e86
|
Swift
|
yuchao-chen/RemindMe
|
/RemindMe/Model/Task.swift
|
UTF-8
| 2,539
| 3.03125
| 3
|
[] |
no_license
|
//
// Task.swift
// RemindMe
//
// Created by Yuchao CHEN on 7/6/19.
// Copyright © 2019 Yuchao CHEN. All rights reserved.
//
import Foundation
import os.log
struct Task: Equatable {
// MARK: Properties
var title: String
var notes: String?
var timestamp: Double?
var location: Location?
// MARK: Types
struct PropertyKey {
static let title = "title"
static let notes = "notes"
static let timestamp = "timestamp"
static let altitude = "altitude"
static let latitude = "latitude"
static let longitude = "longitude"
}
var plist: [String: Any] {
var d = [String: Any]()
d[PropertyKey.title] = title
d[PropertyKey.notes] = notes
d[PropertyKey.timestamp] = timestamp
if let location = location {
d[PropertyKey.latitude] = location.coordinate.latitude
d[PropertyKey.longitude] = location.coordinate.longitude
d[PropertyKey.altitude] = location.altitude
}
return d
}
// MARK: Initialization
init(title: String, notes: String? = nil, timestamp: Double? = nil, location: Location? = nil) {
self.title = title
self.notes = notes
// if timestamp is not given, timestamp is automatically generated
self.timestamp = timestamp ?? NSDate().timeIntervalSince1970
self.location = location
}
init?(dict: [String: Any]) {
guard let title = dict[PropertyKey.title] as? String else { return nil }
let notes = dict[PropertyKey.notes] as? String
let timestamp = dict[PropertyKey.timestamp] as? Double
let location: Location?
if let lat = dict[PropertyKey.latitude] as? Double,
let lon = dict[PropertyKey.longitude] as? Double,
let alt = dict[PropertyKey.altitude] as? Double {
location = Location(latitude: lat, longitude: lon, altitude: alt)
} else {
location = nil
}
self.title = title
self.notes = notes
self.timestamp = timestamp
self.location = location
}
// MARK: Equatable
public static func == (l: Task, r: Task) -> Bool {
if l.title != r.title {
return false
}
if l.notes != r.notes {
return false
}
if l.timestamp != r.timestamp {
return false
}
if l.location != r.location {
return false;
}
return true
}
}
| true
|
8d82f97ec245bebfd5be9ba72005d934c3ab36f2
|
Swift
|
carolynlea/Q-and-A
|
/Q&A/ViewControllers/AnswerQuestionViewController.swift
|
UTF-8
| 1,256
| 2.609375
| 3
|
[] |
no_license
|
//
// AnswerQuestionViewController.swift
// Q&A
//
// Created by Carolyn Lea on 7/30/18.
// Copyright © 2018 Carolyn Lea. All rights reserved.
//
import UIKit
class AnswerQuestionViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var askerLabel: UILabel!
@IBOutlet weak var answererNameTextfield: UITextField!
@IBOutlet weak var answerTextView: UITextView!
var questionController = QuestionController()
var question: Question?
override func viewWillAppear(_ animated: Bool) {
updateViews()
}
@IBAction func submitAnswer(_ sender: Any) {
guard let answererName = answererNameTextfield.text,
let answer = answerTextView.text else {return}
//questionController.updateWithAnswer(with: question!, answer: answer, answerer: answererName)
questionController.updateQuestion(with: question!, aQuestion: (question?.aQuestion)!, asker: (question?.asker)!, answer: answer, answerer: answererName)
navigationController?.popViewController(animated: true)
}
func updateViews() {
questionLabel.text = question?.aQuestion
askerLabel.text = question?.asker
}
}
| true
|
f09945693087d19924ffd771c76881750829fc79
|
Swift
|
ruanvictorreis/movies-database
|
/TMDBTests/Source/Features/MovieDetails/MovieDetailsSpec.swift
|
UTF-8
| 3,948
| 2.609375
| 3
|
[] |
no_license
|
//
// MovieDetailsSpec.swift
// TMDBTests
//
// Created by Ruan Reis on 20/07/20.
// Copyright © 2020 Ruan Reis. All rights reserved.
//
import Quick
import Nimble
@testable import TMDB
class MovieDetailsSpec: QuickSpec {
override func spec() {
var viewController: MovieDetailsViewControllerMock!
describe("Movie Details") {
context("Given that the MovieDetails scene has initialized") {
it("All components of the architecture must be initialized") {
let interactor = MovieDetailsInteractor()
expect(interactor).notTo(beNil())
let presenter = MovieDetailsPresenter()
expect(presenter).notTo(beNil())
}
}
context("Given that the user selected a movie") {
afterEach {
viewController = nil
}
beforeEach {
viewController = MovieDetailsBuilderMock()
.build(movieDetailsWorker: MovieDetailsWorkerSucessMock())
}
it("view is presenting the movie details") {
viewController.interactor.fetchMovieDetails(of: 1)
expect(viewController.details).notTo(beNil())
expect(viewController.showMovieDetailsCalled).to(beTrue())
expect(viewController.details?.duration).to(equal("2h"))
expect(viewController.details?.budget).to(equal("$1,000,000.00"))
expect(viewController.details?.revenue).to(equal("$2,000,000.00"))
expect(viewController.details?.cast.count).to(beGreaterThan(0))
expect(viewController.details?.crew.count).to(beGreaterThan(0))
expect(viewController.details?.genres.count).to(beGreaterThan(0))
expect(viewController.details?.recommendations.count).to(beGreaterThan(0))
}
}
context("Given that an error occurred while fetching the movie details") {
afterEach {
viewController = nil
}
beforeEach {
viewController = MovieDetailsBuilderMock()
.build(movieDetailsWorker: MovieDetailsWorkerFailureMock())
}
it("view is presenting error alert") {
viewController.interactor.fetchMovieDetails(of: 1)
expect(viewController.details).to(beNil())
expect(viewController.showMovieDetailsCalled).to(beFalse())
expect(viewController.showMovieDetailsErrorCalled).to(beTrue())
expect(viewController.errorMessage).to(equal(R.Localizable.errorDescription()))
}
}
context("Given that the api returns an empty response and status code 200") {
afterEach {
viewController = nil
}
beforeEach {
viewController = MovieDetailsBuilderMock()
.build(movieDetailsWorker: MovieDetailsWorkerEmptyMock())
}
it("view is presenting error alert when response is empty") {
viewController.interactor.fetchMovieDetails(of: 1)
expect(viewController.details).to(beNil())
expect(viewController.showMovieDetailsCalled).to(beFalse())
expect(viewController.showMovieDetailsErrorCalled).to(beTrue())
expect(viewController.errorMessage).to(equal(R.Localizable.errorDescription()))
}
}
}
}
}
| true
|
ac668d5ebb81fd9098fda4aaf717d113744fdf64
|
Swift
|
siposeduard/swiftUIPopupDemo
|
/SwiftUIPopup/Popup/Somepopup.swift
|
UTF-8
| 2,065
| 3.03125
| 3
|
[] |
no_license
|
//
// Somepopup.swift
// SwiftUIPopup
//
// Created by Sipos Eduard on 14/05/2020.
//
import SwiftUI
struct Somepopup: View {
@EnvironmentObject var popupManager: PopupManager
var body: some View {
ZStack {
Color.white.edgesIgnoringSafeArea(.all).opacity(0.40)
ZStack {
VStack(spacing: 0) {
HStack(spacing: 0) {
Divider().frame(width: 5, height: 0).opacity(0)
Button (action: {
self.popupManager.dismissPopup.send(true)
}) {
Image("xIcon")
.resizable()
.frame(width: 10, height: 12)
.scaledToFit()
.foregroundColor(Color.white)
.padding()
}
Spacer()
}
Text("Some text")
.foregroundColor(Color.white)
.padding()
Button(action: {
print("Big Button Pressed")
}) {
HStack {
Spacer()
Text("Big Button Text")
.foregroundColor(Color.white)
.bold()
.padding()
Spacer()
}
.background(Color.green)
.cornerRadius(8)
}
.frame(height: 50)
.padding()
}
.background(Color.black.opacity(0.80))
.cornerRadius(20)
}.padding()
}
}
}
struct Somepopup_Previews: PreviewProvider {
static var previews: some View {
Somepopup()
}
}
| true
|
8918ca8b3b30dfdd5a23beb369e6727f0e081da7
|
Swift
|
sdkshredder/SocialMe
|
/SocialMe/SocialMe/MessageLabel.swift
|
UTF-8
| 1,022
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// MessageLabel.swift
// SocialMe
//
// Created by Matt Duhamel on 5/26/15.
// Copyright (c) 2015 new. All rights reserved.
//
import UIKit
class MessageLabel: UILabel {
override func drawTextInRect(rect: CGRect) {
var inset = UIEdgeInsetsMake(0, 10, 0, 0)
if (self.accessibilityHint == "x") {
print("yoooo")
inset = UIEdgeInsetsMake(0, 0, 0, 10)
}
// super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(0, 10, 0, 10)))
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, inset))
}
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let size = CGSizeMake(270.0, 1000.0)
let frame = NSString(string: self.text!).boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleBody)], context: nil)
return CGRectMake(0, 0, frame.width + 20, frame.height + 10)
}
}
| true
|
42ee481589e751a06d305bc6589a56983261b270
|
Swift
|
Banner2404/Railway
|
/Railway/Data/DataManager.swift
|
UTF-8
| 2,841
| 2.65625
| 3
|
[] |
no_license
|
//
// DataManager.swift
// Railway
//
// Created by Соболь Евгений on 10/27/17.
// Copyright © 2017 Insoft. All rights reserved.
//
import Foundation
protocol DataManager {
init()
func details(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ object: Model?, _ error: Error?) -> Void)
func create(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ object: Model?, _ error: Error?) -> Void)
func update(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ error: Error?) -> Void)
func delete(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ error: Error?) -> Void)
}
class DefaultDataManager<T: Model>: DataManager {
required init() {}
func details(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ object: Model?, _ error: Error?) -> Void) {
guard let object = object as? T else {
fatalError("incorrect object type")
}
details(object: object, token: token, completion: completion)
}
func create(_ object: Model, token: String, completion: @escaping (Bool, Model?, Error?) -> Void) {
guard let object = object as? T else {
fatalError("incorrect object type")
}
create(object: object, token: token, completion: completion)
}
func update(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
guard let object = object as? T else {
fatalError("incorrect object type")
}
update(object: object, token: token, completion: completion)
}
func delete(_ object: Model, token: String, completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
guard let object = object as? T else {
fatalError("incorrect object type")
}
delete(object: object, token: token, completion: completion)
}
func details(object: T, token: String, completion: @escaping (Bool, T?, Error?) -> Void) {
RequestManager.shared.load(id: object.id, token: token, completion: { (success: Bool, result: Result<T>?, error: Error?) in
completion(success, result?.data, error)
})
}
func create(object: T, token: String, completion: @escaping (Bool, T?, Error?) -> Void) {
RequestManager.shared.create(object, token: token, completion: completion)
}
func update(object: T, token: String, completion: @escaping (Bool, Error?) -> Void) {
RequestManager.shared.update(object, token: token, completion: completion)
}
func delete(object: T, token: String, completion: @escaping (Bool, Error?) -> Void) {
RequestManager.shared.delete(object, token: token, completion: completion)
}
}
| true
|
d2de6cb944409531a958c5cda37109b6dfb3186f
|
Swift
|
Musjoy/Swift-MJModel
|
/Source/Core/AnyExtension.swift
|
UTF-8
| 1,395
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// AnyExtension.swift
// Alamofire
//
// Created by 黄磊 on 2019/7/12.
//
import Foundation
/// 用协议方式扩展Any
protocol _AnyExtension {}
extension _AnyExtension {
/// 读取指定内存位置的数据,并转化成当前类型
static func _read(from rawPointer: UnsafeRawPointer) -> Self? {
let value = rawPointer.assumingMemoryBound(to: self).pointee
return value
}
/// 将数据写入到指定内存
static func _write(_ value: Any, to rawPointer: UnsafeMutableRawPointer) {
guard let this = value as? Self else {
return
}
rawPointer.assumingMemoryBound(to: self).pointee = this
}
/// 获取当前类型的内存占用尺寸
static func _size() -> Int {
return MemoryLayout<Self>.size
}
/// 获取当前类型的内存对齐步长
static func _alignment() -> Int {
return MemoryLayout<Self>.alignment
}
}
/// 获取给定类型的扩展类型
func _theExtension(withType type: Any.Type) -> _AnyExtension.Type {
struct Extension : _AnyExtension {}
var aExtension: _AnyExtension.Type = Extension.self
withUnsafePointer(to: &aExtension) { pointer in
// 偷梁换柱,修改类型
UnsafeMutableRawPointer(mutating: pointer).assumingMemoryBound(to: Any.Type.self).pointee = type
}
return aExtension
}
| true
|
c20cb98e4985bc36c9364231ee3e1c072e70ef7a
|
Swift
|
BrianJayD/CarSpot
|
/CarSpot/CarSpot/Extensions/Int64.swift
|
UTF-8
| 971
| 3.1875
| 3
|
[] |
no_license
|
//
// Advanced iOS - MADS4005
// CarSpot
//
// Group 7
// Brian Domingo - 101330689
// Daryl Dyck - 101338429
//
import Foundation
extension Int64
{
// add option to convert to phone number String
func toPhoneString() -> String
{
let phone = String(self)
var format: String = ""
if(phone.count > 10)
{
format = "X (XXX) XXX-XXXX"
}
else
{
format = "(XXX) XXX-XXXX"
}
let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
var result = ""
var index = numbers.startIndex
for ch in format where index < numbers.endIndex
{
if ch == "X"
{
result.append(numbers[index])
index = numbers.index(after: index)
}
else
{
result.append(ch)
}
}
return result
}
}
| true
|
6be220aba970f4451a1c4aa0e6956df44025f007
|
Swift
|
Dwashi2/swift-GettheCentury
|
/GettheCentury/ViewController.swift
|
UTF-8
| 1,163
| 3.78125
| 4
|
[] |
no_license
|
//
// ViewController.swift
// GettheCentury
//
// Created by Daniel Washington Ignacio on 30/05/21.
//
/*
Create a function that takes in a year and returns the correct century.
Examples
century(1756) ➞ "18th century"
century(1555) ➞ "16th century"
century(1000) ➞ "10th century"
century(1001) ➞ "11th century"
century(2005) ➞ "21st century"
Notes
All years will be between 1000 and 2010.
The 11th century is between 1001 and 1100.
The 18th century is between 1701-1800.
*/
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(self.century(1756))
print(self.century(1555))
print(self.century(1000))
print(self.century(1001))
print(self.century(2005))
}
func century(_ year: Int) -> String {
var newYear: Float = Float(year)
newYear = newYear/100
let (wholePart, fractionalPart) = modf(newYear)
if fractionalPart != 0.0 {
newYear = newYear + 1
}
return "\(Int(newYear))th century"
}
}
| true
|
2d051e87bcd8b19f53b2829638580457e4a136a3
|
Swift
|
bhartiios/PropertyApp
|
/PropertyApp/Networking/PropertyApiManager.swift
|
UTF-8
| 1,271
| 2.75
| 3
|
[] |
no_license
|
//
// StatsApiManager.swift
// NRLStats
//
// Created by Bharti Sharma on 15/11/17.
// Copyright © 2017 Bharti Sharma. All rights reserved.
//
import Foundation
protocol PropertyApiManager: ApiManager {}
extension PropertyApiManager{
//MARK:- Webservices
/// Webservice to fetch Property details
///
/// - Parameters:
/// - completionHandler: block to handle success
/// - failureHandler: block to handle failure
func getPropertyList(completionHandler: @escaping (_ arrMatch:[Property]) -> Void, failureHandler: @escaping (_ error: Error?) -> Void){
self.makeGETWebserviceCall(strURL: AppConstants.statsUrl, completionHandler: { (response) in
guard let dictResponse = response as? [String:AnyObject], let arrResult = dictResponse["data"] as? [[String:AnyObject]] else{
failureHandler(nil)
return
}
var arrProperty = [Property]()
for dictProp in arrResult{
var property = Property()
property.fillData(dictProperty: dictProp)
arrProperty.append(property)
}
completionHandler(arrProperty)
}) { (error) in
failureHandler(error)
}
}
}
| true
|
99f0ebf66a58dea1697de612d01f48d3c3555bb2
|
Swift
|
taikhoanthunghiemcuatoi/swift
|
/UIImage/UIImage/ViewController.swift
|
UTF-8
| 3,445
| 2.96875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// UIImage
//
// Created by Paris on 11/4/16.
// Copyright © 2016 domisu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var txtURL: UITextField!
@IBOutlet weak var imgResult: UIImageView!
let sampleImageURL = "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loadImageURL(_ sender: Any) {
//http://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift
if let text = txtURL.text{
if let url = URL(string: text){
//downloadImageSync(url: url, imageView: imgResult)
//downloadImage(url: url, imageView: imgResult)
imgResult.downloadedFrom(url:url)
}
}
}
@IBAction func loadSpiderMan(_ sender: Any) {
imgResult.image = loadImage(imageName: "spiderman-wallpaper")
}
@IBAction func loadHulk(_ sender: Any) {
imgResult.image = loadImage(imageName: "5.jpg")
}
func loadImage(imageName: String) -> UIImage?{
if let image = UIImage(named: imageName){
return image
}else{
print("invalid image")
}
return nil
}
func downloadImageSync(url: URL, imageView: UIImageView){
let imageData = try? Data(contentsOf: url)
imageView.image = UIImage(data: imageData!)
}
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
func downloadImage(url: URL, imageView: UIImageView) {
print("Download Started")
getDataFromUrl(url: url) { (data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
imageView.image = UIImage(data: data)
}
}
}
}
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
print("calling downloadedFrom")
contentMode = mode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
| true
|
3667947c8145cfcbebdfbeaeacf25aa051a25902
|
Swift
|
fredyshox/ChineseCheckers
|
/client/ChineseCheckers/ChineseCheckers Shared/HexagonNodeDelegate.swift
|
UTF-8
| 379
| 2.53125
| 3
|
[] |
no_license
|
//
// HexagonNodeDelegate.swift
// ChineseCheckers macOS
//
// Created by Kacper Raczy on 28.12.2017.
// Copyright © 2017 Kacper Raczy. All rights reserved.
//
import Foundation
/**
To be notified about interaction events of HexagonNode object,
conform this protocol and implement provided methods.
*/
protocol HexagonNodeDelegate {
func hexNodeClicked(_ node: HexagonNode)
}
| true
|
81c746ab09b2d0a5f1b16293878051d6b22f39a4
|
Swift
|
zhuansun0502/ezCash
|
/ezCash/ViewControllers/TableViewController.swift
|
UTF-8
| 1,530
| 2.546875
| 3
|
[] |
no_license
|
import UIKit
class TableViewController: UITableViewController {
@IBOutlet weak var backButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
@objc func backToMap() {
dismiss(animated: true, completion: nil)
}
func setupNavigationBar() {
let config = UIImage.SymbolConfiguration(pointSize: 20, weight: .semibold)
let backButtonIcon = UIImage(systemName: "xmark", withConfiguration: config)
backButton.tintColor = .black
backButton.setImage(backButtonIcon, for: .normal)
backButton.sizeToFit()
navigationItem.title = "Nearby Postings"
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
@IBAction func backButtonTouched(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Hello"
return cell
}
}
| true
|
4efc6256bbc120d5b239d261b65f6f75ca6f25ef
|
Swift
|
rhale2/PA8
|
/PA8/GooglePlacesAPI.swift
|
UTF-8
| 6,185
| 2.9375
| 3
|
[] |
no_license
|
//
// GooglePlacesAPI.swift
// PA8
//
// Created by Sophia Braun on 12/6/20.
// Copyright © 2020 Rebekah Hale. All rights reserved.
//
import Foundation
import UIKit
struct GooglePlacesAPI {
private static let apiKey = "AIzaSyCqr-r3261KQcBV7G_BT-HZyy7SBKdAoxs"
static var input: String = ""
static var latitude: String = ""
static var longitude: String = ""
static func googleNearBySearchesURL (input: String, latitude: String, longitude: String) -> URL {
let baseURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
let params = [
"key": GooglePlacesAPI.apiKey,
"location": "\(latitude), \(longitude)",
"radius": "1000",
"keyword": "\(input)"
]
var queryItems = [URLQueryItem]()
for (key, value) in params {
queryItems.append(URLQueryItem(name: key, value: value))
}
var components = URLComponents(string: baseURL)!
components.queryItems = queryItems
let url = components.url!
print(url)
return url
}
static func googlePlaceDetailsURL (placeID: String) -> URL {
let baseURL = "https://maps.googleapis.com/maps/api/place/details/json?"
let params = [
"key": GooglePlacesAPI.apiKey,
"place_id": "\(placeID)",
"fields": "place_id,name,vicinity,rating,photos[]"
]
var queryItems = [URLQueryItem]()
for (key, value) in params {
queryItems.append(URLQueryItem(name: key, value: value))
}
var components = URLComponents(string: baseURL)!
components.queryItems = queryItems
let url = components.url!
print(url)
return url
}
/*
static func googlePlacePhotosURL (photoRefrence: String) -> URL {
let baseURL = "https://maps.googleapis.com/maps/api/place/photo?"
let params = [
"key": GooglePlacesAPI.apiKey,
"photoreference": "\(photoRefrence)",
"maxwidth": "1600"
]
var queryItems = [URLQueryItem]()
for (key, value) in params {
queryItems.append(URLQueryItem(name: key, value: value))
}
var components = URLComponents(string: baseURL)!
components.queryItems = queryItems
let url = components.url!
print(url)
return url
}*/
static func fetchPlaces (completion: @escaping ([Place]?) -> Void) {
let nearBySearchURL = GooglePlacesAPI.googleNearBySearchesURL(input: input, latitude: latitude, longitude: longitude)
let task = URLSession.shared.dataTask(with: nearBySearchURL) { (dataOptional, urlResponseOptional, errorOptional) in
if let data = dataOptional, let dataString = String(data: data, encoding: .utf8) {
print("we got data!!!")
print(dataString)
if let places = places(fromData: data) {
print("we got an [InterestingPhoto] with \(places.count) photos")
DispatchQueue.main.async {
completion(places)
}
}
else {
DispatchQueue.main.async {
completion(nil)
}
}
}
else {
if let error = errorOptional {
print("Error getting data \(error)")
}
DispatchQueue.main.async {
completion(nil)
}
}
}
task.resume()
}
static func places (fromData data: Data) -> [Place]? {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
/*guard let jsonDictionary = jsonObject as? [String: Any], let placesObject = jsonDictionary["html_attributions"] as? [String: Any], let placesArray = placesObject["results"] as? [[String: Any]] else {
print("Error parsing JSON")
return nil
}*/
guard let jsonDictionary = jsonObject as? [String: Any], let placesArray = jsonDictionary["results"] as? [[String: Any]] else {
print("Error parsing JSON")
return nil
}
print("successfully got placesArray")
var places = [Place]()
for placeObject in placesArray {
if let place = place(fromJSON: placeObject) {
places.append(place)
}
}
if !places.isEmpty {
return places
}
}
catch {
print("Error converting Data to JSON \(error)")
}
return nil
}
static func place (fromJSON json: [String: Any]) -> Place? {
guard let id = json["place_id"] as? Int, let name = json["name"] as? String, let vicinity = json["vicinity"] as? String, let rating = json["rating"] as? Int, let photoURL = json["photo_reference"] as? String else {
return nil
}
return Place(ID: id, name: name, vicinity: vicinity, rating: rating, photoRefrence: photoURL)
}
static func fetchImage (fromURLString urlString: String, completion: @escaping (UIImage?) -> Void) {
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { (dataOptional, urlResponseOptional, errorOptional) in
if let data = dataOptional, let image = UIImage(data: data) {
DispatchQueue.main.async {
completion(image)
}
}
else {
if let error = errorOptional {
print("error fetching image \(error)")
}
DispatchQueue.main.async {
completion(nil)
}
}
}
task.resume()
}
}
| true
|
c56587aa2cce5666649210e73f34406f7b5405ec
|
Swift
|
y-ich/SwiftShogi
|
/Sources/SwiftShogi/Square.swift
|
UTF-8
| 1,900
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
// north
// ihgfedcba
// 000000000 1
// 000000000 2
// 000000000 3
// 000000000 4
// west 000000000 5 east
// 000000000 6
// 000000000 7
// 000000000 8
// 000000000 9
// south
public enum File: Int, CaseIterable { // rawValueは左オリジンにする
case i
case h
case g
case f
case e
case d
case c
case b
case a
}
public enum Rank: Int, CaseIterable {
case one
case two
case three
case four
case five
case six
case seven
case eight
case nine
}
public enum Square: Int, CaseIterable {
// 将棋盤は右上が原点なので、以下は左右反転させて見る
case i1, h1, g1, f1, e1, d1, c1, b1, a1
case i2, h2, g2, f2, e2, d2, c2, b2, a2
case i3, h3, g3, f3, e3, d3, c3, b3, a3
case i4, h4, g4, f4, e4, d4, c4, b4, a4
case i5, h5, g5, f5, e5, d5, c5, b5, a5
case i6, h6, g6, f6, e6, d6, c6, b6, a6
case i7, h7, g7, f7, e7, d7, c7, b7, a7
case i8, h8, g8, f8, e8, d8, c8, b8, a8
case i9, h9, g9, f9, e9, d9, c9, b9, a9
}
extension Square {
public init(file: File, rank: Rank) {
self.init(rawValue: rank.rawValue * File.allCases.count + file.rawValue)!
}
public var file: File { File(rawValue: rawValue % File.allCases.count)! }
public var rank: Rank { Rank(rawValue: rawValue / File.allCases.count)! }
public static func cases(at file: File) -> [Self] {
let f = file
return allCases.filter { $0.file == f }
}
public static func cases(at rank: Rank) -> [Self] {
let r = rank
return allCases.filter { $0.rank == r }
}
public static func promotableCases(for color: Color) -> [Self] {
let ranks: [Rank] = color.isBlack ? [.one, .two, .three] : [.seven, .eight, .nine]
return allCases.filter { ranks.contains($0.rank) }
}
}
| true
|
c9a7ec0ca5ab2f0959157f8e8ee82862002ba303
|
Swift
|
carlosdelamora/SillySongs
|
/SillySong/MainViewController.swift
|
UTF-8
| 2,292
| 2.9375
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// SillySong
//
// Created by Carlos De la mora on 12/7/16.
// Copyright © 2016 Carlos De la mora. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
//The outles
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var lyricsTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameTextField.delegate = self
nameTextField.autocapitalizationType = UITextAutocapitalizationType(rawValue: 0)!
nameTextField.returnKeyType = .done
}
//editing did begin action for text field
//clear the nameTextField and lyricsView text view
@IBAction func reset(_ sender: Any) {
nameTextField.text = ""
lyricsTextView.text = ""
}
//editing did end action
//display the lyrics once we are doe editing
@IBAction func displayLyrics(_ sender: Any) {
let name = nameTextField.text
if let name = name {
let lyrics = lyricsForName(bananaFanaTemplate, name)
lyricsTextView.text = lyrics
}
}
}
extension MainViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
func shortFormOfName(_ name: String ) -> String{
var shortName : String
let name = name.localizedLowercase
let setOfVowels = CharacterSet(charactersIn: "aeiou")
if let index = name.rangeOfCharacter(from: setOfVowels)?.lowerBound {
shortName = String(name.characters.suffix(from: index))
}else{
shortName = name
}
return shortName
}
func lyricsForName(_ lyricsTemplate:String, _ fullName: String )-> String{
let shortName = shortFormOfName(fullName)
let replaceFullName = lyricsTemplate.replacingOccurrences(of: "<FULL_NAME>", with: fullName)
let replaceShortAndFull = replaceFullName.replacingOccurrences(of: "<SHORT_NAME>", with: shortName)
return replaceShortAndFull
}
let bananaFanaTemplate = [
"<FULL_NAME>, <FULL_NAME>, Bo B<SHORT_NAME>",
"Banana Fana Fo F<SHORT_NAME>",
"Me My Mo M<SHORT_NAME>",
"<FULL_NAME>"].joined(separator: "\n")
| true
|
fa3d7076f266af59d9150bf7ba2dde81b45425b7
|
Swift
|
gsagot/oc_p10_reciplease
|
/Reciplease/Controller/TableViewController.swift
|
UTF-8
| 6,214
| 2.8125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Reciplease
//
// Created by Gilles Sagot on 07/08/2021.
//
import UIKit
class TableViewController: UIViewController, UITableViewDelegate {
//MARK: - UI VARIABLES
@IBOutlet weak var tableView: UITableView!
var indicator = UIActivityIndicatorView()
var officer = UILabel()
//MARK: - DATA VARIABLES
var recipes:[Recipe]!
var isFavorite = false
//MARK: - PREPARE
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.title = "Reciplease"
// Prepare array with from persistent data
if isFavorite{
recipes = FavoriteRecipe.makePresentable(favorites: FavoriteRecipe.all)
}
// Delegate things ...
tableView.delegate = self
tableView.dataSource = self
// Officer
officer.font = UIFont(name: "Chalkduster", size: 21)
officer.frame = CGRect(x: 10, y: 0, width: self.view.frame.width - 20, height: 200)
officer.center.y = self.view.center.y - 100
officer.textColor = .white
officer.numberOfLines = 0
officer.textAlignment = .justified
officer.isHidden = true
officer.backgroundColor = .clear
self.view.addSubview(officer)
// Indicator
indicator.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
indicator.color = UIColor.white
indicator.hidesWhenStopped = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: indicator)
}
override func viewDidAppear(_ animated: Bool) {
if isFavorite{
recipes = FavoriteRecipe.makePresentable(favorites: FavoriteRecipe.all)
if recipes.count == 0 {
officer.isHidden = false
print (self.view.frame)
officer.text = "It's empty here ! Please make a search first, then choose a recipe. You will be able to add it in your favorite with the icon (star) in the upper right "
}else {
officer.isHidden = true
}
}
tableView.reloadData()
}
}
//MARK: - TABLEVIEW PROTOCOL
extension TableViewController: UITableViewDataSource {
// Row number
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
// Row height
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 160;
}
// Arrange Cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
indicator.startAnimating()
// Customized cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellView
// Image
var image = String()
image = recipes[indexPath.row].image
ImageService.shared.getImage(url: image, completionHandler: { (success, error, result) in
if success {
cell.backgroundView = UIImageView(image: UIImage(data: result!) )
}else {
cell.backgroundView = UIImageView(image: UIImage(named: "full-english") )
}
cell.backgroundView?.contentMode = .scaleAspectFill
})
// Title
cell.title.text = recipes[indexPath.row].label
// Desciption
cell.ingredientsView.text = formatString(recipes[indexPath.row].ingredientLines)
// Gradient
cell.gradient(frame: cell.frame)
// Insert
cell.insertView.center.x = cell.frame.maxX - 60 - 10
cell.insertView.textYield.text = String(recipes[indexPath.row].yield)
cell.insertView.textTime.text = timeToString(interval:recipes[indexPath.row].totalTime)
indicator.stopAnimating()
// Ready
return cell
}
// Handle User input
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
if isFavorite {
vc.isFavorite = true
}else {
vc.isFavorite = false
}
vc.currentRecipe = recipes[indexPath.row]
// Present controller
navigationController?.pushViewController(vc, animated: true)
}// End condition
}// End function
//MARK: - UTILS
func timeToString (interval:Double) ->String{
if interval != 0 {
let time = TimeInterval(interval * 60)
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.hour, .minute]
return formatter.string(from: time)!
}else{
return "N/A"
}
}
func formatString (_ recipe:[String])->String {
var string = String()
for step in recipe {
var ingredient = step.replacingOccurrences(of: "\\s?\\([\\w\\s]*\\)", with: "", options: .regularExpression)
ingredient = ingredient.components(separatedBy: CharacterSet.decimalDigits).joined()
ingredient = ingredient.components(separatedBy: CharacterSet.punctuationCharacters).joined()
for substring in ingredient.components(separatedBy: " ") {
if substring.count < 3 {
ingredient = ingredient.components(separatedBy: substring).joined()
}
}
ingredient = ingredient.replacingOccurrences(of: " ", with: " ")
string.append(ingredient)
string.append(",")
}
if let i = string.lastIndex(of: ","){
string.remove(at: i)
string.append(".")
}
return string
}
}// End class
| true
|
2acc746f53ccc27801ebc3091201c479bd77f26c
|
Swift
|
chauchinyiu/SwiftUI-Combine-Demo
|
/SwiftUI-Combine-Demo/viewModel/SearchRepositoriesViewModel.swift
|
UTF-8
| 1,465
| 2.953125
| 3
|
[] |
no_license
|
//
// SearchRepositoriesViewModel.swift
// SwiftUI-Combine-Demo
//
// Created by Chinyiu Chau on 07.07.19.
// Copyright © 2019 Chinyiu Chau. All rights reserved.
//
import Combine
import SwiftUI
final class SearchRepositoriesViewModel: ObservableObject {
let client = GithubServicesClient()
var subscriber: AnyCancellable?
var cancellables = Set<AnyCancellable>()
let q = DispatchQueue.main //DispatchQueue(label: "debounce-queue")
var requestingQuery = ""
@Published var repositories = [Repository]() {
didSet {
requestingQuery = ""
}
}
@Published var query = "" {
didSet {
print(query)
}
}
// set up debounce for query string and publish the results of repositiories
init() {
AnyCancellable( $query
.debounce(for: 0.5, scheduler: DispatchQueue.main)
.sink(receiveValue: { query in
guard !query.isEmpty else {
self.repositories = []
return
}
self.search()
})).store(in: &cancellables)
}
func search() {
guard requestingQuery != query else {
return
}
print("Searching keyword: ", query)
self.subscriber = self.client.request(query: query)
.catch { _ in Just([]) }
.assign(to: \.repositories, on: self)
requestingQuery = query
}
}
| true
|
a5129fe047fc15cdf411972c4df9583c0ca051a5
|
Swift
|
niketh90/lightapp_ios
|
/Light/View Controllers/Settings/UserStatisticsViewController.swift
|
UTF-8
| 3,136
| 2.515625
| 3
|
[] |
no_license
|
//
// UserStatisticsViewController.swift
// Light
//
// Created by apple on 09/04/20.
// Copyright © 2020 Seraphic. All rights reserved.
//
import UIKit
class UserStatisticsViewController: UIViewController {
@IBOutlet var profileImage:UIImageView!
@IBOutlet var userNameLabel:UILabel!
@IBOutlet var currentStreakLabel:UILabel!
@IBOutlet var healingDaysLabel:UILabel!
@IBOutlet var healingMinutesLabel:UILabel!
@IBOutlet var contentView:UIView!
override func viewDidLoad() {
super.viewDidLoad()
profileImage.layer.cornerRadius = profileImage.bounds.width/2
let profileDetail = getUserDetails()
userNameLabel.text = "\(profileDetail?.firstName ?? "") \(profileDetail?.lastName ?? "")"
profileImage.sd_setImage(with: URL.init(string: profileDetail?.profileImage ?? ""), placeholderImage: UIImage.init(named: "img_avatar_camera"), options: .refreshCached, completed: nil)
currentStreakLabel.text = profileDetail?.currentStreak?.description ?? ""
healingDaysLabel.text = profileDetail?.healingDays?.description ?? ""
healingMinutesLabel.text = profileDetail?.healingTime?.description ?? ""
if #available(iOS 12.0, *) {
self.navigationController?.navigationBar.barTintColor = UIColor.bgColor
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func goBackAction() {
self.navigationController?.popViewController(animated: true)
}
@IBAction func shareAction() {
let tempImage = UIImageView()
contentView.backgroundColor = UIColor.init(named: "StatisticsFontColor")
let layer = contentView.layer
UIGraphicsBeginImageContextWithOptions(contentView.frame.size, false, contentView.contentScaleFactor)
guard let context = UIGraphicsGetCurrentContext() else {return }
layer.render(in:context)
if let image = UIGraphicsGetImageFromCurrentImageContext() {
tempImage.image = image
}
UIGraphicsEndImageContext()
contentView.backgroundColor = .clear
let imageToShare = [tempImage.image]
let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToFacebook , UIActivity.ActivityType.postToTwitter]
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
}
@IBAction func goHomeAction() {
self.dismiss(animated: true) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.navigationController?.popViewController(animated: true)
}
}
}
}
| true
|
97e95e3e147aff5227262fb53da858959c480a3a
|
Swift
|
rfree18/WWDC2017
|
/WWDC.playground/Sources/AppCell.swift
|
UTF-8
| 609
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import UIKit
open class AppCell: UICollectionViewCell {
var textField: UITextField!
public override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 0.3 * bounds.width
textField = UITextField(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
textField.textAlignment = .center
textField.isUserInteractionEnabled = false
addSubview(textField)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
f5ea3ae36769cd40555184893c1c64215f0d6c19
|
Swift
|
SLingFeng/Battery
|
/Battery/Manager/CoreDataManager.swift
|
UTF-8
| 1,692
| 2.59375
| 3
|
[] |
no_license
|
//
// CoreDataManager.swift
// Battery
//
// Created by 孙凌锋 on 2018/7/18.
// Copyright © 2018年 孙凌锋. All rights reserved.
//
import UIKit
import CoreData
class CoreDataManager: NSObject {
///当前上下文
public lazy var mangerContext: NSManagedObjectContext = {
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
///需要设置一个调度器
context.persistentStoreCoordinator = self.persistentStoreCoordinator
return context
}()
// 2、调度器的创建
///调度器 设置保存的路径
public lazy var persistentStoreCoordinator:NSPersistentStoreCoordinator = {
//需要保存的Datamodle
let coordinator = NSPersistentStoreCoordinator(managedObjectModel:self.mangerModel)
let dirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let fileURL = URL(string: "db.sqlite", relativeTo: dirURL)
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: fileURL, options: nil)
} catch {
fatalError("Error configuring persistent store: \(error)")
}
return coordinator
}()
// 3、 DataModel
//调度器管理 model 也就是 创建的DataModel
public lazy var mangerModel:NSManagedObjectModel = {
guard let url = Bundle.main.url(forResource: "RegionDataModel", withExtension: "momd") else{
fatalError("加载错误")
}
guard let model = NSManagedObjectModel(contentsOf: url) else{
fatalError("加载错误")
}
return model
}()
}
| true
|
f75dad6f0e1fa4bd0c1910d46f2143a32af75935
|
Swift
|
louie0817/Swift-Poker-LHE-Simulator
|
/poker/Model/Cards/Card.swift
|
UTF-8
| 517
| 3.046875
| 3
|
[] |
no_license
|
//
// Card.swift
// poker
//
// Created by Puroof on 10/3/17.
// Copyright © 2017 ModalApps. All rights reserved.
//
import Foundation
struct Card {
let suit: Suit
let rank: Rank
public static func ==(lhs: Card, rhs: Card) -> Bool{
return
lhs.suit == rhs.suit &&
lhs.rank == rhs.rank
}
public static func !=(lhs: Card, rhs: Card) -> Bool{
return
lhs.suit != rhs.suit &&
lhs.rank != rhs.rank
}
}
| true
|
a2a2181a5952f50a80ba490e9bbdef4a29d3676f
|
Swift
|
ClementDums/DrawMySheepBLE
|
/DrawMySheepClient/Helpers.swift
|
UTF-8
| 590
| 2.59375
| 3
|
[] |
no_license
|
//
// Helpers.swift
// DrawMySheepClient
//
// Created by on 10/03/2020.
// Copyright © 2020 clementdumas. All rights reserved.
//
import Foundation
import UIKit
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
extension UIImage {
func resized(to size: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { (context) in
self.draw(in: CGRect(origin: .zero, size: size))
}
}
}
| true
|
927bb3a6227b46eadf02fbda09e93fff13081123
|
Swift
|
samrithyoeun/ios-pm-skyapp
|
/ios-pm-skyapp/Model/Manager/KeychainManager.swift
|
UTF-8
| 855
| 2.640625
| 3
|
[] |
no_license
|
//
// KeychainManager.swift
// ios-pm-skyapp
//
// Created by Samrith Yoeun on 7/13/18.
// Copyright © 2018 samrith. All rights reserved.
//
import Foundation
import KeychainSwift
class KeychainManager {
static let shared = KeychainManager()
let keychain = KeychainSwift()
func setUserInfoToKeychain(user: User?) {
if let user = user {
keychain.set(user.username! , forKey: "username")
keychain.set(user.password! , forKey: "password")
}
}
func getUserInfoFromKeyChain() -> User? {
let username = keychain.get("username")
let password = keychain.get("password")
if let username = username, let password = password {
return User(username: username, password: password)
} else {
return nil
}
}
}
| true
|
77c1d0afb819f0c7c22a12790bbdc4e69e903712
|
Swift
|
werminghoff/local-places-app
|
/LocalPlaces/Models/GooglePlaceModel.swift
|
UTF-8
| 4,963
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
//
// Place.swift
// LocalPlaces
//
// Created by Bruno Rigo Werminghoff on 07/03/20.
// Copyright © 2020 Bruno Rigo Werminghoff. All rights reserved.
//
import Foundation
/// Struct that holds any required info from Google Places API
struct GooglePlaceModel {
struct Location: Decodable {
enum CodingKeys: String, CodingKey {
case latitude = "lat"
case longitude = "lng"
}
let latitude: Double
let longitude: Double
}
struct Geometry: Decodable {
enum CodingKeys: String, CodingKey {
case location
}
let location: Location
}
struct Photo: Decodable {
enum CodingKeys: String, CodingKey {
case reference = "photo_reference"
}
let reference: String?
}
struct OpeningHours: Decodable {
enum CodingKeys: String, CodingKey {
case openNow = "open_now"
}
let openNow: Bool?
}
struct Review: Decodable {
enum CodingKeys: String, CodingKey {
case author = "author_name"
case rating
case text
}
let author: String
let rating: Double
let text: String
}
struct Place: Decodable {
enum CodingKeys: String, CodingKey {
case geometry
case iconUrl = "icon"
case photos
case id = "place_id"
case name
case openingHours = "opening_hours"
case rating
}
let name: String
let geometry: Geometry
let iconUrl: String?
let photos: [Photo]?
let openingHours: OpeningHours?
let id: String
let rating: Double?
var distance: Double = 0.0
var formattedDistance: String = ""
}
enum ResponseStatus: String, Decodable {
/// OK indicates that no errors occurred; the place was successfully detected and at least one result was returned.
case ok = "OK"
/// ZERO_RESULTS indicates that the search was successful but returned no results. This may occur if the search was passed a latlng in a remote location.
case zeroResults = "ZERO_RESULTS"
// OVER_QUERY_LIMIT indicates that you are over your quota.
case overQueryLimit = "OVER_QUERY_LIMIT"
/// REQUEST_DENIED indicates that your request was denied, generally because of lack of an invalid key parameter.
case requestDenied = "REQUEST_DENIED"
/// INVALID_REQUEST generally indicates that a required query parameter (location or radius) is missing.
case invalidRequest = "INVALID_REQUEST"
/// UNKNOWN_ERROR indicates a server-side error; trying again may be successful.
case unknownError = "UNKNOWN_ERROR"
}
struct ResponseMultiple: Decodable {
enum CodingKeys: String, CodingKey {
case nextPageToken = "next_page_token"
case results
case status = "status"
}
/// `next_page_token` contains a token that can be used to return up to 20 additional results. A next_page_token will not be returned if there are no additional results to display. The maximum number of results that can be returned is 60. There is a short delay between when a next_page_token is issued, and when it will become valid.
let nextPageToken: String?
/// `results` contains an array of places, with information about each. See Search Results for information about these results. The Places API returns up to 20 establishment results per query. Additionally, political results may be returned which serve to identify the area of the request.
let results: [Place]
/// `status` contains metadata on the request.
let status: ResponseStatus?
}
struct PlaceReviews: Decodable {
enum CodingKeys: String, CodingKey {
case reviews
}
var reviews: [Review]?
}
struct ResponseReviews: Decodable {
enum CodingKeys: String, CodingKey {
case result
case status = "status"
}
/// `result` contains a single place
let result: PlaceReviews?
/// `status` contains metadata on the request.
let status: ResponseStatus?
}
}
// MARK: - AbstractPlace
extension GooglePlaceModel.Place: AbstractPlace {
var coordinate: Coordinate { Coordinate(latitude: self.geometry.location.latitude, longitude: self.geometry.location.longitude) }
var isOpenNow: Bool? { self.openingHours?.openNow }
var photoIdentifier: String? { self.photos?.compactMap({ $0.reference }).first }
}
// MARK: - AbstractReview
extension GooglePlaceModel.Review: AbstractReview {
var username: String { self.author }
}
| true
|
94a78f4148e6661ca92baee0907344af88331a4e
|
Swift
|
asgeY/PoetForSwiftUI
|
/Poet/Screens/Tutorial/Views/MainTitleView.swift
|
UTF-8
| 638
| 2.75
| 3
|
[] |
no_license
|
//
// MainTitle.swift
// Poet
//
// Created by Stephen E. Cotner on 5/21/20.
// Copyright © 2020 Steve Cotner. All rights reserved.
//
import SwiftUI
struct MainTitleView: View {
@ObservedObject var text: ObservableString
let height: CGFloat
var body: some View {
VStack {
Spacer().frame(height: self.height / 2.0 - 40)
HStack {
Spacer()
ObservingTextView(self.text, alignment: .center, kerning: -0.05)
.font(Font.system(size: 32, weight: .semibold).monospacedDigit())
Spacer()
}
Spacer()
}
}
}
| true
|
0a1ce24f51baff5d4ac1181264360b5b764ab2f1
|
Swift
|
wayne97023/maskImage
|
/maskImage/ViewController.swift
|
UTF-8
| 729
| 2.546875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// maskImage
//
// Created by 林奇杰 on 2020/3/14.
// Copyright © 2020 林奇杰. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var maskImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func setMask(_ sender: UIButton) {
maskImage.image = sender.currentImage
let dogImage = UIImage(named: "dog_mask")
let dogImageView = UIImageView(image: dogImage)
dogImageView.frame = CGRect(x: 0, y: 0, width: 414, height: 495)
maskImage.mask = dogImageView
print(maskImage)
}
}
| true
|
4ccc57113e526b359182ec8cfec696d2611bc9e4
|
Swift
|
Yeehaareal/ChuckNorrisApp
|
/SwiftFirestorePhotoAlbum/Pages/Albums List/AlbumListViewController.swift
|
UTF-8
| 4,036
| 2.515625
| 3
|
[] |
no_license
|
//
// AlbumListViewController.swift
// SwiftFirestorePhotoAlbum
//
// Created by Alex Akrimpai on 03/09/2018.
// Copyright © 2018 Alex Akrimpai. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import FirebaseFirestore
class AlbumListViewController: UIViewController {
var chuckNorrisJoke = "There must be a Chuck Norris Joke"
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var albums: [AlbumEntity]?
var queryListener: ListenerRegistration!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
//MARK: - Joke Button
@IBAction func chuckNorrisJokeButton(_ sender: Any) {
//MARK: - Get data from JSON
AF.request("https://api.chucknorris.io/jokes/random", method: .get).responseJSON { (response) in
if response.value != nil {
print("We got Chuck Norris Joke, Yes!")
let data = JSON(response.value!)
let joke = data["value"].stringValue
self.chuckNorrisJoke = joke
print(joke)
self.jokeAlert()
}else{
print("ERROR \(String(describing: response.error))")
self.jokeAlert()
}
}
}
//MARK: - Alert
func jokeAlert(){
let alert = UIAlertController(title: "Chuck Norris", message: chuckNorrisJoke, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
//Add imageview to alert
let imgViewTitle = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
imgViewTitle.image = UIImage(named:"chuck-norris.png")
alert.view.addSubview(imgViewTitle)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
queryListener = AlbumService.shared.getAll { albums in
self.albums = albums
if albums.isEmpty {
self.tableView.addNoDataLabel(text: "No Albums added\n\nPlease press the + button above to start")
} else {
self.tableView.removeNoDataLabel()
}
self.tableView.reloadData()
self.activityIndicator.stopAnimating()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
queryListener.remove()
}
private func setupUI() {
tableView.tableFooterView = UIView()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AlbumDetailsSegue", let index = sender as? Int, let albumDetailsController = segue.destination as? AlbumDetailsViewController, let album = albums?[index] {
albumDetailsController.album = album
}
}
@IBAction func addAlbumTappedHandler(_ sender: Any) {
let alertController = UIAlertController(title: "Add new album", message: nil, preferredStyle: .alert)
alertController.addTextField { textField in
textField.placeholder = "Album name"
}
let textField = alertController.textFields![0] as UITextField
let saveAction = UIAlertAction(title: "Save", style: .default) { _ in
self.activityIndicator.startAnimating()
AlbumService.shared.addAlbumWith(name: textField.text ?? "No Name")
alertController.dismiss(animated: true)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive)
alertController.addAction(cancelAction)
alertController.addAction(saveAction)
self.present(alertController, animated: true)
}
}
| true
|
c5cb51a33f0f029b18b97a665270cda4c9bda53a
|
Swift
|
kasei/swift-sparql-syntax
|
/Sources/SPARQLSyntax/Expression.swift
|
UTF-8
| 44,025
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// Expression.swift
// Kineo
//
// Created by Gregory Todd Williams on 7/31/16.
// Copyright © 2016 Gregory Todd Williams. All rights reserved.
//
import Foundation
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable:next type_body_length
public indirect enum Expression: Equatable, Hashable, CustomStringConvertible {
case node(Node)
case window(WindowApplication)
case aggregate(Aggregation)
case neg(Expression)
case not(Expression)
case isiri(Expression)
case isblank(Expression)
case isliteral(Expression)
case isnumeric(Expression)
case lang(Expression)
case langmatches(Expression, Expression)
case datatype(Expression)
case sameterm(Expression, Expression)
case bound(Expression)
case boolCast(Expression)
case intCast(Expression)
case floatCast(Expression)
case doubleCast(Expression)
case decimalCast(Expression)
case dateTimeCast(Expression)
case dateCast(Expression)
case stringCast(Expression)
case eq(Expression, Expression)
case ne(Expression, Expression)
case lt(Expression, Expression)
case le(Expression, Expression)
case gt(Expression, Expression)
case ge(Expression, Expression)
case add(Expression, Expression)
case sub(Expression, Expression)
case div(Expression, Expression)
case mul(Expression, Expression)
case and(Expression, Expression)
case or(Expression, Expression)
case between(Expression, Expression, Expression)
case valuein(Expression, [Expression])
case call(String, [Expression])
case exists(Algebra)
public init(variable name: String) {
self = .node(.variable(name, binding: true))
}
public init(integer value: Int) {
self = .node(.bound(Term(integer: value)))
}
public var variables: Set<String> {
switch self {
case .node(.variable(let s, binding: _)):
return Set([s])
case .node(_):
return Set()
case .not(let expr), .isiri(let expr), .isblank(let expr), .isliteral(let expr), .isnumeric(let expr), .lang(let expr), .datatype(let expr), .bound(let expr), .boolCast(let expr), .intCast(let expr), .floatCast(let expr), .doubleCast(let expr), .decimalCast(let expr), .dateTimeCast(let expr), .dateCast(let expr), .stringCast(let expr), .neg(let expr):
return expr.variables
case .eq(let lhs, let rhs), .ne(let lhs, let rhs), .lt(let lhs, let rhs), .le(let lhs, let rhs), .gt(let lhs, let rhs), .ge(let lhs, let rhs), .add(let lhs, let rhs), .sub(let lhs, let rhs), .div(let lhs, let rhs), .mul(let lhs, let rhs), .and(let lhs, let rhs), .or(let lhs, let rhs), .langmatches(let lhs, let rhs), .sameterm(let lhs, let rhs):
return lhs.variables.union(rhs.variables)
case .between(let a, let b, let c):
return a.variables.union(b.variables).union(c.variables)
case .call(_, let exprs):
return exprs.reduce(Set()) { $0.union($1.variables) }
case .valuein(let expr, let exprs):
return exprs.reduce(expr.variables) { $0.union($1.variables) }
case .aggregate(let a):
return a.variables
case .window(let w):
return w.variables
case .exists(let p):
return p.inscope
}
}
public var hasAggregation: Bool {
switch self {
case .aggregate(_):
return true
case .window(_):
return false
case .node(_), .exists(_):
return false
case .not(let expr), .isiri(let expr), .isblank(let expr), .isliteral(let expr), .isnumeric(let expr), .lang(let expr), .datatype(let expr), .bound(let expr), .boolCast(let expr), .intCast(let expr), .floatCast(let expr), .doubleCast(let expr), .decimalCast(let expr), .dateTimeCast(let expr), .dateCast(let expr), .stringCast(let expr), .neg(let expr):
return expr.hasAggregation
case .eq(let lhs, let rhs), .ne(let lhs, let rhs), .lt(let lhs, let rhs), .le(let lhs, let rhs), .gt(let lhs, let rhs), .ge(let lhs, let rhs), .add(let lhs, let rhs), .sub(let lhs, let rhs), .div(let lhs, let rhs), .mul(let lhs, let rhs), .and(let lhs, let rhs), .or(let lhs, let rhs), .langmatches(let lhs, let rhs), .sameterm(let lhs, let rhs):
return lhs.hasAggregation || rhs.hasAggregation
case .between(let a, let b, let c):
return a.hasAggregation || b.hasAggregation || c.hasAggregation
case .call(_, let exprs):
return exprs.reduce(false) { $0 || $1.hasAggregation }
case .valuein(let expr, let exprs):
return exprs.reduce(expr.hasAggregation) { $0 || $1.hasAggregation }
}
}
func removeAggregations(_ counter: AnyIterator<Int>, mapping: inout [String:Aggregation]) -> Expression {
switch self {
case .node(_), .exists(_):
return self
case .neg(let expr):
return .neg(expr.removeAggregations(counter, mapping: &mapping))
case .not(let expr):
return .not(expr.removeAggregations(counter, mapping: &mapping))
case .isiri(let expr):
return .isiri(expr.removeAggregations(counter, mapping: &mapping))
case .isblank(let expr):
return .isblank(expr.removeAggregations(counter, mapping: &mapping))
case .isliteral(let expr):
return .isliteral(expr.removeAggregations(counter, mapping: &mapping))
case .isnumeric(let expr):
return .isnumeric(expr.removeAggregations(counter, mapping: &mapping))
case .lang(let expr):
return .lang(expr.removeAggregations(counter, mapping: &mapping))
case .langmatches(let expr, let pattern):
return .langmatches(expr.removeAggregations(counter, mapping: &mapping), pattern.removeAggregations(counter, mapping: &mapping))
case .sameterm(let expr, let pattern):
return .sameterm(expr.removeAggregations(counter, mapping: &mapping), pattern.removeAggregations(counter, mapping: &mapping))
case .datatype(let expr):
return .datatype(expr.removeAggregations(counter, mapping: &mapping))
case .bound(let expr):
return .bound(expr.removeAggregations(counter, mapping: &mapping))
case .boolCast(let expr):
return .boolCast(expr.removeAggregations(counter, mapping: &mapping))
case .intCast(let expr):
return .intCast(expr.removeAggregations(counter, mapping: &mapping))
case .floatCast(let expr):
return .floatCast(expr.removeAggregations(counter, mapping: &mapping))
case .doubleCast(let expr):
return .doubleCast(expr.removeAggregations(counter, mapping: &mapping))
case .decimalCast(let expr):
return .decimalCast(expr.removeAggregations(counter, mapping: &mapping))
case .dateTimeCast(let expr):
return .dateTimeCast(expr.removeAggregations(counter, mapping: &mapping))
case .dateCast(let expr):
return .dateCast(expr.removeAggregations(counter, mapping: &mapping))
case .stringCast(let expr):
return .stringCast(expr.removeAggregations(counter, mapping: &mapping))
case .call(let f, let exprs):
return .call(f, exprs.map { $0.removeAggregations(counter, mapping: &mapping) })
case .eq(let lhs, let rhs):
return .eq(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .ne(let lhs, let rhs):
return .ne(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .lt(let lhs, let rhs):
return .lt(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .le(let lhs, let rhs):
return .le(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .gt(let lhs, let rhs):
return .gt(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .ge(let lhs, let rhs):
return .ge(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .add(let lhs, let rhs):
return .add(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .sub(let lhs, let rhs):
return .sub(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .div(let lhs, let rhs):
return .div(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .mul(let lhs, let rhs):
return .mul(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .and(let lhs, let rhs):
return .and(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .or(let lhs, let rhs):
return .or(lhs.removeAggregations(counter, mapping: &mapping), rhs.removeAggregations(counter, mapping: &mapping))
case .between(let a, let b, let c):
return .between(a.removeAggregations(counter, mapping: &mapping), b.removeAggregations(counter, mapping: &mapping), c.removeAggregations(counter, mapping: &mapping))
case .aggregate(let agg):
guard let c = counter.next() else { fatalError("No fresh variable available") }
let name = ".agg-\(c)"
mapping[name] = agg
let node: Node = .variable(name, binding: true)
return .node(node)
case .window(let w):
return .window(w)
case .valuein(let expr, let exprs):
return .valuein(expr.removeAggregations(counter, mapping: &mapping), exprs.map { $0.removeAggregations(counter, mapping: &mapping) })
}
}
public var hasWindow: Bool {
switch self {
case .aggregate(_):
return false
case .window(_):
return true
case .node(_), .exists(_):
return false
case .not(let expr), .isiri(let expr), .isblank(let expr), .isliteral(let expr), .isnumeric(let expr), .lang(let expr), .datatype(let expr), .bound(let expr), .boolCast(let expr), .intCast(let expr), .floatCast(let expr), .doubleCast(let expr), .decimalCast(let expr), .dateTimeCast(let expr), .dateCast(let expr), .stringCast(let expr), .neg(let expr):
return expr.hasWindow
case .eq(let lhs, let rhs), .ne(let lhs, let rhs), .lt(let lhs, let rhs), .le(let lhs, let rhs), .gt(let lhs, let rhs), .ge(let lhs, let rhs), .add(let lhs, let rhs), .sub(let lhs, let rhs), .div(let lhs, let rhs), .mul(let lhs, let rhs), .and(let lhs, let rhs), .or(let lhs, let rhs), .langmatches(let lhs, let rhs), .sameterm(let lhs, let rhs):
return lhs.hasWindow || rhs.hasWindow
case .between(let a, let b, let c):
return a.hasWindow || b.hasWindow || c.hasWindow
case .call(_, let exprs):
return exprs.reduce(false) { $0 || $1.hasWindow }
case .valuein(let expr, let exprs):
return exprs.reduce(expr.hasWindow) { $0 || $1.hasWindow }
}
}
func removeWindows(_ counter: AnyIterator<Int>, mapping: inout [String:WindowApplication]) -> Expression {
switch self {
case .node(_), .exists(_):
return self
case .neg(let expr):
return .neg(expr.removeWindows(counter, mapping: &mapping))
case .not(let expr):
return .not(expr.removeWindows(counter, mapping: &mapping))
case .isiri(let expr):
return .isiri(expr.removeWindows(counter, mapping: &mapping))
case .isblank(let expr):
return .isblank(expr.removeWindows(counter, mapping: &mapping))
case .isliteral(let expr):
return .isliteral(expr.removeWindows(counter, mapping: &mapping))
case .isnumeric(let expr):
return .isnumeric(expr.removeWindows(counter, mapping: &mapping))
case .lang(let expr):
return .lang(expr.removeWindows(counter, mapping: &mapping))
case .langmatches(let expr, let pattern):
return .langmatches(expr.removeWindows(counter, mapping: &mapping), pattern.removeWindows(counter, mapping: &mapping))
case .sameterm(let expr, let pattern):
return .sameterm(expr.removeWindows(counter, mapping: &mapping), pattern.removeWindows(counter, mapping: &mapping))
case .datatype(let expr):
return .datatype(expr.removeWindows(counter, mapping: &mapping))
case .bound(let expr):
return .bound(expr.removeWindows(counter, mapping: &mapping))
case .boolCast(let expr):
return .boolCast(expr.removeWindows(counter, mapping: &mapping))
case .intCast(let expr):
return .intCast(expr.removeWindows(counter, mapping: &mapping))
case .floatCast(let expr):
return .floatCast(expr.removeWindows(counter, mapping: &mapping))
case .doubleCast(let expr):
return .doubleCast(expr.removeWindows(counter, mapping: &mapping))
case .decimalCast(let expr):
return .decimalCast(expr.removeWindows(counter, mapping: &mapping))
case .dateTimeCast(let expr):
return .dateTimeCast(expr.removeWindows(counter, mapping: &mapping))
case .dateCast(let expr):
return .dateCast(expr.removeWindows(counter, mapping: &mapping))
case .stringCast(let expr):
return .stringCast(expr.removeWindows(counter, mapping: &mapping))
case .call(let f, let exprs):
return .call(f, exprs.map { $0.removeWindows(counter, mapping: &mapping) })
case .eq(let lhs, let rhs):
return .eq(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .ne(let lhs, let rhs):
return .ne(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .lt(let lhs, let rhs):
return .lt(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .le(let lhs, let rhs):
return .le(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .gt(let lhs, let rhs):
return .gt(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .ge(let lhs, let rhs):
return .ge(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .add(let lhs, let rhs):
return .add(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .sub(let lhs, let rhs):
return .sub(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .div(let lhs, let rhs):
return .div(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .mul(let lhs, let rhs):
return .mul(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .and(let lhs, let rhs):
return .and(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .or(let lhs, let rhs):
return .or(lhs.removeWindows(counter, mapping: &mapping), rhs.removeWindows(counter, mapping: &mapping))
case .between(let a, let b, let c):
return .between(a.removeWindows(counter, mapping: &mapping), b.removeWindows(counter, mapping: &mapping), c.removeWindows(counter, mapping: &mapping))
case .aggregate(let agg):
return .aggregate(agg)
case .window(let w):
guard let c = counter.next() else { fatalError("No fresh variable available") }
let name = ".window-\(c)"
mapping[name] = w
let node: Node = .variable(name, binding: true)
return .node(node)
case .valuein(let expr, let exprs):
return .valuein(expr.removeWindows(counter, mapping: &mapping), exprs.map { $0.removeWindows(counter, mapping: &mapping) })
}
}
var isBuiltInCall: Bool {
switch self {
case .aggregate, .stringCast, .lang, .langmatches, .datatype, .bound, .call("IRI", _), .call("BNODE", _), .call("RAND", _), .call("ABS", _), .call("CEIL", _), .call("FLOOR", _), .call("ROUND", _), .call("CONCAT", _), .call("STRLEN", _), .call("UCASE", _), .call("LCASE", _), .call("ENCODE_FOR_URI", _), .call("CONTAINS", _), .call("STRSTARTS", _), .call("STRENDS", _), .call("STRBEFORE", _), .call("STRAFTER", _), .call("YEAR", _), .call("MONTH", _), .call("DAY", _), .call("HOURS", _), .call("MINUTES", _), .call("SECONDS", _), .call("TIMEZONE", _), .call("TZ", _), .call("NOW", _), .call("UUID", _), .call("STRUUID", _), .call("MD5", _), .call("SHA1", _), .call("SHA256", _), .call("SHA384", _), .call("SHA512", _), .call("COALESCE", _), .call("IF", _), .call("STRLANG", _), .call("STRDT", _), .sameterm(_, _), .isiri, .isblank, .isliteral, .isnumeric, .call("REGEX", _), .exists, .not(.exists):
return true
default:
return false
}
}
public var isNumeric: Bool {
switch self {
case .node(.bound(let term)) where term.isNumeric:
return true
case .neg(let expr):
return expr.isNumeric
case .add(let l, let r), .sub(let l, let r), .div(let l, let r), .mul(let l, let r):
return l.isNumeric && r.isNumeric
case .intCast(let expr), .floatCast(let expr), .doubleCast(let expr):
return expr.isNumeric
default:
return false
}
}
public var description: String {
switch self {
case .aggregate(let a):
return a.description
case .window(let w):
return w.description
case .node(let node):
return node.description
case .eq(let lhs, let rhs):
return "(\(lhs) == \(rhs))"
case .ne(let lhs, let rhs):
return "(\(lhs) != \(rhs))"
case .gt(let lhs, let rhs):
return "(\(lhs) > \(rhs))"
case .between(let val, let lower, let upper):
return "(\(val) BETWEEN \(lower) AND \(upper))"
case .lt(let lhs, let rhs):
return "(\(lhs) < \(rhs))"
case .ge(let lhs, let rhs):
return "(\(lhs) >= \(rhs))"
case .le(let lhs, let rhs):
return "(\(lhs) <= \(rhs))"
case .add(let lhs, let rhs):
return "(\(lhs) + \(rhs))"
case .sub(let lhs, let rhs):
return "(\(lhs) - \(rhs))"
case .mul(let lhs, let rhs):
return "(\(lhs) * \(rhs))"
case .div(let lhs, let rhs):
return "(\(lhs) / \(rhs))"
case .neg(let expr):
return "-(\(expr))"
case .and(let lhs, let rhs):
return "(\(lhs) && \(rhs))"
case .or(let lhs, let rhs):
return "(\(lhs) || \(rhs))"
case .isiri(let expr):
return "ISIRI(\(expr))"
case .isblank(let expr):
return "ISBLANK(\(expr))"
case .isliteral(let expr):
return "ISLITERAL(\(expr))"
case .isnumeric(let expr):
return "ISNUMERIC(\(expr))"
case .boolCast(let expr):
return "xsd:boolean(\(expr.description))"
case .intCast(let expr):
return "xsd:integer(\(expr.description))"
case .floatCast(let expr):
return "xsd:float(\(expr.description))"
case .doubleCast(let expr):
return "xsd:double(\(expr.description))"
case .decimalCast(let expr):
return "xsd:decimal(\(expr.description))"
case .dateTimeCast(let expr):
return "xsd:dateTime(\(expr.description))"
case .dateCast(let expr):
return "xsd:date(\(expr.description))"
case .stringCast(let expr):
return "xsd:string(\(expr.description))"
case .call(let iri, let exprs):
let strings = exprs.map { $0.description }
return "<\(iri)>(\(strings.joined(separator: ",")))"
case .lang(let expr):
return "LANG(\(expr))"
case .langmatches(let expr, let m):
return "LANGMATCHES(\(expr), \"\(m)\")"
case .sameterm(let lhs, let rhs):
return "SAMETERM(\(lhs), \(rhs))"
case .datatype(let expr):
return "DATATYPE(\(expr))"
case .bound(let expr):
return "BOUND(\(expr))"
case .not(.valuein(let expr, let exprs)):
let strings = exprs.map { $0.description }
return "\(expr) NOT IN (\(strings.joined(separator: ",")))"
case .valuein(let expr, let exprs):
let strings = exprs.map { $0.description }
return "\(expr) IN (\(strings.joined(separator: ",")))"
case .not(.exists(let child)):
return "NOT EXISTS { \(child) }"
case .not(let expr):
return "NOT(\(expr))"
case .exists(let child):
return "EXISTS { \(child) }"
}
}
}
extension Expression: Codable {
private enum CodingKeys: String, CodingKey {
case type
case node
case lhs
case rhs
case value
case algebra
case name
case expressions
case aggregate
case window
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "node":
let node = try container.decode(Node.self, forKey: .node)
self = .node(node)
case "aggregate":
let agg = try container.decode(Aggregation.self, forKey: .aggregate)
self = .aggregate(agg)
case "window":
let window = try container.decode(WindowApplication.self, forKey: .window)
self = .window(window)
case "neg":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .neg(lhs)
case "not":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .not(lhs)
case "isiri":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .isiri(lhs)
case "isblank":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .isblank(lhs)
case "isliteral":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .isliteral(lhs)
case "isnumeric":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .isnumeric(lhs)
case "lang":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .lang(lhs)
case "langmatches":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .langmatches(lhs, rhs)
case "datatype":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .datatype(lhs)
case "sameterm":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .sameterm(lhs, rhs)
case "bound":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .bound(lhs)
case "bool":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .boolCast(lhs)
case "int":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .intCast(lhs)
case "float":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .floatCast(lhs)
case "double":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .doubleCast(lhs)
case "decimal":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .decimalCast(lhs)
case "dateTime":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .dateTimeCast(lhs)
case "date":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .dateCast(lhs)
case "string":
let lhs = try container.decode(Expression.self, forKey: .lhs)
self = .stringCast(lhs)
case "eq":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .eq(lhs, rhs)
case "ne":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .ne(lhs, rhs)
case "lt":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .lt(lhs, rhs)
case "le":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .le(lhs, rhs)
case "gt":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .gt(lhs, rhs)
case "ge":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .ge(lhs, rhs)
case "add":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .add(lhs, rhs)
case "sub":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .sub(lhs, rhs)
case "div":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .div(lhs, rhs)
case "mul":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .mul(lhs, rhs)
case "and":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .and(lhs, rhs)
case "or":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .or(lhs, rhs)
case "between":
let value = try container.decode(Expression.self, forKey: .value)
let lhs = try container.decode(Expression.self, forKey: .lhs)
let rhs = try container.decode(Expression.self, forKey: .rhs)
self = .between(value, lhs, rhs)
case "valuein":
let lhs = try container.decode(Expression.self, forKey: .lhs)
let exprs = try container.decode([Expression].self, forKey: .expressions)
self = .valuein(lhs, exprs)
case "call":
let name = try container.decode(String.self, forKey: .name)
let exprs = try container.decode([Expression].self, forKey: .expressions)
self = .call(name, exprs)
case "exists":
let algebra = try container.decode(Algebra.self, forKey: .algebra)
self = .exists(algebra)
default:
throw SPARQLSyntaxError.serializationError("Unexpected expression type '\(type)' found")
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .node(node):
try container.encode("node", forKey: .type)
try container.encode(node, forKey: .node)
case let .aggregate(agg):
try container.encode("aggregate", forKey: .type)
try container.encode(agg, forKey: .aggregate)
case let .window(window):
try container.encode("window", forKey: .type)
try container.encode(window, forKey: .window)
case let .neg(lhs):
try container.encode("neg", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .not(lhs):
try container.encode("not", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .isiri(lhs):
try container.encode("isiri", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .isblank(lhs):
try container.encode("isblank", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .isliteral(lhs):
try container.encode("isliteral", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .isnumeric(lhs):
try container.encode("isnumeric", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .lang(lhs):
try container.encode("lang", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .langmatches(lhs, rhs):
try container.encode("langmatches", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .datatype(lhs):
try container.encode("datatype", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .sameterm(lhs, rhs):
try container.encode("sameterm", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .bound(lhs):
try container.encode("bound", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .boolCast(lhs):
try container.encode("bool", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .intCast(lhs):
try container.encode("int", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .floatCast(lhs):
try container.encode("float", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .doubleCast(lhs):
try container.encode("double", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .decimalCast(lhs):
try container.encode("decimal", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .dateTimeCast(lhs):
try container.encode("dateTime", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .dateCast(lhs):
try container.encode("date", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .stringCast(lhs):
try container.encode("string", forKey: .type)
try container.encode(lhs, forKey: .lhs)
case let .eq(lhs, rhs):
try container.encode("eq", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .ne(lhs, rhs):
try container.encode("ne", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .lt(lhs, rhs):
try container.encode("lt", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .le(lhs, rhs):
try container.encode("le", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .gt(lhs, rhs):
try container.encode("gt", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .ge(lhs, rhs):
try container.encode("ge", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .add(lhs, rhs):
try container.encode("add", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .sub(lhs, rhs):
try container.encode("sub", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .div(lhs, rhs):
try container.encode("div", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .mul(lhs, rhs):
try container.encode("mul", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .and(lhs, rhs):
try container.encode("and", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .or(lhs, rhs):
try container.encode("or", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .between(value, lhs, rhs):
try container.encode("between", forKey: .type)
try container.encode(value, forKey: .value)
try container.encode(lhs, forKey: .lhs)
try container.encode(rhs, forKey: .rhs)
case let .valuein(lhs, exprs):
try container.encode("valuein", forKey: .type)
try container.encode(lhs, forKey: .lhs)
try container.encode(exprs, forKey: .expressions)
case let .call(name, exprs):
try container.encode("call", forKey: .type)
try container.encode(name, forKey: .name)
try container.encode(exprs, forKey: .expressions)
case let .exists(algebra):
try container.encode("exists", forKey: .type)
try container.encode(algebra, forKey: .algebra)
}
}
}
public extension Expression {
func replace(_ map: [String:Term]) throws -> Expression {
let nodes = map.mapValues { Node.bound($0) }
return try self.replace(nodes)
}
func replace(_ map: [String:Node]) throws -> Expression {
return try self.replace({ (e) -> Expression? in
switch e {
case let .node(.variable(name, _)):
if let n = map[name] {
return .node(n)
} else {
return e
}
case .node(_):
return self
case .aggregate(let a):
return try .aggregate(a.replace(map))
case .window(let w):
return try .window(w.replace(map))
case .neg(let expr):
return try .neg(expr.replace(map))
case .eq(let lhs, let rhs):
return try .eq(lhs.replace(map), rhs.replace(map))
case .ne(let lhs, let rhs):
return try .ne(lhs.replace(map), rhs.replace(map))
case .gt(let lhs, let rhs):
return try .gt(lhs.replace(map), rhs.replace(map))
case .lt(let lhs, let rhs):
return try .lt(lhs.replace(map), rhs.replace(map))
case .ge(let lhs, let rhs):
return try .ge(lhs.replace(map), rhs.replace(map))
case .le(let lhs, let rhs):
return try .le(lhs.replace(map), rhs.replace(map))
case .add(let lhs, let rhs):
return try .add(lhs.replace(map), rhs.replace(map))
case .sub(let lhs, let rhs):
return try .sub(lhs.replace(map), rhs.replace(map))
case .mul(let lhs, let rhs):
return try .mul(lhs.replace(map), rhs.replace(map))
case .div(let lhs, let rhs):
return try .div(lhs.replace(map), rhs.replace(map))
case .between(let val, let lower, let upper):
return try .between(val.replace(map), lower.replace(map), upper.replace(map))
case .and(let lhs, let rhs):
return try .and(lhs.replace(map), rhs.replace(map))
case .or(let lhs, let rhs):
return try .or(lhs.replace(map), rhs.replace(map))
case .isiri(let expr):
return try .isiri(expr.replace(map))
case .isblank(let expr):
return try .isblank(expr.replace(map))
case .isliteral(let expr):
return try .isliteral(expr.replace(map))
case .isnumeric(let expr):
return try .isnumeric(expr.replace(map))
case .boolCast(let expr):
return try .boolCast(expr.replace(map))
case .intCast(let expr):
return try .intCast(expr.replace(map))
case .floatCast(let expr):
return try .floatCast(expr.replace(map))
case .doubleCast(let expr):
return try .doubleCast(expr.replace(map))
case .decimalCast(let expr):
return try .decimalCast(expr.replace(map))
case .dateTimeCast(let expr):
return try .dateTimeCast(expr.replace(map))
case .dateCast(let expr):
return try .dateCast(expr.replace(map))
case .stringCast(let expr):
return try .stringCast(expr.replace(map))
case .call(let iri, let exprs):
return try .call(iri, exprs.map { try $0.replace(map) })
case .lang(let expr):
return try .lang(expr.replace(map))
case .langmatches(let expr, let m):
return try .langmatches(expr.replace(map), m)
case .sameterm(let lhs, let rhs):
return try .sameterm(lhs.replace(map), rhs.replace(map))
case .datatype(let expr):
return try .datatype(expr.replace(map))
case .bound(let expr):
return try .bound(expr.replace(map))
case .valuein(let expr, let exprs):
return try .valuein(expr.replace(map), exprs.map { try $0.replace(map) })
case .not(let expr):
return try .not(expr.replace(map))
case .exists(let a):
return try .exists(a.replace(map))
}
})
}
func replace(_ map: (Expression) throws -> Expression?) throws -> Expression {
return try self.rewrite { (e) -> RewriteStatus<Expression> in
if let r = try map(e) {
return .rewrite(r)
} else {
return .rewriteChildren(e)
}
}
}
func rewrite(_ map: (Expression) throws -> RewriteStatus<Expression>) throws -> Expression {
let status = try map(self)
switch status {
case .keep:
return self
case .rewrite(let e):
return e
case .rewriteChildren(let e):
switch e {
case .node(_):
return e
case .aggregate(let a):
return try .aggregate(a.rewrite(map))
case .window(let w):
return try .window(w.rewrite(map))
case .neg(let expr):
return try .neg(expr.rewrite(map))
case .eq(let lhs, let rhs):
return try .eq(lhs.rewrite(map), rhs.rewrite(map))
case .ne(let lhs, let rhs):
return try .ne(lhs.rewrite(map), rhs.rewrite(map))
case .gt(let lhs, let rhs):
return try .gt(lhs.rewrite(map), rhs.rewrite(map))
case .lt(let lhs, let rhs):
return try .lt(lhs.rewrite(map), rhs.rewrite(map))
case .ge(let lhs, let rhs):
return try .ge(lhs.rewrite(map), rhs.rewrite(map))
case .le(let lhs, let rhs):
return try .le(lhs.rewrite(map), rhs.rewrite(map))
case .add(let lhs, let rhs):
return try .add(lhs.rewrite(map), rhs.rewrite(map))
case .sub(let lhs, let rhs):
return try .sub(lhs.rewrite(map), rhs.rewrite(map))
case .mul(let lhs, let rhs):
return try .mul(lhs.rewrite(map), rhs.rewrite(map))
case .div(let lhs, let rhs):
return try .div(lhs.rewrite(map), rhs.rewrite(map))
case .between(let val, let lower, let upper):
return try .between(val.rewrite(map), lower.rewrite(map), upper.rewrite(map))
case .and(let lhs, let rhs):
return try .and(lhs.rewrite(map), rhs.rewrite(map))
case .or(let lhs, let rhs):
return try .or(lhs.rewrite(map), rhs.rewrite(map))
case .isiri(let expr):
return try .isiri(expr.rewrite(map))
case .isblank(let expr):
return try .isblank(expr.rewrite(map))
case .isliteral(let expr):
return try .isliteral(expr.rewrite(map))
case .isnumeric(let expr):
return try .isnumeric(expr.rewrite(map))
case .boolCast(let expr):
return try .boolCast(expr.rewrite(map))
case .intCast(let expr):
return try .intCast(expr.rewrite(map))
case .floatCast(let expr):
return try .floatCast(expr.rewrite(map))
case .doubleCast(let expr):
return try .doubleCast(expr.rewrite(map))
case .decimalCast(let expr):
return try .decimalCast(expr.rewrite(map))
case .dateTimeCast(let expr):
return try .dateTimeCast(expr.rewrite(map))
case .dateCast(let expr):
return try .dateCast(expr.rewrite(map))
case .stringCast(let expr):
return try .stringCast(expr.rewrite(map))
case .call(let iri, let exprs):
return try .call(iri, exprs.map { try $0.rewrite(map) })
case .lang(let expr):
return try .lang(expr.rewrite(map))
case .langmatches(let expr, let m):
return try .langmatches(expr.rewrite(map), m)
case .sameterm(let lhs, let rhs):
return try .sameterm(lhs.rewrite(map), rhs.rewrite(map))
case .datatype(let expr):
return try .datatype(expr.rewrite(map))
case .bound(let expr):
return try .bound(expr.rewrite(map))
case .valuein(let expr, let exprs):
return try .valuein(expr.rewrite(map), exprs.map { try $0.rewrite(map) })
case .not(let expr):
return try .not(expr.rewrite(map))
case .exists(_):
return e
}
}
}
}
| true
|
f836b2741adc094c0b9a204b381cba7ea5d1a13d
|
Swift
|
1024jp/WFColorCode
|
/Sources/ColorCode/SwiftUI/Color+ColorCode.swift
|
UTF-8
| 3,369
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
//
// Color+ColorCode.swift
//
// Created by 1024jp on 2021-05-08.
/*
The MIT License (MIT)
© 2014-2022 1024jp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import SwiftUI
/// This extension on Color allows creating Color instance from a CSS color code string.
public extension Color {
/// Initialize with the given color code. Or returns `nil` if color code is invalid.
///
/// Example usage:
/// ```
/// var type: ColorCodeType?
/// let whiteColor = Color(colorCode: "hsla(0,0%,100%,0.5)", type: &type)
/// ```
///
/// - Parameters:
/// - colorCode: The CSS3 style color code string. The given code as hex or CSS keyword is case insensitive.
/// - type: Upon return, contains the detected color code type.
init?(colorCode: String, type: inout ColorCodeType?) {
guard let components = ColorComponents(colorCode: colorCode, type: &type) else {
return nil
}
self.init(components: components)
}
/// Initialize with the given color code. Or returns `nil` if color code is invalid.
///
/// - Parameter colorCode: The CSS3 style color code string. The given code as hex or CSS keyword is case insensitive.
init?(colorCode: String) {
var type: ColorCodeType?
self.init(colorCode: colorCode, type: &type)
}
/// Initialize with the given hex color code. Or returns `nil` if color code is invalid.
///
/// Example usage:
/// ```
/// let redColor = Color(hex: 0xFF0000)
/// ```
///
/// - Parameters:
/// - hex: The 6-digit hexadecimal color code.
init?(hex: Int) {
guard let components = ColorComponents(hex: hex) else {
return nil
}
self.init(components: components)
}
}
extension Color {
init(components: ColorComponents) {
switch components {
case let .rgb(r, g, b, alpha: alpha):
self.init(.sRGB, red: r, green: g, blue: b, opacity: alpha)
case let .hsl(h, s, l, alpha: alpha):
self.init(hue: h, saturation: s, lightness: l, opacity: alpha)
case let .hsb(h, s, b, alpha: alpha):
self.init(hue: h, saturation: s, brightness: b, opacity: alpha)
}
}
}
| true
|
dd3acfdb62f6742417330cc8e1beae8854c1893d
|
Swift
|
anniemiken/IOS-todolist
|
/IOS-todolist/Tasks/taskViewController.swift
|
UTF-8
| 4,037
| 2.796875
| 3
|
[] |
no_license
|
//
// taskViewController.swift
// IOS-todolist
//
// Created by Annie Johansson on 2020-11-18.
//
import UIKit
class taskViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tdoTableView: UITableView!
@IBAction func addNewTask(_ sender: Any){
let todoTask = UIAlertController(title: "Add Todo", message: "Add a new task", preferredStyle: .alert)
todoTask.addTextField()
let addTodoAction = UIAlertAction(title: "Add", style: .default){ (action) in
let newTask = Tasks(userId: 6000, id: 0, title: todoTask.textFields![0].text!, completed: false)
//let newTask = todoTask.textFields![0]
self.task.append(newTask)
self.tdoTableView.reloadData()
}
let cancel = UIAlertAction(title: "Cancel", style: .default)
todoTask.addAction(cancel)
todoTask.addAction(addTodoAction)
present(todoTask, animated: true, completion: nil)
}
private var task = [Tasks]()
override func viewDidLoad() {
super.viewDidLoad()
tdoTableView.delegate = self
tdoTableView.dataSource = self
fetchTodoData()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return task.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "todoCell", for: indexPath) as? todoCell else{ return UITableViewCell()
}
print(self.task)
cell.todoLabel.text = task[indexPath.row].title
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 66
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! todoCell
if cell.isChecked == false{
cell.todoImage.image = UIImage(named: "check.png")
cell.isChecked = true
}else{
cell.todoImage.image = nil
cell.isChecked = false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
task.remove(at: indexPath.row)
tdoTableView.reloadData()
}
}
private func fetchTodoData(){
guard let downloadURL = URL(string: "https://jsonplaceholder.typicode.com/todos") else{
return
}
URLSession.shared.dataTask(with: downloadURL) {data, URLResponse, error in
print("Downloaded")
guard let data = data, error == nil, URLResponse != nil else{
print("something is wrong")
return
}
do{
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let tasksdown = try decoder.decode([Tasks].self, from: data)
print(tasksdown)
self.task = tasksdown
DispatchQueue.main.async {
self.tdoTableView.reloadData()
}
}catch{
print(error)
print("Something wrong after downloading")
}
}.resume()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
| true
|
1902825b582edb89ea06840db636ece8d2f1999f
|
Swift
|
Arrankar/Gifka
|
/Gifka/Controllers/FullImageViewController.swift
|
UTF-8
| 566
| 2.546875
| 3
|
[] |
no_license
|
//
// FullImageViewController.swift
// Gifka
//
// Created by Александр on 04.07.2020.
// Copyright © 2020 Александр. All rights reserved.
//
import UIKit
import SDWebImage
class FullImageViewController: UIViewController {
@IBOutlet weak var fullGifImage: SDAnimatedImageView!
var gifId = ""
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://media2.giphy.com/media/\(gifId)/giphy.gif") else { return }
fullGifImage.sd_setImage(with: url, completed: nil)
}
}
| true
|
72c6e974a640302b8dee26f9c3bf6b710d6e8d75
|
Swift
|
pranjas/TicTacToe-Gravity
|
/TicTacToe-Gravity/ViewController.swift
|
UTF-8
| 2,803
| 3.078125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TicTacToe-Gravity
//
// Created by Jasleen Arora Srivastava on 02/11/18.
// Copyright © 2018 Jasleen Arora Srivastava. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let emojiX = "❌"
let emojiO = "⭕️"
var toogleEmoji = true
private var indexTag = 0
@IBOutlet weak var mainStackView: UIStackView!
@IBAction func onButtonClick(_ sender: UIButton) {
if game.isGameOver {
if !resetButton.isEnabled{
resetButton.isEnabled = true
resetButton.setTitle("Reset Game", for: .normal)
}
return
}
if sender.title(for: .normal) == ""{
let currentEmoji = toogleEmoji ?emojiX: emojiO
sender.setTitle(currentEmoji, for: .normal)
toogleEmoji = !toogleEmoji
sender.backgroundColor = .orange
let row = sender.tag / rows
let col = sender.tag % cols
game.setCardIdentifierAt(row, col, identifier: currentEmoji)
resetButton.setTitle("Board is full", for: .normal)
}
}
var allButtons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addAllButtons(numRows: rows)
resetButton.isEnabled = false
resetButton.setTitle("", for: .normal)
}
@IBOutlet weak var resetButton: UIButton!
@IBAction func onResetClick(_ sender: UIButton) {
game.resetBoard()
for btn in allButtons {
btn.setTitle("", for: .normal)
}
resetButton.isEnabled = false
resetButton.setTitle("", for: .normal)
}
let rows = 3
let cols = 3
lazy var game = TicTacToe(rows: rows)
//TODO: Fix the vertical sizing of the grid, still not coming
private func addButtonRow(numButtons: Int){
let horizStackView = UIStackView()
horizStackView.alignment = .fill
horizStackView.distribution = .equalSpacing
horizStackView.axis = .horizontal
horizStackView.spacing = 5.0
for _ in 0..<numButtons {
let btn = UIButton()
btn.setTitle("", for: .normal)
btn.backgroundColor = .orange
horizStackView.addArrangedSubview(btn)
btn.addTarget(self, action: #selector(onButtonClick(_:)), for: .touchUpInside)
btn.tag = indexTag
indexTag += 1
allButtons.append(btn)
}
mainStackView.addArrangedSubview(horizStackView)
}
private func addAllButtons(numRows :Int) {
for _ in 0..<numRows {
addButtonRow(numButtons: numRows)
}
}
}
| true
|
88ca2425ce529237ccba3ae999a0b4ab41a11761
|
Swift
|
ochan4/DonaldTheTower.spritebuilder
|
/GameData.swift
|
UTF-8
| 1,122
| 2.6875
| 3
|
[] |
no_license
|
//
// GameData.swift
// DonaldTheTower
//
// Created by Oi I Chan on 11/15/15.
// Copyright (c) 2015 Apportable. All rights reserved.
//
import Foundation
class GameStateSingleton: NSObject {
var lastscore:Int = NSUserDefaults.standardUserDefaults().integerForKey("currentscore") {
didSet {
NSUserDefaults.standardUserDefaults().setObject(lastscore, forKey:"currentscore")
}
}
var highestscore:Int = NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
didSet {
NSUserDefaults.standardUserDefaults().setObject(highestscore, forKey:"highscore")
}
}
class var sharedInstance : GameStateSingleton {
struct Static {
static let instance : GameStateSingleton = GameStateSingleton()
}
return Static.instance
}
// func checkHighScore () {
// if lastscore > highestscore {
// NSUserDefaults.standardUserDefaults().setObject(lastscore, forKey: "highscore")
// GameCenterInteractor.sharedInstance.reportHighScoreToGameCenter()
// }
// }
}
| true
|
88d2d26d703df6929451ff3784a741c682d704f9
|
Swift
|
HIIT/JustUsed
|
/JustUsed/Extensions/NSDate+Extensions.swift
|
UTF-8
| 2,783
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright (c) 2015 Aalto University
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
extension Date {
/// Number of ms since 1/1/1970.
var unixTime_ms: Int { get {
return Int(round(self.timeIntervalSince1970 * 1000))
}
}
/// Creates a date from a unix time in microsec
init(fromUnixTime_μs μs: Int) {
self.init(timeIntervalSince1970: Double(μs) / 1000000)
}
/// Number of microsec since 1/1/1970.
var unixTime_μs: Int { get {
return Int(round(self.timeIntervalSince1970 * 1000000))
}
}
/// Creates a date from a ldap timestamp.
init(fromLdapTime lt: Int) {
let unixtime_s = Double(lt)/1000000-11644473600
self.init(timeIntervalSince1970: unixtime_s)
}
/// Returns the corresponding date as a LDAP timestamp.
var ldapTime: Int { get {
return Int(round(1000000 * (11644473600 + self.timeIntervalSince1970)))
}
}
/// Returns the current time in a short format, e.g. 16:30.45
/// Use this to pass dates to DiMe
static func shortTime() -> String {
let currentDate = Date()
let dsf = DateFormatter()
dsf.dateFormat = "HH:mm.ss"
return dsf.string(from: currentDate)
}
/// Returns an NSDate that representing this date plus the given offset.
/// e.g. NSDate().yearOffset(2) represents two years from now.
func yearOffset(_ year: Int) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
var addComponents = DateComponents()
addComponents.year = year
return (calendar as NSCalendar).date(byAdding: addComponents, to: self, options: .matchStrictly)!
}
}
| true
|
84f568a56280fa01623988f66f1c3b4d2bde1ee0
|
Swift
|
Rupesh17/UIImage-Category-Swift
|
/UIImage_Category_Swift/UIImage+Alpha.swift
|
UTF-8
| 4,749
| 2.984375
| 3
|
[] |
no_license
|
//
// UIImage+Alpha.swift
//
// Created by Rupesh Kumar on 10/23/15.
// Copyright © 2015 Rupesh Kumar. All rights reserved.
//
import Foundation
import UIKit
extension UIImage
{
// Returns true if the image has an alpha layer
func hasAlpha() -> Bool
{
let alpha: CGImageAlphaInfo = CGImageGetAlphaInfo(self.CGImage)
return (alpha == CGImageAlphaInfo.First || alpha == CGImageAlphaInfo.Last || alpha == CGImageAlphaInfo.PremultipliedFirst || alpha == CGImageAlphaInfo.PremultipliedLast)
}
// Returns a copy of the given image, adding an alpha channel if it doesn't already have one
func imageWithAlpha() -> UIImage
{
if self.hasAlpha()
{
return self
}
let imageRef: CGImageRef = self.CGImage!
let width: Int = CGImageGetWidth(imageRef)
let height: Int = CGImageGetHeight(imageRef)
// The bitsPerComponent and bitmapInfo values are hard-coded to prevent an "unsupported parameter combination" error
let offscreenContext: CGContextRef = CGBitmapContextCreate(nil, width, height, 8, 0, CGImageGetColorSpace(imageRef), CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.PremultipliedFirst.rawValue)!
// Draw the image into the context and retrieve the new image, which will now have an alpha layer
CGContextDrawImage(offscreenContext, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)
let imageRefWithAlpha: CGImageRef = CGBitmapContextCreateImage(offscreenContext)!
let imageWithAlpha: UIImage = UIImage(CGImage:imageRefWithAlpha)
return imageWithAlpha
}
// Returns a copy of the image with a transparent border of the given size added around its edges.
// If the image has no alpha layer, one will be added to it.
func transparentBorderImage(borderSize: CGFloat) -> UIImage
{
// If the image does not have an alpha layer, add one
let image: UIImage = self.imageWithAlpha()
let newRect: CGRect = CGRectMake(0, 0, image.size.width + borderSize * 2, image.size.height + borderSize * 2)
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
// Build a context that's the same dimensions as the new size
let bitmap: CGContextRef = CGBitmapContextCreate(nil, Int(newRect.size.width), Int(newRect.size.height), CGImageGetBitsPerComponent(self.CGImage), 0, CGImageGetColorSpace(self.CGImage), bitmapInfo.rawValue)!
// Draw the image in the center of the context, leaving a gap around the edges
let imageLocation: CGRect = CGRectMake(borderSize, borderSize, image.size.width, image.size.height)
CGContextDrawImage(bitmap, imageLocation, self.CGImage)
let borderImageRef: CGImageRef = CGBitmapContextCreateImage(bitmap)!
// Create a mask to make the border transparent, and combine it with the image
let maskImageRef: CGImageRef = self.newBorderMask(CGFloat(borderSize), size: newRect.size)
let transparentBorderImageRef: CGImageRef = CGImageCreateWithMask(borderImageRef, maskImageRef)!
let transparentBorderImage: UIImage = UIImage(CGImage:transparentBorderImageRef)
return transparentBorderImage
}
// Creates a mask that makes the outer edges transparent and everything else opaque
// The size must include the entire mask (opaque part + transparent border)
// The caller is responsible for releasing the returned reference by calling CGImageRelease
private func newBorderMask(borderSize: CGFloat, size: CGSize) -> CGImageRef
{
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
// Build a context that's the same dimensions as the new size
let maskContext: CGContextRef = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, 0, colorSpace, CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.None.rawValue)!
// Start with a mask that's entirely transparent
CGContextSetFillColorWithColor(maskContext, UIColor.blackColor().CGColor)
CGContextFillRect(maskContext, CGRectMake(0, 0, size.width, size.height))
// Make the inner part (within the border) opaque
CGContextSetFillColorWithColor(maskContext, UIColor.whiteColor().CGColor)
CGContextFillRect(maskContext, CGRectMake(borderSize, borderSize, size.width - borderSize * 2, size.height - borderSize * 2))
// Get an image of the context
let maskImageRef: CGImageRef = CGBitmapContextCreateImage(maskContext)!
return maskImageRef
}
}
| true
|
2a07f49e9305e566706bc8fd8fd981c78ffd9b6a
|
Swift
|
BhavinGupta/ImagesDownloadAndCache
|
/ImagesDownloadAndCache/URLService/RestManager.swift
|
UTF-8
| 2,061
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//
// URLSessionTaskService.swift
// ImagesDownloadAndCache
//
// Created by Bhavin Gupta on 02/07/20.
// Copyright © 2020 Bhavin Gupta. All rights reserved.
//
import Foundation
import SwiftyJSON
class RestManager: NSObject {
// Service Call Method
func getJson(completionHandler: @escaping (Response) -> Void){
guard let url = URL(string: "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
let responseStrInISOLatin = String(data: dataResponse, encoding: String.Encoding.isoLatin1)
guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else {
print("could not convert data to UTF-8 format")
return
}
do{
//here dataResponse received from a network request
let json = try JSON(data: modifiedDataInUTF8Format)
var strTitle = String()
if let title = json["title"].string {
strTitle = title
}
var rowObject: [Rows] = []
var rows: Rows?
for item in json["rows"].arrayValue {
var strTitle = String()
var strDescription = String()
var strImageURL = String()
if let title = item["title"].string {
strTitle = title
}
if let description = item["description"].string {
strDescription = description
}
if let imageURL = item["imageHref"].string {
strImageURL = imageURL
}
rows = Rows(title: strTitle, descriptions: strDescription, imageHref: strImageURL)
rowObject.append(rows!)
}
let jsonResponse = Response(title: strTitle, rows:rowObject)
completionHandler(jsonResponse)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
}
| true
|
9299658fb59557fd3b582859b65f686f085c30cf
|
Swift
|
tsznokwong/Blockchain
|
/BlockChain.playground/Sources/Blockchain.swift
|
UTF-8
| 1,214
| 3.375
| 3
|
[] |
no_license
|
import Foundation
public class BlockChain<Element: Hashable>: CustomStringConvertible {
public private(set) var chain: [Block<Element>]
public let difficulty: UInt
public init(genesisBlock: Block<Element>, difficulty: UInt = 4) {
self.difficulty = difficulty
self.chain = [genesisBlock]
}
public func latestBlock() -> Block<Element>? {
return self.chain.last
}
public func addNewBlock(_ newBlock: Block<Element>) {
newBlock.previousHash = self.latestBlock()?.hash ?? ""
newBlock.index = (self.latestBlock()?.index ?? 0) + 1
newBlock.mineBlock(difficulty: self.difficulty)
self.chain.append(newBlock)
}
public func isValid() -> Bool {
for index in 1 ..< self.chain.count {
if self.chain[index - 1].hash != self.chain[index].previousHash {
return false
}
if self.chain[index].hash != self.chain[index].calculateHash() {
return false
}
}
return true
}
public var description: String {
return self.chain.map({ $0.description }).joined(separator: " -> ")
}
}
| true
|
49b92db7735fae20cadab81048e6bcba9ff31df0
|
Swift
|
anotherNight/MathWS
|
/JDLeetCode/JDSwiftLeetCode/JDSwiftLeetCode/Array/RemoveDuplicates.swift
|
UTF-8
| 1,193
| 3.6875
| 4
|
[
"MIT"
] |
permissive
|
//
// RemoveDuplicates.swift
// JDSwiftLeetCode
//
// Created by 吴俊东 on 8/9/2020.
// Copyright © 2020 吴俊东. All rights reserved.
//
import Foundation
/**
题目大意 #
给定一个有序数组 nums,对数组中的元素进行去重,使得原数组中的每个元素只有一个。最后返回去重以后数组的长度值。
解题思路 #
这里数组的删除并不是真的删除,只是将删除的元素移动到数组后面的空间内,然后返回数组实际剩余的元素个数,OJ 最终判断题目的时候会读取数组剩余个数的元素进行输出
*/
struct RemoveDuplicates: JDLeetCodeProtocol{
func main() {
var nums: [Int] = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicates(&nums))
}
func removeDuplicates(_ nums: inout [Int]) -> Int {
if nums.count <= 1 {
return nums.count
}
var len: Int = nums.count
var index = 0
while index < nums.count-1{
if nums[index] == nums[index+1]{
len -= 1
nums.remove(at: index+1)
}else{
index += 1
}
}
return len
}
}
| true
|
2cf34e7e4b319946f3f5b6ba25c91cc381db1697
|
Swift
|
ShotaKashihara/atcoder-swift
|
/abc188/Sources/D/main.swift
|
UTF-8
| 936
| 3.203125
| 3
|
[] |
no_license
|
// D - Snuke Prime
// https://atcoder.jp/contests/abc188/tasks/abc188_d
import Foundation
let (N, C): (Int, Int) = { let line = readLine()!.split(separator: " ").map(String.init); return (Int(line[0])!, Int(line[1])!) }()
let (s, e, c) = (0..<N).reduce(into: ([Int](), [Int](), [Int]())) { r, _ in
let l = readLine()!.split(separator: " ").map(String.init)
r.0.append(Int(l[0])! - 1)
r.1.append(Int(l[1])! - 1)
r.2.append(Int(l[2])!)
}
// n日目に +c円追加で払う
var imos = [Int: Int]()
for i in 0..<N {
imos[s[i]] = (imos[s[i]] ?? 0) + c[i]
imos[e[i]+1] = (imos[e[i]+1] ?? 0) - c[i]
}
var sum = 0
var current = -1
var value = 0
let imoss = Array(imos.sorted(by: { $0.key < $1.key }).enumerated())
for i in 0..<imoss.count-1 {
// i...i+1 のdays
let day = imoss[i+1].element.key - imoss[i].element.key
value += imoss[i].element.value
sum += day * (value > C ? C : value)
}
print(sum)
| true
|
87c9c772c340de5e49a8c3ae381a53d4d06fef06
|
Swift
|
dyadav4/FindErr
|
/FindErr/CoreData/CoreDataManager.swift
|
UTF-8
| 6,513
| 2.78125
| 3
|
[] |
no_license
|
//
// CoreDataManager.swift
// FindErr
//
// Created by Dharamvir Yadav on 6/10/20.
//
import Foundation
import CoreData
public class CoreDataManager {
// MARK: - Core Data stack
private init() {}
public static let _shared = CoreDataManager()
class func shared() -> CoreDataManager {
return _shared
}
lazy var managedContext = {
return self.persistentContainer.viewContext
}()
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "FindErr")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
//Mergepolicy is needed for avoiding the error when updating the already same attribute by shopid key
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
//save the new records
func prepare(dataForSaving: Store){
_ = self.createEntityFrom(store: dataForSaving)
saveContextInBackground()
}
//create the record for the entity
private func createEntityFrom(store: Store) -> H_Stores?{
guard let id = store.id, let name = store.name, let image = store.image, let coordinates = store.coordinates, let latitude = coordinates.latitude, let longitude = coordinates.longitude else {
return nil
}
let shop = H_Stores(context: self.managedContext)
shop.placeid = id
shop.name = name
shop.image = image
shop.latitude = latitude
shop.longitude = longitude
shop.rating = 4
return shop
}
// MARK: - Core Data Saving support
func saveContext() {
let context = self.managedContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
//if wants to save the record in background
func saveContextInBackground() {
persistentContainer.performBackgroundTask { (context) in
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
// func isShopStoredLocall(id: String, entityName: String, completion: @escaping (Bool) -> Void){
// let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
//
// let predicate = NSPredicate(format: "id == %@", id)
// request.predicate = predicate
//
// do {
// let count = try persistentContainer.viewContext.count(for: request)
// if count > 0 {
// completion(true)
// }else{
// completion(false)
// }
// }catch let error as NSError{
// completion(false)
// print(error)
// }
//
// }
// func isShopStoredLocally(id: String, entityName: String) -> Bool {
// let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
//
// let predicate = NSPredicate(format: "id == %@", id)
// request.predicate = predicate
//
// do {
// let count = try persistentContainer.viewContext.count(for: request)
// if count > 0 {
// return true
// }else{
// return false
// }
// }catch let error as NSError{
// print(error)
// }
// }
// func fetch<T: NSManagedObject>(_ type: T.Type, completion: @escaping ([T]) -> Void){
// let request = NSFetchRequest<T>(entityName: String(describing: type))
// do {
// let result = try managedContext.fetch(request)
// completion(result)
// }catch {
// print(error)
// completion([])
// }
// }
// func getAllStoresWith100Miles(_ entityName: String) -> [AnyObject]?{
// let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
// let result: [AnyObject]?
// do {
// result = try persistentContainer.viewContext.fetch(request)
//
// }catch let error as NSError{
// print(error)
// result = nil
// }
// return result
// }
}
| true
|
95e6b30e65cccdd31b06fcd3c02a32991bc89caa
|
Swift
|
mdichiara101/Cocktail-Recipes
|
/Cocktail Recipes/Views/CocktailView.swift
|
UTF-8
| 2,181
| 3.140625
| 3
|
[] |
no_license
|
//
// CocktailView.swift
// Cocktail Recipes
//
// Created by Michael Dichiara on 4/1/21.
//
import SwiftUI
import URLImage
struct CocktailView: View {
var drink: Drink
var ingredients: [String?] {
var f: [String?] = []
let m: [String?] = [drink.strMeasure1, drink.strMeasure2, drink.strMeasure3, drink.strMeasure4, drink.strMeasure5, drink.strMeasure6, drink.strMeasure7, drink.strMeasure8, drink.strMeasure9, drink.strMeasure10, drink.strMeasure11, drink.strMeasure12, drink.strMeasure13, drink.strMeasure14, drink.strMeasure15]
let s: [String?] = [drink.strIngredient1, drink.strIngredient2, drink.strIngredient3, drink.strIngredient4, drink.strIngredient5, drink.strIngredient6, drink.strIngredient7, drink.strIngredient8, drink.strIngredient9, drink.strIngredient10, drink.strIngredient11, drink.strIngredient12, drink.strIngredient13, drink.strIngredient14, drink.strIngredient15]
var i = 0
while(i < 15) {
if(s[i] != nil){
f += ["\(s[i] ?? ""): \(m[i] ?? "Desired Amount")"]
}
i+=1
}
return f
}
var body: some View {
VStack{
URLImage(url: URL(string: "\(drink.strDrinkThumb)")!,
content: { image in
image
.resizable()
.aspectRatio(contentMode: .fit)
})
Text(drink.strCategory)
.font(.subheadline)
Form{
Section(header: Text("Ingredients")){
List(ingredients, id: \.self){
ingredient in
Text("\(ingredient!)")
}
}
Section(header: Text("Instructions")){
Text("\(drink.strInstructions)")
}
}
} .navigationBarTitle(drink.strDrink, displayMode: .inline)
}
}
| true
|
f5ffb8788cecec11e64342c2e4e23f8e65faf08a
|
Swift
|
kandallov/cityEvents
|
/cityEvents/CityEventsUIKit/Cells/LinedImageView.swift
|
UTF-8
| 1,307
| 2.6875
| 3
|
[] |
no_license
|
//
// LinedImageView.swift
// cityEvents
//
// Created by Aleksandr Kandalov on 12/13/18.
// Copyright © 2018 Aleksandr Kandalov. All rights reserved.
//
import UIKit
import SnapKit
public class LinedImageView: BaseKitView, AppearanceView {
public struct LinedImageViewAppearance: Appearance {
public var accessebilityId = "linedImageView"
public var contentInset = Sizes.M.value
public var lineImageViewBackgroundColor = UIColor.clear
public var lineImageViewWight = 100
public var lineImageViewHight = 20
}
public var lineImageView = UIImageView()
public var appearance = LinedImageViewAppearance () {
didSet {
configureSubviews()
makeConstraints()
}
}
override func addSubviews() {
addSubview(lineImageView)
}
override func configureSubviews() {
accessibilityIdentifier = appearance.accessebilityId
lineImageView.backgroundColor = appearance.lineImageViewBackgroundColor
}
override func makeConstraints() {
lineImageView.snp.remakeConstraints { make in
make.center.equalToSuperview()
make.width.equalTo(appearance.lineImageViewWight)
make.height.equalTo(appearance.lineImageViewHight)
}
}
}
| true
|
476cd7acb3b3f21df554e642e7e7a07ac27c1a90
|
Swift
|
himanshupadia/UserLocation
|
/UserLocation/DistanceTravelled.swift
|
UTF-8
| 2,033
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// DistanceTravelled.swift
// UserLocation
//
// Created by Himanshu H. Padia on 20/11/17.
// Copyright © 2017 TechWorld. All rights reserved.
//
import UIKit
import MapKit
class DistanceTravelled: UIViewController {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var lblDistance:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
self.lblDistance.text = "Traveled Distance: 0.0\nTotal Traveled Distance: 0.0"
}
fileprivate func performOperation(_ totalTravelledDistance: Double?, _ travelledDistance: Double?) {
// display local notification
self.appDelegate.displayNotification()
// core data operation
let context = self.appDelegate.persistentContainer.viewContext
let task = History (context: context)
task.historydate = String(describing: Date().string(with: "E, d MMM yyyy HH:mm:ss"))
task.totaldistance = String(totalTravelledDistance!.rounded(toPlaces: 4))
task.travaldistance = String(travelledDistance!.rounded(toPlaces: 4))
// Save the data to coredata
self.appDelegate.saveContext()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
LocationService.sharedLocationServices.requestTravelledDistance { (travelledDistance, totalTravelledDistance, error) in
if error != nil {
self.lblDistance.text = "Unable to get Location, Please allow location access from setting. (\(String(describing: error)))"
return
}
self.lblDistance.text = "Traveled Distance: \(travelledDistance!)\nTotal Traveled Distance: \(totalTravelledDistance!)"
if travelledDistance! >= LocationService.sharedLocationServices.userTravelledDistance {
self.performOperation(totalTravelledDistance, travelledDistance)
}
}
}
}
| true
|
bff0d572d6cd7f548873a2e42c21b2e4ad39a435
|
Swift
|
ajaysharmalike/ios-search-venue
|
/VenueSearch/Manager/MapProvider.swift
|
UTF-8
| 2,313
| 2.8125
| 3
|
[] |
no_license
|
//
// MapProvider.swift
// VenueSearch
//
// Created by Ajay Sharma on 11/03/21.
// Copyright © 2021 TTN. All rights reserved.
//
import Foundation
import MapKit
protocol MapProviderProtocol: AnyObject {
func mapCoordinates(didReceiveCoordinates model: LocationCoordinates?)
}
class MapCoordinator: NSObject {
private var mapView: MKMapView?
private let locationService = LocationService()
weak var delegate: MapProviderProtocol?
/// Configure MapView
func configureMapView() {
mapView = MKMapView(frame: UIScreen.main.bounds)
mapView?.showsUserLocation = true
mapView?.delegate = self
}
func getCurrentLocation() {
locationService.getCurrentLocation {[weak self] (location) in
self?.setMapViewRegionWith(currentLocation: location)
}
}
/// Set Map Region
/// - Parameter location: current location from Location Manager
private func setMapViewRegionWith(currentLocation location: CLLocation?) {
let center = CLLocationCoordinate2D(latitude: location?.coordinate.latitude ?? 0, longitude: location?.coordinate.longitude ?? 0)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView?.setRegion(region, animated: true)
}
}
// MARK: - MKMapViewDelegate Delegate -
extension MapCoordinator: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
let topLeftCoordinate = mapView.convert(.zero, toCoordinateFrom: mapView)
let bottomRightCoordinate = mapView.convert(CGPoint(x: mapView.bounds.size.width, y: mapView.bounds.size.height), toCoordinateFrom: mapView)
//Create Model
let mapInfoModel = LocationCoordinates(topLeftLat: topLeftCoordinate.latitude, topLeftLon: topLeftCoordinate.longitude, bottomRightLat: bottomRightCoordinate.latitude, bottomRightLon: bottomRightCoordinate.longitude, zoomLevel: getZoomLevel(with: mapView))
delegate?.mapCoordinates(didReceiveCoordinates: mapInfoModel)
}
private func getZoomLevel(with mapView: MKMapView) -> Float {
return Float(log2(360 * (Double(mapView.bounds.size.width/256) / mapView.region.span.longitudeDelta)) + 1)
}
}
| true
|
f2568bb77ed4e8bd37fe4864b4fa22cffebdfdcc
|
Swift
|
emirkucukosman/pay-mate
|
/PayMate/PayMate/Extensions/UIViewController+.swift
|
UTF-8
| 964
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// UIViewController+.swift
// PayMate
//
// Created by Emir Küçükosman on 11.11.2020.
//
import UIKit
extension UIViewController {
func getAlert(title: String, message: String?, handler: ((UIAlertAction) -> Void)?) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: handler))
return alert
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height / 2
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
}
| true
|
fe2d6984ff32a0a20601012ef3b9ca197cd0a23e
|
Swift
|
radityakurnianto/RWExtensionPack
|
/Sources/RWExtensionPack/Regex.swift
|
UTF-8
| 650
| 2.984375
| 3
|
[] |
no_license
|
//
// Regex.swift
// RWExtensionPack
//
// Created by Raditya Kurnianto on 9/21/20.
//
import Foundation
public class Regex: NSObject {
public static func check(keyword: String, pattern: String) -> Bool {
do {
let searchRange = NSRange(location: 0, length: keyword.count)
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let match = regex.firstMatch(in: keyword, options: [], range: searchRange)
guard let matched = match else { return false }
return matched.numberOfRanges > 0
} catch {
return false
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.